paxton-front/composables/useProduct.ts
alsaze 7a7d27c7ae
All checks were successful
Deploy / build (push) Successful in 45s
создаю телегу товаров
2025-10-03 19:26:39 +03:00

77 lines
2.7 KiB
TypeScript

import { useGetProductsDetail, useGetProductsVariationsList } from '~/api/queries/wp'
export const useProduct = (variantId) => {
const route = useRoute()
const currentId = ref<number>(route.params.id ?? variantId)
const { data: productsData } = useGetProductsDetail(currentId)
const { data: productsVariationsData } = useGetProductsVariationsList(currentId)
function getAttribute(attributes: string[], name: string) {
return attributes?.find(attribute => attribute?.name === name)
}
const defaultColor = computed(() => getAttribute(productsData?.value?.default_attributes, 'color')?.option)
const defaultMaterial = computed(() => getAttribute(productsData?.value?.default_attributes, 'material')?.option)
const defaultSize = computed(() => getAttribute(productsData?.value?.default_attributes, 'size')?.option)
const defaultVariant = computed(() => {
return productsVariationsData?.value?.find(variation => getAttribute(variation?.attributes, 'color')?.option === defaultColor?.value)
&& productsVariationsData?.value?.find(variation => getAttribute(variation?.attributes, 'material')?.option === defaultMaterial?.value)
})
const colors = computed(() => getAttribute(productsData?.value?.attributes, 'color')?.options)
const materials = computed(() => getAttribute(productsData?.value?.attributes, 'material')?.options)
const sizes = computed(() => getAttribute(productsData?.value?.attributes, 'size')?.options)
const color = computed(() => getAttribute(productsData?.value?.attributes, 'color')?.option)
const material = computed(() => getAttribute(productsData?.value?.attributes, 'material')?.option)
const size = computed(() => getAttribute(productsData?.value?.attributes, 'size')?.option)
function getIdentifier(productVariant) {
const color = getAttribute(productVariant?.attributes, 'color')?.option
const material = getAttribute(productVariant?.attributes, 'material')?.option
return `${color}_${material}`
}
const variations = computed(() =>
colors?.value?.map((color) => {
if (!productsVariationsData?.value) {
return []
}
const productAsColor = productsVariationsData?.value?.filter(variant => getAttribute(variant?.attributes, 'color')?.option === color)
const identifier = getIdentifier(productAsColor[0])
return {
identifier,
image: productsData?.value?.images?.filter(img => img?.src?.includes(`${identifier}_`)),
options: productAsColor,
}
}) ?? [])
return {
productsData,
productsVariationsData,
defaultColor,
defaultMaterial,
defaultSize,
defaultVariant,
colors,
materials,
sizes,
color,
material,
size,
variations,
getAttribute,
getIdentifier,
}
}