freshyo/packages/db_helper_sqlite/src/lib/sku-features.ts
2026-08-02 10:03:21 +05:30

44 lines
1.4 KiB
TypeScript

export interface SkuFeatureLike {
featureName?: string | null
featureValue: string
}
export const cleanFeatureValue = (value: string): string =>
value.replace(/\.0(?=\D|$)/g, '')
export function splitQuantityFeature(features: SkuFeatureLike[]): {
quantity: string
others: string[]
} {
if (!features || features.length === 0) {
return { quantity: '', others: [] }
}
const quantityFeature = features.find((f) => f.featureName === 'quantity')
const otherFeatures = features.filter((f) => f.featureName !== 'quantity')
return {
quantity: quantityFeature ? cleanFeatureValue(quantityFeature.featureValue) : '',
others: otherFeatures.map((f) => cleanFeatureValue(f.featureValue)),
}
}
/**
* Builds the unit notation for a SKU: the quantity feature value only.
* Falls back to joining all feature values when no quantity feature exists.
*/
export function composeUnitNotation(features: SkuFeatureLike[]): string {
const { quantity, others } = splitQuantityFeature(features)
if (quantity) return quantity
if (others.length > 0) return others.join(' ')
return ''
}
/**
* Builds the display name for a SKU: the product name followed by the
* values of all non-quantity features (values only).
*/
export function composeSkuName(baseName: string, features: SkuFeatureLike[]): string {
const { others } = splitQuantityFeature(features)
return [baseName, ...others].filter(Boolean).join(' ')
}