Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(shopping): send a product or a category to the Action Center with the work that gets it on the AI shelf (Product Visibility, part 7) (#1642)
Cihan21fcdebd3a05
diff --git a/server/src/lib/action-center/from-products.js b/server/src/lib/action-center/from-products.jsnew file mode 100644index 000000000..78495b552--- /dev/null+++ b/server/src/lib/action-center/from-products.js@@ -0,0 +1,225 @@+/**+ * Actions from Product Visibility (ECOM-013): a product, or a category of+ * the brand's catalog, sent to the Action Center with the work that gets it+ * on the AI shelf. The person picks the work types, each for themselves+ * ("Me") or the agent ("Agent"):+ *+ * - optimize_page: rewrite its page for what AI asked for (optimize_content);+ * - create_content: a comparison, a buying guide or descriptions+ * (create_content_brief, then create_content_draft);+ * - get_listed: the review sites and "best X" lists AI quotes+ * (prepare_outreach, then execute_outreach, which a person sends);+ * - technical: GTIN, feed fields and structured data (fix_structured_data,+ * which a person does).+ *+ * The action is measured afterwards on the shopping questions sent with it+ * and the product's page (basket-metrics.js). One stays open per product or+ * category: sending it again returns it. Work none of whose tasks can be+ * planned for the brand opens nothing (422): an action without tasks.+ */++import supabaseAdmin from '../../config/supabase.js';+import { priorityOnCreate } from './priority-data.js';+import { resolveBrandSources } from './sources.js';+import { planTasks } from './tasks/plan.js';+import { getTask } from './tasks/registry.js';++export const PRODUCT_ACTION_KIND = 'shopping_product';+export const CATEGORY_ACTION_KIND = 'shopping_category';+export const PRODUCT_WORK_TYPES = ['optimize_page', 'create_content', 'get_listed', 'technical'];++/** The library tasks each work type plans, in order. */+const WORK_TASKS = {+ optimize_page: ['optimize_content'],+ create_content: ['create_content_brief', 'create_content_draft'],+ get_listed: ['prepare_outreach', 'execute_outreach'],+ technical: ['fix_structured_data'],+};++const ACTIVE = ['new', 'in_progress', 'on_hold'];+const KPI_KEYS = ['ai_visibility', 'mentions'];+/** Questions an action lists by id; it's measured on them. */+export const MAX_PROMPTS = 50;++function httpError(message, status) {+ const err = new Error(message);+ err.status = status;+ return err;+}++/** One open action per product or category. */+export function productActionDedupKey(target) {+ return `${target.type === 'category' ? CATEGORY_ACTION_KIND : PRODUCT_ACTION_KIND}:${target.id}`;+}++/**+ * A task's mode for who does it: the agent where the task can be an agent's,+ * else a person; "Me" is always a person.+ */+export function modeFor(taskKey, who) {+ const mode = getTask(taskKey)?.mode ?? 'human';+ if (who !== 'agent') return 'human';+ return mode === 'human' ? 'human' : 'agent';+}++/**+ * The action's tasks: each picked work type's, in its order, the person's+ * line on it ("Rewrite the page for women's fit and weight") as the task's+ * why, and the product's page where it's done on the page.+ */+export function productTasks(work, { sources, payload }) {+ const keys = work.flatMap((item) => WORK_TASKS[item.type] ?? []);+ const plan = planTasks(+ { id: PRODUCT_ACTION_KIND, tasks: keys.map((id) => ({ id })) },+ { sources, payload },+ );+ return plan.map((item) => {+ const from = work.find((w) => WORK_TASKS[w.type]?.includes(item.taskKey));+ return {+ ...item,+ mode: modeFor(item.taskKey, from?.who),+ details: {+ ...(item.details ?? {}),+ ...(from?.why ? { why: from.why } : {}),+ workType: from?.type ?? null,+ },+ };+ });+}++/**+ * Creates the action, or returns the open one for the same product or+ * category.+ *+ * @param {string} brandId - checked against the caller's org by the route+ * @param {{+ * target: { type: 'product'|'category', id: string },+ * work: { type: string, who: 'me'|'agent', why?: string }[],+ * promptIds: string[],+ * userId: string,+ * }} opts+ * @returns {Promise<{ actionId: string, actionNo: number, created: boolean }>}+ * @throws a 404 for a product or category not the brand's, a 422 for work+ * with no task to plan+ */+export async function sendProductActions(brandId, { target, work, promptIds, userId }) {+ const isCategory = target.type === 'category';+ const { data: subject, error: subjectErr } = isCategory+ ? await supabaseAdmin+ .from('catalog_categories')+ .select('id, name')+ .eq('id', target.id)+ .eq('brand_id', brandId)+ .maybeSingle()+ : await supabaseAdmin+ .from('catalog_products')+ .select('id, title, url')+ .eq('id', target.id)+ .eq('brand_id', brandId)+ .is('removed_at', null)+ .maybeSingle();+ if (subjectErr) throw new Error(subjectErr.message);+ if (!subject) throw httpError(isCategory ? 'Category not found' : 'Product not found', 404);++ const kind = isCategory ? CATEGORY_ACTION_KIND : PRODUCT_ACTION_KIND;+ const dedupKey = productActionDedupKey(target);+ const openAction = async () => {+ const { data } = await supabaseAdmin+ .from('actions')+ .select('id, action_no')+ .eq('brand_id', brandId)+ .eq('dedup_key', dedupKey)+ .in('status', ACTIVE)+ .maybeSingle();+ return data;+ };+ const open = await openAction();+ if (open) return { actionId: open.id, actionNo: Number(open.action_no), created: false };++ // Only the brand's own questions are kept.+ const ids = [...new Set(promptIds)].slice(0, MAX_PROMPTS);+ const { data: prompts, error: promptsErr } = ids.length+ ? await supabaseAdmin+ .from('prompts')+ .select('id, text, prompt_sets!inner(brand_id)')+ .in('id', ids)+ .eq('prompt_sets.brand_id', brandId)+ : { data: [], error: null };+ if (promptsErr) throw new Error(promptsErr.message);++ const name = isCategory ? subject.name.split('>').at(-1).trim() : subject.title;+ const payload = {+ source: 'shopping',+ target: { type: target.type, id: subject.id, name },+ title: name,+ workTypes: [...new Set(work.map((w) => w.type))],+ // Measured on the product's page once done (basket-metrics.js).+ pages: !isCategory && subject.url ? [subject.url] : [],+ promptIds: (prompts ?? []).map((p) => p.id),+ targetEntity: 'prompts',+ targetCount: (prompts ?? []).length,+ targets: (prompts ?? []).map((p) => ({ id: p.id, label: p.text })),+ };++ // Planned before the action opens: one without a task isn't opened.+ const sources = await resolveBrandSources(brandId);+ const plan = productTasks(work, { sources, payload });+ if (!plan.length) {+ throw httpError('None of the work picked has a task to plan for this brand.', 422);+ }++ // A product gets onto the shelf (Growth); a category is won from rivals (Compete).+ const category = isCategory ? 'compete' : 'growth';+ const impact = 'medium';+ const { data: action, error } = await supabaseAdmin+ .from('actions')+ .insert({+ brand_id: brandId,+ category,+ kind,+ definition_version: 1,+ impact,+ payload,+ kpi_keys: KPI_KEYS,+ baseline: {},+ dedup_key: dedupKey,+ ...(await priorityOnCreate({ kind, category, impact, payload })),+ })+ .select('id, action_no')+ .single();+ if (error) {+ // Two sends at once: the other one opened it (the open-action dedup index, 00084).+ if (error.code === '23505') {+ const winner = await openAction();+ if (winner) {+ return { actionId: winner.id, actionNo: Number(winner.action_no), created: false };+ }+ }+ throw new Error(error.message);+ }++ const { error: tasksErr } = await supabaseAdmin.from('action_tasks').insert(+ plan.map((item) => ({+ action_id: action.id,+ position: item.position,+ task_key: item.taskKey,+ task_version: item.version,+ mode: item.mode,+ permission: item.permission,+ depends_on: item.dependsOn,+ title_params: item.titleParams,+ details: item.details,+ status: 'todo',+ })),+ );+ if (tasksErr) throw new Error(tasksErr.message);++ await supabaseAdmin.from('action_events').insert({+ action_id: action.id,+ event: 'created',+ actor_id: userId,+ data: { source: 'shopping', target: payload.target, taskCount: plan.length },+ });++ return { actionId: action.id, actionNo: Number(action.action_no), created: true };+}diff --git a/server/src/lib/action-center/from-products.test.js b/server/src/lib/action-center/from-products.test.jsnew file mode 100644index 000000000..5915ea7d7--- /dev/null+++ b/server/src/lib/action-center/from-products.test.js@@ -0,0 +1,216 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Actions from Product Visibility (ECOM-013): a product or a category sent to+ * the Action Center with the work types picked, each for a person or the+ * agent, and found again when sent twice.+ */++const BRAND = '33333333-3333-3333-3333-333333333333';+const PRODUCT = '11111111-0000-0000-0000-000000000001';+const CATEGORY = '22222222-0000-0000-0000-000000000002';++let subject;+let openRow;+let inserted;+let reads;++function table(name) {+ const state = { name, op: 'select', filters: {} };+ const result = () => {+ if (name === 'catalog_products' || name === 'catalog_categories') {+ reads.push({ table: name, filters: state.filters });+ return { data: subject, error: null };+ }+ if (name === 'actions') {+ if (state.op === 'insert') return { data: { id: 'a1', action_no: 301 }, error: null };+ return { data: openRow, error: null };+ }+ if (name === 'prompts') {+ return {+ data: (state.filters.id ?? [])+ .filter((id) => id !== 'not-ours')+ .map((id) => ({ id, text: `prompt ${id}` })),+ error: null,+ };+ }+ return { data: null, error: null };+ };+ const chain = {+ select: () => chain,+ eq: (col, val) => ((state.filters[col] = val), chain),+ is: () => chain,+ in: (col, val) => ((state.filters[col] = val), chain),+ insert: (row) => {+ state.op = 'insert';+ inserted.push({ table: name, row });+ return chain;+ },+ maybeSingle: async () => result(),+ single: async () => result(),+ then: (resolve, reject) => Promise.resolve(result()).then(resolve, reject),+ };+ return chain;+}++vi.mock('../../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));+vi.mock('./priority-data.js', () => ({ priorityOnCreate: async () => ({ priority_score: 55 }) }));+vi.mock('./sources.js', () => ({ resolveBrandSources: async () => new Set() }));+// The planner, as it is, unless a test has it plan nothing.+let planNothing = false;+vi.mock('./tasks/plan.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, planTasks: (...args) => (planNothing ? [] : actual.planTasks(...args)) };+});++const { modeFor, productActionDedupKey, productTasks, sendProductActions } =+ await import('./from-products.js');++beforeEach(() => {+ subject = {+ id: PRODUCT,+ title: 'Ridge 30L Backpack',+ url: 'https://northwind.example/products/ridge-30',+ };+ openRow = null;+ inserted = [];+ reads = [];+ planNothing = false;+});++const insertedInto = (name) => inserted.filter((i) => i.table === name).map((i) => i.row);++describe('modeFor', () => {+ it("gives the agent a task it can do, and a person every task that's theirs", () => {+ expect(modeFor('optimize_content', 'agent')).toBe('agent');+ expect(modeFor('optimize_content', 'me')).toBe('human');+ expect(modeFor('fix_structured_data', 'agent')).toBe('human');+ expect(modeFor('execute_outreach', 'agent')).toBe('human');+ expect(modeFor('create_content_brief', 'agent')).toBe('agent');+ });+});++describe('productTasks', () => {+ it("plans each work type's tasks in order, with the person's line as the why", () => {+ const plan = productTasks(+ [+ { type: 'optimize_page', who: 'agent', why: "Rewrite the page for women's fit and weight" },+ { type: 'get_listed', who: 'me' },+ { type: 'technical', who: 'agent' },+ ],+ { sources: new Set(), payload: { pages: ['https://northwind.example/products/ridge-30'] } },+ );+ expect(plan.map((t) => [t.taskKey, t.mode, t.details.workType])).toEqual([+ ['optimize_content', 'agent', 'optimize_page'],+ ['prepare_outreach', 'human', 'get_listed'],+ ['execute_outreach', 'human', 'get_listed'],+ ['fix_structured_data', 'human', 'technical'],+ ]);+ expect(plan[0].details).toMatchObject({+ why: "Rewrite the page for women's fit and weight",+ check: 'auto',+ url: 'https://northwind.example/products/ridge-30',+ });+ expect(plan[1].details.why).toBeUndefined();+ });+});++describe('sendProductActions', () => {+ it("opens a product's action with its tasks and its own questions, measured on its page", async () => {+ const result = await sendProductActions(BRAND, {+ target: { type: 'product', id: PRODUCT },+ work: [+ { type: 'optimize_page', who: 'agent', why: 'Women’s fit and weight in the title' },+ { type: 'create_content', who: 'me', why: 'Ridge 30L vs Summit Daypack 30 W' },+ ],+ promptIds: ['q1', 'q2', 'q1', 'not-ours'],+ userId: 'u1',+ });+ expect(result).toEqual({ actionId: 'a1', actionNo: 301, created: true });+ const [action] = insertedInto('actions');+ expect(action).toMatchObject({+ brand_id: BRAND,+ kind: 'shopping_product',+ category: 'growth',+ dedup_key: `shopping_product:${PRODUCT}`,+ kpi_keys: ['ai_visibility', 'mentions'],+ payload: {+ source: 'shopping',+ target: { type: 'product', id: PRODUCT, name: 'Ridge 30L Backpack' },+ title: 'Ridge 30L Backpack',+ workTypes: ['optimize_page', 'create_content'],+ pages: ['https://northwind.example/products/ridge-30'],+ promptIds: ['q1', 'q2'],+ targetCount: 2,+ },+ });+ expect(+ insertedInto('action_tasks')+ .flat()+ .map((t) => [t.task_key, t.mode]),+ ).toEqual([+ ['optimize_content', 'agent'],+ ['create_content_brief', 'human'],+ ['create_content_draft', 'human'],+ ]);+ expect(insertedInto('action_events')[0]).toMatchObject({ event: 'created', actor_id: 'u1' });+ expect(reads[0].filters).toMatchObject({ id: PRODUCT, brand_id: BRAND });+ });++ it("opens a category's as Compete, without a page, named by its last level", async () => {+ subject = { id: CATEGORY, name: 'Bags > Hiking backpacks' };+ await sendProductActions(BRAND, {+ target: { type: 'category', id: CATEGORY },+ work: [{ type: 'create_content', who: 'agent' }],+ promptIds: [],+ userId: 'u1',+ });+ expect(insertedInto('actions')[0]).toMatchObject({+ kind: 'shopping_category',+ category: 'compete',+ dedup_key: `shopping_category:${CATEGORY}`,+ payload: { title: 'Hiking backpacks', pages: [], promptIds: [] },+ });+ expect(reads[0].table).toBe('catalog_categories');+ });++ it('returns the open action for the same product, and refuses one not in the catalog', async () => {+ openRow = { id: 'a0', action_no: 299 };+ expect(+ await sendProductActions(BRAND, {+ target: { type: 'product', id: PRODUCT },+ work: [{ type: 'technical', who: 'me' }],+ promptIds: [],+ userId: 'u1',+ }),+ ).toEqual({ actionId: 'a0', actionNo: 299, created: false });+ expect(insertedInto('actions')).toEqual([]);++ subject = null;+ await expect(+ sendProductActions(BRAND, {+ target: { type: 'product', id: PRODUCT },+ work: [{ type: 'technical', who: 'me' }],+ promptIds: [],+ userId: 'u1',+ }),+ ).rejects.toMatchObject({ status: 404 });+ expect(productActionDedupKey({ type: 'category', id: 'c' })).toBe('shopping_category:c');+ });++ it('opens no action for work with no task to plan, and says so', async () => {+ planNothing = true;+ await expect(+ sendProductActions(BRAND, {+ target: { type: 'product', id: PRODUCT },+ work: [{ type: 'technical', who: 'me' }],+ promptIds: [],+ userId: 'u1',+ }),+ ).rejects.toMatchObject({+ status: 422,+ message: 'None of the work picked has a task to plan for this brand.',+ });+ expect(inserted).toEqual([]);+ });+});diff --git a/server/src/lib/action-center/priority.js b/server/src/lib/action-center/priority.jsindex 700445afb..a78adbd3e 100644--- a/server/src/lib/action-center/priority.js+++ b/server/src/lib/action-center/priority.js@@ -390,6 +390,17 @@ function sentByHand(action) {subject: { entity: p.targetEntity ?? 'prompts', count: p.targetCount ?? null },};}+ // A product or category sent from Product Visibility (ECOM-013): getting+ // onto AI shopping shelves its rivals hold.+ if (action.kind === 'shopping_product' || action.kind === 'shopping_category') {+ return {+ change: 'gap',+ severity: 0.5,+ confidence: 0.55,+ recoverability: 0.6,+ subject: { entity: p.targetEntity ?? 'prompts', count: p.targetCount ?? null },+ };+ }// A live page linking products that no longer sell (shopping path, part 7):// the catalog says so, and swapping the links is quick work.if (action.kind === 'shopping_links') {diff --git a/server/src/lib/action-center/validate.js b/server/src/lib/action-center/validate.jsindex 89fc1bd1c..ecd43505b 100644--- a/server/src/lib/action-center/validate.js+++ b/server/src/lib/action-center/validate.js@@ -572,7 +572,9 @@ async function measureReading(// gap (VIS-010) or opportunity (VIS-011) sent from Insights on the topic's// prompts, answers sent from Mentions (MS-08) on their prompts, and pages// sent from AI Traffic (AT-006) on those pages. A draft sent from the- // Content Editor (CE-015) on its prompts and its page.+ // Content Editor (CE-015) on its prompts and its page, and a product or+ // category sent from Product Visibility (ECOM-013) on its shopping+ // questions and the product's page.if (action.kind === 'content_opportunity' ||action.kind === 'content_draft' ||@@ -580,7 +582,9 @@ async function measureReading(action.kind === 'topic_competitor_gap' ||action.kind === 'topic_opportunity' ||action.kind === 'mention_review' ||- action.kind === 'traffic_pages'+ action.kind === 'traffic_pages' ||+ action.kind === 'shopping_product' ||+ action.kind === 'shopping_category') {const scope = await basketScope(action);const [before, after] = await Promise.all([diff --git a/server/src/routes/action-center-content-drafts.test.js b/server/src/routes/action-center-content-drafts.test.jsindex eb73adda1..ecd30b9b7 100644--- a/server/src/routes/action-center-content-drafts.test.js+++ b/server/src/routes/action-center-content-drafts.test.js@@ -19,7 +19,10 @@ async function startApp() {vi.doMock('../config/supabase.js', () => ({ default: {} }));vi.doMock('../lib/access.js', () => ({ assertBrandAccess }));vi.doMock('../lib/action-center/priority-data.js', () => ({ rescoreActionsForSignal: vi.fn() }));- vi.doMock('../lib/plan-guard.js', () => ({ PlanLimitError: class extends Error {} }));+ vi.doMock('../lib/plan-guard.js', () => ({+ PlanLimitError: class extends Error {},+ requireFeature: () => (_req, _res, next) => next(),+ }));vi.doMock('../lib/action-center/task-writer/index.js', () => ({TaskWriterError: class extends Error {},isTaskWriterEnabled: () => false,diff --git a/server/src/routes/action-center-delete.test.js b/server/src/routes/action-center-delete.test.jsindex 745b9bbad..7e7d23d09 100644--- a/server/src/routes/action-center-delete.test.js+++ b/server/src/routes/action-center-delete.test.js@@ -49,7 +49,10 @@ vi.mock('../config/supabase.js', () => ({const assertBrandAccess = vi.fn();vi.mock('../lib/access.js', () => ({ assertBrandAccess: (...args) => assertBrandAccess(...args) }));vi.mock('../lib/action-center/priority-data.js', () => ({ rescoreActionsForSignal: vi.fn() }));-vi.mock('../lib/plan-guard.js', () => ({ PlanLimitError: class extends Error {} }));+vi.mock('../lib/plan-guard.js', () => ({+ PlanLimitError: class extends Error {},+ requireFeature: () => (_req, _res, next) => next(),+}));vi.mock('../lib/action-center/task-writer/index.js', () => ({TaskWriterError: class extends Error {},isTaskWriterEnabled: () => false,diff --git a/server/src/routes/action-center-pages.test.js b/server/src/routes/action-center-pages.test.jsindex 18a2efbdc..272ae7119 100644--- a/server/src/routes/action-center-pages.test.js+++ b/server/src/routes/action-center-pages.test.js@@ -20,7 +20,10 @@ async function startApp() {vi.doMock('../config/supabase.js', () => ({ default: {} }));vi.doMock('../lib/access.js', () => ({ assertBrandAccess }));vi.doMock('../lib/action-center/priority-data.js', () => ({ rescoreActionsForSignal: vi.fn() }));- vi.doMock('../lib/plan-guard.js', () => ({ PlanLimitError: class extends Error {} }));+ vi.doMock('../lib/plan-guard.js', () => ({+ PlanLimitError: class extends Error {},+ requireFeature: () => (_req, _res, next) => next(),+ }));vi.doMock('../lib/action-center/task-writer/index.js', () => ({TaskWriterError: class extends Error {},isTaskWriterEnabled: () => false,diff --git a/server/src/routes/action-center-products.test.js b/server/src/routes/action-center-products.test.jsnew file mode 100644index 000000000..49388ceeb--- /dev/null+++ b/server/src/routes/action-center-products.test.js@@ -0,0 +1,150 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Route-level tests for "Send to Action Center" on Product Visibility+ * (ECOM-013): POST /api/action-center/products. The action itself is tested+ * in from-products.test.js; here, what the route lets through.+ */++const assertBrandAccess = vi.fn();+const sendProductActions = vi.fn();+// The features the routes ask for, and whether the caller's plan has them.+const featuresAsked = [];+let planHasFeature = true;++let server;+let baseUrl;++async function startApp() {+ vi.resetModules();+ vi.doMock('../config/supabase.js', () => ({ default: {} }));+ vi.doMock('../lib/access.js', () => ({ assertBrandAccess }));+ vi.doMock('../lib/action-center/priority-data.js', () => ({ rescoreActionsForSignal: vi.fn() }));+ vi.doMock('../lib/plan-guard.js', () => ({+ PlanLimitError: class extends Error {},+ requireFeature: (feature) => (_req, res, next) => {+ featuresAsked.push(feature);+ if (planHasFeature) return next();+ return res.status(403).json({ success: false, error: 'plan_limit' });+ },+ }));+ vi.doMock('../lib/action-center/task-writer/index.js', () => ({+ TaskWriterError: class extends Error {},+ isTaskWriterEnabled: () => false,+ writeTasksForAction: vi.fn(),+ }));+ vi.doMock('../lib/action-center/task-send.js', () => ({+ TaskSendError: class extends Error {},+ loadTask: vi.fn(),+ sendTaskToContent: vi.fn(),+ sendTaskToWebhook: vi.fn(),+ }));+ vi.doMock('../lib/action-center/from-products.js', () => ({+ MAX_PROMPTS: 50,+ PRODUCT_WORK_TYPES: ['optimize_page', 'create_content', 'get_listed', 'technical'],+ sendProductActions,+ }));++ const { default: router } = await import('./action-center.js');+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/action-center', router);++ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/action-center`;+}++// Seeded ids aren't RFC 4122 versions; the route must still take them.+const BRAND = '33333333-3333-3333-3333-333333333333';+const PRODUCT = '11111111-0000-0000-0000-000000000001';++const post = (body) =>+ fetch(`${baseUrl}/products`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++beforeEach(async () => {+ assertBrandAccess.mockReset().mockResolvedValue({});+ sendProductActions.mockReset();+ featuresAsked.length = 0;+ planHasFeature = true;+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('POST /api/action-center/products', () => {+ const body = {+ brandId: BRAND,+ target: { type: 'product', id: PRODUCT },+ work: [{ type: 'optimize_page', who: 'agent', why: 'Fit and weight in the title' }],+ promptIds: ['44444444-4444-4444-4444-444444444444'],+ };++ it('sends the product with its work for a member of the brand, 201 when it opened one', async () => {+ sendProductActions.mockResolvedValue({ actionId: 'a1', actionNo: 301, created: true });+ const res = await post(body);+ expect(res.status).toBe(201);+ expect(await res.json()).toEqual({ actionId: 'a1', actionNo: 301, created: true });+ expect(assertBrandAccess).toHaveBeenCalledWith(BRAND, 'u1');+ expect(sendProductActions).toHaveBeenCalledWith(BRAND, {+ target: body.target,+ work: body.work,+ promptIds: body.promptIds,+ userId: 'u1',+ });+ });++ it('answers 200 with the action already open', async () => {+ sendProductActions.mockResolvedValue({ actionId: 'a0', actionNo: 299, created: false });+ expect((await post(body)).status).toBe(200);+ });++ it('refuses no work, an unknown work type or target, and passes the not-found status on', async () => {+ expect((await post({ ...body, work: [] })).status).toBe(400);+ expect((await post({ ...body, work: [{ type: 'teleport', who: 'me' }] })).status).toBe(400);+ expect((await post({ ...body, target: { type: 'brand', id: PRODUCT } })).status).toBe(400);+ expect(sendProductActions).not.toHaveBeenCalled();+ sendProductActions.mockRejectedValue(+ Object.assign(new Error('Product not found'), { status: 404 }),+ );+ expect((await post(body)).status).toBe(404);+ });++ it("refuses a caller outside the brand's organization", async () => {+ assertBrandAccess.mockRejectedValue(Object.assign(new Error('Forbidden'), { status: 403 }));+ expect((await post(body)).status).toBe(403);+ expect(sendProductActions).not.toHaveBeenCalled();+ });++ it('refuses a plan without Product Visibility (shopping_analytics), and passes on a 422 for work with no task', async () => {+ planHasFeature = false;+ expect((await post(body)).status).toBe(403);+ expect(featuresAsked).toEqual(['shopping_analytics']);+ expect(sendProductActions).not.toHaveBeenCalled();++ planHasFeature = true;+ sendProductActions.mockRejectedValue(+ Object.assign(new Error('None of the work picked has a task to plan for this brand.'), {+ status: 422,+ }),+ );+ const res = await post(body);+ expect(res.status).toBe(422);+ expect((await res.json()).details).toBe(+ 'None of the work picked has a task to plan for this brand.',+ );+ });+});diff --git a/server/src/routes/action-center-tasks.test.js b/server/src/routes/action-center-tasks.test.jsindex 253bbf652..8fd04f841 100644--- a/server/src/routes/action-center-tasks.test.js+++ b/server/src/routes/action-center-tasks.test.js@@ -39,7 +39,10 @@ class PlanLimitError extends Error {this.statusCode = statusCode;}}-vi.mock('../lib/plan-guard.js', () => ({ PlanLimitError }));+vi.mock('../lib/plan-guard.js', () => ({+ PlanLimitError,+ requireFeature: () => (_req, _res, next) => next(),+}));vi.mock('../lib/action-center/task-writer/index.js', () => ({TaskWriterError,isTaskWriterEnabled: () => enabled,diff --git a/server/src/routes/action-center.js b/server/src/routes/action-center.jsindex 22ef4f3d8..7f1e201bb 100644--- a/server/src/routes/action-center.js+++ b/server/src/routes/action-center.js@@ -3,7 +3,7 @@ import { z } from 'zod';import supabaseAdmin from '../config/supabase.js';import { assertBrandAccess } from '../lib/access.js';import { rescoreActionsForSignal } from '../lib/action-center/priority-data.js';-import { PlanLimitError } from '../lib/plan-guard.js';+import { PlanLimitError, requireFeature } from '../lib/plan-guard.js';import {TaskSendError,loadTask,@@ -21,6 +21,11 @@ import {sendTrafficPagesToActionCenter,} from '../lib/action-center/from-traffic-pages.js';import { sendContentDraftToActionCenter } from '../lib/action-center/from-content-draft.js';+import {+ MAX_PROMPTS as MAX_PRODUCT_PROMPTS,+ PRODUCT_WORK_TYPES,+ sendProductActions,+} from '../lib/action-center/from-products.js';import { runTaskCheck } from '../lib/action-center/task-checks.js';import { taskCheckLimiter } from '../middleware/rate-limiter.js';@@ -347,4 +352,55 @@ router.post('/content-drafts', async (req, res) => {}});+const productActionsSchema = z.object({+ // guid, not uuid: seeded ids aren't RFC 4122 versions.+ brandId: z.guid(),+ target: z.object({ type: z.enum(['product', 'category']), id: z.guid() }),+ work: z+ .array(+ z.object({+ type: z.enum(PRODUCT_WORK_TYPES),+ who: z.enum(['me', 'agent']),+ why: z.string().trim().max(500).optional(),+ }),+ )+ .min(1)+ .max(PRODUCT_WORK_TYPES.length * 2),+ promptIds: z.array(z.guid()).max(MAX_PRODUCT_PROMPTS).default([]),+});++/**+ * POST /api/action-center/products+ * Body: { brandId, target: { type, id }, work: [{ type, who, why? }], promptIds }+ *+ * "Send to Action Center" on Product Visibility (ECOM-013): a product, or a+ * category, with the work that gets it on the AI shelf. Sending the same+ * product or category again returns the action already open. Product+ * Visibility's plans only (shopping_analytics), as its page.+ */+router.post('/products', requireFeature('shopping_analytics'), async (req, res) => {+ try {+ const parsed = productActionsSchema.safeParse(req.body ?? {});+ if (!parsed.success) {+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });+ }+ const { brandId, target, work, promptIds } = parsed.data;+ await assertBrandAccess(brandId, req.user.id);+ const result = await sendProductActions(brandId, {+ target,+ work,+ promptIds,+ userId: req.user.id,+ });+ return res.status(result.created ? 201 : 200).json(result);+ } catch (error) {+ const status = error.status || 500;+ req.log.error({ err: error }, 'product actions error');+ return res.status(status).json({+ error: 'Failed to send to the Action Center',+ details: error.message,+ });+ }+});+export default router;diff --git a/web/messages/en.json b/web/messages/en.jsonindex f5c38a93c..226e3d00b 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2483,6 +2483,20 @@"description": "Sent from the Content Editor: a draft for someone on the team to write, with its page type and the prompts it should answer.","goal": "Publish the page and get the brand into AI answers for these prompts."},+ "shopping_product": {+ "title": "Get a product on the AI shelf for {targets}",+ "titleGeneric": "Get a product on the AI shelf",+ "namedTitle": "Get {name} on the shelf",+ "description": "Sent from Product Visibility: a product of your catalog that AI leaves off the shelf, with the work to get it there.",+ "goal": "Get the product into AI shopping answers for these questions."+ },+ "shopping_category": {+ "title": "Win a category in AI answers for {targets}",+ "titleGeneric": "Win a category in AI answers",+ "namedTitle": "Win “{name}” in AI answers",+ "description": "Sent from Product Visibility: a category of your catalog where rivals hold the AI shelf, with the work to win it.",+ "goal": "Raise your share of the AI shelf for this category's questions."+ },"shopping_links": {"title": "Swap the products that no longer sell on {targets}","titleGeneric": "Swap the products that no longer sell",@@ -7986,6 +8000,48 @@"trends": "Trends","failed": "Couldn't read the shelves right now. The other tabs still work; try again in a moment."},+ "plan": {+ "types": {+ "optimize_page": "Optimize page",+ "create_content": "Create content",+ "get_listed": "Get listed",+ "technical": "Technical"+ },+ "lines": {+ "optimizeWords": "Rewrite the page for what AI asked for: {words}",+ "optimizeQuestion": "Rewrite the page to answer “{prompt}” first",+ "compare": "A comparison, {product} vs {winner}, with an FAQ",+ "guide": "A buying guide that features {product}",+ "listed": "Ask the review sites AI quotes to include {product}",+ "gtinSchema": "Add the GTIN to the feed, and Product and AggregateRating structured data",+ "schema": "Check the product's Product, Offer and AggregateRating structured data",+ "categoryPage": "Category page: an answer-first intro, filters named as attributes, an FAQ",+ "buyingGuide": "Buying guide: how to choose {category}",+ "bestLists": "Get into the “best {category}” lists AI quotes",+ "feedFields": "Fill the feed fields AI reads for the category's {count, plural, one {# product} other {# products}}"+ },+ "where": {+ "productMode": "Content Editor · the product's page",+ "categoryMode": "Content Editor · the category page",+ "newPage": "Content Editor · a new page",+ "newPost": "Content Editor · a new post",+ "outreach": "Outreach drafts · you send them",+ "feed": "Your store's feed and the page's code"+ },+ "who": "Who does it",+ "whos": {+ "me": "Me",+ "agent": "Agent"+ },+ "personOnly": "A person does this one.",+ "pick": "Send {type}",+ "send": "Send {count, plural, one {# action} other {# actions}} to Action Center",+ "sending": "Sending to Action Center…",+ "sent": "Sent to Action Center as #{number}",+ "alreadySent": "Already in Action Center as #{number}",+ "open": "Open",+ "failed": "Couldn't send to Action Center. Try again."+ },"detail": {"back": "Products","onShelves": "On {count} of {total} shelves",@@ -8027,6 +8083,10 @@"lower": "{percent}% lower","firstWords": "ChatGPT reads about 40 words"},+ "actions": {+ "title": "Actions to get on the shelf",+ "lead": "Grouped by type. Choose who does each one, then send them to Action Center."+ },"shelves": {"title": "Where it shows","question": "Shopping question",@@ -8045,8 +8105,13 @@"share": "Shelf share","onShelf": "On shelf","rival": "Top rival",- "revenue": "AI revenue"+ "revenue": "AI revenue",+ "plan": "Actions"},+ "plan": "Plan actions",+ "planFor": "Plan actions for {category}",+ "planTitle": "Category actions · {category}",+ "planLead": "Shelf share {share}% · {onShelf} of {products} products on the shelf · {prompts, plural, one {# shopping question} other {# shopping questions}}.","prompts": "{count, plural, one {# shopping question} other {# shopping questions}}","attention": "needs attention","empty": "Your catalog has no categories yet. Categories come from your feed's product type or Google product category, or your store's collections.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-plan.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-plan.test.tsxnew file mode 100644index 000000000..0c3ad4574--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-plan.test.tsx@@ -0,0 +1,139 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { PlannedWork } from '@/lib/shopping/action-plan';++/** "Actions to get on the shelf" (ECOM-013). */++const sendShoppingActions = vi.hoisted(() => vi.fn());+const push = vi.hoisted(() => vi.fn());+const toast = vi.hoisted(() =>+ Object.assign(vi.fn(), {+ loading: vi.fn(() => 't1'),+ success: vi.fn(),+ info: vi.fn(),+ error: vi.fn(),+ }),+);+vi.mock('@/lib/actions/shopping', () => ({ sendShoppingActions }));+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push }) }));+vi.mock('sonner', () => ({ toast }));++const { ActionPlan } = await import('./_action-plan');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ sendShoppingActions.mockReset();+ push.mockReset();+ for (const fn of [toast.success, toast.info, toast.error]) fn.mockReset();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++const plan: PlannedWork[] = [+ {+ type: 'optimize_page',+ who: 'agent',+ where: 'productMode',+ agentCan: true,+ line: { key: 'optimizeWords', values: { words: 'women, lightweight' } },+ },+ { type: 'technical', who: 'me', where: 'feed', agentCan: false, line: { key: 'gtinSchema' } },+];++function render(onSent = vi.fn()) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <ActionPlan+ brandId="b1"+ target={{ type: 'product', id: 'p1' }}+ plan={plan}+ promptIds={['q1']}+ onSent={onSent}+ />+ </NextIntlClientProvider>,+ );+ });+ return onSent;+}++const button = (label: string) =>+ [...container.querySelectorAll('button')].find(+ (b) => b.textContent?.trim() === label,+ ) as HTMLButtonElement;++describe('ActionPlan', () => {+ it('lists each work type with its line and where it happens, the agent off for a technical fix', () => {+ render();+ expect(container.textContent).toContain(+ 'Optimize page · Rewrite the page for what AI asked for: women, lightweight',+ );+ expect(container.textContent).toContain('Content Editor · the product');+ const agents = [...container.querySelectorAll('button')].filter(+ (b) => b.textContent === 'Agent',+ );+ expect(agents.map((b) => [b.getAttribute('aria-pressed'), b.disabled])).toEqual([+ ['true', false],+ ['false', true],+ ]);+ });++ it('sends what is picked, with who does it and its line, and opens the action from the toast', async () => {+ sendShoppingActions.mockResolvedValue({ actionId: 'a1', actionNo: 301, created: true });+ const onSent = render();+ // Me for the page, then leave the technical fix out.+ act(() =>+ [...container.querySelectorAll('button')].find((b) => b.textContent === 'Me')!.click(),+ );+ act(() =>+ (container.querySelectorAll('button[role="checkbox"]')[1] as HTMLButtonElement).click(),+ );+ await act(async () => button('Send 1 action to Action Center').click());+ expect(sendShoppingActions).toHaveBeenCalledWith(+ 'b1',+ { type: 'product', id: 'p1' },+ [+ {+ type: 'optimize_page',+ who: 'me',+ why: 'Rewrite the page for what AI asked for: women, lightweight',+ },+ ],+ ['q1'],+ );+ expect(toast.success).toHaveBeenCalledWith(+ 'Sent to Action Center as #301',+ expect.objectContaining({ id: 't1' }),+ );+ toast.success.mock.calls[0][1].action.onClick();+ expect(push).toHaveBeenCalledWith('/dashboard/action-center/actions?action=a1');+ expect(onSent).toHaveBeenCalled();+ });++ it('says when it was already sent, or failed', async () => {+ sendShoppingActions.mockResolvedValueOnce({ actionId: 'a0', actionNo: 299, created: false });+ render();+ await act(async () => button('Send 2 actions to Action Center').click());+ expect(toast.info).toHaveBeenCalledWith('Already in Action Center as #299', expect.anything());+ sendShoppingActions.mockResolvedValueOnce({ error: 'Product not found' });+ await act(async () => button('Send 2 actions to Action Center').click());+ expect(toast.error).toHaveBeenCalledWith("Couldn't send to Action Center. Try again.", {+ id: 't1',+ description: 'Product not found',+ });+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-plan.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-plan.tsxnew file mode 100644index 000000000..75f0c4c83--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-plan.tsx@@ -0,0 +1,135 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Loader2, Send } from 'lucide-react';+import { useRouter } from '@/i18n/navigation';+import { Button } from '@/components/ui/button';+import { Checkbox } from '@/components/ui/checkbox';+import { sendShoppingActions } from '@/lib/actions/shopping';+import type { PlannedWork } from '@/lib/shopping/action-plan';+import { cn } from '@/lib/utils';++/**+ * "Actions to get on the shelf" (ECOM-013): the proposed work for a product+ * or a category, by type, each picked or not and set to Me or Agent, sent to+ * the Action Center as one action. The agent can't take a technical fix: a+ * person does it.+ */+export function ActionPlan({+ brandId,+ target,+ plan,+ promptIds,+ onSent,+}: {+ brandId: string;+ target: { type: 'product' | 'category'; id: string };+ plan: PlannedWork[];+ /** The shopping questions it's measured on. */+ promptIds: string[];+ onSent?: () => void;+}) {+ const t = useTranslations('shopping.plan');+ const router = useRouter();+ const [rows, setRows] = useState(() => plan.map((work) => ({ ...work, picked: true })));+ const [sending, setSending] = useState(false);+ const picked = rows.filter((row) => row.picked);++ const send = async () => {+ setSending(true);+ const toastId = toast.loading(t('sending'));+ try {+ const result = await sendShoppingActions(+ brandId,+ target,+ picked.map((row) => ({+ type: row.type,+ who: row.who,+ why: t(`lines.${row.line.key}`, row.line.values),+ })),+ promptIds,+ );+ if ('error' in result) {+ toast.error(t('failed'), { id: toastId, description: result.error });+ return;+ }+ const open = {+ label: t('open'),+ onClick: () => router.push(`/dashboard/action-center/actions?action=${result.actionId}`),+ };+ (result.created ? toast.success : toast.info)(+ result.created+ ? t('sent', { number: result.actionNo })+ : t('alreadySent', { number: result.actionNo }),+ { id: toastId, duration: 10_000, action: open },+ );+ onSent?.();+ } catch {+ toast.error(t('failed'), { id: toastId });+ } finally {+ setSending(false);+ }+ };++ return (+ <div className="space-y-3">+ <ul className="divide-y rounded-lg border">+ {rows.map((row, i) => (+ <li key={`${row.type}:${i}`} className="flex flex-wrap items-center gap-3 px-3 py-2.5">+ <Checkbox+ checked={row.picked}+ aria-label={t('pick', { type: t(`types.${row.type}`) })}+ onCheckedChange={(checked) =>+ setRows((all) =>+ all.map((r, j) => (j === i ? { ...r, picked: checked === true } : r)),+ )+ }+ />+ <div className="min-w-0 flex-1">+ <p className="text-sm">+ <span className="font-medium">{t(`types.${row.type}`)}</span>+ <span className="text-muted-foreground">+ {' '}+ · {t(`lines.${row.line.key}`, row.line.values)}+ </span>+ </p>+ <p className="text-xs text-muted-foreground">{t(`where.${row.where}`)}</p>+ </div>+ <div+ role="group"+ aria-label={t('who')}+ className="inline-flex shrink-0 rounded-full border bg-muted/40 p-0.5"+ >+ {(['me', 'agent'] as const).map((who) => (+ <button+ key={who}+ type="button"+ aria-pressed={row.who === who}+ disabled={who === 'agent' && !row.agentCan}+ title={who === 'agent' && !row.agentCan ? t('personOnly') : undefined}+ onClick={() => setRows((all) => all.map((r, j) => (j === i ? { ...r, who } : r)))}+ className={cn(+ 'rounded-full px-2.5 py-0.5 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',+ row.who === who+ ? 'bg-background text-foreground shadow-sm'+ : 'text-muted-foreground',+ )}+ >+ {t(`whos.${who}`)}+ </button>+ ))}+ </div>+ </li>+ ))}+ </ul>+ <div className="flex justify-end">+ <Button className="gap-2" disabled={!picked.length || sending} onClick={() => void send()}>+ {sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}+ {t('send', { count: picked.length })}+ </Button>+ </div>+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.test.tsxindex 4ef7b1057..91cdf896d 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.test.tsx@@ -1,10 +1,23 @@import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { NextIntlClientProvider } from 'next-intl';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../../../../messages/en.json';import type { CategoryRow } from '@/lib/shopping/categories';-import { CategoriesTable } from './_categories-table';++const sendShoppingActions = vi.hoisted(() => vi.fn());+vi.mock('@/lib/actions/shopping', () => ({ sendShoppingActions }));+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }));+vi.mock('sonner', () => ({+ toast: Object.assign(vi.fn(), {+ loading: vi.fn(),+ success: vi.fn(),+ info: vi.fn(),+ error: vi.fn(),+ }),+}));++const { CategoriesTable } = await import('./_categories-table');/** The Categories table (ECOM-008). */@@ -41,6 +54,7 @@ const row = (over: Partial<CategoryRow>): CategoryRow => ({name: 'Shoes > Trail running shoes',leaf: 'Trail running shoes',prompts: 14,+ promptIds: [],shelfShare: 0.31,productsOnShelf: 6,products: 24,@@ -81,6 +95,38 @@ describe('CategoriesTable', () => {]);});+ it("plans a category's actions in a dialog, measured on its questions", async () => {+ sendShoppingActions.mockResolvedValue({ actionId: 'a1', actionNo: 302, created: true });+ render(+ <CategoriesTable+ brandId="b1"+ categories={[+ row({ promptIds: ['q1', 'q2'], needsAttention: true, leaf: 'Hiking backpacks' }),+ ]}+ loading={false}+ failed={false}+ />,+ );+ const plan = [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'Plan actions',+ )!;+ // Named for its row's category, the visible text first.+ expect(plan.getAttribute('aria-label')).toBe('Plan actions for Hiking backpacks');+ act(() => plan.click());+ expect(document.body.textContent).toContain('Category actions · Hiking backpacks');+ expect(document.body.textContent).toContain('Buying guide: how to choose hiking backpacks');+ const send = [...document.body.querySelectorAll('button')].find(+ (b) => b.textContent?.trim() === 'Send 4 actions to Action Center',+ )!;+ await act(async () => send.click());+ expect(sendShoppingActions).toHaveBeenCalledWith(+ 'b1',+ { type: 'category', id: 'shoes' },+ expect.arrayContaining([expect.objectContaining({ type: 'create_content', who: 'agent' })]),+ ['q1', 'q2'],+ );+ });+it('says when the catalog has no categories, or they could not be read', () => {expect(render(<CategoriesTable categories={null} loading={false} failed={false} />)).toContain('Your catalog has no categories yet.',diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.tsxindex 72673ba66..cac931322 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.tsx@@ -1,6 +1,15 @@'use client';+import { useState } from 'react';import { useTranslations } from 'next-intl';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';import { Card } from '@/components/ui/card';import { Skeleton } from '@/components/ui/skeleton';import {@@ -15,25 +24,32 @@ import { getFaviconUrl } from '@/lib/favicon';import { formatNumber } from '@/lib/format';import { priceText } from '@/lib/shopping/price';import { cn } from '@/lib/utils';+import { categoryPlan } from '@/lib/shopping/action-plan';import type { CategoryRow } from '@/lib/shopping/categories';+import { ActionPlan } from './_action-plan';/*** The Categories table (ECOM-008): one row per catalog category, with its* shopping questions, the brand's share of their shelves, its products on* them, the rival with the most slots there and its products' AI revenue.- * A category the brand barely shows in is marked "needs attention".+ * A category the brand barely shows in is marked "needs attention". Its+ * Plan actions sends the category's work to the Action Center (ECOM-013).*/export function CategoriesTable({categories,loading,failed,+ brandId,}: {/** Null for a catalog without categories. */categories: CategoryRow[] | null;loading: boolean;failed: boolean;+ /** The brand, to send a category's actions with; none, no Plan actions. */+ brandId?: string;}) {const t = useTranslations('shopping.categories');+ const [planning, setPlanning] = useState<CategoryRow | null>(null);if (loading) return <Skeleton className="h-[240px] w-full" />;if (failed || !categories?.length) {return (@@ -51,7 +67,14 @@ export function CategoriesTable({<TableHead className="text-right">{t('columns.share')}</TableHead><TableHead className="text-right">{t('columns.onShelf')}</TableHead><TableHead>{t('columns.rival')}</TableHead>- <TableHead className="pr-4 text-right">{t('columns.revenue')}</TableHead>+ <TableHead className={cn('text-right', !brandId && 'pr-4')}>+ {t('columns.revenue')}+ </TableHead>+ {brandId && (+ <TableHead className="w-0 pr-4">+ <span className="sr-only">{t('columns.plan')}</span>+ </TableHead>+ )}</TableRow></TableHeader><TableBody>@@ -116,13 +139,55 @@ export function CategoriesTable({<span className="text-muted-foreground">—</span>)}</TableCell>- <TableCell className="pr-4 text-right tabular-nums">+ <TableCell className={cn('text-right tabular-nums', !brandId && 'pr-4')}>{row.revenue ? priceText(Math.round(row.revenue.value), row.revenue.currency) : '—'}</TableCell>+ {brandId && (+ <TableCell className="pr-4 text-right">+ <Button+ variant={row.needsAttention ? 'default' : 'outline'}+ size="sm"+ className="h-7 text-xs"+ aria-label={t('planFor', { category: row.leaf })}+ onClick={() => setPlanning(row)}+ >+ {t('plan')}+ </Button>+ </TableCell>+ )}</TableRow>))}</TableBody></Table>+ {brandId && (+ <Dialog open={!!planning} onOpenChange={(open) => !open && setPlanning(null)}>+ <DialogContent className="sm:max-w-2xl">+ {planning && (+ <>+ <DialogHeader>+ <DialogTitle>{t('planTitle', { category: planning.leaf })}</DialogTitle>+ <DialogDescription>+ {t('planLead', {+ share: Math.round((planning.shelfShare ?? 0) * 100),+ onShelf: planning.productsOnShelf,+ products: planning.products,+ prompts: planning.prompts,+ })}+ </DialogDescription>+ </DialogHeader>+ <ActionPlan+ key={planning.id}+ brandId={brandId}+ target={{ type: 'category', id: planning.id }}+ plan={categoryPlan(planning)}+ promptIds={planning.promptIds}+ onSent={() => setPlanning(null)}+ />+ </>+ )}+ </DialogContent>+ </Dialog>+ )}</Card>);}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsxindex fcf65554d..73c769c22 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx@@ -19,7 +19,9 @@ import { formatNumber } from '@/lib/format';import { priceText } from '@/lib/shopping/price';import { READINESS_CHECKS } from '@/lib/shopping/products';import type { ComparisonState } from '@/lib/shopping/product-detail';+import { productPlan } from '@/lib/shopping/action-plan';import { cn } from '@/lib/utils';+import { ActionPlan } from './_action-plan';const platformName = (platform: string) => PLATFORM_LABELS[platform] ?? platform;@@ -35,7 +37,14 @@ const STATE_ICON: Record<ComparisonState, React.ReactNode> = {* orders, "Why not your product?" beside the winner, where it shows, and* its readiness.*/-export function ProductDetailView({ detail }: { detail: ShoppingProductDetail }) {+export function ProductDetailView({+ detail,+ brandId,+}: {+ detail: ShoppingProductDetail;+ /** The brand, to send the actions with; none, no actions. */+ brandId?: string;+}) {const t = useTranslations('shopping.detail');const tReady = useTranslations('shopping.products.readiness');const { product, focus } = detail;@@ -164,6 +173,23 @@ export function ProductDetailView({ detail }: { detail: ShoppingProductDetail }))}</Card>+ {brandId && (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-base">{t('actions.title')}</CardTitle>+ <p className="text-sm text-muted-foreground">{t('actions.lead')}</p>+ </CardHeader>+ <CardContent>+ <ActionPlan+ brandId={brandId}+ target={{ type: 'product', id: product.id }}+ plan={productPlan(detail)}+ promptIds={[...new Set(detail.shelves.map((line) => line.promptId))]}+ />+ </CardContent>+ </Card>+ )}+{detail.shelves.length > 0 && (<Card><CardHeader className="pb-2">diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsxindex 27910345a..df66c1c01 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx@@ -504,6 +504,7 @@ export default function ShoppingPage() {<TabsContent value="categories" className="space-y-6">{hasFullAccess ? (<CategoriesTable+ brandId={activeBrandId}categories={categoriesRead === 'failed' ? null : (categoriesRead ?? null)}loading={categoriesRead === undefined}failed={categoriesRead === 'failed'}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsxindex 2693cc486..8d63c0ba5 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsx@@ -17,6 +17,15 @@ vi.mock('@/i18n/navigation', () => ({{children}</a>),+ useRouter: () => ({ push: vi.fn() }),+}));+vi.mock('sonner', () => ({+ toast: Object.assign(vi.fn(), {+ loading: vi.fn(),+ success: vi.fn(),+ info: vi.fn(),+ error: vi.fn(),+ }),}));vi.mock('@/stores/use-brand-store', () => ({useBrandStore: (select: (s: { activeBrandId: string }) => unknown) =>@@ -150,6 +159,9 @@ describe('ShoppingProductPage', () => {expect(text).toContain('Not on the shelf');expect(text).toContain('Missing: a GTIN (−20)');expect(container.querySelector('a[href="/dashboard/shopping?tab=products"]')).not.toBeNull();+ // Actions to get on the shelf, from what it misses beside the winner (ECOM-013).+ expect(text).toContain('Actions to get on the shelf');+ expect(text).toContain('Send 4 actions to Action Center');});it('says when the product is gone, or locked', async () => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsxindex 2c9d79284..bdcab0fb0 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsx@@ -82,7 +82,7 @@ export default function ShoppingProductPage() {return (<div className="space-y-6">{back}- <ProductDetailView detail={detail} />+ <ProductDetailView detail={detail} brandId={activeBrandId ?? undefined} /></div>);}diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex a0ce8c4ef..cae7f3b93 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -54,8 +54,20 @@ describe('actionTexts', () => {expect(() => actionGoal(kind, t)).not.toThrow();});- it("holds copy for all sixty-two definitions, the seven person-sent kinds and the catalog check's", () => {- expect(ACTION_KINDS).toHaveLength(70);+ it("holds copy for all sixty-two definitions, the nine person-sent kinds and the catalog check's", () => {+ expect(ACTION_KINDS).toHaveLength(72);+ });++ it('names a product or category sent from Product Visibility after it (ECOM-013)', () => {+ expect(+ actionTexts(action({ kind: 'shopping_product', payload: { title: 'Ridge 30L Backpack' } }), t)+ .title,+ ).toBe('Get Ridge 30L Backpack on the shelf');+ expect(+ actionTexts(action({ kind: 'shopping_category', payload: { title: 'Hiking backpacks' } }), t)+ .title,+ ).toBe('Win “Hiking backpacks” in AI answers');+ expect(actionContextTags(action({ kind: 'shopping_product', payload: {} }), t)).toEqual([]);});it('names pages sent from AI Traffic after their list and page, or how many (AT-006)', () => {diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex 840c01423..e8895bd8d 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -92,6 +92,17 @@ export function actionTexts(description: t('content_draft.description'),};}+ // A product or category sent from Product Visibility (ECOM-013) is named after it.+ if (+ (action.kind === 'shopping_product' || action.kind === 'shopping_category') &&+ typeof p.title === 'string' &&+ p.title+ ) {+ return {+ title: t(`${action.kind}.namedTitle`, { name: p.title }),+ description: t(`${action.kind}.description`),+ };+ }// A live page linking products that no longer sell (shopping path, part 7)// is named after the page and how many.if (action.kind === 'shopping_links' && Array.isArray(p.products) && p.products.length) {@@ -286,6 +297,8 @@ const PERSON_SENT_KINDS: string[] = ['mention_review','traffic_pages','content_draft',+ 'shopping_product',+ 'shopping_category','shopping_links',];diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.tsindex a9c0c4233..808a1dd4f 100644--- a/web/src/lib/action-center/registry.ts+++ b/web/src/lib/action-center/registry.ts@@ -117,6 +117,9 @@ export type ActionKind =| 'traffic_pages'// Sent by a person from the Content Editor's Start, as Team (CE-015).| 'content_draft'+ // Sent by a person from Product Visibility: a product, or a catalog category (ECOM-013).+ | 'shopping_product'+ | 'shopping_category'// Raised by the catalog check for a live page linking products that no// longer sell (shopping path, part 7), and closed by it once fixed.| 'shopping_links';@@ -270,6 +273,8 @@ export const ACTION_KINDS: readonly ActionKind[] = ['mention_review','traffic_pages','content_draft',+ 'shopping_product',+ 'shopping_category','shopping_links',];diff --git a/web/src/lib/actions/shopping-categories.test.ts b/web/src/lib/actions/shopping-categories.test.tsindex 61d1f3a46..2d78d2f77 100644--- a/web/src/lib/actions/shopping-categories.test.ts+++ b/web/src/lib/actions/shopping-categories.test.ts@@ -96,6 +96,7 @@ describe('getShoppingCategories', () => {name: 'Hiking backpacks',leaf: 'Hiking backpacks',prompts: 1,+ promptIds: ['q1'],shelfShare: 0.5,productsOnShelf: 1,products: 1,diff --git a/web/src/lib/actions/shopping-send-actions.test.ts b/web/src/lib/actions/shopping-send-actions.test.tsnew file mode 100644index 000000000..08351a554--- /dev/null+++ b/web/src/lib/actions/shopping-send-actions.test.ts@@ -0,0 +1,89 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++/** "Send to Action Center" from Product Visibility (ECOM-013): the body the route gets. */++const BRAND = '33333333-3333-3333-3333-333333333333';+const CATEGORY = '22222222-0000-0000-0000-000000000002';++vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({+ auth: { getSession: async () => ({ data: { session: { access_token: 'token' } } }) },+ }),+}));+vi.mock('@/config/api', () => ({ API_BASE_URL: 'https://api.example' }));++const { sendShoppingActions } = await import('./shopping');++afterEach(() => {+ vi.unstubAllGlobals();+});++function sent() {+ const fetch = vi.fn(+ async () => new Response(JSON.stringify({ actionId: 'a1', actionNo: 301, created: true })),+ );+ vi.stubGlobal('fetch', fetch);+ return () => {+ const [url, init] = fetch.mock.calls[0] as unknown as [string, RequestInit];+ return { url, body: JSON.parse(String(init.body)) };+ };+}++const promptId = (i: number) => `00000000-0000-0000-0000-${String(i).padStart(12, '0')}`;++describe('sendShoppingActions', () => {+ it("sends a category's first 50 questions: the route refuses more", async () => {+ const body = sent();+ const ids = Array.from({ length: 80 }, (_, i) => promptId(i));+ expect(+ await sendShoppingActions(+ BRAND,+ { type: 'category', id: CATEGORY },+ [{ type: 'create_content', who: 'agent', why: 'Buying guide: how to choose tents' }],+ [ids[0], ...ids],+ ),+ ).toEqual({ actionId: 'a1', actionNo: 301, created: true });+ expect(body().url).toBe('https://api.example/api/action-center/products');+ expect(body().body.promptIds).toEqual(ids.slice(0, 50));+ expect(body().body.work).toEqual([+ { type: 'create_content', who: 'agent', why: 'Buying guide: how to choose tents' },+ ]);+ });++ it('cuts a work line past 500 characters at a word: the route refuses it whole', async () => {+ const body = sent();+ const title = 'Ridge 30L Ultralight Waterproof Hiking Backpack '.repeat(8).trim();+ const why = `A comparison, ${title} vs ${title}, with an FAQ`;+ expect(why.length).toBeGreaterThan(500);+ await sendShoppingActions(+ BRAND,+ { type: 'product', id: CATEGORY },+ [+ { type: 'create_content', who: 'agent', why },+ { type: 'technical', who: 'me' },+ ],+ [],+ );+ const [line, technical] = body().body.work;+ expect(line.why.length).toBeLessThanOrEqual(500);+ expect(line.why.endsWith('…')).toBe(true);+ expect(why.startsWith(line.why.slice(0, -1))).toBe(true);+ // At a word: the text before the ellipsis ends where a word of the line ends.+ expect(why[line.why.length - 1]).toBe(' ');+ expect(technical).toEqual({ type: 'technical', who: 'me' });+ });++ it('never leaves half of a character written as two', async () => {+ const body = sent();+ // No space to cut at, and an emoji across the 499th character.+ const why = `${'x'.repeat(498)}😀${'y'.repeat(20)}`;+ await sendShoppingActions(+ BRAND,+ { type: 'product', id: CATEGORY },+ [{ type: 'optimize_page', who: 'agent', why }],+ [],+ );+ const [line] = body().body.work;+ expect(line.why).toBe(`${'x'.repeat(498)}…`);+ });+});diff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.tsindex ed0dcf563..9d9705ee7 100644--- a/web/src/lib/actions/shopping.ts+++ b/web/src/lib/actions/shopping.ts@@ -1,5 +1,6 @@'use server';+import { API_BASE_URL } from '@/config/api';import { createClient } from '@/lib/supabase/server';import { readAllRpcRows } from '@/lib/supabase/rpc-pages';import { expandDateToEndOfDay } from '@/lib/dates';@@ -1766,3 +1767,67 @@ export async function getShoppingProductDetail(},};}++// ── Actions from Product Visibility (ECOM-013) ────────────────────────────────++/** A work type sent with a product or category, for a person ("me") or the agent. */+export interface ShoppingWork {+ type: 'optimize_page' | 'create_content' | 'get_listed' | 'technical';+ who: 'me' | 'agent';+ /** The line the person saw for it: the task's why. */+ why?: string;+}++/** Questions the route takes with an action at most (from-products.js MAX_PROMPTS). */+const ACTION_MAX_PROMPTS = 50;+/** A work line's length the route takes at most. */+const ACTION_WHY_MAX = 500;++/** A work line cut to what the route takes, at a word where one is near. */+function cutWhy(why: string): string {+ const text = why.trim();+ if (text.length <= ACTION_WHY_MAX) return text;+ let cut = text.slice(0, ACTION_WHY_MAX - 1);+ // Not half of a character written as two.+ if (/[\uD800-\uDBFF]$/.test(cut)) cut = cut.slice(0, -1);+ const space = cut.lastIndexOf(' ');+ return `${(space > ACTION_WHY_MAX - 100 ? cut.slice(0, space) : cut).trimEnd()}…`;+}++/**+ * Sends a product or a category to the Action Center with the work picked+ * (POST /api/action-center/products); the open one comes back when it was+ * sent before. A category's questions past ACTION_MAX_PROMPTS, and a work+ * line past ACTION_WHY_MAX, are cut here: the route refuses them whole.+ */+export async function sendShoppingActions(+ brandId: string,+ target: { type: 'product' | 'category'; id: string },+ work: ShoppingWork[],+ promptIds: string[],+): Promise<{ actionId: string; actionNo: number; created: boolean } | { error: string }> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return { error: 'Not authenticated' };+ const res = await fetch(`${API_BASE_URL}/api/action-center/products`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({+ brandId,+ target,+ work: work.map((item) => (item.why ? { ...item, why: cutWhy(item.why) } : item)),+ promptIds: [...new Set(promptIds)].slice(0, ACTION_MAX_PROMPTS),+ }),+ });+ // Returned, not thrown: a thrown error's message is masked in production.+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ return { error: body.details || body.error || `Server error: ${res.status}` };+ }+ return res.json();+}diff --git a/web/src/lib/shopping/action-plan.test.ts b/web/src/lib/shopping/action-plan.test.tsnew file mode 100644index 000000000..123f7188d--- /dev/null+++ b/web/src/lib/shopping/action-plan.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from 'vitest';+import type { ShoppingProductDetail } from '@/lib/actions/shopping';+import { categoryPlan, productPlan } from './action-plan';+import type { CategoryRow } from './categories';++/** The proposed work for a product or a category (ECOM-013). */++const detail = (over: Partial<ShoppingProductDetail> = {}): ShoppingProductDetail => ({+ product: {+ id: 'p1',+ title: 'Ridge 30L Backpack',+ url: null,+ productType: 'Backpacks',+ brand: 'Northwind',+ description: null,+ image: null,+ category: 'Hiking backpacks',+ price: 119,+ currency: 'USD',+ inStock: true,+ hasGtin: false,+ },+ readiness: { score: 48, missing: ['gtin', 'description'] },+ shelves: [],+ focus: {+ promptId: 'q1',+ promptText: 'lightweight 30L hiking backpack for women',+ platform: 'chatgpt-shopping',+ rank: null,+ winner: {+ title: 'Summit Daypack 30 W',+ price: 110,+ currency: 'USD',+ rating: 4.8,+ reviews: 2140,+ merchant: null,+ image: null,+ },+ score: 41,+ winnerScore: 88,+ missing: ['women', 'lightweight', 'litre', 'trail'],+ },+ comparison: [],+ ai: { visits: 0, orders: 0, revenue: null, currency: null },+ ...over,+});++describe('productPlan', () => {+ it('proposes the four work types from what the product misses beside the winner', () => {+ expect(productPlan(detail()).map((w) => [w.type, w.who, w.agentCan, w.line])).toEqual([+ [+ 'optimize_page',+ 'agent',+ true,+ { key: 'optimizeWords', values: { words: 'women, lightweight, litre' } },+ ],+ [+ 'create_content',+ 'agent',+ true,+ {+ key: 'compare',+ values: { product: 'Ridge 30L Backpack', winner: 'Summit Daypack 30 W' },+ },+ ],+ ['get_listed', 'me', true, { key: 'listed', values: { product: 'Ridge 30L Backpack' } }],+ ['technical', 'me', false, { key: 'gtinSchema' }],+ ]);+ });++ it('falls back to the question, a buying guide and a schema check', () => {+ const plan = productPlan(detail({ focus: null, readiness: { score: 100, missing: [] } }));+ expect(plan.map((w) => w.line.key)).toEqual(['optimizeQuestion', 'guide', 'listed', 'schema']);+ });+});++describe('categoryPlan', () => {+ it('proposes the category page, a buying guide, the best-of lists and the feed fields', () => {+ const row = { leaf: 'Hiking backpacks', products: 18 } as CategoryRow;+ expect(categoryPlan(row).map((w) => [w.type, w.line])).toEqual([+ ['optimize_page', { key: 'categoryPage' }],+ ['create_content', { key: 'buyingGuide', values: { category: 'hiking backpacks' } }],+ ['get_listed', { key: 'bestLists', values: { category: 'hiking backpacks' } }],+ ['technical', { key: 'feedFields', values: { count: 18 } }],+ ]);+ });+});diff --git a/web/src/lib/shopping/action-plan.ts b/web/src/lib/shopping/action-plan.tsnew file mode 100644index 000000000..b32190d05--- /dev/null+++ b/web/src/lib/shopping/action-plan.ts@@ -0,0 +1,99 @@+import type { ShoppingProductDetail } from '@/lib/actions/shopping';+import type { CategoryRow } from '@/lib/shopping/categories';++/**+ * The work Product Visibility proposes to get a product or a category on the+ * AI shelf (ECOM-013, spec §3.7), in its four types, each with the line the+ * person reads (en.json shopping.plan.lines, by key and values) and who does+ * it by default: the agent for the page and the content, a person for the+ * listings and the technical fixes.+ */++export type WorkType = 'optimize_page' | 'create_content' | 'get_listed' | 'technical';++export interface PlannedWork {+ type: WorkType;+ who: 'me' | 'agent';+ /** Where the work happens (en.json shopping.plan.where). */+ where: string;+ line: { key: string; values?: Record<string, string | number> };+ /** Whether the agent can take it: technical fixes and sending outreach are a person's. */+ agentCan: boolean;+}++/** The work for one product, from its page: what it misses beside the winner. */+export function productPlan(detail: ShoppingProductDetail): PlannedWork[] {+ const { product, focus, readiness } = detail;+ const words = focus?.missing.slice(0, 3).join(', ');+ const plan: PlannedWork[] = [+ {+ type: 'optimize_page',+ who: 'agent',+ where: 'productMode',+ agentCan: true,+ line: words+ ? { key: 'optimizeWords', values: { words } }+ : { key: 'optimizeQuestion', values: { prompt: focus?.promptText ?? product.title } },+ },+ {+ type: 'create_content',+ who: 'agent',+ where: 'newPage',+ agentCan: true,+ line: focus?.winner+ ? { key: 'compare', values: { product: product.title, winner: focus.winner.title } }+ : { key: 'guide', values: { product: product.title } },+ },+ {+ type: 'get_listed',+ who: 'me',+ where: 'outreach',+ agentCan: true,+ line: { key: 'listed', values: { product: product.title } },+ },+ ];+ const technical = readiness.missing.filter((check) => check === 'gtin' || check === 'image');+ plan.push({+ type: 'technical',+ who: 'me',+ where: 'feed',+ agentCan: false,+ line: technical.includes('gtin') ? { key: 'gtinSchema' } : { key: 'schema' },+ });+ return plan;+}++/** The work for one category, from its row. */+export function categoryPlan(row: CategoryRow): PlannedWork[] {+ const category = row.leaf.toLowerCase();+ return [+ {+ type: 'optimize_page',+ who: 'agent',+ where: 'categoryMode',+ agentCan: true,+ line: { key: 'categoryPage' },+ },+ {+ type: 'create_content',+ who: 'agent',+ where: 'newPost',+ agentCan: true,+ line: { key: 'buyingGuide', values: { category } },+ },+ {+ type: 'get_listed',+ who: 'me',+ where: 'outreach',+ agentCan: true,+ line: { key: 'bestLists', values: { category } },+ },+ {+ type: 'technical',+ who: 'me',+ where: 'feed',+ agentCan: false,+ line: { key: 'feedFields', values: { count: row.products } },+ },+ ];+}diff --git a/web/src/lib/shopping/categories.test.ts b/web/src/lib/shopping/categories.test.tsindex 698602002..62b0c360a 100644--- a/web/src/lib/shopping/categories.test.ts+++ b/web/src/lib/shopping/categories.test.ts@@ -101,6 +101,18 @@ describe('categoryRows', () => {expect(rows.map((row) => row.id)).toEqual(['packs', 'jackets']);});+ it("lists a category's questions in the cards' order, found by name or by products", () => {+ const [row] = categoryRows(+ [{ id: 'packs', name: 'Hiking backpacks', productIds: ['ridge'] }],+ [+ card({ promptId: 'q9', promptText: 'best daypack', role: 'own', productId: 'ridge' }),+ card({}),+ ],+ { competitors, revenueOf: new Map() },+ );+ expect(row.promptIds).toEqual(['q9', 'q1']);+ });+it('marks a category the brand barely shows in, once it has enough questions', () => {const many = categoryRows([{ id: 'packs', name: 'Hiking backpacks', productIds: ['ridge'] }],diff --git a/web/src/lib/shopping/categories.ts b/web/src/lib/shopping/categories.tsindex 5fdbdc2a9..8ce9d2573 100644--- a/web/src/lib/shopping/categories.ts+++ b/web/src/lib/shopping/categories.ts@@ -35,6 +35,8 @@ export interface CategoryRow {/** The category's last level, as the table names it. */leaf: string;prompts: number;+ /** Those questions' ids, for an action to be measured on (ECOM-013). */+ promptIds: string[];/** The brand's share of the slots on the category's shelves; null with none. */shelfShare: number | null;productsOnShelf: number;@@ -89,6 +91,8 @@ interface RivalSlots {/** A question's shelves, counted once for every category it's in. */interface PromptShelves {+ /** Its first card's place among the cards: a category lists its questions in that order. */+ at: number;words: Set<string>;/** The catalog products on its shelves. */products: Set<string>;@@ -117,6 +121,7 @@ export function categoryRows(let prompt = prompts.get(card.promptId);if (!prompt) {prompt = {+ at,words: new Set(categoryWords(card.promptText)),products: new Set(),slots: 0,@@ -201,6 +206,9 @@ export function categoryRows(name: category.name,leaf,prompts: mine.size,+ // In the cards' order, as before counting once per question: the+ // Action Center takes a category's first 50.+ promptIds: [...mine].sort((a, b) => prompts.get(a)!.at - prompts.get(b)!.at),shelfShare,productsOnShelf: shown.size,products: category.productIds.length,