139 lines
7.3 KiB
JavaScript
139 lines
7.3 KiB
JavaScript
const { createHash } = require('node:crypto');
|
||
const { fail } = require('./workspace.cjs');
|
||
const BN_DIGITS = '০১২৩৪৫৬৭৮৯';
|
||
|
||
function amount(value) {
|
||
if (typeof value === 'number') return Number.isFinite(value) && value >= 0 ? value : null;
|
||
if (typeof value !== 'number' && typeof value !== 'string') return null;
|
||
const text = String(value).trim().replace(/[০-৯]/g, digit => String(BN_DIGITS.indexOf(digit)));
|
||
if (text.length > 64) return null;
|
||
if (!/^(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(text)) return null;
|
||
const number = Number(text.replace(/,/g, ''));
|
||
return Number.isFinite(number) && number >= 0 ? number : null;
|
||
}
|
||
|
||
function currencyCode(value) {
|
||
return typeof value === 'string' && /^[A-Z]{3}$/.test(value.trim().toUpperCase()) ? value.trim().toUpperCase() : null;
|
||
}
|
||
|
||
function displayPrice(value, currency) {
|
||
if (value === null) return 'দাম পাওয়া যায়নি';
|
||
try {
|
||
return new Intl.NumberFormat('bn-BD', {
|
||
...(currency ? { style: 'currency', currency } : {}), maximumFractionDigits: 6
|
||
}).format(value);
|
||
} catch { return [currency, String(value)].filter(Boolean).join(' '); }
|
||
}
|
||
|
||
function publicLink(value, base) {
|
||
if (typeof value !== 'string' || !value.trim()) return '';
|
||
try {
|
||
const url = new URL(value, base);
|
||
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return '';
|
||
return url.href;
|
||
} catch { return ''; }
|
||
}
|
||
|
||
function product(record, context) {
|
||
for (const [name, maximum] of Object.entries({ title: 1024, sku: 256, sourceId: 8192, brand: 256, link: 4096, image: 4096 })) {
|
||
if (typeof record[name] === 'string' && record[name].length > maximum) {
|
||
throw fail(502, 'SOURCE_FIELD_TOO_LARGE', 'Website-এর product field অতিরিক্ত বড়; আগের catalog বদলায়নি।');
|
||
}
|
||
}
|
||
const price = amount(record.price), regular = amount(record.regular);
|
||
const currency = currencyCode(record.currency);
|
||
const base = context.documentUrl || context.url;
|
||
const link = publicLink(record.link, base) || context.url;
|
||
const sourceId = String(record.sourceId || record.sku || link + ':' + record.title);
|
||
return {
|
||
id: createHash('sha256').update(context.url + '\0' + sourceId).digest('hex'),
|
||
sourceId, sku: typeof record.sku === 'string' ? record.sku : '',
|
||
title: String(record.title || '').trim(),
|
||
brand: typeof record.brand === 'string' ? record.brand : context.name,
|
||
price: displayPrice(price, currency), rawPrice: price, currency,
|
||
regularPrice: regular === null ? '' : displayPrice(regular, currency), rawRegularPrice: regular,
|
||
image: publicLink(record.image, base), link,
|
||
storeName: context.name, storeId: context.id, category: context.category,
|
||
...(typeof record.inStock === 'boolean' ? { inStock: record.inStock } : {})
|
||
};
|
||
}
|
||
|
||
function shopifyProducts(payload, context, currency) {
|
||
if (!Array.isArray(payload?.products)) return [];
|
||
return payload.products.flatMap(item => {
|
||
if (!item || typeof item.title !== 'string' || !item.title.trim()) return [];
|
||
const valid = Array.isArray(item.variants) ? item.variants.filter(v => v && typeof v === 'object') : [];
|
||
const variants = valid.length ? valid : [{}];
|
||
return variants.map((variant, index) => product({
|
||
sourceId: (item.id ?? item.handle ?? item.title) + ':' + (variant.id ?? (variant.sku || variant.title || index)), sku: variant.sku,
|
||
title: item.title + (typeof variant.title === 'string' && variant.title && variant.title !== 'Default Title' ? ' — ' + variant.title : ''),
|
||
brand: item.vendor, price: variant.price, regular: variant.compare_at_price,
|
||
currency: variant.currency || item.currency || currency, image: variant.featured_image?.src || item.images?.[0]?.src || item.image?.src,
|
||
link: item.handle ? '/products/' + encodeURIComponent(item.handle) : context.url,
|
||
inStock: typeof variant.available === 'boolean' ? variant.available : undefined
|
||
}, context));
|
||
});
|
||
}
|
||
|
||
function wooProducts(payload, context) {
|
||
if (!Array.isArray(payload)) return [];
|
||
return payload.filter(item => item && typeof item.name === 'string' && item.name.trim()).map(item => {
|
||
const units = item.prices?.currency_minor_unit;
|
||
const validUnits = typeof units === 'number' && Number.isInteger(units) && units >= 0 && units <= 6;
|
||
function minor(value) {
|
||
const parsed = amount(value);
|
||
return validUnits && parsed !== null ? parsed / (10 ** units) : null;
|
||
}
|
||
const range = item.prices?.price_range;
|
||
const isParent = item.type === 'variable' || (range && typeof range === 'object');
|
||
const mapped = product({
|
||
sourceId: item.id ?? item.permalink, sku: item.sku, title: item.name,
|
||
price: isParent ? null : minor(item.prices?.price), regular: isParent ? null : minor(item.prices?.regular_price),
|
||
currency: item.prices?.currency_code, image: item.images?.[0]?.src,
|
||
link: item.permalink, inStock: item.is_in_stock
|
||
}, context);
|
||
if (isParent) {
|
||
mapped.requiresVariantSelection = true;
|
||
const minimum = minor(range?.min_amount), maximum = minor(range?.max_amount);
|
||
if (minimum !== null && maximum !== null) {
|
||
mapped.priceRange = { minimum, maximum };
|
||
mapped.price = displayPrice(minimum, mapped.currency) + ' – ' + displayPrice(maximum, mapped.currency);
|
||
}
|
||
}
|
||
return mapped;
|
||
});
|
||
}
|
||
|
||
function schemaProducts(payload, context) {
|
||
const products = [], seen = new Set();
|
||
function visit(node, depth = 0) {
|
||
if (!node || typeof node !== 'object' || depth > 20 || seen.has(node)) return;
|
||
seen.add(node);
|
||
if (Array.isArray(node)) { for (const item of node) visit(item, depth + 1); return; }
|
||
const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']];
|
||
if (types.includes('Product') && typeof node.name === 'string' && node.name.trim()) {
|
||
const validOffers = Array.isArray(node.offers) ? node.offers.filter(o => o && typeof o === 'object') : [];
|
||
const offers = validOffers.length ? validOffers : [node.offers && typeof node.offers === 'object' && !Array.isArray(node.offers) ? node.offers : {}];
|
||
for (const [offerIndex, offer] of offers.entries()) {
|
||
const image = Array.isArray(node.image) ? node.image[0] : node.image;
|
||
const isRegularSpecification = offer.priceSpecification?.priceType === 'https://schema.org/StrikethroughPrice';
|
||
products.push(product({
|
||
sourceId: String(node['@id'] || node.sku || node.url || node.name) + ':' + String(offer['@id'] || offer.sku || offer.url || offer.name || offerIndex),
|
||
sku: offer.sku || node.sku, title: node.name + (offers.length > 1 && offer.name ? ' — ' + offer.name : ''),
|
||
brand: typeof node.brand === 'string' ? node.brand : node.brand?.name,
|
||
price: offer.price ?? (isRegularSpecification ? undefined : offer.priceSpecification?.price),
|
||
regular: isRegularSpecification ? offer.priceSpecification?.price : undefined,
|
||
currency: offer.priceCurrency || offer.priceSpecification?.priceCurrency,
|
||
image: typeof image === 'string' ? image : image?.url,
|
||
link: offer.url || node.url
|
||
}, context));
|
||
}
|
||
}
|
||
for (const value of Object.values(node)) if (value && typeof value === 'object') visit(value, depth + 1);
|
||
}
|
||
visit(payload);
|
||
return products;
|
||
}
|
||
|
||
module.exports = { amount, displayPrice, publicLink, product, shopifyProducts, wooProducts, schemaProducts };
|