Files
b2b/bo/src/stores/product.ts
2026-04-01 09:10:38 +02:00

102 lines
2.9 KiB
TypeScript

import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useFetchJson } from '@/composable/useFetchJson'
import type { ProductDescription } from '@/types/product'
export interface Product {
id: number
image: string
name: string
code: string
inStock: boolean
priceFrom: number
priceTo: number
count: number
description?: string
howToUse?: string
productDetails?: string
}
export interface ProductResponse {
items: Product[]
items_count: number
}
export const useProductStore = defineStore('product', () => {
const productDescription = ref()
const currentProduct = ref<Product | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
async function getProductDescription(langId = 1, productID: number) {
loading.value = true
error.value = null
try {
const response = await useFetchJson<ProductDescription>(
`/api/v1/restricted/product-translation/get-product-description?productID=${productID}&productLangID=${langId}`
)
productDescription.value = response.items
} catch (e: unknown) {
error.value = e instanceof Error ? e.message : 'Failed to load product description'
} finally {
loading.value = false
}
}
async function saveProductDescription(productID?: number) {
const id = productID || 1
try {
const data = await useFetchJson(
`/api/v1/restricted/product-description/save-product-description?productID=${id}&productShopID=1&productLangID=1`,
{
method: 'POST',
body: JSON.stringify(
{
description: productDescription.value.description,
description_short: productDescription.value.description_short,
meta_description: productDescription.value.meta_description,
available_now: productDescription.value.available_now,
usage: productDescription.value.usage
})
}
)
return data
} catch (e) {
console.error(e)
}
}
async function translateProductDescription(productID: number, fromLangId: number, toLangId: number) {
loading.value = true
error.value = null
try {
const response = await useFetchJson<ProductDescription>(`/api/v1/restricted/product-description/translate-product-description?productID=${productID}&productShopID=1&productFromLangID=${fromLangId}&productToLangID=${toLangId}&model=OpenAI`)
productDescription.value = response.items
return response.items
} catch (e: any) {
error.value = e?.message || 'Failed to translate product description'
console.error('Failed to translate product description:', e)
} finally {
loading.value = false
}
}
function clearCurrentProduct() {
currentProduct.value = null
}
return {
productDescription,
currentProduct,
loading,
error,
getProductDescription,
clearCurrentProduct,
saveProductDescription,
translateProductDescription,
}
})