Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions apps/commercetools/AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Agent Guide — commercetools

## What This App Does
Integrates commercetools (e-commerce platform) with Contentful. Lets editors pick commercetools products/categories directly from Contentful field editors. Published as `@contentful/commercetools`.
Integrates commercetools (e-commerce platform) with Contentful. Lets editors pick commercetools products, product variants or categories directly from Contentful field editors. Published as `@contentful/commercetools`.

## Archetype
**Ecommerce base app** — wraps `@contentful/ecommerce-app-base`. Published as `@contentful/commercetools`.
Expand All @@ -12,7 +12,7 @@ Integrates commercetools (e-commerce platform) with Contentful. Lets editors pic
apps/commercetools/
└── src/
├── index.tsx # Mounts ecommerce-app-base with commercetools config
├── api/ # commercetools API client
├── api/ # commercetools API client (products, variants, categories)
├── config.ts # Connection config constants
├── constants.ts
├── dialog.ts # Dialog renderer passed to ecommerce-app-base
Expand All @@ -21,6 +21,18 @@ apps/commercetools/
└── logo.svg
```

## SKU Types

The SKU type is configured per field in the app configuration (`skuTypes` installation parameter):

| SKU type | Stored value | Picker rows |
|----------|--------------|-------------|
| `product` (default) | `masterVariant.sku` | One row per product |
| `variant` | The SKU of the selected variant | One row per variant with a SKU |
| `category` | Category ID | One row per category |

Product values are master variant SKUs, so existing product values still resolve when a field is switched to `variant`.

## Key Dependencies

| Package | Role |
Expand All @@ -36,6 +48,8 @@ apps/commercetools/
- **`additionalDataRenderer.tsx`** renders extra product metadata (e.g. price, stock) alongside the standard product preview — it receives a product object from commercetools. Changes here require that the commercetools API response shape is understood.
- **commercetools API credentials** (client ID, secret, project key) are stored in installation parameters — never log them.
- **`commercetools-without-search`** is a sibling app with the same architecture but without the search capability — keep changes aligned between the two when fixing shared logic.
- **Row `id`s must be unique.** `ecommerce-app-base` uses `product.id` as the React and drag-and-drop key. Variant rows use `${productId}:${variantId}`, missing variant previews use `missing:${sku}`.
- **Variant search paginates per product.** commercetools paginates product projections, so a page in `variant` mode can contain more rows than the page limit.

## Never / Always

Expand Down
17 changes: 16 additions & 1 deletion apps/commercetools/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Pagination, ProductsFn } from '@contentful/ecommerce-app-base';
import { CommerceToolsProduct, ConfigurationParameters, SkuType } from '../types';
import { fetchCategories, fetchCategoryPreviews } from './categories';
import { fetchProductPreviews, fetchProducts } from './products';
import { fetchVariantPreviews, fetchVariants } from './variants';

export async function fetchPreviews(
skus: string[],
Expand All @@ -11,17 +12,31 @@ export async function fetchPreviews(
): Promise<CommerceToolsProduct[]> {
if (skuType === 'category') {
return await fetchCategoryPreviews(skus, config);
} else if (skuType === 'variant') {
return await fetchVariantPreviews(skus, config);
} else {
return await fetchProductPreviews(skus, config);
}
}

const LIMIT = 20;

function getFetchFn(skuType: SkuType) {
if (skuType === 'category') {
return fetchCategories;
}

if (skuType === 'variant') {
return fetchVariants;
}

return fetchProducts;
}

export function createResolver(sdk: DialogAppSDK, skuType: SkuType): ProductsFn {
let offset = 0;

const fetchFn = skuType === 'category' ? fetchCategories : fetchProducts;
const fetchFn = getFetchFn(skuType);

return async (search: string, updatedPagination?: Partial<Pagination>, searchBySku?: boolean) => {
offset = updatedPagination?.offset ?? offset;
Expand Down
26 changes: 19 additions & 7 deletions apps/commercetools/src/api/products.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import { CommerceToolsProduct, ConfigurationParameters } from '../types';
import { createClient } from './client';
import { getLocalizedValue } from './localisation-helpers';

const MAX_LIMIT = 500;
export const MAX_LIMIT = 500;

function getProductAttributes(definitions: AttributeDefinition[], attributes: Attribute[]) {
export function getProductAttributes(definitions: AttributeDefinition[], attributes: Attribute[]) {
const indexedDefinitions = definitions.reduce((acc, definition) => {
acc[definition.name] = definition;

Expand All @@ -33,13 +33,25 @@ function getProductAttributes(definitions: AttributeDefinition[], attributes: At
return productAttributes;
}

function productTransformer({ projectKey, locale, mcUrl }: ConfigurationParameters) {
export function getProductExternalLink(
{ projectKey, mcUrl }: ConfigurationParameters,
productId: string
): string {
const merchantCenterBaseUrl =
mcUrl && mcUrl.length > 0 ? mcUrl : 'https://mc.europe-west1.gcp.commercetools.com';

return (
(projectKey &&
productId &&
`${merchantCenterBaseUrl}/${projectKey}/products/${productId}/general`) ||
''
);
}

function productTransformer(config: ConfigurationParameters) {
return (item: ProductProjection): CommerceToolsProduct => {
const merchantCenterBaseUrl =
mcUrl && mcUrl.length > 0 ? mcUrl : 'https://mc.europe-west1.gcp.commercetools.com';
const id = item.id ?? '';
const externalLink =
(projectKey && id && `${merchantCenterBaseUrl}/${projectKey}/products/${id}/general`) || '';
const externalLink = getProductExternalLink(config, id);

const attributeDefinitions = item.productType.obj?.attributes ?? [];
const attributes = item.masterVariant.attributes ?? [];
Expand Down
137 changes: 137 additions & 0 deletions apps/commercetools/src/api/variants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import type { ProductProjection, ProductVariant } from '@commercetools/platform-sdk';
import { Pagination } from '@contentful/ecommerce-app-base';
import { CommerceToolsProduct, ConfigurationParameters } from '../types';
import { createClient } from './client';
import { getLocalizedValue } from './localisation-helpers';
import { getProductAttributes, getProductExternalLink, MAX_LIMIT } from './products';

function getVariants(item: ProductProjection): ProductVariant[] {
return [item.masterVariant, ...(item.variants ?? [])].filter(
(variant): variant is ProductVariant => !!variant?.sku
);
}

/**
* Turns a product projection into one row per variant that has a SKU.
* Row ids combine product and variant id, so they stay unique across variants
* of the same product.
*/
export function variantTransformer(config: ConfigurationParameters) {
return (item: ProductProjection): CommerceToolsProduct[] => {
const productId = item.id ?? '';
const productName = getLocalizedValue(item.name) ?? '';
const externalLink = getProductExternalLink(config, productId);
const attributeDefinitions = item.productType?.obj?.attributes ?? [];

return getVariants(item).map((variant) => {
const sku = variant.sku as string;

return {
id: `${productId}:${variant.id}`,
sku,
image: variant.images?.[0]?.url ?? item.masterVariant?.images?.[0]?.url ?? '',
name: productName ? `${productName} (${sku})` : sku,
externalLink,
description: getLocalizedValue(item.description),
additionalData: {
createdAt: item.createdAt,
updatedAt: item.lastModifiedAt,
attributes: getProductAttributes(attributeDefinitions, variant.attributes ?? []),
},
};
});
};
}

export async function fetchVariantPreviews(
skus: string[],
config: ConfigurationParameters
): Promise<CommerceToolsProduct[]> {
if (skus.length === 0) {
return [];
}

const client = createClient(config);
const response = await client
.productProjections()
.search()
.get({
queryArgs: {
expand: ['description', 'productType'],
'filter.query': [`variants.sku:${skus.map((sku) => `"${sku}"`).join(',')}`],
limit: MAX_LIMIT,
},
})
.execute();

if (response.statusCode !== 200) {
throw new Error(`Request failed with status ${response.statusCode}`);
}

const rowsBySku = new Map<string, CommerceToolsProduct>();
for (const row of response.body.results.flatMap(variantTransformer(config))) {
rowsBySku.set(row.sku, row);
}

return skus.map(
(sku) =>
rowsBySku.get(sku) ?? {
sku,
image: '',
id: `missing:${sku}`,
name: '',
isMissing: true,
}
);
}

/**
* Searches products like `fetchProducts`, but returns one row per variant.
*
* Pagination is per product, as commercetools paginates product projections:
* `limit`, `offset`, `count` and `total` count products, so a page can contain
* more rows than `limit`.
*/
export async function fetchVariants(
config: ConfigurationParameters,
search: string,
pagination: { offset: number; limit: number },
searchBySku: boolean
): Promise<{
pagination: Pagination;
products: CommerceToolsProduct[];
}> {
const client = createClient(config);
const isSkuSearch = !!search && searchBySku;

const response = await client
.productProjections()
.search()
.get({
queryArgs: {
...(isSkuSearch
? { 'filter.query': [`variants.sku:"${search}"`] }
: { [`text.${config.locale}`]: search }),
limit: pagination?.limit,
offset: pagination?.offset,
},
})
.execute();

if (response.statusCode !== 200) {
throw new Error(`Request failed with status ${response.statusCode}`);
}

const rows = response.body.results.flatMap(variantTransformer(config));

return {
pagination: {
offset: response.body.offset,
total: response.body.total!,
count: response.body.count,
limit: response.body.limit,
hasNextPage: response.body.offset + response.body.count < response.body.total!,
},
products: isSkuSearch ? rows.filter((row) => row.sku === search) : rows,
};
}
4 changes: 4 additions & 0 deletions apps/commercetools/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@ export const SKU_TYPES = [
id: 'category',
name: 'Category',
},
{
id: 'variant',
name: 'Product variant',
},
];
17 changes: 16 additions & 1 deletion apps/commercetools/src/dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,26 @@ function makeSaveBtnText(skuType: SkuType) {
}
};
}

if (skuType === 'variant') {
return (selectedSKUs: string[]) => {
switch (selectedSKUs.length) {
case 0:
return 'Save variants';
case 1:
return 'Save 1 variant';
default:
return `Save ${selectedSKUs.length} variants`;
}
};
}
}

function makeSearchPlaceholderText(skuType: string | undefined): string {
if (skuType === 'category') {
return 'Search by category name, slug, or key...';
} else if (skuType === 'variant') {
return 'Search for a product or variant...';
} else {
return 'Search for a product...';
}
Expand Down Expand Up @@ -69,7 +84,7 @@ export async function renderDialog(sdk: DialogAppSDK) {
makeSearchPlaceholderText,
makeSearchHelpText,
hideSearch: false,
showSearchBySkuOption: skuType === 'product',
showSearchBySkuOption: skuType === 'product' || skuType === 'variant',
});

sdk.window.startAutoResizer();
Expand Down
2 changes: 2 additions & 0 deletions apps/commercetools/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ function makeCTA(fieldType: string, skuType?: string) {
const isArray = fieldType === 'Array';
if (skuType === 'category') {
return `Select ${isArray ? 'categories' : 'a category'}`;
} else if (skuType === 'variant') {
return `Select ${isArray ? 'product variants' : 'a product variant'}`;
} else {
return `Select ${isArray ? 'products' : 'a product'}`;
}
Expand Down
2 changes: 1 addition & 1 deletion apps/commercetools/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export interface ConfigurationParameters {
skuTypes?: Record<string, Record<string, SkuType | undefined> | undefined>;
}

export type SkuType = 'product' | 'category';
export type SkuType = 'product' | 'category' | 'variant';

export type CommerceToolsProduct = Product & {
additionalData?: {
Expand Down