Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(CTC-140): Add base controller/processor for published product #39

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
12 changes: 6 additions & 6 deletions event/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion event/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"@commercetools-backend/loggers": "22.28.0",
"@commercetools/platform-sdk": "7.9.0",
"@commercetools/sdk-client-v2": "2.5.0",
"@fulfillmenttools/fulfillmenttools-sdk-typescript": "0.1.16",
"@fulfillmenttools/fulfillmenttools-sdk-typescript": "0.1.17",
"body-parser": "1.20.2",
"date-fns": "2.30.0",
"dotenv": "16.4.5",
Expand Down
4 changes: 3 additions & 1 deletion event/src/channel/channelProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ export class ChannelProcessor {

async processChannel(message: Message & { notificationType?: string }): Promise<void> {
if (message.resource?.typeId != 'channel') {
logger.warn(`Could not process CT message - resource.typeId '${message.resource?.typeId}' != 'channel'`);
logger.warn(
`Could not process CT message '${message.resource?.id}' - resource.typeId '${message.resource?.typeId}' != 'channel'`
);
return;
}

Expand Down
112 changes: 40 additions & 72 deletions event/src/connector/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,14 @@ import { ByProjectKeyRequestBuilder } from '@commercetools/platform-sdk/dist/dec

const ORDER_SUBSCRIPTION_KEY = 'fft-ctc-orders';
const CHANNEL_RESOURCE_SUBSCRIPTION_KEY = 'fft-ctc-channels';
const PRODUCT_SUBSCRIPTION_KEY = 'fft-ctc-products';

export async function createOrderSubscription(
apiRoot: ByProjectKeyRequestBuilder,
topicName: string,
projectId: string
): Promise<void> {
const {
body: { results: subscriptions },
} = await apiRoot
.subscriptions()
.get({
queryArgs: {
where: `key = "${ORDER_SUBSCRIPTION_KEY}"`,
},
})
.execute();

if (subscriptions.length > 0) {
const subscription = subscriptions[0];

await apiRoot
.subscriptions()
.withKey({ key: ORDER_SUBSCRIPTION_KEY })
.delete({
queryArgs: {
version: subscription?.version || 0,
},
})
.execute();
}
await deleteOrderSubscription(apiRoot);

await apiRoot
.subscriptions()
Expand All @@ -55,90 +33,80 @@ export async function createOrderSubscription(
}

export async function deleteOrderSubscription(apiRoot: ByProjectKeyRequestBuilder): Promise<void> {
const {
body: { results: subscriptions },
} = await apiRoot
.subscriptions()
.get({
queryArgs: {
where: `key = "${ORDER_SUBSCRIPTION_KEY}"`,
},
})
.execute();

if (subscriptions.length > 0) {
const subscription = subscriptions[0];

await apiRoot
.subscriptions()
.withKey({ key: ORDER_SUBSCRIPTION_KEY })
.delete({
queryArgs: {
version: subscription?.version || 0,
},
})
.execute();
}
await deleteSubscription(ORDER_SUBSCRIPTION_KEY, apiRoot);
}

export async function createChannelResourceSubscription(
apiRoot: ByProjectKeyRequestBuilder,
topicName: string,
projectId: string
): Promise<void> {
const {
body: { results: subscriptions },
} = await apiRoot
await deleteChannelResourceSubscription(apiRoot);

await apiRoot
.subscriptions()
.get({
queryArgs: {
where: `key = "${CHANNEL_RESOURCE_SUBSCRIPTION_KEY}"`,
.post({
body: {
key: CHANNEL_RESOURCE_SUBSCRIPTION_KEY,
destination: {
type: 'GoogleCloudPubSub',
topic: topicName,
projectId,
},
changes: [
{
resourceTypeId: 'channel',
},
],
},
})
.execute();
}

if (subscriptions.length > 0) {
const subscription = subscriptions[0];
export async function deleteChannelResourceSubscription(apiRoot: ByProjectKeyRequestBuilder): Promise<void> {
await deleteSubscription(CHANNEL_RESOURCE_SUBSCRIPTION_KEY, apiRoot);
}

await apiRoot
.subscriptions()
.withKey({ key: CHANNEL_RESOURCE_SUBSCRIPTION_KEY })
.delete({
queryArgs: {
version: subscription?.version || 0,
},
})
.execute();
}
export async function createProductSubscription(
apiRoot: ByProjectKeyRequestBuilder,
topicName: string,
projectId: string
): Promise<void> {
await deleteProductSubscription(apiRoot);

await apiRoot
.subscriptions()
.post({
body: {
key: CHANNEL_RESOURCE_SUBSCRIPTION_KEY,
key: PRODUCT_SUBSCRIPTION_KEY,
destination: {
type: 'GoogleCloudPubSub',
topic: topicName,
projectId,
},
changes: [
messages: [
{
resourceTypeId: 'channel',
resourceTypeId: 'product',
types: ['ProductPublished'],
},
],
},
})
.execute();
}

export async function deleteChannelResourceSubscription(apiRoot: ByProjectKeyRequestBuilder): Promise<void> {
export async function deleteProductSubscription(apiRoot: ByProjectKeyRequestBuilder): Promise<void> {
await deleteSubscription(PRODUCT_SUBSCRIPTION_KEY, apiRoot);
}

async function deleteSubscription(key: string, apiRoot: ByProjectKeyRequestBuilder): Promise<void> {
const {
body: { results: subscriptions },
} = await apiRoot
.subscriptions()
.get({
queryArgs: {
where: `key = "${CHANNEL_RESOURCE_SUBSCRIPTION_KEY}"`,
where: `key = "${key}"`,
},
})
.execute();
Expand All @@ -148,7 +116,7 @@ export async function deleteChannelResourceSubscription(apiRoot: ByProjectKeyReq

await apiRoot
.subscriptions()
.withKey({ key: CHANNEL_RESOURCE_SUBSCRIPTION_KEY })
.withKey({ key })
.delete({
queryArgs: {
version: subscription?.version || 0,
Expand Down
4 changes: 2 additions & 2 deletions event/src/connector/post-deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import dotenv from 'dotenv';
dotenv.config();

import { assertString, assertError, createApiRoot } from 'shared';
import { createChannelResourceSubscription, createOrderSubscription } from './actions';
import { createChannelResourceSubscription, createOrderSubscription, createProductSubscription } from './actions';

const CONNECT_GCP_TOPIC_NAME_KEY = 'CONNECT_GCP_TOPIC_NAME';
const CONNECT_GCP_PROJECT_ID_KEY = 'CONNECT_GCP_PROJECT_ID';
Expand All @@ -15,7 +15,7 @@ async function postDeploy(properties: Map<string, unknown>): Promise<void> {
assertString(projectId, CONNECT_GCP_PROJECT_ID_KEY);

const apiRoot = createApiRoot();
const actions = [createOrderSubscription, createChannelResourceSubscription];
const actions = [createOrderSubscription, createProductSubscription, createChannelResourceSubscription];
await Promise.all(actions.map(async (a) => await a(apiRoot, topicName, projectId)));
}

Expand Down
4 changes: 2 additions & 2 deletions event/src/connector/pre-undeploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import dotenv from 'dotenv';
dotenv.config();

import { assertError, createApiRoot } from 'shared';
import { deleteChannelResourceSubscription, deleteOrderSubscription } from './actions';
import { deleteChannelResourceSubscription, deleteOrderSubscription, deleteProductSubscription } from './actions';

async function preUndeploy(): Promise<void> {
const apiRoot = createApiRoot();
const actions = [deleteOrderSubscription, deleteChannelResourceSubscription];
const actions = [deleteOrderSubscription, deleteProductSubscription, deleteChannelResourceSubscription];
await Promise.all(actions.map(async (a) => await a(apiRoot)));
}

Expand Down
24 changes: 22 additions & 2 deletions event/src/controllers/eventController.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
import { NextFunction, Request, Response } from 'express';
import { Message, OrderCreatedMessage, OrderStateChangedMessage, Reference } from '@commercetools/platform-sdk';
import {
Message,
OrderCreatedMessage,
OrderStateChangedMessage,
ProductPublishedMessage,
Reference,
} from '@commercetools/platform-sdk';

import { logger, CustomError, SubscriptionMessage } from 'shared';
import { OrderProcessor } from '../order/orderProcessor';
import { ChannelProcessor } from '../channel/channelProcessor';
import { ProductProcessor } from '../product/productProcessor';

export class EventController {
constructor(private readonly orderProcessor: OrderProcessor, private readonly channelProcessor: ChannelProcessor) {
constructor(
private readonly orderProcessor: OrderProcessor,
private readonly productProcessor: ProductProcessor,
private readonly channelProcessor: ChannelProcessor
) {
this.post = this.post.bind(this);
}

Expand Down Expand Up @@ -36,6 +47,11 @@ export class EventController {
await this.orderProcessor.cancelOrder(resourceRef.id, message.resourceUserProvidedIdentifiers?.orderNumber);
}
break;
case 'product':
if (this.isProductPublishedMessage(message)) {
await this.productProcessor.processProductPublished(message as ProductPublishedMessage);
}
break;
case 'channel':
if (this.isChannelMessage(message)) {
await this.channelProcessor.processChannel(message);
Expand Down Expand Up @@ -129,4 +145,8 @@ export class EventController {
notificationType === 'ResourceDeleted'
);
}

private isProductPublishedMessage(message: Message): boolean {
return message.type === 'ProductPublished';
}
}
1 change: 1 addition & 0 deletions event/src/order/orderMapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@
}

private mapOrderLineItems(commercetoolsOrder: CommercetoolsOrder): OrderLineItemForCreation[] {
function getStringValue(value: { [key: string]: any }): string {

Check warning on line 115 in event/src/order/orderMapper.ts

View workflow job for this annotation

GitHub Actions / build (event)

Unexpected any. Specify a different type
// TODO map languages defined in CT project using ProjectService.getProject
const locales = ['en-US', 'en-GB', 'en-AU', 'en-CA', 'en', 'de-DE', 'de-AT', 'de-CH', 'de'];
let result: string | undefined = undefined;
for (const locale of locales) {
Expand All @@ -127,7 +128,7 @@
return result || ' ';
}

function mapAttributeValue(value: any): string {

Check warning on line 131 in event/src/order/orderMapper.ts

View workflow job for this annotation

GitHub Actions / build (event)

Unexpected any. Specify a different type
if (value === undefined || value === null) {
return ' '; // FFT API does not allow empty attribute value;
} else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
Expand Down
75 changes: 75 additions & 0 deletions event/src/product/productMapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { ProductProjection, ProductVariant } from '@commercetools/platform-sdk';
import {
ArticleAttributeItem,
ListingAttributeItem,
ListingForReplacement,
LocaleString,
} from '@fulfillmenttools/fulfillmenttools-sdk-typescript';

export class ProductMapper {
public async mapProduct(
product: ProductProjection,
languages: string[],
tenantArticleId: string
): Promise<ListingForReplacement | undefined> {
const variant = this.getVariant(product, tenantArticleId);
if (!variant) {
return undefined;
}

const listing: ListingForReplacement = {
tenantArticleId,
title: 'title', // will be overwritten by localized title
};

const titleLocalized: LocaleString = {};
for (const language of languages) {
if (product.name[language]) {
titleLocalized[this.mapLocale(language)] = product.name[language];
}
}
listing.titleLocalized = titleLocalized;

const attr: ListingAttributeItem = {
category: ArticleAttributeItem.CategoryEnum.Descriptive,
key: '%%subtitle%%',
value: 'value', // will be overwritten by localized value
};

const valueLocalized: LocaleString = {};
for (const language of languages) {
if (product.description?.[language]) {
valueLocalized[this.mapLocale(language)] = product.description[language];
}
}
attr.valueLocalized = valueLocalized;

listing.attributes = [attr];

if (variant.images !== undefined && variant.images.length > 0) {
listing.imageUrl = variant.images[0].url;
}

listing.customAttributes = {
ctProductId: product.id,
ctProductVariant: variant.id,
};

if (product.key) {
listing.customAttributes.ctProductKey = product.key;
}

return listing;
}

getVariant(product: ProductProjection, tenantArticleId: string): ProductVariant | undefined {
if (product.masterVariant.sku === tenantArticleId) {
return product.masterVariant;
}
return product.variants.find((variant) => variant.sku === tenantArticleId);
}

mapLocale(source: string): string {
return source.replace('-', '_');
}
}
Loading