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): assign, mark as a priority or hide a Content plan row (#1321)

Cihan3993c6c5d0ba
diff --git a/supabase/migrations/00229_content_plan_marks.sql b/supabase/migrations/00229_content_plan_marks.sql
new file mode 100644
index 000000000..a6422820d
--- /dev/null
+++ b/supabase/migrations/00229_content_plan_marks.sql
@@ -0,0 +1,77 @@
+-- ============================================================================
+-- 00229: the Content plan's row marks — priority and hidden (CE-014)
+-- ============================================================================
+-- The Plan's priority list is built on each read (content_plan_pages, 00221,
+-- and the brand's open opportunities), so a row has no row of its own to
+-- keep a choice on. Admins and managers mark a row as a priority, or hide
+-- it, per brand:
+--
+-- * content_plan_marks: one row per brand and Plan row, keyed as the app
+-- keys the rows: 'opportunity:<id>' or 'page:<host/path>'. priority puts
+-- the row at the top of the list with a Priority tag; hidden_at takes it
+-- off the list until someone shows it again. Hiding an opportunity's row
+-- also dismisses the opportunity (the app does it through its status),
+-- so the Opportunities page agrees; restore_status is the status it had,
+-- given back when the row is shown again.
+-- * Members of the brand's organization read the marks; admins and managers
+-- write them, as they do the workspace's rule sets (00214).
+
+create table if not exists public.content_plan_marks (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ row_key text not null check (char_length(row_key) between 1 and 600),
+ priority boolean not null default false,
+ hidden_at timestamptz,
+ restore_status text check (restore_status in ('new', 'reviewed', 'sent', 'in_progress')),
+ updated_by uuid references public.profiles(id) on delete set null,
+ updated_at timestamptz not null default now(),
+ primary key (brand_id, row_key)
+);
+
+alter table public.content_plan_marks enable row level security;
+
+create policy "content_plan_marks: member select"
+ on public.content_plan_marks
+ for select
+ using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "content_plan_marks: manager insert"
+ on public.content_plan_marks
+ for insert
+ with check (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid() and p.role in ('admin', 'manager')
+ )
+ and updated_by = auth.uid()
+ );
+
+create policy "content_plan_marks: manager update"
+ on public.content_plan_marks
+ for update
+ using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid() and p.role in ('admin', 'manager')
+ )
+ )
+ with check (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid() and p.role in ('admin', 'manager')
+ )
+ and updated_by = auth.uid()
+ );
+
+grant select, insert, update on public.content_plan_marks to authenticated;
+
+comment on table public.content_plan_marks is
+ 'Content Editor (CE-014): an admin''s or manager''s marks on a Content plan row — priority (top of the list) or hidden (off it until shown again), with the opportunity''s status to give back.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 8e67b809b..ed0a1635d 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -33541,6 +33541,87 @@ create trigger profiles_guard_server_columns
before update on public.profiles
for each row execute function public.guard_profile_server_columns();
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00229_content_plan_marks.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00229: the Content plan's row marks — priority and hidden (CE-014)
+-- ============================================================================
+-- The Plan's priority list is built on each read (content_plan_pages, 00221,
+-- and the brand's open opportunities), so a row has no row of its own to
+-- keep a choice on. Admins and managers mark a row as a priority, or hide
+-- it, per brand:
+--
+-- * content_plan_marks: one row per brand and Plan row, keyed as the app
+-- keys the rows: 'opportunity:<id>' or 'page:<host/path>'. priority puts
+-- the row at the top of the list with a Priority tag; hidden_at takes it
+-- off the list until someone shows it again. Hiding an opportunity's row
+-- also dismisses the opportunity (the app does it through its status),
+-- so the Opportunities page agrees; restore_status is the status it had,
+-- given back when the row is shown again.
+-- * Members of the brand's organization read the marks; admins and managers
+-- write them, as they do the workspace's rule sets (00214).
+
+create table if not exists public.content_plan_marks (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ row_key text not null check (char_length(row_key) between 1 and 600),
+ priority boolean not null default false,
+ hidden_at timestamptz,
+ restore_status text check (restore_status in ('new', 'reviewed', 'sent', 'in_progress')),
+ updated_by uuid references public.profiles(id) on delete set null,
+ updated_at timestamptz not null default now(),
+ primary key (brand_id, row_key)
+);
+
+alter table public.content_plan_marks enable row level security;
+
+create policy "content_plan_marks: member select"
+ on public.content_plan_marks
+ for select
+ using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "content_plan_marks: manager insert"
+ on public.content_plan_marks
+ for insert
+ with check (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid() and p.role in ('admin', 'manager')
+ )
+ and updated_by = auth.uid()
+ );
+
+create policy "content_plan_marks: manager update"
+ on public.content_plan_marks
+ for update
+ using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid() and p.role in ('admin', 'manager')
+ )
+ )
+ with check (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid() and p.role in ('admin', 'manager')
+ )
+ and updated_by = auth.uid()
+ );
+
+grant select, insert, update on public.content_plan_marks to authenticated;
+
+comment on table public.content_plan_marks is
+ 'Content Editor (CE-014): an admin''s or manager''s marks on a Content plan row — priority (top of the list) or hidden (off it until shown again), with the opportunity''s status to give back.';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00230_content_start_prompts.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/messages/en.json b/web/messages/en.json
index 36ddf1a82..bcd5420d9 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3103,7 +3103,8 @@
"cards": {
"create": { "title": "Create", "hint": "New pages AI needs" },
"optimize": { "title": "Optimize", "hint": "Pages losing ground" },
- "protect": { "title": "Protect", "hint": "Top pages · edit with care" }
+ "protect": { "title": "Protect", "hint": "Top pages · edit with care" },
+ "priority": { "title": "Priority", "hint": "Marked by your team" }
},
"results": {
"label": "From AI visits · {days} full days to yesterday (UTC):",
@@ -3140,7 +3141,8 @@
"action": "Action",
"why": "Why · last {days} days",
"who": "Who",
- "start": "Start"
+ "start": "Start",
+ "menu": "Row actions"
},
"newPage": "New page",
"actions": { "create": "Create", "optimize": "Optimize", "protect": "Protect" },
@@ -3163,7 +3165,32 @@
"empty": "Nothing to work on yet. New opportunities and your pages' AI citations show up here.",
"emptyFiltered": "Nothing here for this period.",
"loadError": "Couldn't load the content plan.",
- "retry": "Try again"
+ "retry": "Try again",
+ "priority": "Priority",
+ "rowMenu": {
+ "label": "Actions for {title}",
+ "assign": "Assign to…",
+ "markPriority": "Mark as priority",
+ "unmarkPriority": "Remove priority",
+ "hide": "Hide from the plan",
+ "hidden": "Hidden: {title}",
+ "undo": "Undo",
+ "failed": "Couldn't save that. Try again."
+ },
+ "hidden": {
+ "toggle": "{count, plural, one {# hidden row} other {# hidden rows}} · {open, select, true {Hide} other {Show}}",
+ "show": "Show again"
+ },
+ "assign": {
+ "title": "Assign “{title}”",
+ "description": "It goes to the Action Center as a task for this teammate.",
+ "member": "Teammate",
+ "pick": "Pick a teammate",
+ "submit": "Assign",
+ "cancel": "Cancel",
+ "done": "Assigned to {name}",
+ "failed": "Couldn't assign it. Try again."
+ }
},
"agentState": {
"writing": "Agent writing…",
@@ -3330,7 +3357,10 @@
"team": {
"title": "Team",
"hint": "Send to Action Center"
- }
+ },
+ "assignTo": "Assign to",
+ "assignNone": "No one yet",
+ "assignFailed": "Sent, but couldn't assign it. Assign it in the Action Center."
},
"overlap": {
"label": "Overview",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx
index 9d561f3d3..25ccd6ba4 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx
@@ -17,6 +17,9 @@ vi.mock('@/lib/actions/content-drafts', () => ({
getContentStartOptions: (...args: unknown[]) => getContentStartOptions(...args),
createContentDraft: vi.fn(),
}));
+// Start's Team: its assignee picker reads the team, and the sent task is assigned.
+vi.mock('@/lib/actions/team', () => ({ listMembers: vi.fn(async () => []) }));
+vi.mock('@/lib/actions/action-center', () => ({ assignAction: vi.fn() }));
const push = vi.fn();
vi.mock('@/i18n/navigation', () => ({
Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_assign-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_assign-dialog.tsx
new file mode 100644
index 000000000..cdb2ed1ea
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_assign-dialog.tsx
@@ -0,0 +1,124 @@
+'use client';
+
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Label } from '@/components/ui/label';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { assignAction } from '@/lib/actions/action-center';
+import { sendContentDraftToActionCenter } from '@/lib/actions/content-drafts';
+import type { TeamMember } from '@/lib/actions/team';
+import { memberLabel } from '@/lib/action-center/display';
+import type { PlanRow } from '@/lib/content/plan';
+
+/**
+ * Assign a Plan row that has a draft (CE-014): its Action Center task goes
+ * to a teammate. A draft not sent yet is sent first, as Start's Team does.
+ * A row with no draft starts in Start instead, with Team and its assignee.
+ */
+export function AssignDialog({
+ brandId,
+ row,
+ members,
+ onClose,
+ onAssigned,
+}: {
+ brandId: string;
+ /** The row to assign; the dialog is closed while it is null. */
+ row: PlanRow | null;
+ members: TeamMember[];
+ onClose: () => void;
+ onAssigned: () => void;
+}) {
+ const t = useTranslations('contentEditor.plan.assign');
+ const [memberId, setMemberId] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+ const draft = row?.draft ?? null;
+
+ const assign = async () => {
+ if (!draft || !memberId) return;
+ setSaving(true);
+ try {
+ let actionId = draft.actionId;
+ if (!actionId) {
+ const sent = await sendContentDraftToActionCenter(brandId, draft.id);
+ if ('error' in sent) throw new Error(sent.error);
+ actionId = sent.actionId;
+ }
+ await assignAction(brandId, actionId, memberId);
+ const member = members.find((m) => m.userId === memberId);
+ toast.success(t('done', { name: member ? memberLabel(member) : '' }));
+ setMemberId(null);
+ onAssigned();
+ } catch (err) {
+ console.error('Failed to assign the Plan row:', err);
+ toast.error(t('failed'));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Dialog
+ open={row !== null}
+ onOpenChange={(open) => {
+ if (!open) {
+ setMemberId(null);
+ onClose();
+ }
+ }}
+ >
+ {/* One column no wider than the dialog: a long title wraps, clear of the close button. */}
+ <DialogContent className="grid-cols-[minmax(0,1fr)] sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle className="pr-6 leading-snug [overflow-wrap:anywhere]">
+ {t('title', { title: row?.title ?? '' })}
+ </DialogTitle>
+ <DialogDescription>{t('description')}</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-2">
+ <Label htmlFor="plan-assign-member">{t('member')}</Label>
+ <Select
+ value={memberId}
+ onValueChange={(value) => setMemberId(value as string | null)}
+ items={members.map((member) => ({ value: member.userId, label: memberLabel(member) }))}
+ >
+ <SelectTrigger id="plan-assign-member" className="w-full">
+ <SelectValue placeholder={t('pick')} />
+ </SelectTrigger>
+ <SelectContent>
+ {members.map((member) => (
+ <SelectItem key={member.userId} value={member.userId}>
+ {memberLabel(member)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={onClose} disabled={saving}>
+ {t('cancel')}
+ </Button>
+ <Button onClick={() => void assign()} disabled={!memberId || saving}>
+ {t('submit')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-table.tsx
index 8b68d5ae3..06c84b3c4 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-table.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-table.tsx
@@ -1,10 +1,17 @@
'use client';
import { useFormatter, useTranslations } from 'next-intl';
-import { Bot, User } from 'lucide-react';
+import { Bot, EyeOff, MoreHorizontal, Star, User, UserPlus } from 'lucide-react';
import { Link } from '@/i18n/navigation';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
import { buttonVariants } from '@/components/ui/button-variants';
import {
Table,
@@ -32,16 +39,26 @@ export const PLAN_ACTION_BADGE: Record<PlanAction, string> = {
/**
* The Plan's priority list (CE-014): rank, the page (a new one, or the
* brand's own), the action, why for the period with where it comes from,
- * who is on it, and the button that starts it — or opens its draft.
+ * who is on it, the button that starts it — or opens its draft — and a row
+ * menu: assign it to a teammate, and for admins and managers, mark it as a
+ * priority or hide it.
*/
export function PlanTable({
rows,
days,
+ canManage,
onStart,
+ onAssign,
+ onPriority,
+ onHide,
}: {
rows: PlanRow[];
days: PlanPeriod;
+ canManage: boolean;
onStart: (row: PlanRow) => void;
+ onAssign: (row: PlanRow) => void;
+ onPriority: (row: PlanRow, priority: boolean) => void;
+ onHide: (row: PlanRow) => void;
}) {
const t = useTranslations('contentEditor.plan');
const tTypes = useTranslations('contentEditor.pageTypes');
@@ -56,18 +73,29 @@ export function PlanTable({
<TableHead>{t('columns.why', { days })}</TableHead>
{/* Wide windows only: the row's button says the same once a draft exists. */}
<TableHead className="hidden xl:table-cell">{t('columns.who')}</TableHead>
- <TableHead className="pr-6">
+ <TableHead>
<span className="sr-only">{t('columns.start')}</span>
</TableHead>
+ <TableHead className="w-8 pl-0 pr-3">
+ <span className="sr-only">{t('columns.menu')}</span>
+ </TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((row, i) => (
<TableRow key={row.key}>
<TableCell className="pl-6 tabular-nums text-muted-foreground">{i + 1}</TableCell>
- <TableCell className="max-w-[260px]">
- <p className="truncate font-medium" title={row.title}>
- {row.title}
+ <TableCell className="max-w-[250px]">
+ <p className="flex min-w-0 items-center gap-1.5 font-medium">
+ <span className="truncate" title={row.title}>
+ {row.title}
+ </span>
+ {row.priority && (
+ <Badge variant="outline" className="shrink-0 gap-1 font-normal">
+ <Star aria-hidden className="h-3 w-3" />
+ {t('priority')}
+ </Badge>
+ )}
</p>
<p className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
{isPageType(row.pageType) && (
@@ -92,7 +120,12 @@ export function PlanTable({
</span>
</TableCell>
<TableCell className="hidden text-muted-foreground xl:table-cell">
- {row.draft ? (
+ {row.draft?.assignee ? (
+ <span className="inline-flex items-center gap-1.5">
+ <User aria-hidden className="h-3.5 w-3.5" />
+ {row.draft.assignee.name}
+ </span>
+ ) : row.draft ? (
<span className="inline-flex items-center gap-1.5">
{row.draft.author === 'agent' ? (
<Bot aria-hidden className="h-3.5 w-3.5" />
@@ -109,7 +142,7 @@ export function PlanTable({
'—'
)}
</TableCell>
- <TableCell className="pr-6 text-right">
+ <TableCell className="text-right">
{row.draft ? (
<Link
href={contentEditorPath(row.draft.id)}
@@ -127,6 +160,15 @@ export function PlanTable({
</Button>
)}
</TableCell>
+ <TableCell className="pl-0 pr-3">
+ <RowMenu
+ row={row}
+ canManage={canManage}
+ onAssign={onAssign}
+ onPriority={onPriority}
+ onHide={onHide}
+ />
+ </TableCell>
</TableRow>
))}
</TableBody>
@@ -134,6 +176,51 @@ export function PlanTable({
);
}
+function RowMenu({
+ row,
+ canManage,
+ onAssign,
+ onPriority,
+ onHide,
+}: {
+ row: PlanRow;
+ canManage: boolean;
+ onAssign: (row: PlanRow) => void;
+ onPriority: (row: PlanRow, priority: boolean) => void;
+ onHide: (row: PlanRow) => void;
+}) {
+ const t = useTranslations('contentEditor.plan.rowMenu');
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className="rounded p-1 text-muted-foreground hover:bg-muted"
+ aria-label={t('label', { title: row.title })}
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-48">
+ <DropdownMenuItem onClick={() => onAssign(row)}>
+ <UserPlus className="h-4 w-4" />
+ {t('assign')}
+ </DropdownMenuItem>
+ {canManage && (
+ <>
+ <DropdownMenuItem onClick={() => onPriority(row, !row.priority)}>
+ <Star className="h-4 w-4" />
+ {row.priority ? t('unmarkPriority') : t('markPriority')}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => onHide(row)}>
+ <EyeOff className="h-4 w-4" />
+ {t('hide')}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
function WhyText({ why }: { why: PlanWhy }) {
const t = useTranslations('contentEditor.plan.why');
const format = useFormatter();
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx
index 6c6d3407e..9c307f396 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx
@@ -8,10 +8,29 @@ import ContentPlanPage from './page';
const getContentPlan = vi.fn();
const getContentPlanInsights = vi.fn();
+const setPlanRowPriority = vi.fn();
+const hidePlanRow = vi.fn();
+const showPlanRow = vi.fn();
vi.mock('@/lib/actions/content-plan', () => ({
getContentPlan: (...args: unknown[]) => getContentPlan(...args),
getContentPlanInsights: (...args: unknown[]) => getContentPlanInsights(...args),
+ setPlanRowPriority: (...args: unknown[]) => setPlanRowPriority(...args),
+ hidePlanRow: (...args: unknown[]) => hidePlanRow(...args),
+ showPlanRow: (...args: unknown[]) => showPlanRow(...args),
}));
+const listMembers = vi.fn();
+vi.mock('@/lib/actions/team', () => ({
+ listMembers: (...args: unknown[]) => listMembers(...args),
+}));
+// Assigning a draft's task is _assign-dialog's; here, which rows open it.
+vi.mock('./_assign-dialog', () => ({
+ AssignDialog: ({ row }: { row: { title: string } | null }) =>
+ row ? <div data-testid="assign-dialog">{row.title}</div> : null,
+}));
+const role = vi.hoisted(() => ({ canManage: true }));
+vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => role }));
+const toast = vi.hoisted(() => Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
// New content is new-content-dialog.test.tsx's; here, what the Plan opens it on.
const dialog = vi.hoisted(() => ({ props: null as Record<string, unknown> | null }));
vi.mock('@/components/content/new-content-dialog', () => ({
@@ -134,6 +153,13 @@ beforeEach(() => {
root = createRoot(container);
getContentPlan.mockReset().mockResolvedValue(PLAN);
getContentPlanInsights.mockReset().mockResolvedValue(INSIGHTS);
+ setPlanRowPriority.mockReset().mockResolvedValue(undefined);
+ hidePlanRow.mockReset().mockResolvedValue(undefined);
+ showPlanRow.mockReset().mockResolvedValue(undefined);
+ listMembers.mockReset().mockResolvedValue([]);
+ toast.mockReset();
+ toast.error.mockReset();
+ role.canManage = true;
dialog.props = null;
});
@@ -149,6 +175,7 @@ describe('the Content plan', () => {
expect(button('Create').textContent).toBe('Create1New pages AI needs');
expect(button('Optimize').textContent).toBe('Optimize1Pages losing ground');
expect(button('Protect').textContent).toBe('Protect1Top pages · edit with care');
+ expect(button('Priority').textContent).toBe('Priority0Marked by your team');
// Pages cited for the same prompts are no warning: no Overlaps card.
expect(button('Overlaps')).toBeUndefined();
@@ -446,3 +473,137 @@ describe('the Content plan', () => {
expect(rowTexts()).toHaveLength(3);
});
});
+
+describe('a Plan row’s menu', () => {
+ const ESPRESSO = 'page:acme.example/guides/espresso';
+ const menuItems = async (title: string) => {
+ const trigger = container.querySelector<HTMLElement>(`[aria-label="Actions for ${title}"]`)!;
+ await act(async () => trigger.click());
+ return [...document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+ };
+ const hiddenList = (toggle: string) => button(toggle).parentElement!.querySelector('ul')!;
+ const clickItem = async (title: string, item: string) => {
+ const found = (await menuItems(title)).find((el) => el.textContent === item)!;
+ await act(async () => found.click());
+ };
+
+ it('puts the rows marked as a priority on top, tagged, with a card to filter them', async () => {
+ getContentPlan.mockResolvedValue({
+ ...PLAN,
+ marks: [{ rowKey: ESPRESSO, priority: true, hidden: false }],
+ });
+ await renderPage();
+ expect(rowTexts().map((r) => r[0])).toEqual([
+ 'Espresso guidePriorityHow-to guide/guides/espresso',
+ 'Office coffee subscriptionsNew page',
+ 'Coffee subscriptionsHow-to guide/guides/coffee-subscriptions',
+ ]);
+ expect(button('Priority').textContent).toBe('Priority1Marked by your team');
+
+ await act(async () => button('Priority').click());
+ expect(rowTexts().map((r) => r[1])).toEqual(['Protect']);
+
+ await clickItem('Espresso guide', 'Remove priority');
+ expect(setPlanRowPriority).toHaveBeenCalledWith('brand-1', ESPRESSO, false);
+ });
+
+ it('marks a row as a priority, and reads the plan again', async () => {
+ await renderPage();
+ const items = await menuItems('Espresso guide');
+ expect(items.map((el) => el.textContent)).toEqual([
+ 'Assign to…',
+ 'Mark as priority',
+ 'Hide from the plan',
+ ]);
+ await act(async () => items[1].click());
+ expect(setPlanRowPriority).toHaveBeenCalledWith('brand-1', ESPRESSO, true);
+ expect(getContentPlan).toHaveBeenCalledTimes(2);
+ });
+
+ it('hides a row, with an undo, and lists the hidden rows to show again', async () => {
+ await renderPage();
+ await clickItem('Office coffee subscriptions', 'Hide from the plan');
+ expect(hidePlanRow).toHaveBeenCalledWith('brand-1', 'opportunity:o1');
+ expect(getContentPlan).toHaveBeenCalledTimes(2);
+ expect(toast).toHaveBeenCalledWith('Hidden: Office coffee subscriptions', {
+ action: { label: 'Undo', onClick: expect.any(Function) },
+ });
+ await act(async () => toast.mock.calls[0][1].action.onClick());
+ expect(showPlanRow).toHaveBeenCalledWith('brand-1', 'opportunity:o1');
+
+ getContentPlan.mockResolvedValue({
+ ...PLAN,
+ marks: [{ rowKey: 'opportunity:o1', priority: false, hidden: true }],
+ });
+ await act(async () => button('Last 7 days').click());
+ expect(rowTexts()).toHaveLength(2);
+ expect(button('Create').textContent).toBe('Create0New pages AI needs');
+ expect(container.textContent).not.toContain('Show again');
+
+ await act(async () => button('1 hidden row · Show').click());
+ const hidden = hiddenList('1 hidden row · Hide');
+ expect(hidden.textContent).toBe('Office coffee subscriptionsShow again');
+ showPlanRow.mockClear();
+ await act(async () => hidden.querySelector('button')!.click());
+ expect(showPlanRow).toHaveBeenCalledWith('brand-1', 'opportunity:o1');
+ expect(button('1 hidden row · Hide').getAttribute('aria-expanded')).toBe('true');
+ });
+
+ it('says so when a mark can’t be saved', async () => {
+ hidePlanRow.mockRejectedValue(new Error('denied'));
+ await renderPage();
+ await clickItem('Espresso guide', 'Hide from the plan');
+ expect(toast.error).toHaveBeenCalledWith("Couldn't save that. Try again.");
+ expect(getContentPlan).toHaveBeenCalledTimes(1);
+ });
+
+ it('lets members assign a row, but not mark, hide or show one', async () => {
+ role.canManage = false;
+ getContentPlan.mockResolvedValue({
+ ...PLAN,
+ marks: [{ rowKey: 'opportunity:o1', priority: false, hidden: true }],
+ });
+ await renderPage();
+ expect((await menuItems('Espresso guide')).map((el) => el.textContent)).toEqual(['Assign to…']);
+ await act(async () => button('1 hidden row · Show').click());
+ expect(hiddenList('1 hidden row · Hide').textContent).toBe('Office coffee subscriptions');
+ });
+
+ it('assigns a row without a draft in Start, on Team; one with a draft, its task', async () => {
+ getContentPlan.mockResolvedValue({
+ ...PLAN,
+ drafts: [
+ {
+ id: 'd1',
+ author: 'user',
+ isMine: false,
+ method: 'optimize',
+ opportunityId: null,
+ sourceUrl: 'https://acme.example/guides/espresso',
+ actionId: 'a1',
+ assignee: { id: 'u2', name: 'Ada Lovelace' },
+ },
+ ],
+ });
+ await renderPage();
+ // Who does it: the teammate the task is assigned to.
+ expect(container.querySelectorAll('tbody tr')[2].textContent).toContain('Ada Lovelace');
+
+ await clickItem('Coffee subscriptions', 'Assign to…');
+ expect(listMembers).toHaveBeenCalledTimes(1);
+ expect(dialog.props).toMatchObject({
+ open: true,
+ preset: {
+ kind: 'page',
+ url: 'https://acme.example/guides/coffee-subscriptions',
+ who: 'team',
+ },
+ });
+ expect(container.querySelector('[data-testid="assign-dialog"]')).toBeNull();
+
+ await clickItem('Espresso guide', 'Assign to…');
+ expect(container.querySelector('[data-testid="assign-dialog"]')!.textContent).toBe(
+ 'Espresso guide',
+ );
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
index c2009946a..b8408c125 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
@@ -2,11 +2,20 @@
import { useEffect, useMemo, useState } from 'react';
import { useFormatter, useTranslations } from 'next-intl';
+import { toast } from 'sonner';
import { Loader2, Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { NewContentDialog, type DialogPreset } from '@/components/content/new-content-dialog';
-import { getContentPlan, getContentPlanInsights } from '@/lib/actions/content-plan';
+import {
+ getContentPlan,
+ getContentPlanInsights,
+ hidePlanRow,
+ setPlanRowPriority,
+ showPlanRow,
+} from '@/lib/actions/content-plan';
+import { listMembers, type TeamMember } from '@/lib/actions/team';
+import { useUserRole } from '@/hooks/use-user-role';
import type { PageType } from '@/lib/content/drafts';
import { pageTypeMix } from '@/lib/content/plan-mix';
import { siteTypeOf } from '@/lib/content/page-types';
@@ -24,6 +33,7 @@ import { formatNumber } from '@/lib/format';
import { readUrlChoice, writeUrlParams } from '@/lib/url-state';
import { cn } from '@/lib/utils';
import { useBrandStore } from '@/stores/use-brand-store';
+import { AssignDialog } from './_assign-dialog';
import { AiResultsStrip, PageTypeMix } from './_plan-insights';
import { PlanTable } from './_plan-table';
@@ -41,20 +51,27 @@ type InsightsRead = {
data: Awaited<ReturnType<typeof getContentPlanInsights>>;
};
-/** Each card's color, as its action's tag: Create blue, Optimize amber, Protect green. */
+/**
+ * Each card's color, as its action's tag: Create blue, Optimize amber,
+ * Protect green; Priority, the rows marked, in ink as its outline badge.
+ */
const CARD_DOT: Record<PlanCard, string> = {
create: 'bg-blue-600 dark:bg-blue-400',
optimize: 'bg-amber-600 dark:bg-amber-400',
protect: 'bg-green-600 dark:bg-green-400',
+ priority: 'bg-foreground',
};
/**
* The Content plan (Content Editor CE-014, spec v2 §4): what to create,
- * optimize or protect next, for the last 7, 30 or 90 days. Three cards count
- * the work and filter the list, as a row of the page-type mix does; the list
- * ranks it, and each row starts it in New content (Start for an opportunity,
- * an existing page read to optimize) or opens the draft already being
- * written. The period lives in the URL (?days=7).
+ * optimize or protect next, for the last 7, 30 or 90 days. The cards count
+ * the work and the priorities and filter the list, as a row of the
+ * page-type mix does; the list ranks it, priorities first, and each row
+ * starts it in New content (Start for an opportunity, an existing page read
+ * to optimize) or opens the draft already being written. A row's menu
+ * assigns it to a teammate, and lets admins and managers mark it as a
+ * priority or hide it; hidden rows can be shown again below the list. The
+ * period lives in the URL (?days=7).
*/
export default function ContentPlanPage() {
const t = useTranslations('contentEditor.plan');
@@ -71,6 +88,10 @@ export default function ContentPlanPage() {
const [attempt, setAttempt] = useState(0);
const [starting, setStarting] = useState(false);
const [preset, setPreset] = useState<DialogPreset | null>(null);
+ const { canManage } = useUserRole();
+ const [members, setMembers] = useState<TeamMember[]>([]);
+ const [assigning, setAssigning] = useState<PlanRow | null>(null);
+ const [showHidden, setShowHidden] = useState(false);
// Another brand starts unfiltered: its cards and types are its own.
const [filtersFor, setFiltersFor] = useState(activeBrandId);
if (filtersFor !== activeBrandId) {
@@ -144,20 +165,78 @@ export default function ContentPlanPage() {
writeUrlParams({ days: String(next) }, { days: '30' });
};
+ const presetFor = (row: PlanRow): DialogPreset =>
+ row.opportunityId
+ ? {
+ kind: 'opportunity',
+ id: row.opportunityId,
+ // An opportunity for an existing page starts on that page.
+ page: row.page ? { url: row.page, title: row.title } : null,
+ }
+ : { kind: 'page', url: row.page! };
+
const startRow = (row: PlanRow) => {
- setPreset(
- row.opportunityId
- ? {
- kind: 'opportunity',
- id: row.opportunityId,
- // An opportunity for an existing page starts on that page.
- page: row.page ? { url: row.page, title: row.title } : null,
- }
- : { kind: 'page', url: row.page! },
- );
+ setPreset(presetFor(row));
+ setStarting(true);
+ };
+
+ // The team, for assigning: read once, when first needed.
+ const loadMembers = () => {
+ if (members.length > 0) return;
+ listMembers()
+ .then(setMembers)
+ .catch((err) => console.error('Failed to load the team:', err));
+ };
+
+ // A row with a draft assigns its task; one without starts in Start, as Team.
+ const assignRow = (row: PlanRow) => {
+ loadMembers();
+ if (row.draft) {
+ setAssigning(row);
+ return;
+ }
+ setPreset({ ...presetFor(row), who: 'team' });
setStarting(true);
};
+ const reload = () => setAttempt((n) => n + 1);
+
+ const markRow = async (row: PlanRow, priority: boolean) => {
+ if (!activeBrandId) return;
+ try {
+ await setPlanRowPriority(activeBrandId, row.key, priority);
+ reload();
+ } catch (err) {
+ console.error('Failed to mark the Plan row:', err);
+ toast.error(t('rowMenu.failed'));
+ }
+ };
+
+ const showRow = async (row: PlanRow) => {
+ if (!activeBrandId) return;
+ try {
+ await showPlanRow(activeBrandId, row.key);
+ reload();
+ } catch (err) {
+ console.error('Failed to show the Plan row:', err);
+ toast.error(t('rowMenu.failed'));
+ }
+ };
+
+ const hideRow = async (row: PlanRow) => {
+ if (!activeBrandId) return;
+ try {
+ await hidePlanRow(activeBrandId, row.key);
+ reload();
+ toast(t('rowMenu.hidden', { title: row.title }), {
+ action: { label: t('rowMenu.undo'), onClick: () => void showRow(row) },
+ });
+ } catch (err) {
+ console.error('Failed to hide the Plan row:', err);
+ toast.error(t('rowMenu.failed'));
+ }
+ };
+
if (!activeBrandId) {
return (
<div className="flex min-h-[400px] items-center justify-center">
@@ -223,7 +302,7 @@ export default function ContentPlanPage() {
onSent={() => setAttempt((n) => n + 1)}
/>
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
{PLAN_CARDS.map((value) => (
<button
key={value}
@@ -310,13 +389,62 @@ export default function ContentPlanPage() {
{filtered ? t('emptyFiltered') : t('empty')}
</p>
) : (
- <PlanTable rows={rows} days={current?.days ?? 30} onStart={startRow} />
+ <PlanTable
+ rows={rows}
+ days={current?.days ?? 30}
+ canManage={canManage}
+ onStart={startRow}
+ onAssign={assignRow}
+ onPriority={(row, priority) => void markRow(row, priority)}
+ onHide={(row) => void hideRow(row)}
+ />
)}
</CardContent>
</Card>
+ {plan && plan.hidden.length > 0 && (
+ <div className="space-y-2">
+ <button
+ type="button"
+ aria-expanded={showHidden}
+ onClick={() => setShowHidden((v) => !v)}
+ className="text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
+ >
+ {t('hidden.toggle', { count: plan.hidden.length, open: String(showHidden) })}
+ </button>
+ {showHidden && (
+ <ul className="divide-y rounded-xl border">
+ {plan.hidden.map((row) => (
+ <li
+ key={row.key}
+ className="flex items-center justify-between gap-3 px-4 py-2 text-sm"
+ >
+ <span className="min-w-0 truncate text-muted-foreground" title={row.title}>
+ {row.title}
+ </span>
+ {canManage && (
+ <Button size="sm" variant="outline" onClick={() => void showRow(row)}>
+ {t('hidden.show')}
+ </Button>
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
</div>
</>
)}
+ <AssignDialog
+ brandId={activeBrandId}
+ row={assigning}
+ members={members}
+ onClose={() => setAssigning(null)}
+ onAssigned={() => {
+ setAssigning(null);
+ reload();
+ }}
+ />
</div>
);
}
diff --git a/web/src/components/content/new-content-dialog.test.tsx b/web/src/components/content/new-content-dialog.test.tsx
index b43944e55..40f568dfb 100644
--- a/web/src/components/content/new-content-dialog.test.tsx
+++ b/web/src/components/content/new-content-dialog.test.tsx
@@ -21,6 +21,57 @@ vi.mock('@/lib/actions/content-drafts', () => ({
getContentOverlap: (...args: unknown[]) => getContentOverlap(...args),
}));
// What the agent is given is agent-write.test.ts's; here, that Start hands it over.
+const listMembers = vi.fn();
+vi.mock('@/lib/actions/team', () => ({
+ listMembers: (...args: unknown[]) => listMembers(...args),
+}));
+const assignAction = vi.fn();
+vi.mock('@/lib/actions/action-center', () => ({
+ assignAction: (...args: unknown[]) => assignAction(...args),
+}));
+// Team's assignee picker as a native select: Base UI's popup doesn't open in jsdom.
+vi.mock('@/components/ui/select', () => ({
+ Select: ({
+ value,
+ onValueChange,
+ children,
+ }: {
+ value: string | null;
+ onValueChange: (value: string | null) => void;
+ children: React.ReactNode;
+ }) => (
+ <select data-select value={value ?? ''} onChange={(e) => onValueChange(e.target.value || null)}>
+ <option value="" />
+ {children}
+ </select>
+ ),
+ SelectTrigger: () => null,
+ SelectValue: () => null,
+ SelectContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ SelectItem: ({ value, children }: { value: string; children: React.ReactNode }) => (
+ <option value={value}>{children}</option>
+ ),
+}));
+const MEMBERS = [
+ {
+ userId: 'u1',
+ email: '[email protected]',
+ fullName: 'Mia Chen',
+ avatarUrl: null,
+ role: 'admin',
+ createdAt: '2026-01-01',
+ isCurrentUser: true,
+ },
+ {
+ userId: 'u2',
+ email: '[email protected]',
+ fullName: 'Ada Lovelace',
+ avatarUrl: null,
+ role: 'member',
+ createdAt: '2026-01-02',
+ isCurrentUser: false,
+ },
+];
const agentWriteRequest = vi.fn();
const describeRule = vi.fn();
vi.mock('@/lib/content/agent-write', () => ({
@@ -118,6 +169,8 @@ beforeEach(() => {
getContentOverlap.mockReset().mockResolvedValue({ totalPrompts: 2, pages: [] });
importContentPage.mockReset().mockResolvedValue({ error: 'failed' });
sendContentDraftToActionCenter.mockReset();
+ listMembers.mockReset().mockResolvedValue(MEMBERS);
+ assignAction.mockReset().mockResolvedValue(undefined);
startAgentWriting.mockReset();
agentWriteRequest.mockReset().mockResolvedValue({ sources: 'kept', rules: [] });
onSent.mockReset();
@@ -479,6 +532,16 @@ describe('New content', () => {
expect(radio('Optimize /pricing instead')).toBeUndefined();
});
+ it('opens on Team when the plan asks to assign the work', async () => {
+ await render('b2b', { kind: 'opportunity', id: 'o2', who: 'team' });
+ await act(async () => {});
+ const team = [
+ ...document.querySelectorAll<HTMLElement>('[aria-labelledby="start-who"] [role="radio"]'),
+ ].find((r) => r.textContent?.startsWith('Team'))!;
+ expect(team.getAttribute('aria-checked')).toBe('true');
+ expect(listMembers).toHaveBeenCalled();
+ });
+
it('leaves an opportunity no longer open to pick', async () => {
await render('b2b', { kind: 'opportunity', id: 'gone' });
expect(button('Continue')).toBeDefined();
@@ -767,6 +830,45 @@ describe('New content', () => {
expect(push).toHaveBeenCalledWith('/dashboard/action-center/actions?action=a1');
});
+ it('assigns the task to the teammate picked under Team', async () => {
+ sendContentDraftToActionCenter.mockResolvedValue({
+ actionId: 'a1',
+ actionNo: 214,
+ created: true,
+ });
+ await startNewPage();
+ await click(whoOption('Team'));
+ await act(async () => {});
+ expect(document.body.textContent).toContain('Assign to');
+ const picker = document.querySelector<HTMLSelectElement>('select[data-select]')!;
+ expect([...picker.options].map((o) => o.textContent)).toEqual([
+ '',
+ 'Mia Chen',
+ 'Ada Lovelace',
+ ]);
+ await act(async () => {
+ picker.value = 'u2';
+ picker.dispatchEvent(new Event('change', { bubbles: true }));
+ });
+ await click(button('Send to Action Center'));
+
+ expect(sendContentDraftToActionCenter).toHaveBeenCalledWith('b1', 'd9');
+ expect(assignAction).toHaveBeenCalledWith('b1', 'a1', 'u2');
+ expect(toast.success.mock.calls[0][0]).toBe('Sent to the Action Center');
+ });
+
+ it('sends the task unassigned when no one is picked', async () => {
+ sendContentDraftToActionCenter.mockResolvedValue({
+ actionId: 'a1',
+ actionNo: 214,
+ created: true,
+ });
+ await startNewPage();
+ await click(whoOption('Team'));
+ await click(button('Send to Action Center'));
+ expect(assignAction).not.toHaveBeenCalled();
+ });
+
it('says the draft is kept when sending it fails, and opens it on request', async () => {
sendContentDraftToActionCenter.mockResolvedValue({ error: 'Failed to send' });
await startNewPage();
diff --git a/web/src/components/content/new-content-dialog.tsx b/web/src/components/content/new-content-dialog.tsx
index b6db9fb2d..7c82c327b 100644
--- a/web/src/components/content/new-content-dialog.tsx
+++ b/web/src/components/content/new-content-dialog.tsx
@@ -27,6 +27,13 @@ import {
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Textarea } from '@/components/ui/textarea';
import {
@@ -37,6 +44,9 @@ import {
sendContentDraftToActionCenter,
startAgentWriting,
} from '@/lib/actions/content-drafts';
+import { assignAction } from '@/lib/actions/action-center';
+import { listMembers, type TeamMember } from '@/lib/actions/team';
+import { memberLabel } from '@/lib/action-center/display';
import { agentWriteRequest, useRuleDescriber } from '@/lib/content/agent-write';
import { MAX_ATTACHMENT_BYTES, textToHtml } from '@/lib/content/attachments';
import { cleanHtml } from '@/lib/content/clean-html';
@@ -121,9 +131,13 @@ interface StartChoice {
* What the dialog opens on, from the Content plan (CE-014): an opportunity
* (for an existing page, Start optimizes that page), or a page to read.
*/
-export type DialogPreset =
+export type DialogPreset = (
| { kind: 'opportunity'; id: string; page?: { url: string; title: string | null } | null }
- | { kind: 'page'; url: string };
+ | { kind: 'page'; url: string }
+) & {
+ /** Opened to assign the work (the Plan's "Assign to…"): Start chooses Team. */
+ who?: 'team';
+};
/** Who does the page (Start, CE-015): the person, the Content Agent, or the team. */
type Who = 'me' | 'agent' | 'team';
@@ -185,6 +199,9 @@ export function NewContentDialog({
const [start, setStart] = useState<StartChoice | null>(null);
const [opening, setOpening] = useState(false);
const [who, setWho] = useState<Who>('me');
+ // Team's assignee: the task goes to this teammate once it is sent.
+ const [members, setMembers] = useState<TeamMember[]>([]);
+ const [assigneeId, setAssigneeId] = useState<string | null>(null);
const [overlapRead, setOverlapRead] = useState<OverlapRead | null>(null);
const [overlapAttempt, setOverlapAttempt] = useState(0);
const fileRef = useRef<HTMLInputElement>(null);
@@ -208,11 +225,22 @@ export function NewContentDialog({
};
}, [open, brandId, attempt]);
+ // The team, for Team's assignee: read once, when Team is first chosen.
+ const membersRead = useRef(false);
+ useEffect(() => {
+ if (who !== 'team' || membersRead.current) return;
+ membersRead.current = true;
+ listMembers()
+ .then(setMembers)
+ .catch((err) => console.error('Failed to load the team:', err));
+ }, [who]);
+
// From the Content plan: Start for its opportunity once the options are in
// (one no longer open is left to pick), or its page read to optimize.
const presetApplied = useRef(false);
useEffect(() => {
if (!open || !preset || presetApplied.current) return;
+ if (preset.who === 'team') setWho('team');
if (preset.kind === 'page') {
presetApplied.current = true;
setMethod('optimize');
@@ -286,6 +314,7 @@ export function NewContentDialog({
setOpening(false);
setOverlapRead(null);
setWho('me');
+ setAssigneeId(null);
};
const changeOpen = (next: boolean) => {
if (!next) reset();
@@ -537,6 +566,15 @@ export function NewContentDialog({
});
return;
}
+ if (assigneeId) {
+ try {
+ await assignAction(brandId, sent.actionId, assigneeId);
+ } catch (err) {
+ // The task is sent all the same; it can be assigned in the Action Center.
+ console.error('Failed to assign the sent draft:', err);
+ toast.warning(t('who.assignFailed'));
+ }
+ }
toast.success(t('start.sent'), {
description: t('start.sentDescription', { number: sent.actionNo }),
duration: 10_000,
@@ -650,6 +688,32 @@ export function NewContentDialog({
</button>
))}
</div>
+ {who === 'team' && (
+ <div className="space-y-1.5">
+ <Label htmlFor="start-assignee" className="text-xs text-muted-foreground">
+ {t('who.assignTo')}
+ </Label>
+ <Select
+ value={assigneeId}
+ onValueChange={(value) => setAssigneeId(value as string | null)}
+ items={members.map((member) => ({
+ value: member.userId,
+ label: memberLabel(member),
+ }))}
+ >
+ <SelectTrigger id="start-assignee" className="w-full">
+ <SelectValue placeholder={t('who.assignNone')} />
+ </SelectTrigger>
+ <SelectContent>
+ {members.map((member) => (
+ <SelectItem key={member.userId} value={member.userId}>
+ {memberLabel(member)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )}
</div>
<DialogFooter className="sticky -bottom-4 z-10 bg-muted">
<Button variant="ghost" onClick={() => setStart(null)} disabled={opening}>
diff --git a/web/src/lib/actions/content-plan.test.ts b/web/src/lib/actions/content-plan.test.ts
index 2ddebcad2..b4e6115e8 100644
--- a/web/src/lib/actions/content-plan.test.ts
+++ b/web/src/lib/actions/content-plan.test.ts
@@ -6,11 +6,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
*/
const BRAND = '33333333-3333-3333-3333-333333333333';
+const O9 = '99999999-9999-9999-9999-999999999999';
let reads: Record<string, unknown>;
let rpcResult: unknown;
let rpcCalls: [string, unknown][];
let filters: [string, string, string, unknown][];
+/** One row a .maybeSingle() read or write returns, by table (null: none). */
+let single: Record<string, unknown>;
+let writes: { table: string; op: string; value: unknown; options?: unknown }[];
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
@@ -20,30 +24,59 @@ vi.mock('@/lib/supabase/server', () => ({
{ data: rpcResult, error: null }
),
from: (table: string) => {
+ // A read by id (the hidden opportunities) answers from `${table}#id`.
+ let byId = false;
const chain: Record<string, unknown> = {
select: () => chain,
eq: (col: string, v: unknown) => (filters.push([table, 'eq', col, v]), chain),
- in: (col: string, v: unknown) => (filters.push([table, 'in', col, v]), chain),
+ in: (col: string, v: unknown) => {
+ filters.push([table, 'in', col, v]);
+ if (col === 'id') byId = true;
+ return chain;
+ },
order: () => chain,
limit: () => chain,
- then: (resolve: (r: unknown) => void) => resolve({ data: reads[table] ?? [], error: null }),
+ upsert: async (value: unknown, options: unknown) => {
+ writes.push({ table, op: 'upsert', value, options });
+ return { error: null };
+ },
+ update: (value: unknown) => (writes.push({ table, op: 'update', value }), chain),
+ maybeSingle: async () => ({
+ data: table in single ? single[table] : null,
+ error: null,
+ }),
+ then: (resolve: (r: unknown) => void) =>
+ resolve({
+ data: (byId && reads[`${table}#id`]) || reads[table] || [],
+ error: null,
+ }),
};
return chain;
},
})),
}));
+const readAssignees = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/action-center/assignees', () => ({ readAssignees }));
+const updateOpportunityStatus = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/actions/content', () => ({ updateOpportunityStatus }));
+
const getSuggestionSourceStates = vi.hoisted(() => vi.fn());
vi.mock('@/lib/actions/integrations', () => ({ getSuggestionSourceStates }));
const GA_CONNECTED = { configured: true, connected: true, mapped: true, lastDataAt: '2026-10-20' };
-const { getContentPlan, getContentPlanInsights } = await import('./content-plan');
+const { getContentPlan, getContentPlanInsights, hidePlanRow, setPlanRowPriority, showPlanRow } =
+ await import('./content-plan');
beforeEach(() => {
reads = {};
rpcResult = { days: 30, pages: [] };
rpcCalls = [];
filters = [];
+ single = {};
+ writes = [];
+ readAssignees.mockReset().mockResolvedValue(new Map());
+ updateOpportunityStatus.mockReset().mockResolvedValue({});
getSuggestionSourceStates.mockReset().mockResolvedValue({ ga: GA_CONNECTED });
});
@@ -92,8 +125,16 @@ describe('getContentPlan', () => {
method: 'create',
opportunity_id: 'o2',
source_url: null,
+ action_id: 'a1',
},
];
+ reads.actions = [{ id: 'a1', assignee_id: 'u2' }];
+ readAssignees.mockResolvedValue(
+ new Map([['u2', { id: 'u2', fullName: null, avatarUrl: null, email: '[email protected]' }]]),
+ );
+ reads.content_plan_marks = [
+ { row_key: 'page:acme.example/guides/espresso', priority: true, hidden_at: null },
+ ];
await expect(getContentPlan(BRAND, 7)).resolves.toEqual({
pages: [
@@ -129,9 +170,14 @@ describe('getContentPlan', () => {
method: 'create',
opportunityId: 'o2',
sourceUrl: null,
+ actionId: 'a1',
+ // Named as the Action Center names them: the e-mail when there's no name.
+ assignee: { id: 'u2', name: '[email protected]' },
},
],
+ marks: [{ rowKey: 'page:acme.example/guides/espresso', priority: true, hidden: false }],
});
+ expect(readAssignees).toHaveBeenCalledWith(expect.anything(), BRAND, ['u2']);
expect(rpcCalls).toEqual([['content_plan_pages', { p_brand_id: BRAND, p_days: 7 }]]);
expect(filters).toContainEqual(['content_opportunities', 'eq', 'type', 'owned']);
expect(filters).toContainEqual([
@@ -156,6 +202,108 @@ describe('getContentPlan', () => {
});
});
+describe('the Plan’s row marks (00229)', () => {
+ it('reads a hidden opportunity, dismissed with its row, to show it again', async () => {
+ rpcResult = { pages: [] };
+ reads.content_opportunities = [
+ { id: 'o1', title: 'Open one', decision: 'create', opportunity_score: 50, source_data: {} },
+ ];
+ reads['content_opportunities#id'] = [
+ { id: O9, title: 'Hidden one', decision: 'create', opportunity_score: 40, source_data: {} },
+ ];
+ reads.content_plan_marks = [
+ { row_key: `opportunity:${O9}`, priority: false, hidden_at: '2026-10-21T10:00:00Z' },
+ // Not an opportunity's id: never read.
+ { row_key: 'opportunity:o8', priority: false, hidden_at: '2026-10-21T10:00:00Z' },
+ ];
+ const plan = await getContentPlan(BRAND, 30);
+ expect(plan?.opportunities.map((o) => o.id)).toEqual(['o1', O9]);
+ expect(plan?.marks[0]).toEqual({ rowKey: `opportunity:${O9}`, priority: false, hidden: true });
+ expect(filters).toContainEqual(['content_opportunities', 'in', 'id', [O9]]);
+ // Only while it is still dismissed: one completed or reopened since isn't hidden.
+ expect(filters).toContainEqual(['content_opportunities', 'eq', 'status', 'dismissed']);
+ });
+
+ it('marks a row as a priority, as the member', async () => {
+ await setPlanRowPriority(BRAND, 'page:acme.example/pricing', true);
+ expect(writes).toEqual([
+ {
+ table: 'content_plan_marks',
+ op: 'upsert',
+ value: expect.objectContaining({
+ brand_id: BRAND,
+ row_key: 'page:acme.example/pricing',
+ priority: true,
+ updated_by: 'u1',
+ }),
+ options: { onConflict: 'brand_id,row_key' },
+ },
+ ]);
+ });
+
+ it('hides an opportunity’s row and dismisses it, keeping the status it had', async () => {
+ single.content_opportunities = { status: 'reviewed' };
+ await hidePlanRow(BRAND, 'opportunity:22222222-2222-2222-2222-222222222222');
+ expect(writes[0]).toMatchObject({
+ table: 'content_plan_marks',
+ op: 'upsert',
+ value: {
+ row_key: 'opportunity:22222222-2222-2222-2222-222222222222',
+ restore_status: 'reviewed',
+ },
+ });
+ expect((writes[0].value as { hidden_at: string }).hidden_at).toEqual(expect.any(String));
+ expect(updateOpportunityStatus).toHaveBeenCalledWith(
+ '22222222-2222-2222-2222-222222222222',
+ 'dismissed',
+ );
+ });
+
+ it('hides a page’s row without touching any opportunity', async () => {
+ await hidePlanRow(BRAND, 'page:acme.example/blog/a');
+ expect(writes[0]).toMatchObject({ value: { restore_status: null } });
+ expect(updateOpportunityStatus).not.toHaveBeenCalled();
+ });
+
+ it('shows a row again, giving its opportunity back the status it had', async () => {
+ single.content_plan_marks = { restore_status: 'sent', row_key: 'opportunity:o' };
+ single.content_opportunities = { status: 'dismissed' };
+ await showPlanRow(BRAND, 'opportunity:22222222-2222-2222-2222-222222222222');
+ expect(writes).toEqual([
+ {
+ table: 'content_plan_marks',
+ op: 'update',
+ value: expect.objectContaining({ hidden_at: null, restore_status: null, updated_by: 'u1' }),
+ },
+ ]);
+ expect(updateOpportunityStatus).toHaveBeenCalledWith(
+ '22222222-2222-2222-2222-222222222222',
+ 'sent',
+ );
+ });
+
+ it('leaves an opportunity completed or reopened while hidden as it is', async () => {
+ single.content_plan_marks = { restore_status: 'new', row_key: 'opportunity:o' };
+ single.content_opportunities = { status: 'completed' };
+ await showPlanRow(BRAND, 'opportunity:22222222-2222-2222-2222-222222222222');
+ expect(writes).toEqual([
+ expect.objectContaining({ table: 'content_plan_marks', op: 'update' }),
+ ]);
+ expect(updateOpportunityStatus).not.toHaveBeenCalled();
+ });
+
+ it('shows nothing it can’t write, and refuses what isn’t a row key', async () => {
+ await expect(showPlanRow(BRAND, 'page:acme.example/x')).rejects.toThrow('not_found');
+ await expect(setPlanRowPriority('b1', 'page:x', true)).rejects.toThrow('invalid');
+ await expect(hidePlanRow(BRAND, '')).rejects.toThrow('invalid');
+ // The opportunity comes from the key: one without an id is refused.
+ await expect(hidePlanRow(BRAND, 'opportunity:not-an-id')).rejects.toThrow('invalid');
+ await expect(showPlanRow(BRAND, 'opportunity:not-an-id')).rejects.toThrow('invalid');
+ expect(writes).toEqual([]);
+ expect(updateOpportunityStatus).not.toHaveBeenCalled();
+ });
+});
+
describe('getContentPlanInsights', () => {
it('reads what AI cites and what AI visits brought in', async () => {
rpcResult = {
diff --git a/web/src/lib/actions/content-plan.ts b/web/src/lib/actions/content-plan.ts
index 8f56e43b7..0e2d334bd 100644
--- a/web/src/lib/actions/content-plan.ts
+++ b/web/src/lib/actions/content-plan.ts
@@ -3,12 +3,16 @@
import { z } from 'zod';
import { createClient } from '@/lib/supabase/server';
import { getSuggestionSourceStates } from '@/lib/actions/integrations';
+import { updateOpportunityStatus } from '@/lib/actions/content';
+import { readAssignees } from '@/lib/action-center/assignees';
+import { memberLabel } from '@/lib/action-center/display';
import type { DraftMethod } from '@/lib/content/drafts';
import type { CitedAddress, PlanResults } from '@/lib/content/plan-mix';
import {
PLAN_PERIODS,
type PlanAnswers,
type PlanDraft,
+ type PlanMark,
type PlanOpportunity,
type PlanPage,
type PlanPeriod,
@@ -19,8 +23,10 @@ import { googleSourceStatus } from '@/lib/traffic-sources';
/**
* What the Content plan (CE-014) is built from, read through the signed-in
* member's session: the brand's pages as AI cites them (content_plan_pages,
- * 00220), its open opportunities for its own pages, and the drafts still
- * being written. lib/content/plan.ts ranks them.
+ * 00220), its open opportunities for its own pages, the drafts still being
+ * written (with who their Action Center task is assigned to), and the rows
+ * marked as a priority or hidden (content_plan_marks, 00229).
+ * lib/content/plan.ts ranks them.
*/
/** Open opportunities, as New content offers them. */
@@ -39,6 +45,17 @@ const planInput = z.object({
const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '');
+const OPPORTUNITY_COLUMNS = 'id, title, decision, opportunity_score, brief, source_data';
+const OPPORTUNITY_KEY = 'opportunity:';
+/**
+ * The opportunity a row's key names (`opportunity:<id>`), or null for a
+ * page's row. The server reads it from the key the mark is written under,
+ * so a row's status change can't land on another opportunity.
+ */
+function opportunityIdOf(rowKey: string): string | null {
+ return rowKey.startsWith(OPPORTUNITY_KEY) ? rowKey.slice(OPPORTUNITY_KEY.length) : null;
+}
+
export async function getContentPlan(
brandId: string,
days: PlanPeriod,
@@ -48,15 +65,16 @@ export async function getContentPlan(
tracking: PlanTracking;
opportunities: PlanOpportunity[];
drafts: PlanDraft[];
+ marks: PlanMark[];
} | null> {
if (!planInput.safeParse({ brandId, days }).success) throw new Error('invalid');
const supabase = await createClient();
- const [userRes, pagesRes, opportunitiesRes, draftsRes] = await Promise.all([
+ const [userRes, pagesRes, opportunitiesRes, draftsRes, marksRes] = await Promise.all([
supabase.auth.getUser(),
supabase.rpc('content_plan_pages', { p_brand_id: brandId, p_days: days }),
supabase
.from('content_opportunities')
- .select('id, title, decision, opportunity_score, brief, source_data')
+ .select(OPPORTUNITY_COLUMNS)
.eq('brand_id', brandId)
.eq('type', 'owned')
.in('status', OPEN_OPPORTUNITY_STATUSES)
@@ -64,15 +82,20 @@ export async function getContentPlan(
.limit(OPPORTUNITY_LIMIT),
supabase
.from('content_drafts')
- .select('id, author, created_by, method, opportunity_id, source_url')
+ .select('id, author, created_by, method, opportunity_id, source_url, action_id')
.eq('brand_id', brandId)
.in('status', ['draft', 'in_review', 'ready'])
.order('updated_at', { ascending: false })
.limit(DRAFT_LIMIT),
+ supabase
+ .from('content_plan_marks')
+ .select('row_key, priority, hidden_at')
+ .eq('brand_id', brandId),
]);
if (pagesRes.error) throw new Error(pagesRes.error.message);
if (opportunitiesRes.error) throw new Error(opportunitiesRes.error.message);
if (draftsRes.error) throw new Error(draftsRes.error.message);
+ if (marksRes.error) throw new Error(marksRes.error.message);
// Null: not the member's brand.
if (!pagesRes.data) return null;
const me = userRes.data.user?.id ?? null;
@@ -99,40 +122,213 @@ export async function getContentPlan(
aiVisits: Number(p.aiVisits ?? 0),
}));
- const opportunities = (opportunitiesRes.data ?? []).map((o): PlanOpportunity => {
- const sd = (o.source_data ?? {}) as Record<string, unknown>;
- const brief = (o.brief ?? null) as { suggestedTitle?: unknown } | null;
- const target = Array.isArray(sd.targetPages)
- ? (sd.targetPages as { url?: unknown; title?: unknown }[]).find((p) => text(p?.url))
- : undefined;
- return {
- id: o.id,
- title: o.title,
- pageTitle: text(brief?.suggestedTitle) || null,
- decision: o.decision,
- score: Number(o.opportunity_score ?? 0),
- targetPage: target ? text(target.url) : null,
- targetTitle: text(target?.title) || null,
- competitorsCited: Array.isArray(sd.competitorsCited)
- ? sd.competitorsCited.map(text).filter(Boolean).slice(0, 2)
- : [],
- visibility: typeof sd.visibilityScore === 'number' ? sd.visibilityScore : null,
- prompts: Array.isArray(sd.prompts) ? sd.prompts.length : 0,
- };
- });
+ const marks = (marksRes.data ?? []).map(
+ (m): PlanMark => ({ rowKey: m.row_key, priority: m.priority, hidden: m.hidden_at !== null }),
+ );
+ // A hidden opportunity's row was dismissed with it: read it too, to show
+ // again, while it is still dismissed (not completed or reopened since).
+ const openIds = new Set((opportunitiesRes.data ?? []).map((o) => o.id));
+ const hiddenIds = marks
+ .filter((m) => m.hidden)
+ .map((m) => opportunityIdOf(m.rowKey))
+ .filter((id): id is string => id !== null && z.guid().safeParse(id).success)
+ .filter((id) => !openIds.has(id));
+ const hiddenRes = hiddenIds.length
+ ? await supabase
+ .from('content_opportunities')
+ .select(OPPORTUNITY_COLUMNS)
+ .eq('brand_id', brandId)
+ .eq('status', 'dismissed')
+ .in('id', hiddenIds)
+ : { data: [], error: null };
+ if (hiddenRes.error) throw new Error(hiddenRes.error.message);
+
+ const opportunities = [...(opportunitiesRes.data ?? []), ...(hiddenRes.data ?? [])].map(
+ (o): PlanOpportunity => {
+ const sd = (o.source_data ?? {}) as Record<string, unknown>;
+ const brief = (o.brief ?? null) as { suggestedTitle?: unknown } | null;
+ const target = Array.isArray(sd.targetPages)
+ ? (sd.targetPages as { url?: unknown; title?: unknown }[]).find((p) => text(p?.url))
+ : undefined;
+ return {
+ id: o.id,
+ title: o.title,
+ pageTitle: text(brief?.suggestedTitle) || null,
+ decision: o.decision,
+ score: Number(o.opportunity_score ?? 0),
+ targetPage: target ? text(target.url) : null,
+ targetTitle: text(target?.title) || null,
+ competitorsCited: Array.isArray(sd.competitorsCited)
+ ? sd.competitorsCited.map(text).filter(Boolean).slice(0, 2)
+ : [],
+ visibility: typeof sd.visibilityScore === 'number' ? sd.visibilityScore : null,
+ prompts: Array.isArray(sd.prompts) ? sd.prompts.length : 0,
+ };
+ },
+ );
- const drafts = (draftsRes.data ?? []).map(
- (d): PlanDraft => ({
+ // Who each draft's Action Center task is assigned to.
+ const actionIds = [
+ ...new Set((draftsRes.data ?? []).map((d) => d.action_id).filter(Boolean)),
+ ] as string[];
+ const actionsRes = actionIds.length
+ ? await supabase.from('actions').select('id, assignee_id').in('id', actionIds)
+ : { data: [], error: null };
+ if (actionsRes.error) throw new Error(actionsRes.error.message);
+ const assigneeOf = new Map(
+ (actionsRes.data ?? []).map((a) => [a.id as string, a.assignee_id as string | null]),
+ );
+ const people = await readAssignees(
+ supabase,
+ brandId,
+ [...assigneeOf.values()].filter(Boolean) as string[],
+ );
+
+ const drafts = (draftsRes.data ?? []).map((d): PlanDraft => {
+ const assigneeId = d.action_id ? (assigneeOf.get(d.action_id) ?? null) : null;
+ const person = assigneeId ? people.get(assigneeId) : undefined;
+ return {
id: d.id,
author: d.author === 'agent' ? 'agent' : 'user',
isMine: me !== null && d.created_by === me,
method: d.method as DraftMethod,
opportunityId: d.opportunity_id,
sourceUrl: d.source_url,
- }),
+ actionId: d.action_id ?? null,
+ assignee: person
+ ? {
+ id: person.id,
+ name: memberLabel({ fullName: person.fullName, email: person.email ?? '' }),
+ }
+ : null,
+ };
+ });
+
+ return { pages, answers, tracking, opportunities, drafts, marks };
+}
+
+const markInput = z.object({
+ brandId: z.guid(),
+ rowKey: z.string().min(1).max(600),
+});
+
+/** A row key's opportunity, checked: 'invalid' for an opportunity key without a uuid. */
+function checkedOpportunityId(rowKey: string): string | null {
+ const id = opportunityIdOf(rowKey);
+ if (id !== null && !z.guid().safeParse(id).success) throw new Error('invalid');
+ return id;
+}
+
+/**
+ * Mark a Plan row as a priority, or take the mark off (admins and managers;
+ * content_plan_marks' policies refuse anyone else).
+ */
+export async function setPlanRowPriority(
+ brandId: string,
+ rowKey: string,
+ priority: boolean,
+): Promise<void> {
+ if (!markInput.safeParse({ brandId, rowKey }).success) throw new Error('invalid');
+ const supabase = await createClient();
+ const { data: user } = await supabase.auth.getUser();
+ if (!user.user) throw new Error('not_found');
+ const { error } = await supabase.from('content_plan_marks').upsert(
+ {
+ brand_id: brandId,
+ row_key: rowKey,
+ priority,
+ updated_by: user.user.id,
+ updated_at: new Date().toISOString(),
+ },
+ { onConflict: 'brand_id,row_key' },
);
+ if (error) throw new Error(error.message);
+}
- return { pages, answers, tracking, opportunities, drafts };
+/**
+ * Hide a Plan row until someone shows it again (admins and managers). An
+ * opportunity's row dismisses the opportunity too, so the Opportunities page
+ * agrees, and remembers the status it had for showing it again.
+ */
+export async function hidePlanRow(brandId: string, rowKey: string): Promise<void> {
+ if (!markInput.safeParse({ brandId, rowKey }).success) throw new Error('invalid');
+ const opportunityId = checkedOpportunityId(rowKey);
+ const supabase = await createClient();
+ const { data: user } = await supabase.auth.getUser();
+ if (!user.user) throw new Error('not_found');
+ let restoreStatus: string | null = null;
+ if (opportunityId) {
+ const { data, error } = await supabase
+ .from('content_opportunities')
+ .select('status')
+ .eq('id', opportunityId)
+ .eq('brand_id', brandId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!data) throw new Error('not_found');
+ restoreStatus = OPEN_OPPORTUNITY_STATUSES.includes(data.status) ? data.status : 'new';
+ }
+ // The mark first: one that isn't the member's to write stops here.
+ const { error } = await supabase.from('content_plan_marks').upsert(
+ {
+ brand_id: brandId,
+ row_key: rowKey,
+ hidden_at: new Date().toISOString(),
+ restore_status: restoreStatus,
+ updated_by: user.user.id,
+ updated_at: new Date().toISOString(),
+ },
+ { onConflict: 'brand_id,row_key' },
+ );
+ if (error) throw new Error(error.message);
+ if (opportunityId) await updateOpportunityStatus(opportunityId, 'dismissed');
+}
+
+/**
+ * Show a hidden Plan row again. An opportunity still dismissed gets back the
+ * status it had; one completed or reopened elsewhere since keeps its status,
+ * and only the mark goes.
+ */
+export async function showPlanRow(brandId: string, rowKey: string): Promise<void> {
+ if (!markInput.safeParse({ brandId, rowKey }).success) throw new Error('invalid');
+ const opportunityId = checkedOpportunityId(rowKey);
+ const supabase = await createClient();
+ const { data: user } = await supabase.auth.getUser();
+ if (!user.user) throw new Error('not_found');
+ const { data: mark, error: readError } = await supabase
+ .from('content_plan_marks')
+ .select('restore_status')
+ .eq('brand_id', brandId)
+ .eq('row_key', rowKey)
+ .maybeSingle();
+ if (readError) throw new Error(readError.message);
+ if (!mark) throw new Error('not_found');
+ const { data, error } = await supabase
+ .from('content_plan_marks')
+ .update({
+ hidden_at: null,
+ restore_status: null,
+ updated_by: user.user.id,
+ updated_at: new Date().toISOString(),
+ })
+ .eq('brand_id', brandId)
+ .eq('row_key', rowKey)
+ .select('row_key')
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ // No row changed: not the member's to write.
+ if (!data) throw new Error('not_found');
+ if (!opportunityId) return;
+ const { data: opportunity, error: statusError } = await supabase
+ .from('content_opportunities')
+ .select('status')
+ .eq('id', opportunityId)
+ .eq('brand_id', brandId)
+ .maybeSingle();
+ if (statusError) throw new Error(statusError.message);
+ if (opportunity?.status === 'dismissed') {
+ await updateOpportunityStatus(opportunityId, mark.restore_status ?? 'new');
+ }
}
/**
diff --git a/web/src/lib/content/plan.test.ts b/web/src/lib/content/plan.test.ts
index 875885925..bb11d15ed 100644
--- a/web/src/lib/content/plan.test.ts
+++ b/web/src/lib/content/plan.test.ts
@@ -7,6 +7,7 @@ import {
rowsFor,
type PlanAnswers,
type PlanDraft,
+ type PlanMark,
type PlanOpportunity,
type PlanPage,
} from './plan';
@@ -43,7 +44,8 @@ const plan = (
opportunities: PlanOpportunity[] = [],
drafts: PlanDraft[] = [],
answers: PlanAnswers = { cur: 100, prev: 100 },
-) => buildPlan({ pages, answers, opportunities, drafts, siteType: 'b2b' });
+ marks: PlanMark[] = [],
+) => buildPlan({ pages, answers, opportunities, drafts, marks, siteType: 'b2b' });
describe('buildPlan', () => {
it('creates a new page for an opportunity, named by its brief, with its evidence', () => {
@@ -72,7 +74,7 @@ describe('buildPlan', () => {
draft: null,
}),
]);
- expect(counts).toEqual({ create: 1, optimize: 0, protect: 0 });
+ expect(counts).toEqual({ create: 1, optimize: 0, protect: 0, priority: 0 });
});
it('optimizes a page losing citations, by how much it lost, with the platforms citing it less', () => {
@@ -192,7 +194,7 @@ describe('buildPlan', () => {
page('/guides/losing', { citations: { cur: 2, prev: 8 } }),
];
const { rows, counts } = plan(pages, opportunities);
- expect(counts).toEqual({ create: 60, optimize: 1, protect: 1 });
+ expect(counts).toEqual({ create: 60, optimize: 1, protect: 1, priority: 0 });
expect(rowsFor(rows, null)).toHaveLength(MAX_ROWS);
// Below the 50 opportunities on score, and still shown on their cards.
expect(rowsFor(rows, 'protect').map((r) => r.title)).toEqual(['top']);
@@ -206,7 +208,7 @@ describe('buildPlan', () => {
page('/guides/espresso', { citations: { cur: 12, prev: 10 } }),
]);
expect(rows.map((r) => [r.action, r.why.kind])).toEqual([['protect', 'top']]);
- expect(counts).toEqual({ create: 0, optimize: 0, protect: 1 });
+ expect(counts).toEqual({ create: 0, optimize: 0, protect: 1, priority: 0 });
});
it('finds the draft being written for an opportunity or a page', () => {
@@ -218,6 +220,8 @@ describe('buildPlan', () => {
method: 'create',
opportunityId: 'o1',
sourceUrl: null,
+ actionId: null,
+ assignee: null,
},
{
id: 'd2',
@@ -226,6 +230,8 @@ describe('buildPlan', () => {
method: 'optimize',
opportunityId: null,
sourceUrl: 'https://acme.example/features/forecasting/',
+ actionId: 'a1',
+ assignee: { id: 'u2', name: 'Ada Lovelace' },
},
];
const { rows } = plan(
@@ -235,5 +241,41 @@ describe('buildPlan', () => {
);
// The opportunity (70) ranks over the page losing ground (1 of 9: 66).
expect(rows.map((r) => r.draft?.id)).toEqual(['d1', 'd2']);
+ expect(rows[1].draft?.assignee).toEqual({ id: 'u2', name: 'Ada Lovelace' });
+ });
+
+ it('puts the rows marked as a priority first, and counts them', () => {
+ const marks: PlanMark[] = [{ rowKey: 'page:acme.example/top', priority: true, hidden: false }];
+ const { rows, counts } = plan(
+ [page('/top', { citations: { cur: 30, prev: 30 } })],
+ [opportunity('o1', { score: 90 })],
+ [],
+ undefined,
+ marks,
+ );
+ // The protected page (50) outranks the opportunity (90) once it is a priority.
+ expect(rows.map((r) => [r.title, r.priority])).toEqual([
+ ['top', true],
+ ['Opportunity o1', false],
+ ]);
+ expect(counts.priority).toBe(1);
+ expect(rowsFor(rows, 'priority').map((r) => r.title)).toEqual(['top']);
+ });
+
+ it('takes hidden rows off the list and its counts, to show again', () => {
+ const marks: PlanMark[] = [
+ { rowKey: 'opportunity:o1', priority: true, hidden: true },
+ { rowKey: 'page:acme.example/losing', priority: false, hidden: true },
+ ];
+ const { rows, hidden, counts } = plan(
+ [page('/losing', { citations: { cur: 2, prev: 8 } })],
+ [opportunity('o1'), opportunity('o2')],
+ [],
+ undefined,
+ marks,
+ );
+ expect(rows.map((r) => r.key)).toEqual(['opportunity:o2']);
+ expect(hidden.map((r) => r.key)).toEqual(['opportunity:o1', 'page:acme.example/losing']);
+ expect(counts).toEqual({ create: 1, optimize: 0, protect: 0, priority: 0 });
});
});
diff --git a/web/src/lib/content/plan.ts b/web/src/lib/content/plan.ts
index b4f9749a6..a898231cd 100644
--- a/web/src/lib/content/plan.ts
+++ b/web/src/lib/content/plan.ts
@@ -20,8 +20,8 @@ export const PLAN_PERIODS = [7, 30, 90] as const;
export type PlanPeriod = (typeof PLAN_PERIODS)[number];
export type PlanAction = 'create' | 'optimize' | 'protect';
-/** The cards over the list, each a filter by its action. */
-export const PLAN_CARDS = ['create', 'optimize', 'protect'] as const;
+/** The cards over the list, each a filter: by its action, or the rows marked as a priority. */
+export const PLAN_CARDS = ['create', 'optimize', 'protect', 'priority'] as const;
export type PlanCard = (typeof PLAN_CARDS)[number];
/** The brand's tracked answers in each period: what makes their citations comparable. */
@@ -74,6 +74,16 @@ export interface PlanDraft {
method: DraftMethod;
opportunityId: string | null;
sourceUrl: string | null;
+ /** The Action Center task it was sent as (Start's Team), and who it is assigned to. */
+ actionId: string | null;
+ assignee: { id: string; name: string } | null;
+}
+
+/** An admin's or manager's mark on a row (content_plan_marks, 00229), by the row's key. */
+export interface PlanMark {
+ rowKey: string;
+ priority: boolean;
+ hidden: boolean;
}
/** Why a row is on the list, and where the signal comes from. */
@@ -95,6 +105,8 @@ export interface PlanRow {
score: number;
opportunityId: string | null;
draft: PlanDraft | null;
+ /** Marked as a priority: at the top of the list, tagged. */
+ priority: boolean;
}
/**
@@ -130,21 +142,24 @@ const PROTECT_DECISIONS = new Set(['defend']);
/**
* Every row, ranked, and what each card counts: the list shows the first
* MAX_ROWS of a card's rows (rowsFor), so a card never counts rows it can't
- * show.
+ * show. Rows marked as a priority come first; hidden rows leave the list
+ * and its counts for `hidden`, to be shown again.
*/
export function buildPlan({
pages,
answers,
opportunities,
drafts,
+ marks = [],
siteType,
}: {
pages: PlanPage[];
answers: PlanAnswers;
opportunities: PlanOpportunity[];
drafts: PlanDraft[];
+ marks?: PlanMark[];
siteType: SiteType;
-}): { rows: PlanRow[]; counts: Record<PlanCard, number> } {
+}): { rows: PlanRow[]; hidden: PlanRow[]; counts: Record<PlanCard, number> } {
const byPage = new Map<string, PlanPage>();
for (const page of pages) {
const key = pageKey(page.page);
@@ -192,6 +207,7 @@ export function buildPlan({
: Math.round(o.score),
opportunityId: o.id,
draft: draftFor(o.id, create ? null : o.targetPage),
+ priority: false,
});
if (key && !create) pagesTaken.add(key);
}
@@ -206,6 +222,7 @@ export function buildPlan({
pageType: typeOf(title, page.page),
opportunityId: null,
draft: draftFor(null, page.page),
+ priority: false,
};
const drop = dropOf(page, answers);
if (drop) {
@@ -231,21 +248,33 @@ export function buildPlan({
protect.sort((a, b) => b.score - a.score || a.title.localeCompare(b.title));
rows.push(...protect.slice(0, MAX_PROTECT));
- rows.sort((a, b) => b.score - a.score || a.title.localeCompare(b.title));
+ const markOf = new Map(marks.map((m) => [m.rowKey, m]));
+ const hidden: PlanRow[] = [];
+ const listed: PlanRow[] = [];
+ for (const row of rows) {
+ const mark = markOf.get(row.key);
+ if (mark?.hidden) hidden.push(row);
+ else listed.push({ ...row, priority: Boolean(mark?.priority) });
+ }
+ const ranked = (a: PlanRow, b: PlanRow) => b.score - a.score || a.title.localeCompare(b.title);
+ listed.sort((a, b) => Number(b.priority) - Number(a.priority) || ranked(a, b));
+ hidden.sort(ranked);
return {
- rows,
+ rows: listed,
+ hidden,
counts: {
- create: rows.filter((r) => r.action === 'create').length,
- optimize: rows.filter((r) => r.action === 'optimize').length,
- protect: rows.filter((r) => r.action === 'protect').length,
+ create: listed.filter((r) => r.action === 'create').length,
+ optimize: listed.filter((r) => r.action === 'optimize').length,
+ protect: listed.filter((r) => r.action === 'protect').length,
+ priority: listed.filter((r) => r.priority).length,
},
};
}
/**
- * The rows a card shows, the first MAX_ROWS: its action's; all without a
- * card. A page type (the mix's filter) narrows them before the cut, so its
- * rows are never cut off by others.
+ * The rows a card shows, the first MAX_ROWS: its action's, or the
+ * priorities; all without a card. A page type (the mix's filter) narrows
+ * them before the cut, so its rows are never cut off by others.
*/
export function rowsFor(
rows: PlanRow[],
@@ -253,7 +282,11 @@ export function rowsFor(
pageType: PageType | null = null,
): PlanRow[] {
return rows
- .filter((r) => (!card || r.action === card) && (!pageType || r.pageType === pageType))
+ .filter(
+ (r) =>
+ (!card || (card === 'priority' ? r.priority : r.action === card)) &&
+ (!pageType || r.pageType === pageType),
+ )
.slice(0, MAX_ROWS);
}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index bb3838327..c9952e6c6 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -825,6 +825,36 @@ export type Database = {
},
]
}
+ content_plan_marks: {
+ Row: {
+ brand_id: string
+ hidden_at: string | null
+ priority: boolean
+ restore_status: string | null
+ row_key: string
+ updated_at: string
+ updated_by: string | null
+ }
+ Insert: {
+ brand_id: string
+ hidden_at?: string | null
+ priority?: boolean
+ restore_status?: string | null
+ row_key: string
+ updated_at?: string
+ updated_by?: string | null
+ }
+ Update: {
+ brand_id?: string
+ hidden_at?: string | null
+ priority?: boolean
+ restore_status?: string | null
+ row_key?: string
+ updated_at?: string
+ updated_by?: string | null
+ }
+ Relationships: []
+ }
content_rule_sets: {
Row: {
organization_id: string