/** * WooCommerce Formatting Utilities * * Follows WooCommerce formatting patterns for prices, weights, dimensions */ export interface WCSettings { currency_symbol: string; currency_position: 'left' | 'right' | 'left_space' | 'right_space'; price_decimals: number; price_decimal_separator: string; price_thousand_separator: string; weight_unit: string; dimension_unit: string; } /** * Format price according to WooCommerce settings */ export function formatPrice(value: number | string | null | undefined, wcSettings: WCSettings): string { if (value === null || value === undefined || value === '') return '-'; const numValue = typeof value === 'string' ? parseFloat(value) : value; if (isNaN(numValue)) return '-'; // Format number with decimals const decimals = wcSettings.price_decimals; const decimalSep = wcSettings.price_decimal_separator; const thousandSep = wcSettings.price_thousand_separator; const parts = numValue.toFixed(decimals).split('.'); const integerPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandSep); const decimalPart = decimals > 0 ? decimalSep + parts[1] : ''; const formattedNumber = integerPart + decimalPart; // Add currency symbol based on position const symbol = wcSettings.currency_symbol; switch (wcSettings.currency_position) { case 'left': return `${symbol}${formattedNumber}`; case 'right': return `${formattedNumber}${symbol}`; case 'left_space': return `${symbol} ${formattedNumber}`; case 'right_space': default: return `${formattedNumber} ${symbol}`; } } /** * Format price range (for parent products) */ export function formatPriceRange(min: number, max: number, wcSettings: WCSettings): string { if (min === max) { return formatPrice(min, wcSettings); } return `${formatPrice(min, wcSettings)}-${formatPrice(max, wcSettings)}`; } /** * Format weight with unit */ export function formatWeight(value: number | string | null | undefined, wcSettings: WCSettings): string { if (value === null || value === undefined || value === '') return '-'; const numValue = typeof value === 'string' ? parseFloat(value) : value; if (isNaN(numValue)) return '-'; return `${numValue} ${wcSettings.weight_unit}`; } /** * Format dimension with unit */ export function formatDimension(value: number | string | null | undefined, wcSettings: WCSettings): string { if (value === null || value === undefined || value === '') return '-'; const numValue = typeof value === 'string' ? parseFloat(value) : value; if (isNaN(numValue)) return '-'; return `${numValue} ${wcSettings.dimension_unit}`; } /** * Decode HTML entities (e.g., $ → $) */ export function decodeHTMLEntities(text: string): string { const textarea = document.createElement('textarea'); textarea.innerHTML = text; return textarea.value; }