53 lines
1.9 KiB
TypeScript
53 lines
1.9 KiB
TypeScript
import { discountPercent } from "./format";
|
|
import { productHref } from "./slug";
|
|
import { DEMO_PRICING, demoPrice } from "./demoPricing";
|
|
import type { ApiProduct, ProductCardData, StoreSpecial } from "./types";
|
|
|
|
export function productToCard(product: ApiProduct): ProductCardData {
|
|
const base = {
|
|
id: product.id,
|
|
href: productHref(product.id, product.nameFa, product.title),
|
|
title: product.nameFa || product.title,
|
|
image: product.thumbnailUrl || product.image || product.thumbnail,
|
|
};
|
|
|
|
if (product.store.minPrice !== null) {
|
|
return { ...base, price: product.store.minPrice, oldPrice: null, percent: 0, inStock: product.store.inStock };
|
|
}
|
|
|
|
if (DEMO_PRICING) {
|
|
const { price, oldPrice } = demoPrice(product);
|
|
return {
|
|
...base,
|
|
price,
|
|
oldPrice,
|
|
percent: oldPrice ? discountPercent(price, oldPrice) : 0,
|
|
inStock: true,
|
|
};
|
|
}
|
|
|
|
return { ...base, price: null, oldPrice: null, percent: 0, inStock: false };
|
|
}
|
|
|
|
// A curated store-special group carries its own variant pricing, so the
|
|
// discount shown there is the real one rather than a product-level guess.
|
|
export function specialToCards(special: StoreSpecial): ProductCardData[] {
|
|
return special.items
|
|
.filter((item) => item.isActive)
|
|
.map((item) => {
|
|
const variant = item.variants.find((v) => v.discountedPrice !== null) ?? item.variants[0];
|
|
const price = variant?.discountedPrice ?? variant?.price ?? null;
|
|
const oldPrice = variant?.discountedPrice !== null ? variant?.price ?? null : null;
|
|
return {
|
|
id: item.id,
|
|
href: productHref(item.productId, item.productNameFa, item.productTitle),
|
|
title: item.productNameFa || item.productTitle,
|
|
image: item.productImage,
|
|
price,
|
|
oldPrice,
|
|
percent: price !== null && oldPrice !== null ? discountPercent(price, oldPrice) : 0,
|
|
inStock: (variant?.stockQuantity ?? 0) > 0,
|
|
};
|
|
});
|
|
}
|