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(settings): connect Google Merchant Center and pick each brand's account in Settings › Integrations (#1270 part 2) (#1583)

Cihanf27909693769
diff --git a/web/messages/en.json b/web/messages/en.json
index 96cc00403..c673be9fe 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -7353,6 +7353,7 @@
"lockedDescription": "Free and Starter plans see the shopping card rate. Growth unlocks the My Products tab, competitor breakdown, card-eligible prompts, and merchant analytics.",
"tabOverview": "Overview",
"tabMyProducts": "My Products",
+ "connectCatalog": "These are your products as AI shopping cards showed them. Connect your product catalog (Google Merchant Center or a product feed) in <link>Settings › Integrations</link>, and the Content Editor checks your product pages' price, GTIN and stock against it.",
"tabCompetitors": "Competitors",
"colProductTitle": "Product Title",
"colPlatforms": "Platforms",
@@ -7916,6 +7917,8 @@
"integrations_propertyMapping": "Property mapping",
"integrations_notMapped": "Not mapped",
"integrations_selectProperty": "Select a property",
+ "integrations_stores": "Stores and marketplaces",
+ "integrations_cms": "Content management systems",
"integrations_description": "Connect external data sources. Connections are shared with your whole organization.",
"catalog": {
"title": "Product catalog",
@@ -7933,6 +7936,8 @@
},
"products": "{count, plural, one {# product} other {# products}}",
"lastSync": "synced {when}",
+ "issues": "{count, plural, one {# with an issue} other {# with issues}}",
+ "repeated": "{count, plural, one {# listed again, kept once} other {# listed again, kept once}}",
"skipped": "{count, plural, one {# product was skipped} other {# products were skipped}}",
"syncNow": "Sync now",
"remove": "Remove",
@@ -7977,6 +7982,7 @@
"too_many": "A brand can have 10 sources at most.",
"other_account": "This sign-in is for another store. Add that store as a new source.",
"not_configured": "Store connections aren't set up on this server yet.",
+ "not_connected": "The workspace sign-in this source is read with isn't connected anymore. Connect it again above.",
"forbidden": "Only admins and managers can change the catalog.",
"not_found": "This store no longer exists.",
"invalid": "Fill in every field.",
@@ -7987,6 +7993,29 @@
}
}
},
+ "merchantCenter": {
+ "description": "Your products and the problems Merchant Center reports for them. Google AI Overviews and AI Mode show products from it.",
+ "title": "Merchant Center account for {brand}",
+ "hint": "Pick the account that sells this brand's products. They're read every day into the brand's product catalog below, with their issues.",
+ "noBrand": "Pick a brand to add its Merchant Center account.",
+ "pick": "Choose an account",
+ "add": "Add account",
+ "none": "This Google sign-in doesn't open any Merchant Center account. Ask an admin of the account to add you in Merchant Center, then try again.",
+ "retry": "Try again",
+ "alreadyAdded": "{account} · already added",
+ "advanced": "An advanced account that manages several stores holds no products itself: pick the store's own account (a sub-account).",
+ "managersOnly": "Admins and managers pick {brand}'s Merchant Center account. Once added, it's listed in Product catalog below.",
+ "connected": "{account} added to {brand}. Its products are being read now.",
+ "addFailed": "Couldn't add the account. Try again in a moment.",
+ "errors": {
+ "not_connected": "The Google sign-in no longer opens Merchant Center. Disconnect it and connect again.",
+ "connect_failed": "This Google sign-in can't open that account. Pick another one.",
+ "unreachable": "Merchant Center couldn't be reached. Try again in a moment.",
+ "duplicate": "This account is added to the brand already.",
+ "not_configured": "Merchant Center isn't set up correctly on this server, or this Google account can't open Merchant Center. Ask whoever runs your Ansvisor server, or check the account's users in Merchant Center.",
+ "failed": "Couldn't read the Merchant Center accounts."
+ }
+ },
"webflow": {
"title": "Webflow",
"description": "Send to CMS puts {brand}'s pages in a Webflow collection as draft items. You publish them in Webflow.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_catalog-note.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_catalog-note.test.tsx
new file mode 100644
index 000000000..795afaa88
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_catalog-note.test.tsx
@@ -0,0 +1,74 @@
+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';
+
+const listCatalogSources = vi.fn();
+vi.mock('@/lib/actions/catalog', () => ({
+ listCatalogSources: (...args: unknown[]) => listCatalogSources(...args),
+}));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,
+}));
+
+const { CatalogNote } = await import('./_catalog-note');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/** #1270: My Products' note, for a brand with no catalog source yet. */
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ listCatalogSources.mockReset().mockResolvedValue([]);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+async function render(brandId = 'b1') {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <CatalogNote brandId={brandId} />
+ </NextIntlClientProvider>,
+ );
+ });
+ return container.textContent ?? '';
+}
+
+describe('CatalogNote', () => {
+ it('says what the table is and what a catalog adds, with the way to Settings, when the brand has none', async () => {
+ const text = await render();
+ expect(listCatalogSources).toHaveBeenCalledWith('b1');
+ expect(text).toContain('These are your products as AI shopping cards showed them.');
+ expect(text).toContain(
+ "the Content Editor checks your product pages' price, GTIN and stock against it.",
+ );
+ const link = container.querySelector('a')!;
+ expect(link.textContent).toBe('Settings › Integrations');
+ expect(link.getAttribute('href')).toBe('/dashboard/settings/integrations');
+ });
+
+ it('says nothing once the brand has a catalog source, or when they cannot be read', async () => {
+ listCatalogSources.mockResolvedValue([{ id: 's1' }]);
+ expect(await render()).toBe('');
+
+ listCatalogSources.mockRejectedValue(new Error('read failed'));
+ expect(await render('b2')).toBe('');
+ });
+
+ it("doesn't show one brand's answer for another while it reads", async () => {
+ await render('b1');
+ expect(container.textContent).not.toBe('');
+ listCatalogSources.mockReturnValue(new Promise(() => {}));
+ expect(await render('b2')).toBe('');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_catalog-note.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_catalog-note.tsx
new file mode 100644
index 000000000..9fb83daa7
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_catalog-note.tsx
@@ -0,0 +1,51 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Link } from '@/i18n/navigation';
+import { listCatalogSources } from '@/lib/actions/catalog';
+import { CATALOG_SETTINGS_PATH } from '@/lib/content/feed-match';
+
+/**
+ * My Products' note (#1270), for a brand with no catalog source yet: the
+ * table is the products AI shopping cards showed, not the catalog, and what
+ * connecting a catalog does (the Content Editor's price, GTIN and stock
+ * check, CE-053). Shown only once the sources are read and there are none;
+ * a failed read shows nothing.
+ */
+export function CatalogNote({ brandId }: { brandId: string }) {
+ const t = useTranslations('shopping');
+ // Whether the brand has no source, as read for that brand.
+ const [read, setRead] = useState<{ brandId: string; none: boolean } | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ listCatalogSources(brandId).then(
+ (sources) => {
+ if (!cancelled) setRead({ brandId, none: sources.length === 0 });
+ },
+ () => {
+ if (!cancelled) setRead({ brandId, none: false });
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId]);
+
+ if (read?.brandId !== brandId || !read.none) return null;
+ return (
+ <p className="text-sm text-muted-foreground">
+ {t.rich('connectCatalog', {
+ link: (chunks) => (
+ <Link
+ href={CATALOG_SETTINGS_PATH}
+ className="font-medium text-foreground underline underline-offset-4"
+ >
+ {chunks}
+ </Link>
+ ),
+ })}
+ </p>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
index 241392450..04206b2f2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
@@ -94,6 +94,7 @@ import { formatRegionDisplay } from '@/lib/region';
import type { AmazonShareDropAlert } from '@/lib/shopping-amazon-share-alert';
import { formatNumber } from '@/lib/format';
import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';
+import { CatalogNote } from './_catalog-note';
import { ShoppingMarketSwitch, useShoppingMarket } from './_market-switch';
import { MerchantSplitCard } from './merchant_split_card';
import { OpenAiIndexCard } from './openai_index_card';
@@ -431,6 +432,7 @@ export default function ShoppingPage() {
{tCommon('exportCsv')}
</Button>
</div>
+ <CatalogNote brandId={activeBrandId} />
<ProductTable
t={t}
products={ownProducts}
diff --git a/web/src/components/settings/catalog-sources-card.test.tsx b/web/src/components/settings/catalog-sources-card.test.tsx
index 4b5dce7a0..f00da93fa 100644
--- a/web/src/components/settings/catalog-sources-card.test.tsx
+++ b/web/src/components/settings/catalog-sources-card.test.tsx
@@ -4,6 +4,7 @@ import { NextIntlClientProvider } from 'next-intl';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../messages/en.json';
import type { CatalogSource } from '@/lib/catalog';
+import type { CatalogSourcesRead } from './catalog-sources-card';
const listCatalogSources = vi.fn();
const addFeedSource = vi.fn();
@@ -78,6 +79,29 @@ const STORE: CatalogSource = {
lastCounts: null,
};
+/** A Google Merchant Center account (#1270), named "Acme Outdoor" in Merchant Center. */
+const GMC: CatalogSource = {
+ ...FEED,
+ id: 'gmc1',
+ kind: 'merchant_center',
+ url: 'https://merchants.google.com/mc/overview?a=123456789',
+ account: '123456789',
+ label: 'Acme Outdoor',
+ lastCounts: {
+ ...FEED.lastCounts!,
+ skipped: 0,
+ errors: [],
+ issues: { items: 3, disapproved: 1, demoted: 2, not_impacted: 0 },
+ },
+ products: 40,
+};
+const GMC_SIGN_IN = {
+ kind: 'merchant_center',
+ label: 'Google Merchant Center',
+ provider: 'google-merchant-center',
+ configured: true,
+};
+
const ACME = {
kind: 'acme_store',
label: 'Acme Store',
@@ -93,11 +117,11 @@ const ACME = {
],
};
-async function render() {
+async function render(refreshKey?: number, onSources?: (read: CatalogSourcesRead | null) => void) {
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
- <CatalogSourcesCard />
+ <CatalogSourcesCard refreshKey={refreshKey} onSources={onSources} />
</NextIntlClientProvider>,
);
});
@@ -113,6 +137,12 @@ async function type(input: HTMLInputElement, value: string) {
input.dispatchEvent(new Event('input', { bubbles: true }));
});
}
+/** The text of each source's row. */
+const rows = () => [...container.querySelectorAll('li')].map((li) => li.textContent ?? '');
+function remount() {
+ act(() => root.unmount());
+ root = createRoot(container);
+}
const storeForm = () =>
container.querySelector<HTMLFormElement>('form[aria-label="Acme Store sign-in"]');
async function fillAndSubmit(form: HTMLFormElement) {
@@ -136,7 +166,7 @@ beforeEach(() => {
counts: { items: 12 },
});
uploadCatalogFile.mockReset();
- listStoreConnectors.mockReset().mockResolvedValue({ connectors: [], ready: true });
+ listStoreConnectors.mockReset().mockResolvedValue({ connectors: [], ready: true, signIns: [] });
connectStore.mockReset().mockResolvedValue({ ok: true });
updateStoreSignIn.mockReset().mockResolvedValue({ ok: true });
removeStore.mockReset().mockResolvedValue({ ok: true });
@@ -228,7 +258,7 @@ describe('CatalogSourcesCard', () => {
});
it('connects a store with the fields its connector asks for, the secret one hidden', async () => {
- listStoreConnectors.mockResolvedValue({ connectors: [ACME], ready: true });
+ listStoreConnectors.mockResolvedValue({ connectors: [ACME], ready: true, signIns: [] });
await render();
expect(container.textContent).toContain('Connect a store');
await act(async () => button('Connect Acme Store')!.click());
@@ -249,7 +279,7 @@ describe('CatalogSourcesCard', () => {
});
it("shows the store's own words when it couldn't connect, and keeps the form", async () => {
- listStoreConnectors.mockResolvedValue({ connectors: [ACME], ready: true });
+ listStoreConnectors.mockResolvedValue({ connectors: [ACME], ready: true, signIns: [] });
connectStore.mockResolvedValue({
ok: false,
code: 'connect_failed',
@@ -263,14 +293,14 @@ describe('CatalogSourcesCard', () => {
});
it("says the server can't keep a sign-in yet, instead of offering the stores", async () => {
- listStoreConnectors.mockResolvedValue({ connectors: [ACME], ready: false });
+ listStoreConnectors.mockResolvedValue({ connectors: [ACME], ready: false, signIns: [] });
await render();
expect(container.textContent).toContain("Store connections aren't set up on this server yet.");
expect(button('Connect Acme Store')).toBeUndefined();
});
it('names a store by its platform and account, replaces its sign-in, and removes it through the API', async () => {
- listStoreConnectors.mockResolvedValue({ connectors: [ACME], ready: true });
+ listStoreConnectors.mockResolvedValue({ connectors: [ACME], ready: true, signIns: [] });
listCatalogSources.mockResolvedValue([STORE]);
await render();
const text = container.textContent ?? '';
@@ -292,4 +322,103 @@ describe('CatalogSourcesCard', () => {
expect(removeStore).toHaveBeenCalledWith('st1');
expect(removeCatalogSource).not.toHaveBeenCalled();
});
+
+ it('names a Merchant Center account by its name and id, with its items that have issues (#1270)', async () => {
+ listStoreConnectors.mockResolvedValue({ connectors: [], ready: true, signIns: [GMC_SIGN_IN] });
+ listCatalogSources.mockResolvedValue([GMC]);
+ await render();
+ const text = container.textContent ?? '';
+ expect(text).toContain('Google Merchant Center · Acme Outdoor (123456789)');
+ expect(text).toContain('40 products · 3 with issues · synced');
+ // Its sign-in is the workspace's Google one: there's none to update here.
+ expect(button('Update sign-in')).toBeUndefined();
+ expect(button('Sync now')).toBeDefined();
+ });
+
+ it("names a Merchant Center account by its platform when the API's connectors can't be read or don't list it", async () => {
+ listCatalogSources.mockResolvedValue([GMC]);
+ listStoreConnectors.mockResolvedValue(null);
+ await render();
+ expect(rows()[0]).toContain('Google Merchant Center · Acme Outdoor (123456789)');
+ expect(rows()[0]).not.toContain('Acme Outdoor · 123456789');
+
+ // An API that doesn't list its sign-in platforms (yet).
+ listStoreConnectors.mockResolvedValue({ connectors: [], ready: true, signIns: [] });
+ remount();
+ await render();
+ expect(rows()[0]).toContain('Google Merchant Center · Acme Outdoor (123456789)');
+ });
+
+ it('says one item with an issue, and nothing of issues when there are none or no counts yet', async () => {
+ listCatalogSources.mockResolvedValue([
+ {
+ ...GMC,
+ lastCounts: {
+ ...GMC.lastCounts!,
+ issues: { items: 1, disapproved: 0, demoted: 1, not_impacted: 0 },
+ },
+ },
+ {
+ ...GMC,
+ id: 'gmc2',
+ account: '222',
+ products: 12,
+ lastCounts: {
+ ...GMC.lastCounts!,
+ issues: { items: 0, disapproved: 0, demoted: 0, not_impacted: 0 },
+ },
+ },
+ { ...GMC, id: 'gmc3', account: '333', products: 5, lastCounts: null },
+ ]);
+ await render();
+ const [one, none, unread] = rows();
+ expect(one).toContain('40 products · 1 with an issue · synced');
+ expect(none).toContain('12 products · synced');
+ expect(none).not.toContain('with');
+ expect(unread).toContain('5 products · synced');
+ expect(unread).not.toContain('with');
+ });
+
+ it('says how many listings were read again and kept once, only when there are some (#1270)', async () => {
+ listCatalogSources.mockResolvedValue([
+ { ...GMC, lastCounts: { ...GMC.lastCounts!, repeated: 2 } },
+ { ...GMC, id: 'gmc2', account: '222', lastCounts: { ...GMC.lastCounts!, repeated: 1 } },
+ { ...GMC, id: 'gmc3', account: '333', lastCounts: { ...GMC.lastCounts!, repeated: 0 } },
+ // A sync from before it was counted.
+ { ...GMC, id: 'gmc4', account: '444' },
+ ]);
+ await render();
+ const [two, one, none, before] = rows();
+ expect(two).toContain('40 products · 3 with issues · 2 listed again, kept once · synced');
+ expect(one).toContain('3 with issues · 1 listed again, kept once · synced');
+ expect(none).toContain('40 products · 3 with issues · synced');
+ expect(before).toContain('40 products · 3 with issues · synced');
+ });
+
+ it("says when a source's workspace sign-in isn't connected anymore", async () => {
+ listCatalogSources.mockResolvedValue([GMC]);
+ removeStore.mockResolvedValue({ ok: false, code: 'not_connected', message: null });
+ await render();
+ vi.spyOn(window, 'confirm').mockReturnValue(true);
+ await act(async () => button('Remove')!.click());
+ expect(removeStore).toHaveBeenCalledWith('gmc1');
+ expect(toast.error).toHaveBeenCalledWith(
+ "The workspace sign-in this source is read with isn't connected anymore. Connect it again above.",
+ );
+ });
+
+ it('reads the sources again when the page asks (an account added above)', async () => {
+ await render(0);
+ expect(listCatalogSources).toHaveBeenCalledTimes(1);
+ await render(1);
+ expect(listCatalogSources).toHaveBeenCalledTimes(2);
+ });
+
+ it('tells the page what it read, for the brand', async () => {
+ const onSources = vi.fn();
+ await render(0, onSources);
+ expect(onSources).toHaveBeenLastCalledWith(
+ expect.objectContaining({ brandId: 'b1', sources: [FEED] }),
+ );
+ });
});
diff --git a/web/src/components/settings/catalog-sources-card.tsx b/web/src/components/settings/catalog-sources-card.tsx
index 4eb6a4d8a..95ab507ca 100644
--- a/web/src/components/settings/catalog-sources-card.tsx
+++ b/web/src/components/settings/catalog-sources-card.tsx
@@ -10,7 +10,7 @@ import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { useUserRole } from '@/hooks/use-user-role';
import { addFeedSource, listCatalogSources, removeCatalogSource } from '@/lib/actions/catalog';
-import { isStoreSource, type CatalogSource } from '@/lib/catalog';
+import { isStoreSource, SIGN_IN_PLATFORM_LABELS, type CatalogSource } from '@/lib/catalog';
import {
connectStore,
listStoreConnectors,
@@ -19,20 +19,39 @@ import {
updateStoreSignIn,
uploadCatalogFile,
type CatalogSyncResult,
+ type SignInConnector,
type StoreConnector,
type StoreResult,
} from '@/lib/catalog-client';
import { useBrandStore } from '@/stores/use-brand-store';
import { StoreSignInForm } from './catalog-store-form';
+/** A brand's sources as the card read them: null when they couldn't be read. */
+export interface CatalogSourcesRead {
+ brandId: string;
+ sources: CatalogSource[] | null;
+}
+
/**
* Product catalog (#1263): where the active brand's catalog comes from, a
* product feed URL read daily, a CSV / feed file uploaded, or a store
* connected with its sign-in (00282), as the API's connectors offer them.
- * Admins and managers add, sync and remove; members see the sources and how
- * they went.
+ * A Google Merchant Center account (#1270) is added above, under its
+ * Integrations card, and listed here with how many of its products
+ * Merchant Center reports issues for. Admins and managers add, sync and
+ * remove; members see the sources and how they went.
+ *
+ * `refreshKey`: changed by the page to read the sources again (an account
+ * added elsewhere). `onSources` hears each read, for the Merchant Center
+ * picker to mark the accounts the brand has already.
*/
-export function CatalogSourcesCard() {
+export function CatalogSourcesCard({
+ refreshKey = 0,
+ onSources,
+}: {
+ refreshKey?: number;
+ onSources?: (read: CatalogSourcesRead | null) => void;
+}) {
const t = useTranslations('settings.catalog');
const format = useFormatter();
const { activeBrandId, brands } = useBrandStore();
@@ -50,9 +69,11 @@ export function CatalogSourcesCard() {
const [busy, setBusy] = useState<string | null>(null);
const fileInput = useRef<HTMLInputElement>(null);
// The stores the API can connect; null until read, or when it can't be.
- const [stores, setStores] = useState<{ connectors: StoreConnector[]; ready: boolean } | null>(
- null,
- );
+ const [stores, setStores] = useState<{
+ connectors: StoreConnector[];
+ ready: boolean;
+ signIns: SignInConnector[];
+ } | null>(null);
// The store being connected (its kind), or the store whose sign-in is being replaced (its id).
const [connecting, setConnecting] = useState<string | null>(null);
const [signingIn, setSigningIn] = useState<string | null>(null);
@@ -67,6 +88,7 @@ export function CatalogSourcesCard() {
};
}, []);
const connectorOf = (kind: string) => stores?.connectors.find((c) => c.kind === kind) ?? null;
+ const signInOf = (kind: string) => stores?.signIns.find((c) => c.kind === kind) ?? null;
// Bumped to read the sources again, after a sync, an add or a removal.
const [reads, setReads] = useState(0);
@@ -87,9 +109,12 @@ export function CatalogSourcesCard() {
return () => {
cancelled = true;
};
- }, [activeBrandId, reads]);
+ }, [activeBrandId, reads, refreshKey]);
const current = loaded?.brandId === activeBrandId ? loaded : null;
+ useEffect(() => {
+ onSources?.(current);
+ }, [current, onSources]);
const sources = current?.sources ?? null;
const failed = current !== null && current.sources === null;
const now = current?.at ?? new Date();
@@ -173,6 +198,14 @@ export function CatalogSourcesCard() {
const nameOf = (source: CatalogSource) => {
if (source.kind === 'feed_url') return source.url;
if (source.kind === 'upload') return t('upload');
+ // A sign-in platform's account by its name and id ("Google Merchant Center · Acme (123)"),
+ // named by the platform even before (or without) the API's connectors.
+ const signIn = signInOf(source.kind)?.label ?? SIGN_IN_PLATFORM_LABELS[source.kind];
+ if (signIn) {
+ const account =
+ source.label && source.account ? `${source.label} (${source.account})` : source.account;
+ return account ? `${signIn} · ${account}` : signIn;
+ }
const platform = connectorOf(source.kind)?.label ?? source.label ?? source.kind;
return source.account ? `${platform} · ${source.account}` : platform;
};
@@ -265,6 +298,10 @@ export function CatalogSourcesCard() {
</div>
<p className="text-xs text-muted-foreground">
{t('products', { count: source.products })}
+ {(source.lastCounts?.issues?.items ?? 0) > 0 &&
+ ` · ${t('issues', { count: source.lastCounts!.issues!.items })}`}
+ {(source.lastCounts?.repeated ?? 0) > 0 &&
+ ` · ${t('repeated', { count: source.lastCounts!.repeated! })}`}
{source.lastSyncedAt &&
` · ${t('lastSync', { when: format.relativeTime(new Date(source.lastSyncedAt), now) })}`}
</p>
diff --git a/web/src/components/settings/integrations-section.test.tsx b/web/src/components/settings/integrations-section.test.tsx
new file mode 100644
index 000000000..e04bdb1cf
--- /dev/null
+++ b/web/src/components/settings/integrations-section.test.tsx
@@ -0,0 +1,132 @@
+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';
+
+/** Each provider's status as the API answers it: an Error is a failed read. */
+const statuses: Record<string, string | Error> = {};
+const cloud = { on: false };
+vi.mock('@/config/plans', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/config/plans')>()),
+ isCloud: () => cloud.on,
+}));
+vi.mock('@/lib/actions/integrations', () => ({
+ getIntegrationStatus: async (provider: string) => {
+ const status = statuses[provider] ?? 'not_connected';
+ if (status instanceof Error) throw status;
+ return { status };
+ },
+ disconnectIntegration: vi.fn(),
+ getGscProperties: vi.fn(),
+ getGscBrandMappings: vi.fn(),
+ setBrandGscProperty: vi.fn(),
+ getGaProperties: vi.fn(),
+ getGaBrandMappings: vi.fn(),
+ setBrandGaProperty: vi.fn(),
+}));
+vi.mock('@/hooks/use-integration-connect', () => ({
+ useIntegrationConnect: () => ({ connecting: false, connect: vi.fn() }),
+}));
+vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
+// The cards read on their own (tested beside them): here they stand by their names.
+vi.mock('./catalog-sources-card', () => ({
+ CatalogSourcesCard: () => <div data-card="catalog">Product catalog</div>,
+}));
+vi.mock('./merchant-center-accounts', () => ({ MerchantCenterAccounts: () => null }));
+vi.mock('./webflow-card', () => ({ WebflowCard: () => <div data-card="webflow">Webflow</div> }));
+
+const { IntegrationsSection } = await import('./integrations-section');
+const { toast } = await import('sonner');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/** Settings › Integrations: its cards in groups a screen reader finds by their headings. */
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ for (const key of Object.keys(statuses)) delete statuses[key];
+ cloud.on = false;
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <IntegrationsSection />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+/** The elements a screen reader lists as headings. */
+const headings = () => [
+ ...container.querySelectorAll<HTMLElement>('h1, h2, h3, h4, h5, h6, [role="heading"]'),
+];
+/** The heading that names the group an element is in. */
+function groupOf(element: Element | null) {
+ const section = element?.closest('section');
+ const id = section?.getAttribute('aria-labelledby');
+ return id ? document.getElementById(id)?.textContent : null;
+}
+const byText = (text: string) =>
+ [...container.querySelectorAll('p')].find((p) => p.textContent === text) ?? null;
+
+describe('IntegrationsSection', () => {
+ it('names its groups with headings, each group labelled by its own', async () => {
+ await render();
+ expect(headings().map((h) => [h.tagName, h.textContent])).toEqual([
+ ['H3', 'Stores and marketplaces'],
+ ['H3', 'Content management systems'],
+ ]);
+ for (const heading of headings()) {
+ expect(heading.closest('section')?.getAttribute('aria-labelledby')).toBe(heading.id);
+ }
+ });
+
+ it('puts Merchant Center and the catalog with the stores, and Webflow with the CMSs', async () => {
+ await render();
+ expect(groupOf(byText('Google Merchant Center'))).toBe('Stores and marketplaces');
+ expect(groupOf(container.querySelector('[data-card="catalog"]'))).toBe(
+ 'Stores and marketplaces',
+ );
+ expect(groupOf(container.querySelector('[data-card="webflow"]'))).toBe(
+ 'Content management systems',
+ );
+ // The Google data sources come first, in no group.
+ expect(groupOf(byText('Google Search Console'))).toBeNull();
+ expect(groupOf(byText('Google Analytics'))).toBeNull();
+ });
+
+ it("keeps Merchant Center's card hidden while its status can't be read, without a toast", async () => {
+ statuses['google-merchant-center'] = new Error('Unknown integration provider.');
+ vi.mocked(toast.error).mockClear();
+ await render();
+ expect(byText('Google Merchant Center')).toBeNull();
+ expect(toast.error).not.toHaveBeenCalled();
+ // The other cards are there.
+ expect(byText('Google Search Console')).not.toBeNull();
+ expect(container.querySelector('[data-card="catalog"]')).not.toBeNull();
+ });
+
+ it('keeps it hidden on the cloud while it is not set up there; a self-hosted server shows it', async () => {
+ statuses['google-merchant-center'] = 'not_configured';
+ cloud.on = true;
+ await render();
+ expect(byText('Google Merchant Center')).toBeNull();
+ act(() => root.unmount());
+ root = createRoot(container);
+ cloud.on = false;
+ await render();
+ expect(byText('Google Merchant Center')).not.toBeNull();
+ });
+});
diff --git a/web/src/components/settings/integrations-section.tsx b/web/src/components/settings/integrations-section.tsx
index 1508a878e..f6c425d24 100644
--- a/web/src/components/settings/integrations-section.tsx
+++ b/web/src/components/settings/integrations-section.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
+import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from 'react';
import { toast } from 'sonner';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
@@ -23,7 +23,7 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
-import { BarChart3, Loader2, Search, Unplug } from 'lucide-react';
+import { BarChart3, Loader2, Search, ShoppingBag, Unplug } from 'lucide-react';
import { useTranslations } from 'next-intl';
import {
getIntegrationStatus,
@@ -38,7 +38,10 @@ import {
type IntegrationStatus,
} from '@/lib/actions/integrations';
import { matchProperty } from '@/lib/property-match';
-import { CatalogSourcesCard } from './catalog-sources-card';
+import { MERCHANT_CENTER_LABEL } from '@/lib/catalog';
+import { isCloud } from '@/config/plans';
+import { CatalogSourcesCard, type CatalogSourcesRead } from './catalog-sources-card';
+import { MerchantCenterAccounts } from './merchant-center-accounts';
import { WebflowCard } from './webflow-card';
import { useIntegrationConnect } from '@/hooks/use-integration-connect';
@@ -49,9 +52,18 @@ import { useIntegrationConnect } from '@/hooks/use-integration-connect';
* without Composio env) → not connected → connecting (OAuth popup open,
* polling) → connected — so the card and its state live in one place and each
* provider only supplies its labels and any post-connection UI of its own.
+ *
+ * Stores and marketplaces (#1270): Google Merchant Center connects the same
+ * way, then each brand picks its account, whose products land in the
+ * product catalog card below it. Content management systems: where Send to
+ * CMS puts a brand's pages.
*/
export function IntegrationsSection() {
const t = useTranslations('settings');
+ // Bumped when a brand adds a Merchant Center account, so the catalog card lists it.
+ const [catalogReads, setCatalogReads] = useState(0);
+ // The catalog's sources as its card read them, for the picker to mark the accounts added.
+ const [catalogSources, setCatalogSources] = useState<CatalogSourcesRead | null>(null);
return (
<Card>
<CardHeader>
@@ -79,17 +91,56 @@ export function IntegrationsSection() {
<GaPropertyMapping />
</IntegrationCard>
- <CatalogSourcesCard />
-
- <WebflowCard />
+ <IntegrationGroup title={t('integrations_stores')}>
+ <IntegrationCard
+ provider="google-merchant-center"
+ label={MERCHANT_CENTER_LABEL}
+ description={t('merchantCenter.description')}
+ icon={<ShoppingBag className="h-5 w-5 text-muted-foreground" />}
+ authConfigEnv="COMPOSIO_GMC_AUTH_CONFIG_ID"
+ hideUnavailable
+ >
+ <MerchantCenterAccounts
+ sources={catalogSources}
+ onConnected={() => setCatalogReads((n) => n + 1)}
+ />
+ </IntegrationCard>
+
+ <CatalogSourcesCard refreshKey={catalogReads} onSources={setCatalogSources} />
+ </IntegrationGroup>
+
+ {/* Send to CMS destinations: a new CMS's card goes in this group. */}
+ <IntegrationGroup title={t('integrations_cms')}>
+ <WebflowCard />
+ </IntegrationGroup>
</CardContent>
</Card>
);
}
+/**
+ * A group of integration cards under its heading: a section the heading
+ * names, so a screen reader lists the heading and the group by it.
+ */
+function IntegrationGroup({ title, children }: { title: string; children: ReactNode }) {
+ const id = useId();
+ return (
+ <section aria-labelledby={id} className="space-y-4">
+ <h3 id={id} className="pt-2 text-sm font-medium text-muted-foreground">
+ {title}
+ </h3>
+ {children}
+ </section>
+ );
+}
+
/**
* One integration row: status badge, Connect / Disconnect, and whatever the
* provider wants to render once connected (`children`).
+ *
+ * `hideUnavailable`: a newer integration's card isn't shown while its status
+ * can't be read (an API older than the web), nor on the cloud while it isn't
+ * set up there; a self-hosted server keeps the set-up line.
*/
function IntegrationCard({
provider,
@@ -97,6 +148,7 @@ function IntegrationCard({
description,
icon,
authConfigEnv,
+ hideUnavailable = false,
children,
}: {
provider: IntegrationProvider;
@@ -104,10 +156,12 @@ function IntegrationCard({
description: string;
icon: ReactNode;
authConfigEnv: string;
+ hideUnavailable?: boolean;
children?: ReactNode;
}) {
const t = useTranslations('settings');
const [status, setStatus] = useState<IntegrationStatus | null>(null);
+ const [unreadable, setUnreadable] = useState(false);
const [disconnecting, setDisconnecting] = useState(false);
const { connecting, connect: handleConnect } = useIntegrationConnect(provider, {
label,
@@ -121,10 +175,14 @@ function IntegrationCard({
setStatus(result.status);
} catch (err) {
console.error(`Failed to load ${provider} status:`, err);
+ if (hideUnavailable) {
+ setUnreadable(true);
+ return;
+ }
toast.error('Failed to load integration status');
setStatus('not_connected');
}
- }, [provider]);
+ }, [provider, hideUnavailable]);
useEffect(() => {
load();
@@ -143,6 +201,8 @@ function IntegrationCard({
}
};
+ if (hideUnavailable && (unreadable || (status === 'not_configured' && isCloud()))) return null;
+
return (
<div className="space-y-4">
<div className="flex items-center justify-between gap-4 rounded-lg border p-4">
diff --git a/web/src/components/settings/merchant-center-accounts.test.tsx b/web/src/components/settings/merchant-center-accounts.test.tsx
new file mode 100644
index 000000000..6df32fabf
--- /dev/null
+++ b/web/src/components/settings/merchant-center-accounts.test.tsx
@@ -0,0 +1,339 @@
+import { act, type ReactNode } 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 { CatalogSource } from '@/lib/catalog';
+import type { StoreResult } from '@/lib/catalog-client';
+import type { CatalogSourcesRead } from './catalog-sources-card';
+
+const listSignInAccounts = vi.fn();
+const connectSignInAccount = vi.fn();
+vi.mock('@/lib/catalog-client', () => ({
+ listSignInAccounts: (...args: unknown[]) => listSignInAccounts(...args),
+ connectSignInAccount: (...args: unknown[]) => connectSignInAccount(...args),
+}));
+const role = vi.hoisted(() => ({ canManage: true }));
+vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => role }));
+// Two brands, the active one switched by the tests.
+const brandStore = vi.hoisted(() => ({
+ activeBrandId: 'b1' as string | null,
+ brands: [
+ { id: 'b1', name: 'Acme' },
+ { id: 'b2', name: 'Bolt' },
+ ],
+}));
+vi.mock('@/stores/use-brand-store', () => ({ useBrandStore: () => brandStore }));
+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+// The picker's popup isn't what's tested: a plain select stands in for it.
+vi.mock('@/components/ui/select', () => ({
+ Select: ({
+ value,
+ onValueChange,
+ children,
+ }: {
+ value: string | null;
+ onValueChange: (v: string | null) => void;
+ children: ReactNode;
+ }) => (
+ <select
+ aria-label="Choose an account"
+ value={value ?? ''}
+ onChange={(e) => onValueChange(e.target.value || null)}
+ >
+ <option value="" />
+ {children}
+ </select>
+ ),
+ SelectContent: ({ children }: { children: ReactNode }) => <>{children}</>,
+ SelectItem: ({
+ value,
+ disabled,
+ children,
+ }: {
+ value: string;
+ disabled?: boolean;
+ children: ReactNode;
+ }) => (
+ <option value={value} disabled={disabled}>
+ {children}
+ </option>
+ ),
+ SelectTrigger: () => null,
+ SelectValue: () => null,
+}));
+
+const { MerchantCenterAccounts, OWN_ERRORS, accountLabel } =
+ await import('./merchant-center-accounts');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/** Settings › Integrations › Google Merchant Center (#1270): a brand picks its account. */
+
+let container: HTMLDivElement;
+let root: Root;
+const onConnected = vi.fn();
+
+async function render(sources?: CatalogSourcesRead | null) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <MerchantCenterAccounts onConnected={onConnected} sources={sources} />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+const button = (label: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent === label);
+const select = () => container.querySelector('select')!;
+const options = () => [...container.querySelectorAll('option')];
+async function pick(value: string) {
+ await act(async () => {
+ select().value = value;
+ select().dispatchEvent(new Event('change', { bubbles: true }));
+ });
+}
+/** Switches the active brand, as the sidebar's brand switcher does. */
+async function switchTo(brandId: string) {
+ brandStore.activeBrandId = brandId;
+ await render();
+}
+/** A connect that answers when the test says. */
+function heldConnect() {
+ let answer!: (result: StoreResult) => void;
+ connectSignInAccount.mockReturnValue(new Promise<StoreResult>((r) => (answer = r)));
+ return (result: StoreResult) => act(async () => answer(result));
+}
+const source = (account: string): CatalogSource => ({
+ id: `gmc-${account}`,
+ kind: 'merchant_center',
+ format: 'auto',
+ url: null,
+ account,
+ label: null,
+ lastSyncedAt: null,
+ lastStatus: null,
+ lastError: null,
+ lastCounts: null,
+ products: 0,
+});
+
+beforeEach(() => {
+ role.canManage = true;
+ brandStore.activeBrandId = 'b1';
+ listSignInAccounts.mockReset().mockResolvedValue({
+ ok: true,
+ accounts: [
+ { id: '123', name: 'Acme Outdoor' },
+ { id: '456', name: null },
+ ],
+ });
+ connectSignInAccount.mockReset().mockResolvedValue({ ok: true });
+ onConnected.mockReset();
+ toast.error.mockReset();
+ toast.success.mockReset();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('accountLabel', () => {
+ it('names an account by its name and id, or its id', () => {
+ expect(accountLabel({ id: '123', name: 'Acme Outdoor' })).toBe('Acme Outdoor (123)');
+ expect(accountLabel({ id: '456', name: null })).toBe('456');
+ });
+});
+
+describe('MerchantCenterAccounts', () => {
+ it("lists the accounts the workspace's Google sign-in opens, and adds the picked one to the brand", async () => {
+ await render();
+ expect(listSignInAccounts).toHaveBeenCalledWith('b1', 'merchant_center');
+ const text = container.textContent ?? '';
+ expect(text).toContain('Merchant Center account for Acme');
+ expect(options().map((o) => o.textContent)).toEqual(['', 'Acme Outdoor (123)', '456']);
+ expect(button('Add account')!.disabled).toBe(true);
+
+ await pick('123');
+ await act(async () => button('Add account')!.click());
+ expect(connectSignInAccount).toHaveBeenCalledWith('b1', 'merchant_center', '123');
+ expect(toast.success).toHaveBeenCalledWith(
+ 'Acme Outdoor (123) added to Acme. Its products are being read now.',
+ );
+ expect(onConnected).toHaveBeenCalledTimes(1);
+ expect(select().value).toBe('');
+ });
+
+ it("drops the pick when the brand changes: another brand never adds the first one's account", async () => {
+ await render();
+ await pick('123');
+ expect(button('Add account')!.disabled).toBe(false);
+
+ await switchTo('b2');
+ expect(listSignInAccounts).toHaveBeenLastCalledWith('b2', 'merchant_center');
+ expect(container.textContent).toContain('Merchant Center account for Bolt');
+ expect(select().value).toBe('');
+ expect(button('Add account')!.disabled).toBe(true);
+ await act(async () => button('Add account')!.click());
+ expect(connectSignInAccount).not.toHaveBeenCalled();
+
+ // Nor does the second brand's pick carry back to the first.
+ await pick('456');
+ await switchTo('b1');
+ expect(select().value).toBe('');
+ expect(button('Add account')!.disabled).toBe(true);
+ });
+
+ it('adds the account to the brand it was picked for when the brand changes while adding', async () => {
+ const answer = heldConnect();
+ await render();
+ await pick('123');
+ await act(async () => button('Add account')!.click());
+ await switchTo('b2');
+ // One add at a time, and Bolt's picker has nothing picked.
+ expect(button('Add account')!.disabled).toBe(true);
+ expect(select().value).toBe('');
+
+ await answer({ ok: true });
+ expect(connectSignInAccount).toHaveBeenCalledTimes(1);
+ expect(connectSignInAccount).toHaveBeenCalledWith('b1', 'merchant_center', '123');
+ expect(toast.success).toHaveBeenCalledWith(
+ 'Acme Outdoor (123) added to Acme. Its products are being read now.',
+ );
+ expect(container.textContent).toContain('Merchant Center account for Bolt');
+ expect(select().value).toBe('');
+ await pick('456');
+ expect(button('Add account')!.disabled).toBe(false);
+ });
+
+ it('adds once when the button is clicked twice while adding', async () => {
+ const answer = heldConnect();
+ await render();
+ await pick('123');
+ await act(async () => {
+ button('Add account')!.click();
+ button('Add account')!.click();
+ });
+ expect(button('Add account')!.disabled).toBe(true);
+ await act(async () => button('Add account')!.click());
+ await answer({ ok: true });
+ expect(connectSignInAccount).toHaveBeenCalledTimes(1);
+ expect(onConnected).toHaveBeenCalledTimes(1);
+ });
+
+ it('marks the accounts the brand has already, and they cannot be picked', async () => {
+ await render({ brandId: 'b1', sources: [source('123')] });
+ const [, added, other] = options();
+ expect(added.textContent).toBe('Acme Outdoor (123) · already added');
+ expect(added.disabled).toBe(true);
+ expect(other.textContent).toBe('456');
+ expect(other.disabled).toBe(false);
+ await pick('123');
+ expect(button('Add account')!.disabled).toBe(true);
+
+ // Another brand's sources mark nothing here.
+ await render({ brandId: 'b2', sources: [source('123')] });
+ expect(options()[1].disabled).toBe(false);
+ });
+
+ it("says why it couldn't add the account, in plain words", async () => {
+ connectSignInAccount.mockResolvedValue({ ok: false, code: 'duplicate', message: null });
+ await render();
+ await pick('123');
+ await act(async () => button('Add account')!.click());
+ expect(toast.error).toHaveBeenCalledWith('This account is added to the brand already.');
+
+ connectSignInAccount.mockResolvedValue({ ok: false, code: 'failed', message: null });
+ await act(async () => button('Add account')!.click());
+ expect(toast.error).toHaveBeenLastCalledWith(
+ "Couldn't add the account. Try again in a moment.",
+ );
+ expect(onConnected).not.toHaveBeenCalled();
+ // The pick stays, to try again.
+ expect(select().value).toBe('123');
+ });
+
+ it("reads the accounts again with Try again when they couldn't be read", async () => {
+ listSignInAccounts.mockResolvedValue({ ok: false, code: 'failed' });
+ await render();
+ expect(container.textContent).toContain("Couldn't read the Merchant Center accounts.");
+ expect(container.querySelector('select')).toBeNull();
+
+ listSignInAccounts.mockResolvedValue({ ok: false, code: 'unreachable' });
+ await act(async () => button('Try again')!.click());
+ expect(listSignInAccounts).toHaveBeenCalledTimes(2);
+ expect(container.textContent).toContain(
+ "Merchant Center couldn't be reached. Try again in a moment.",
+ );
+
+ listSignInAccounts.mockResolvedValue({ ok: true, accounts: [{ id: '123', name: 'Acme' }] });
+ await act(async () => button('Try again')!.click());
+ expect(listSignInAccounts).toHaveBeenCalledTimes(3);
+ expect(options().map((o) => o.textContent)).toEqual(['', 'Acme (123)']);
+ expect(button('Try again')).toBeUndefined();
+ });
+
+ it('says when the sign-in no longer opens Merchant Center, or opens no account', async () => {
+ listSignInAccounts.mockResolvedValue({ ok: false, code: 'not_connected' });
+ await render();
+ expect(container.textContent).toContain(
+ 'The Google sign-in no longer opens Merchant Center. Disconnect it and connect again.',
+ );
+
+ listSignInAccounts.mockResolvedValue({ ok: true, accounts: [] });
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ expect(container.textContent).toContain(
+ "This Google sign-in doesn't open any Merchant Center account. Ask an admin of the account to add you in Merchant Center, then try again.",
+ );
+ expect(button('Try again')).toBeDefined();
+ });
+
+ it("says who can fix a Merchant Center this server can't open, and reads again once they have", async () => {
+ // The API's 503 not_configured: Composio or Google refused this server's setup (not_set_up).
+ listSignInAccounts.mockResolvedValue({ ok: false, code: 'not_configured' });
+ await render();
+ expect(container.textContent).toContain(
+ "Merchant Center isn't set up correctly on this server, or this Google account can't open Merchant Center. Ask whoever runs your Ansvisor server, or check the account's users in Merchant Center.",
+ );
+ listSignInAccounts.mockResolvedValue({ ok: true, accounts: [{ id: '123', name: 'Acme' }] });
+ await act(async () => button('Try again')!.click());
+ expect(options().map((o) => o.textContent)).toEqual(['', 'Acme (123)']);
+ });
+
+ it('says an advanced account holds no products when the sign-in opens more than one account', async () => {
+ const advanced =
+ "An advanced account that manages several stores holds no products itself: pick the store's own account (a sub-account).";
+ await render();
+ expect(container.textContent).toContain(advanced);
+
+ listSignInAccounts.mockResolvedValue({ ok: true, accounts: [{ id: '123', name: 'Acme' }] });
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ expect(container.textContent).not.toContain(advanced);
+ });
+
+ it('has words of its own for each error it names', () => {
+ for (const code of OWN_ERRORS) {
+ expect(messages.settings.merchantCenter.errors).toHaveProperty(code);
+ }
+ });
+
+ it('tells members who picks the account, in words of its own, and asks the API nothing', async () => {
+ role.canManage = false;
+ await render();
+ expect(listSignInAccounts).not.toHaveBeenCalled();
+ expect(container.textContent).toContain(
+ "Admins and managers pick Acme's Merchant Center account.",
+ );
+ // The catalog card below says this one already.
+ expect(container.textContent).not.toContain('Admins and managers can add and sync sources.');
+ });
+});
diff --git a/web/src/components/settings/merchant-center-accounts.tsx b/web/src/components/settings/merchant-center-accounts.tsx
new file mode 100644
index 000000000..2c6da91a9
--- /dev/null
+++ b/web/src/components/settings/merchant-center-accounts.tsx
@@ -0,0 +1,209 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Loader2, Plus, RefreshCw } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { Skeleton } from '@/components/ui/skeleton';
+import { useUserRole } from '@/hooks/use-user-role';
+import { MERCHANT_CENTER_KIND } from '@/lib/catalog';
+import {
+ connectSignInAccount,
+ listSignInAccounts,
+ type SignInAccount,
+ type StoreError,
+} from '@/lib/catalog-client';
+import { useBrandStore } from '@/stores/use-brand-store';
+import type { CatalogSourcesRead } from './catalog-sources-card';
+
+/**
+ * The errors Merchant Center says in its own words; the rest are the stores'.
+ * `not_configured` is also what the API answers when Composio or Google
+ * refuses this server's setup (its `not_set_up`, lib/catalog/stores.js).
+ */
+export const OWN_ERRORS: readonly StoreError[] = [
+ 'not_connected',
+ 'connect_failed',
+ 'unreachable',
+ 'duplicate',
+ 'not_configured',
+ 'failed',
+];
+
+/** An account as the picker names it: its name and id, or its id. */
+export function accountLabel(account: SignInAccount): string {
+ return account.name ? `${account.name} (${account.id})` : account.id;
+}
+
+/**
+ * Google Merchant Center, once the workspace has connected it (#1270): the
+ * active brand picks one of the accounts its Google sign-in opens, and that
+ * account's products are read into the brand's catalog every day, with the
+ * issues Merchant Center reports for them. The account then shows in
+ * Product catalog, where it is synced or removed. Admins and managers only.
+ *
+ * `sources`: the catalog's sources as its card read them; the accounts the
+ * brand has already are marked in the picker and can't be picked again.
+ */
+export function MerchantCenterAccounts({
+ onConnected,
+ sources,
+}: {
+ onConnected?: () => void;
+ sources?: CatalogSourcesRead | null;
+}) {
+ const t = useTranslations('settings.merchantCenter');
+ const tStores = useTranslations('settings.catalog.stores');
+ const { activeBrandId, brands } = useBrandStore();
+ const { canManage } = useUserRole();
+ const brand = brands.find((b) => b.id === activeBrandId) ?? null;
+
+ // The accounts as read for a brand: another brand's never show.
+ const [loaded, setLoaded] = useState<{
+ brandId: string;
+ accounts: SignInAccount[] | null;
+ error: StoreError | null;
+ } | null>(null);
+ // Bumped to read the accounts again (Try again).
+ const [reads, setReads] = useState(0);
+ // The account picked, with the brand it was picked for: another brand never adds it.
+ const [picked, setPicked] = useState<{ brandId: string; id: string } | null>(null);
+ // The brand an account is being added to. The ref holds a second click
+ // before the button shows it's busy.
+ const [adding, setAdding] = useState<string | null>(null);
+ const addingRef = useRef(false);
+
+ useEffect(() => {
+ if (!activeBrandId || !canManage) return;
+ let cancelled = false;
+ void listSignInAccounts(activeBrandId, MERCHANT_CENTER_KIND).then((result) => {
+ if (cancelled) return;
+ setLoaded(
+ result.ok
+ ? { brandId: activeBrandId, accounts: result.accounts, error: null }
+ : { brandId: activeBrandId, accounts: null, error: result.code },
+ );
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [activeBrandId, canManage, reads]);
+
+ /** A failure in Merchant Center's own words where it has them, else the stores'. */
+ const errorText = (code: StoreError) =>
+ OWN_ERRORS.includes(code) ? t(`errors.${code}`) : tStores(`errors.${code}`);
+
+ const current = loaded?.brandId === activeBrandId ? loaded : null;
+ const accounts = current?.accounts ?? null;
+ const added = new Set(
+ sources?.brandId === activeBrandId
+ ? (sources.sources ?? [])
+ .filter((source) => source.kind === MERCHANT_CENTER_KIND && source.account)
+ .map((source) => source.account!)
+ : [],
+ );
+ const pickedId = picked?.brandId === activeBrandId ? picked.id : null;
+ const chosen = accounts?.find((a) => a.id === pickedId && !added.has(a.id)) ?? null;
+
+ const retry = () => {
+ setLoaded(null);
+ setReads((n) => n + 1);
+ };
+
+ const add = async () => {
+ if (!activeBrandId || !brand || !chosen || addingRef.current) return;
+ // The brand and account as clicked: switching brands meanwhile changes neither.
+ const brandId = activeBrandId;
+ const brandName = brand.name;
+ const account = chosen;
+ addingRef.current = true;
+ setAdding(brandId);
+ const result = await connectSignInAccount(brandId, MERCHANT_CENTER_KIND, account.id);
+ addingRef.current = false;
+ setAdding(null);
+ if (!result.ok) {
+ toast.error(result.code === 'failed' ? t('addFailed') : errorText(result.code));
+ return;
+ }
+ toast.success(t('connected', { account: accountLabel(account), brand: brandName }));
+ setPicked((p) => (p?.brandId === brandId ? null : p));
+ onConnected?.();
+ };
+
+ if (!brand) return <p className="text-xs text-muted-foreground">{t('noBrand')}</p>;
+ if (!canManage)
+ return (
+ <p className="text-xs text-muted-foreground">{t('managersOnly', { brand: brand.name })}</p>
+ );
+
+ const items = (accounts ?? []).map((account) => ({
+ value: account.id,
+ label: added.has(account.id)
+ ? t('alreadyAdded', { account: accountLabel(account) })
+ : accountLabel(account),
+ disabled: added.has(account.id),
+ }));
+ // Worth reading again once someone has fixed it: the list failed, or the sign-in opens no account yet.
+ const canRetry = current !== null && (current.error !== null || items.length === 0);
+
+ return (
+ <div className="space-y-3 rounded-lg border p-4">
+ <div>
+ <p className="text-sm font-medium">{t('title', { brand: brand.name })}</p>
+ <p className="text-xs text-muted-foreground">{t('hint')}</p>
+ </div>
+ {current === null ? (
+ <Skeleton className="h-8 w-full sm:w-80" />
+ ) : current.error ? (
+ <p className="text-xs text-destructive">{errorText(current.error)}</p>
+ ) : items.length === 0 ? (
+ <p className="text-xs text-muted-foreground">{t('none')}</p>
+ ) : (
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
+ <Select
+ items={items}
+ value={chosen?.id ?? null}
+ onValueChange={(v) => setPicked(v ? { brandId: brand.id, id: v } : null)}
+ >
+ <SelectTrigger className="h-8 w-full text-xs sm:w-80" aria-label={t('pick')}>
+ <SelectValue placeholder={t('pick')} />
+ </SelectTrigger>
+ <SelectContent>
+ {items.map((item) => (
+ <SelectItem key={item.value} value={item.value} disabled={item.disabled}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Button size="sm" className="gap-2" disabled={!chosen || adding !== null} onClick={add}>
+ {adding === brand.id ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Plus className="h-3.5 w-3.5" />
+ )}
+ {t('add')}
+ </Button>
+ </div>
+ )}
+ {/* An advanced account is listed with its sub-accounts, and its products are theirs. */}
+ {!current?.error && items.length > 1 && (
+ <p className="text-xs text-muted-foreground">{t('advanced')}</p>
+ )}
+ {canRetry && (
+ <Button size="sm" variant="outline" className="gap-2" onClick={retry}>
+ <RefreshCw className="h-3.5 w-3.5" />
+ {t('retry')}
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/lib/actions/integrations.ts b/web/src/lib/actions/integrations.ts
index ae80ca408..e1657b281 100644
--- a/web/src/lib/actions/integrations.ts
+++ b/web/src/lib/actions/integrations.ts
@@ -4,7 +4,10 @@ import { createClient } from '@/lib/supabase/server';
import { API_BASE_URL } from '@/config/api';
/** Providers that expose the shared connect / status / disconnect flow. */
-export type IntegrationProvider = 'google-search-console' | 'google-analytics';
+export type IntegrationProvider =
+ | 'google-search-console'
+ | 'google-analytics'
+ | 'google-merchant-center';
export type IntegrationStatus = 'not_configured' | 'not_connected' | 'connected';
diff --git a/web/src/lib/catalog-client.test.ts b/web/src/lib/catalog-client.test.ts
index 45f50c267..eb7b9d198 100644
--- a/web/src/lib/catalog-client.test.ts
+++ b/web/src/lib/catalog-client.test.ts
@@ -1,4 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../messages/en.json';
+import type { StoreError } from './catalog-client';
/** #1263: a catalog sync from the browser, through the API's proxy. */
@@ -9,7 +11,9 @@ vi.mock('@/lib/supabase/client', () => ({
}));
const {
+ connectSignInAccount,
connectStore,
+ listSignInAccounts,
listStoreConnectors,
removeStore,
syncCatalogSource,
@@ -79,6 +83,7 @@ describe('stores (00282)', () => {
expect(await listStoreConnectors()).toEqual({
connectors: [{ kind: 'acme_store', label: 'Acme Store', fields: [] }],
ready: true,
+ signIns: [],
});
expect(fetchMock.mock.calls[0][0]).toBe('/api/aeo/api/catalog/connectors');
answer(500, {});
@@ -126,3 +131,116 @@ describe('stores (00282)', () => {
expect(await updateStoreSignIn('st1', {})).toEqual({ ok: false, code: 'busy', message: null });
});
});
+
+describe('sign-in platforms (#1270)', () => {
+ const GMC = {
+ kind: 'merchant_center',
+ label: 'Google Merchant Center',
+ provider: 'google-merchant-center',
+ configured: true,
+ };
+
+ it('lists them with the stores', async () => {
+ answer(200, { connectors: [], ready: false, signIns: [GMC] });
+ expect(await listStoreConnectors()).toEqual({ connectors: [], ready: false, signIns: [GMC] });
+ });
+
+ it("reads the accounts the workspace's sign-in opens, for the brand", async () => {
+ answer(200, { accounts: [{ id: '123', name: 'Acme' }] });
+ expect(await listSignInAccounts('b1', 'merchant_center')).toEqual({
+ ok: true,
+ accounts: [{ id: '123', name: 'Acme' }],
+ });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('/api/aeo/api/catalog/accounts?brandId=b1&kind=merchant_center');
+ expect(init).toMatchObject({ headers: { Authorization: 'Bearer tok' } });
+
+ answer(409, { code: 'not_connected', error: 'Connect Google Merchant Center first.' });
+ expect(await listSignInAccounts('b1', 'merchant_center')).toEqual({
+ ok: false,
+ code: 'not_connected',
+ });
+ answer(500, {});
+ expect(await listSignInAccounts('b1', 'merchant_center')).toEqual({
+ ok: false,
+ code: 'failed',
+ });
+ });
+
+ it('connects the picked account as the input', async () => {
+ answer(201, { id: 'gmc1', account: '123' });
+ expect(await connectSignInAccount('b1', 'merchant_center', '123')).toEqual({ ok: true });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('/api/aeo/api/catalog/sources');
+ expect(JSON.parse(init.body)).toEqual({
+ brandId: 'b1',
+ kind: 'merchant_center',
+ input: { account: '123' },
+ });
+ });
+
+ it("names why the account couldn't be connected, with the platform's own words when it can't open it", async () => {
+ answer(409, { code: 'not_connected', error: 'Connect Google Merchant Center first.' });
+ expect(await connectSignInAccount('b1', 'merchant_center', '123')).toEqual({
+ ok: false,
+ code: 'not_connected',
+ message: null,
+ });
+ answer(400, {
+ code: 'connect_failed',
+ error: "This Google sign-in can't open that Merchant Center account.",
+ });
+ expect(await connectSignInAccount('b1', 'merchant_center', '999')).toEqual({
+ ok: false,
+ code: 'connect_failed',
+ message: "This Google sign-in can't open that Merchant Center account.",
+ });
+ answer(409, { code: 'duplicate' });
+ expect(await connectSignInAccount('b1', 'merchant_center', '123')).toEqual({
+ ok: false,
+ code: 'duplicate',
+ message: null,
+ });
+ answer(502, {});
+ expect(await connectSignInAccount('b1', 'merchant_center', '123')).toEqual({
+ ok: false,
+ code: 'failed',
+ message: null,
+ });
+ fetchMock.mockRejectedValue(new TypeError('Failed to fetch'));
+ const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});
+ expect(await connectSignInAccount('b1', 'merchant_center', '123')).toEqual({
+ ok: false,
+ code: 'failed',
+ message: null,
+ });
+ quiet.mockRestore();
+ });
+});
+
+describe('StoreError', () => {
+ // Every code, so a new one fails the typecheck here until it has its words.
+ const CODES = {
+ connect_failed: true,
+ not_connected: true,
+ auth_failed: true,
+ unreachable: true,
+ duplicate: true,
+ too_many: true,
+ other_account: true,
+ not_configured: true,
+ forbidden: true,
+ not_found: true,
+ invalid: true,
+ session: true,
+ workspace: true,
+ busy: true,
+ failed: true,
+ } satisfies Record<StoreError, true>;
+
+ it('has words for every reason a store call fails', () => {
+ for (const code of Object.keys(CODES)) {
+ expect(messages.settings.catalog.stores.errors).toHaveProperty(code);
+ }
+ });
+});
diff --git a/web/src/lib/catalog-client.ts b/web/src/lib/catalog-client.ts
index 3b5345c11..5661a6b5d 100644
--- a/web/src/lib/catalog-client.ts
+++ b/web/src/lib/catalog-client.ts
@@ -12,7 +12,9 @@ import {
* A catalog sync from the browser (#1263), through the API's same-origin
* proxy: a feed or a store read now, or a file uploaded. Not a server
* action, whose body is limited to 1 MB. Stores are connected here too
- * (00282): their sign-in goes to the API, which alone keeps it.
+ * (00282): their sign-in goes to the API, which alone keeps it. So is an
+ * account of a platform read with the workspace's own sign-in, like Google
+ * Merchant Center (#1270): picked from the accounts that sign-in opens.
*/
export type CatalogSyncError =
@@ -126,6 +128,7 @@ export interface StoreConnector {
export type StoreError =
| 'connect_failed'
+ | 'not_connected'
| 'auth_failed'
| 'unreachable'
| 'duplicate'
@@ -145,6 +148,7 @@ export type StoreResult = { ok: true } | { ok: false; code: StoreError; message:
const STORE_KNOWN: readonly StoreError[] = [
'connect_failed',
+ 'not_connected',
'auth_failed',
'unreachable',
'duplicate',
@@ -194,10 +198,26 @@ async function storeCall(path: string, init: RequestInit): Promise<StoreResult>
}
}
-/** The stores a person can connect, and whether the API can keep a sign-in; null when unreadable. */
+/**
+ * A platform read with the workspace's own sign-in (#1270): its Composio
+ * provider, connected in Settings › Integrations, and whether this server
+ * has that sign-in set up.
+ */
+export interface SignInConnector {
+ kind: string;
+ label: string;
+ provider: string;
+ configured: boolean;
+}
+
+/**
+ * The stores a person can connect, whether the API can keep a sign-in, and
+ * the platforms read with the workspace's sign-in; null when unreadable.
+ */
export async function listStoreConnectors(): Promise<{
connectors: StoreConnector[];
ready: boolean;
+ signIns: SignInConnector[];
} | null> {
try {
const {
@@ -208,8 +228,12 @@ export async function listStoreConnectors(): Promise<{
headers: { Authorization: `Bearer ${session.access_token}` },
});
if (!res.ok) return null;
- const body = (await res.json()) as { connectors?: StoreConnector[]; ready?: boolean };
- return { connectors: body.connectors ?? [], ready: !!body.ready };
+ const body = (await res.json()) as {
+ connectors?: StoreConnector[];
+ ready?: boolean;
+ signIns?: SignInConnector[];
+ };
+ return { connectors: body.connectors ?? [], ready: !!body.ready, signIns: body.signIns ?? [] };
} catch (err) {
console.error('Failed to read the store connectors:', err);
return null;
@@ -237,3 +261,51 @@ export function updateStoreSignIn(id: string, input: Record<string, string>): Pr
export function removeStore(id: string): Promise<StoreResult> {
return storeCall(`/sources/${encodeURIComponent(id)}`, { method: 'DELETE' });
}
+
+/** An account the workspace's sign-in opens on a platform, to connect to a brand. */
+export interface SignInAccount {
+ id: string;
+ name: string | null;
+}
+
+/** The accounts the workspace's sign-in opens on a platform (#1270), for a brand to pick one. */
+export async function listSignInAccounts(
+ brandId: string,
+ kind: string,
+): Promise<{ ok: true; accounts: SignInAccount[] } | { ok: false; code: StoreError }> {
+ try {
+ const {
+ data: { session },
+ } = await createClient().auth.getSession();
+ if (!session) return { ok: false, code: 'session' };
+ const query = new URLSearchParams({ brandId, kind });
+ const res = await fetch(`${BROWSER_API_BASE_URL}/api/catalog/accounts?${query}`, {
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ });
+ const body = (await res.json().catch(() => ({}))) as {
+ accounts?: SignInAccount[];
+ code?: string;
+ };
+ if (res.ok) return { ok: true, accounts: body.accounts ?? [] };
+ const known = STORE_KNOWN.find((c) => c === body.code);
+ if (known) return { ok: false, code: known };
+ const general = apiFailure(res.status, body);
+ return {
+ ok: false,
+ code:
+ general === 'session' || general === 'workspace' || general === 'busy' ? general : 'failed',
+ };
+ } catch (err) {
+ console.error('Failed to read the accounts:', err);
+ return { ok: false, code: 'failed' };
+ }
+}
+
+/** Connects the picked account to a brand; the API reads it right after. */
+export function connectSignInAccount(
+ brandId: string,
+ kind: string,
+ account: string,
+): Promise<StoreResult> {
+ return connectStore(brandId, kind, { account });
+}
diff --git a/web/src/lib/catalog.ts b/web/src/lib/catalog.ts
index cfb937fb0..c6aeae189 100644
--- a/web/src/lib/catalog.ts
+++ b/web/src/lib/catalog.ts
@@ -9,6 +9,18 @@ export type CatalogFormat = 'auto' | 'google_xml' | 'csv' | 'meta_csv';
/** `auth_failed`: the store refused the saved sign-in. */
export type CatalogSyncStatus = 'ok' | 'failed' | 'format_error' | 'auth_failed';
+/** A Google Merchant Center account's kind (#1270), read with the workspace's Google sign-in. */
+export const MERCHANT_CENTER_KIND = 'merchant_center';
+export const MERCHANT_CENTER_LABEL = 'Google Merchant Center';
+
+/**
+ * The platforms read with the workspace's sign-in, named by their kind: the
+ * name a source's row keeps when the API's connectors can't be read.
+ */
+export const SIGN_IN_PLATFORM_LABELS: Readonly<Partial<Record<string, string>>> = {
+ [MERCHANT_CENTER_KIND]: MERCHANT_CENTER_LABEL,
+};
+
/** Whether a source is a store, read with its sign-in, rather than a feed or an upload. */
export function isStoreSource(kind: CatalogSourceKind): boolean {
return kind !== 'feed_url' && kind !== 'upload';
@@ -24,6 +36,17 @@ export interface CatalogCounts {
errors: string[];
products: { added: number; changed: number; removed: number; unchanged: number };
variants: { added: number; changed: number; removed: number; unchanged: number };
+ /**
+ * The issues a platform reports per item (Google Merchant Center, #1270,
+ * 00296): the items with at least one, and the issues per severity.
+ */
+ issues?: { items: number; disapproved: number; demoted: number; not_impacted: number };
+ /**
+ * The listings of an item read already, under another language or feed
+ * label (Google Merchant Center, #1270): kept once, not skipped. Not on
+ * syncs before it was counted.
+ */
+ repeated?: number;
}
export interface CatalogSource {