Skip to content

Commit

Permalink
feat: add Image Label Separated Of Image Text
Browse files Browse the repository at this point in the history
  • Loading branch information
IncognitaDev committed Sep 18, 2023
1 parent f4233be commit 4680866
Showing 1 changed file with 74 additions and 77 deletions.
151 changes: 74 additions & 77 deletions vtex/utils/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ import type {

const DEFAULT_CATEGORY_SEPARATOR = ">";

const isLegacySku = (
sku: LegacySkuVTEX | SkuVTEX,
): sku is LegacySkuVTEX =>
const isLegacySku = (sku: LegacySkuVTEX | SkuVTEX): sku is LegacySkuVTEX =>
typeof (sku as LegacySkuVTEX).variations?.[0] === "string";

const isLegacyProduct = (
Expand Down Expand Up @@ -166,7 +164,9 @@ const splitCategory = (firstCategory: string) =>

const toAdditionalPropertyCategories = <
P extends LegacyProductVTEX | ProductVTEX,
>(product: P): Product["additionalProperty"] => {
>(
product: P,
): Product["additionalProperty"] => {
const categories = splitCategory(product.categories[0]);
const categoryIds = splitCategory(product.categoriesIds[0]);

Expand All @@ -182,7 +182,9 @@ const toAdditionalPropertyCategories = <

const toAdditionalPropertyClusters = <
P extends LegacyProductVTEX | ProductVTEX,
>(product: P): Product["additionalProperty"] => {
>(
product: P,
): Product["additionalProperty"] => {
const mapEntriesToIdName = ([id, name]: [string, unknown]) => ({
id,
name: name as string,
Expand Down Expand Up @@ -237,6 +239,7 @@ export const toProduct = <P extends LegacyProductVTEX | ProductVTEX>(
level = 0, // prevent inifinte loop while self referencing the product
options: ProductOptions,
): Product => {
console.log(product);
const { baseUrl, priceCurrency } = options;
const {
brand,
Expand All @@ -249,12 +252,13 @@ export const toProduct = <P extends LegacyProductVTEX | ProductVTEX>(
items,
} = product;
const { name, ean, itemId: skuId, referenceId = [] } = sku;
const imagesByKey = options.imagesByKey ?? items
.flatMap((i) => i.images)
.reduce((map, img) => {
map.set(getImageKey(img.imageUrl), img.imageUrl);
return map;
}, new Map<string, string>());
const imagesByKey = options.imagesByKey ??
items
.flatMap((i) => i.images)
.reduce((map, img) => {
map.set(getImageKey(img.imageUrl), img.imageUrl);
return map;
}, new Map<string, string>());

const groupAdditionalProperty = isLegacyProduct(product)
? legacyToProductGroupAdditionalProperties(product)
Expand All @@ -266,14 +270,15 @@ export const toProduct = <P extends LegacyProductVTEX | ProductVTEX>(
referenceId,
);
const images = nonEmptyArray(sku.images);
const offers = (sku.sellers ?? []).map(
isLegacyProduct(product) ? toOfferLegacy : toOffer,
).sort(bestOfferFirst);

const offers = (sku.sellers ?? [])
.map(isLegacyProduct(product) ? toOfferLegacy : toOffer)
.sort(bestOfferFirst);
const highPriceIndex = getHighPriceIndex(offers);
const lowPriceIndex = 0;

const isVariantOf = level < 1
? {
? ({
"@type": "ProductGroup",
productGroupID: productId,
hasVariant: items.map((sku) =>
Expand All @@ -283,7 +288,7 @@ export const toProduct = <P extends LegacyProductVTEX | ProductVTEX>(
name: product.productName,
additionalProperty: groupAdditionalProperty,
model: productReference,
} satisfies ProductGroup
} satisfies ProductGroup)
: undefined;

// From schema.org: A category for the item. Greater signs or slashes can be used to informally indicate a category hierarchy
Expand All @@ -294,11 +299,10 @@ export const toProduct = <P extends LegacyProductVTEX | ProductVTEX>(
const categoryAdditionalProperties = toAdditionalPropertyCategories(product);
const clusterAdditionalProperties = toAdditionalPropertyClusters(product);

const additionalProperty = specificationsAdditionalProperty.concat(
categoryAdditionalProperties ?? [],
).concat(clusterAdditionalProperties ?? []).concat(
referenceIdAdditionalProperty ?? [],
);
const additionalProperty = specificationsAdditionalProperty
.concat(categoryAdditionalProperties ?? [])
.concat(clusterAdditionalProperties ?? [])
.concat(referenceIdAdditionalProperty ?? []);

return {
"@type": "Product",
Expand All @@ -322,8 +326,9 @@ export const toProduct = <P extends LegacyProductVTEX | ProductVTEX>(
image: images?.map(({ imageUrl, imageText, imageLabel }) => {
const url = imagesByKey.get(getImageKey(imageUrl)) ?? imageUrl;
const alternateName = imageText || imageLabel || "";
const name = imageLabel || "";

return { "@type": "ImageObject" as const, alternateName, url };
return { "@type": "ImageObject" as const, alternateName, url, name };
}) ?? [DEFAULT_IMAGE],
offers: offers.length > 0
? {
Expand Down Expand Up @@ -355,8 +360,8 @@ const toBreadcrumbList = (
return {
"@type": "ListItem" as const,
name,
item:
new URL(`/${segments.slice(0, position).join("/")}`, baseUrl).href,
item: new URL(`/${segments.slice(0, position).join("/")}`, baseUrl)
.href,
position,
};
}),
Expand All @@ -371,80 +376,73 @@ const toBreadcrumbList = (
};
};

const legacyToProductGroupAdditionalProperties = (
product: LegacyProductVTEX,
) =>
const legacyToProductGroupAdditionalProperties = (product: LegacyProductVTEX) =>
product.allSpecifications?.flatMap((name) => {
const values = (product as unknown as Record<string, string[]>)[name];

return values.map((value) =>
({
return values.map(
(value) => ({
"@type": "PropertyValue",
name,
value,
valueReference: "SPECIFICATION",
}) as const
} as const),
);
}) ?? [];

const toProductGroupAdditionalProperties = ({ properties = [] }: ProductVTEX) =>
properties.flatMap(({ name, values }) =>
values.map((value) =>
({
values.map(
(value) => ({
"@type": "PropertyValue",
name,
value,
valueReference: "PROPERTY" as string,
}) as const
} as const),
)
);

const toAdditionalProperties = (
sku: SkuVTEX,
): PropertyValue[] =>
const toAdditionalProperties = (sku: SkuVTEX): PropertyValue[] =>
sku.variations?.flatMap(({ name, values }) =>
values.map((value) =>
({
values.map(
(value) => ({
"@type": "PropertyValue",
name,
value,
valueReference: "SPECIFICATION",
}) as const
} as const),
)
) ?? [];

const toAdditionalPropertiesLegacy = (sku: LegacySkuVTEX): PropertyValue[] => {
const { variations = [], attachments = [] } = sku;

const specificationProperties = variations.flatMap((variation) =>
sku[variation].map((value) =>
({
sku[variation].map(
(value) => ({
"@type": "PropertyValue",
name: variation,
value,
valueReference: "SPECIFICATION",
}) as const
} as const),
)
);

const attachmentProperties = attachments.map((attachment) =>
({
const attachmentProperties = attachments.map(
(attachment) => ({
"@type": "PropertyValue",
propertyID: `${attachment.id}`,
name: attachment.name,
value: attachment.domainValues,
required: attachment.required,
valueReference: "ATTACHMENT",
}) as const
} as const),
);

return [...specificationProperties, ...attachmentProperties];
};

const toOffer = ({
commertialOffer: offer,
sellerId,
}: SellerVTEX): Offer => ({
const toOffer = ({ commertialOffer: offer, sellerId }: SellerVTEX): Offer => ({
"@type": "Offer",
price: offer.spotPrice ?? offer.Price,
seller: sellerId,
Expand All @@ -462,25 +460,25 @@ const toOffer = ({
priceType: "https://schema.org/SalePrice",
price: offer.Price,
},
...offer.Installments.map((installment): UnitPriceSpecification => ({
"@type": "UnitPriceSpecification",
priceType: "https://schema.org/SalePrice",
priceComponentType: "https://schema.org/Installment",
name: installment.PaymentSystemName,
description: installment.Name,
billingDuration: installment.NumberOfInstallments,
billingIncrement: installment.Value,
price: installment.TotalValuePlusInterestRate,
})),
...offer.Installments.map(
(installment): UnitPriceSpecification => ({
"@type": "UnitPriceSpecification",
priceType: "https://schema.org/SalePrice",
priceComponentType: "https://schema.org/Installment",
name: installment.PaymentSystemName,
description: installment.Name,
billingDuration: installment.NumberOfInstallments,
billingIncrement: installment.Value,
price: installment.TotalValuePlusInterestRate,
}),
),
],
availability: offer.AvailableQuantity > 0
? "https://schema.org/InStock"
: "https://schema.org/OutOfStock",
});

const toOfferLegacy = (
seller: SellerVTEX,
): Offer => ({
const toOfferLegacy = (seller: SellerVTEX): Offer => ({
...toOffer(seller),
teasers: (seller.commertialOffer.Teasers ?? []).map((teaser) => ({
name: teaser["<Name>k__BackingField"],
Expand All @@ -489,21 +487,20 @@ const toOfferLegacy = (
minimumQuantity: teaser["<Conditions>k__BackingField"][
"<MinimumQuantity>k__BackingField"
],
parameters:
teaser["<Conditions>k__BackingField"]["<Parameters>k__BackingField"]
.map((parameter) => ({
name: parameter["<Name>k__BackingField"],
value: parameter["<Value>k__BackingField"],
})),
parameters: teaser["<Conditions>k__BackingField"][
"<Parameters>k__BackingField"
].map((parameter) => ({
name: parameter["<Name>k__BackingField"],
value: parameter["<Value>k__BackingField"],
})),
},
effects: {
parameters:
teaser["<Effects>k__BackingField"]["<Parameters>k__BackingField"].map(
(parameter) => ({
name: parameter["<Name>k__BackingField"],
value: parameter["<Value>k__BackingField"],
}),
),
parameters: teaser["<Effects>k__BackingField"][
"<Parameters>k__BackingField"
].map((parameter) => ({
name: parameter["<Name>k__BackingField"],
value: parameter["<Value>k__BackingField"],
})),
},
})),
});
Expand Down Expand Up @@ -552,13 +549,13 @@ export const legacyFacetToFilter = (
values: facets.map((facet) => {
const selected = mapSet.has(facet.Map) && pathSet.has(facet.Value);

return ({
return {
value: facet.Value,
quantity: facet.Quantity,
url: getLink(facet, selected),
label: facet.Name,
selected,
});
};
}),
};
};
Expand Down

0 comments on commit 4680866

Please sign in to comment.