fix kashkool

This commit is contained in:
2026-06-29 22:43:28 +03:30
parent be17631109
commit 8b855e5ee4
150 changed files with 11974 additions and 4445 deletions
@@ -262,11 +262,12 @@ import type { Transaction } from '@/models/transaction'
import type { TableEngineInput, TableOutput } from '@/models/table'
import { getTransactionTable } from '@/api/transaction'
import { getLastPrices, lastPrice } from '@/utils/price'
import { getProductBaseBuyPrice, getProductBaseSellPrice } from '@/utils/productPrice'
import { Product } from '@/models/products'
import BasicSelect from '@/components/BasicPacks/BasicSelect.vue'
import { SelectItem } from '@/models/SelectItem'
import Bg_main from '@/components/bg_main.vue'
import { useFundUserStore } from '@/store/fundStore'
import { useWalletAssets } from '@/composables/useWalletAssets'
import { useCartStore } from '@/store/cartStore'
const typeDeal: SelectItem[] = [
@@ -295,7 +296,7 @@ const sellItems = ref<Transaction[]>([])
const priceErrorVisible = ref<boolean>(false)
const buyTableOutput = ref<TableOutput<Transaction> | null>(null)
const sellTableOutput = ref<TableOutput<Transaction> | null>(null)
const fundStore = useFundUserStore()
const { loadWalletAssets } = useWalletAssets()
const refInput = ref<FormInstance>()
const el = ref()
@@ -653,18 +654,9 @@ const price = computed((): Price => <Price>lastPrice.value ?? 0)
async function initPrice() {
try {
// chartLoading.value = true
await getLastPrices()
// await setIntervalGetPrice()
loading.value = true
price.value = lastPrice.value
props.ProductItem.price = lastPrice.value?.buy * props.ProductItem?.amount
props.ProductItem.sellPrice = lastPrice.value?.sell * props.ProductItem?.amount
} catch (e) {
console.log(e)
} finally {
loading.value = false
// chartLoading.value = false
}
}
@@ -715,7 +707,9 @@ async function ok() {
infoVisible.value = true
const data = await createOrder({
direction: isBuy.value ? 1 : 2,
price: isBuy.value ? price.value?.buy : price.value?.sell,
price: isBuy.value
? getProductBaseBuyPrice(props.ProductItem)
: getProductBaseSellPrice(props.ProductItem),
amount: form.value.goldValue ?? 0,
gateway: form.value.gateway,
product_id: props.ProductItem.id,
@@ -753,7 +747,7 @@ async function ok() {
}
// refreshTable()
message.success('سفارش شما با موفقیت انجام شد')
await fundStore.getMyFund()
await loadWalletAssets(true)
} catch (e) {
// console.log(e)
// await initPrice()
@@ -94,7 +94,7 @@
</div>
<div class="mt-2 !text-primary text-sm font-bold">
{{ usePrice((props.ProductItem.price ?? 0) + (props.ProductItem.cash_fee_buy ?? 0)) }}
{{ usePrice(getProductBuyPrice(props.ProductItem)) }}
</div>
</div>
</div>
@@ -104,6 +104,7 @@
import { computed } from 'vue'
import type { Product } from '@/models/products'
import { usePrice } from '@/utils/usePrice'
import { getProductBuyPrice } from '@/utils/productPrice'
import ProductImage from '@/components/ProductImage.vue'
interface Props {
@@ -27,7 +27,7 @@
</div>
<div class="mt-auto !text-primary text-sm font-bold">
{{ usePrice((props.ProductItem.price ?? 0) + (props.ProductItem.cash_fee_buy ?? 0)) }}
{{ usePrice(getProductBuyPrice(props.ProductItem)) }}
</div>
</div>
</template>
@@ -36,6 +36,7 @@
import { computed } from 'vue'
import type { Product } from '@/models/products'
import { usePrice } from '@/utils/usePrice'
import { getProductBuyPrice } from '@/utils/productPrice'
import ProductImage from '@/components/ProductImage.vue'
interface Props {
@@ -0,0 +1,193 @@
import { ref, watch } from 'vue'
import { getProductsCatalog, getProductsCatalogRef } from '@/composables/useProductsCatalog'
import type { Product } from '@/models/products'
import { loadProductCategoryTabNames } from '@/utils/categoryTabs'
import { getLastPrices, startLastPricePolling, stopLastPricePolling } from '@/utils/price'
import {
priceSocketConnected,
priceStreamLifecycle,
priceWssEnabled,
shouldUsePricePolling,
} from '@/utils/priceSocketState'
import { subscribeProductListStream } from '@/utils/productStreamBridge'
let initPromise: Promise<void> | null = null
let productListInterval: ReturnType<typeof setInterval> | undefined
let providerMountCount = 0
let pricePollingMountCount = 0
let unsubscribeProductStream: (() => void) | undefined
const initialized = ref(false)
export const productsActiveKey = ref('همه')
export const productsTypeItems = ref<string[]>([])
export const productsFirstItems = ref<Product[]>()
export const productsItems = ref<Product[]>()
export const productsPageLoading = ref(true)
function sortProductsByInventory(products: Product[]) {
return [...products].sort((a, b) => {
const aInStock = Number(a.inventory ?? 0) > 0 ? 0 : 1
const bInStock = Number(b.inventory ?? 0) > 0 ? 0 : 1
if (aInStock !== bInStock) return aInStock - bInStock
return Number(b.inventory ?? 0) - Number(a.inventory ?? 0)
})
}
export function changeProductsTab() {
if (productsActiveKey.value !== 'همه') {
productsItems.value = productsFirstItems.value?.filter(
(val) => val.group_type === productsActiveKey.value,
)
} else {
productsItems.value = productsFirstItems.value
}
}
async function loadCategoryTabs() {
try {
productsTypeItems.value = await loadProductCategoryTabNames()
} catch (error) {
console.error('Product category tabs error:', error)
productsTypeItems.value = []
}
}
function applyProductsList(products: Product[]) {
const sorted = sortProductsByInventory(products)
productsFirstItems.value = sorted
changeProductsTab()
productsPageLoading.value = false
}
export async function refreshProductsPageData() {
try {
const fresh = await getProductsCatalog(true)
if (!fresh?.length) return
applyProductsList(fresh)
} catch (error) {
console.error('Products refresh error:', error)
}
}
export function applyProductsListFromSocket(products: Product[]) {
if (!products?.length) {
return
}
getProductsCatalogRef().value = products
applyProductsList(products)
}
function startProductListPolling() {
if (productListInterval || !shouldUsePricePolling()) {
return
}
productListInterval = setInterval(() => {
if (shouldUsePricePolling()) {
void refreshProductsPageData()
}
}, 10000)
}
function stopProductListPolling() {
if (productListInterval) {
clearInterval(productListInterval)
productListInterval = undefined
}
}
function syncProductListPolling() {
if (shouldUsePricePolling()) {
if (initialized.value) {
startProductListPolling()
}
return
}
stopProductListPolling()
}
watch(
() => [priceWssEnabled.value, priceSocketConnected.value, priceStreamLifecycle.value] as const,
() => {
syncProductListPolling()
if (shouldUsePricePolling() && initialized.value && !productsFirstItems.value?.length) {
void refreshProductsPageData()
}
},
)
export function onProductsPageProviderMounted() {
providerMountCount += 1
pricePollingMountCount += 1
unsubscribeProductStream = subscribeProductListStream(applyProductsListFromSocket)
if (pricePollingMountCount === 1) {
if (shouldUsePricePolling()) {
void getLastPrices()
}
startLastPricePolling()
}
}
export function onProductsPageProviderUnmounted() {
unsubscribeProductStream?.()
unsubscribeProductStream = undefined
providerMountCount = Math.max(0, providerMountCount - 1)
pricePollingMountCount = Math.max(0, pricePollingMountCount - 1)
if (pricePollingMountCount === 0) {
stopLastPricePolling()
}
if (providerMountCount === 0) {
stopProductListPolling()
}
}
export async function initProductsPageData(force = false) {
if (!force && initialized.value) {
syncProductListPolling()
if (productsFirstItems.value?.length) {
productsPageLoading.value = false
}
return
}
if (!force && initPromise) {
return initPromise
}
initPromise = (async () => {
try {
if (!productsFirstItems.value?.length) {
productsPageLoading.value = true
}
await loadCategoryTabs()
// stream-first: polling فقط وقتی SSE قطع/غیرفعال است
if (shouldUsePricePolling()) {
await refreshProductsPageData()
}
initialized.value = true
syncProductListPolling()
} catch (error) {
console.error('Products page initialization error:', error)
} finally {
// اگر استریم قبل از init لیست را داده، loading را دوباره true نکرده‌ایم؛
// اگر API/polling تمام شد یا محصول داریم، اسپینر را قطع کن.
if (productsFirstItems.value?.length || shouldUsePricePolling()) {
productsPageLoading.value = false
}
initPromise = null
}
})()
return initPromise
}
+41 -169
View File
@@ -1,15 +1,16 @@
<template>
<div class="bottom-0 fixed top-0 -z-10 pointer-events-none">
<img :src="img" alt="" class=" w-inherit "
:style="{ backgroundRepeat: 'repeat', }"
/>
</div>
<a-spin :spinning="loading">
<div :class="isDesktop ? 'dpage products-page' : ''">
<div class="bottom-0 fixed top-0 -z-10 pointer-events-none">
<img :src="img" alt="" class=" w-inherit "
:style="{ backgroundRepeat: 'repeat', }"
/>
</div>
<a-spin :spinning="productsPageLoading">
<div class="relative z-0 !h-full overflow-y-scroll">
<div class="w-full flex justify-center top-0 py-5" style="align-self: center">
<ARadioGroup @change="changeTab" v-model:value="activekey" button-style="solid">
<ARadioGroup @change="changeProductsTab" v-model:value="productsActiveKey" button-style="solid">
<ARadioButton class="cats" value="همه">همه</ARadioButton>
<ARadioButton class="cats" v-for="item in typeItems" :value="item">{{ item }}</ARadioButton>
<ARadioButton class="cats" v-for="item in productsTypeItems" :key="item" :value="item">{{ item }}</ARadioButton>
</ARadioGroup>
</div>
<div class="mx-5 flex justify-end" @click="viewVertical=!viewVertical">
@@ -20,7 +21,7 @@
<div class="mx-5 pb-30 pt-2 grid grid-cols-2 gap-3 items-stretch">
<template v-if="viewVertical">
<ProductItemVertical
v-for="item in items"
v-for="item in productsItems"
:key="item.id"
class="h-full"
:ProductItem="item"
@@ -29,7 +30,7 @@
</template>
<template v-else>
<ProductItem
v-for="item in items"
v-for="item in productsItems"
:key="item.id"
class="col-span-2 h-full"
:ProductItem="item"
@@ -40,9 +41,6 @@
</div>
</a-spin>
<!-- <BasicActionSheet v-model:show="showFilter">-->
<!-- <indexGold ></indexGold>-->
<!-- </BasicActionSheet>-->
<BasicActionSheet placement="bottom" v-model:show="showFilter">
<div class="">
@@ -51,191 +49,65 @@
</div>
</BasicActionSheet>
</div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { onMounted, onUnmounted, ref } from 'vue'
import { useDesktopBreakpoint } from '@/layouts/composables/useAppLayout'
import router from '@/router'
import ProductItem from '@/views/base/products/components/ProductItem.vue'
import { getProducts } from '@/api/products'
import {
getLastPrices,
lastPrice,
stopPriceInterval,
setIntervalGetLastPrice
} from '@/utils/price'
import { loading, getToken } from '@/utils'
import { Price } from '@/models/home'
import type { Product } from '@/models/products'
import BasicActionSheet from '@/components/BasicPacks/BasicActionSheet.vue'
import indexGold from '@/views/base/gold/index.vue'
import DealProduct from '@/views/base/products/components/DealProduct.vue'
import { cloneDeep } from 'lodash'
import img from "@/assets/img/user_ly1.svg";
import { message } from 'ant-design-vue'
import BasicButton from "@/App.vue";
import BasicIcon from "@/components/BasicPacks/BasicIcon.vue";
import ProductItemVertical from "@/views/base/products/components/ProductItemVertical.vue";
import { loadProductCategoryTabNames } from '@/utils/categoryTabs'
import { subscribeProductListStream } from '@/utils/productStreamBridge'
import { isProductVisible } from '@/utils/productPrice'
import {
productsActiveKey,
productsTypeItems,
productsItems,
productsPageLoading,
changeProductsTab,
initProductsPageData,
onProductsPageProviderMounted,
onProductsPageProviderUnmounted,
} from '@/views/base/products/composables/useProductsPageData'
const activekey = ref('همه')
const showFilter = ref()
const selectedProduct = ref<Product>()
const viewVertical = ref(true)
const isDesktop = useDesktopBreakpoint()
function clickProduct(item: Product) {
if(item?.show){
// Navigate to product detail page
if (isProductVisible(item)) {
router.push({ name: 'productDetail', params: { id: item.id } })
}
}
function changeTab() {
if (activekey.value != 'همه') {
items.value = firstItems.value?.filter((val) =>
val.group_type == activekey.value
)
} else items.value = firstItems.value
}
function sortProductsByInventory(products: Product[] | undefined) {
if (!products?.length) return products ?? []
return [...products].sort((a, b) => {
const aInStock = Number(a.inventory ?? 0) > 0 ? 0 : 1
const bInStock = Number(b.inventory ?? 0) > 0 ? 0 : 1
if (aInStock !== bInStock) return aInStock - bInStock
return Number(b.inventory ?? 0) - Number(a.inventory ?? 0)
})
}
async function loadCategoryTabs() {
try {
typeItems.value = await loadProductCategoryTabNames()
} catch (e) {
console.log(e)
typeItems.value = []
}
}
const firstItems = ref<Product[]>()
const price = ref<Price>()
const items = ref<Product[]>()
const typeItems = ref([])
let unsubscribeProductStream: (() => void) | undefined
function applyStreamProducts(products: Product[]) {
const sorted = sortProductsByInventory(products)
firstItems.value = sorted
changeTab()
applyLivePricesToProducts(items.value)
applyLivePricesToProducts(firstItems.value)
}
onMounted(async () => {
unsubscribeProductStream = subscribeProductListStream(applyStreamProducts)
onProductsPageProviderMounted()
await initProductsPageData()
try {
loading.value = true
const products = sortProductsByInventory(await getProducts())
items.value = products
firstItems.value = products
await loadCategoryTabs()
await initPrice()
// await setIntervalGetLastPrice()
// console.log('run product')
} catch (e: any) {
console.log(e)
// If 401 error, set empty items to show page without products
if (e?.response?.status === 401) {
items.value = []
firstItems.value = []
typeItems.value = []
}
} finally {
loading.value = false
if (router.currentRoute.value.query.cat=="coin"){
activekey.value="سکه"
changeTab()
}
if (router.currentRoute.value.query.state) {
if (router.currentRoute.value.query.product) {
clickProduct(items.value?.find(x => x.title === 'سکه'))
} else {
clickProduct(items.value?.find(x => x.title === 'آبشده نقدی'))
}
}
}
})
onUnmounted(() => {
unsubscribeProductStream?.()
stopPriceInterval()
})
function applyLivePricesToProducts(products: Product[] | undefined) {
if (!lastPrice.value || !products?.length) {
return
if (router.currentRoute.value.query.cat === 'coin') {
productsActiveKey.value = 'سکه'
changeProductsTab()
}
products.forEach((val) => {
if (val.group_type == 'آبشده') {
val.price = parseInt(String(lastPrice.value?.price_last ?? 0))
val.sellPrice = parseInt(String(lastPrice.value?.sell ?? 0))
if (router.currentRoute.value.query.state) {
if (router.currentRoute.value.query.product) {
clickProduct(productsItems.value?.find((x) => x.title === 'سکه'))
} else {
val.price = parseInt(String(val.amount * lastPrice.value?.price_last))
val.sellPrice = parseInt(String(val.amount * lastPrice.value?.sell))
clickProduct(productsItems.value?.find((x) => x.title === 'آبشده نقدی'))
}
syncProductShow(val)
})
}
/** show از API سرور — بعد از محاسبه قیمت زنده فقط اگر غیرفعال یا قیمت صفر باشد خاموش می‌شود */
function syncProductShow(product: Product) {
if (!product.active) {
product.show = false
return
}
})
const displayPrice = Number(product.price ?? 0) + Number(product.cash_fee_buy ?? 0)
if (displayPrice > 0) {
product.show = true
return
}
product.show = Number(lastPrice.value?.price_last ?? 0) > 0
}
watch(lastPrice, () => {
applyLivePricesToProducts(items.value)
applyLivePricesToProducts(firstItems.value)
}, { deep: true })
async function initPrice() {
try {
// chartLoading.value = true
await getLastPrices()
await setIntervalGetLastPrice()
loading.value = true
price.value = lastPrice.value
applyLivePricesToProducts(items.value)
applyLivePricesToProducts(firstItems.value)
} catch (e: any) {
console.log(e)
// If 401 error, just skip price initialization
if (e?.response?.status === 401) {
// Price will not be available, but page can still be shown
price.value = undefined
}
} finally {
loading.value = false
// chartLoading.value = false
}
}
onUnmounted(() => {
onProductsPageProviderUnmounted()
})
</script>
<style lang="less">
@@ -247,4 +119,4 @@ async function initPrice() {
color: rgba(206, 163, 76, var(--un-text-opacity))!important;
}
</style>
</style>
+18 -258
View File
@@ -1,271 +1,31 @@
<template>
<div class="bottom-0 fixed top-0">
<img :src="img" alt="" class="w-inherit" :style="{ backgroundRepeat: 'repeat' }"/>
<div class="product-detail-page-root">
<DesktopProductDetailView v-show="isDesktop" />
<MobileProductDetailView v-show="!isDesktop" />
<BasicActionSheet placement="bottom" v-model:show="showFilter">
<indexGold v-if="product?.group_type == 'آبشده'" :ProductItem="product" />
<DealProduct v-else :ProductItem="product" @close="showFilter = false" />
</BasicActionSheet>
</div>
<a-spin :spinning="loading">
<div class="!h-full overflow-y-scroll">
<div class="mx-5 pb-30 pt-5" style="color: #1b2b07">
<!-- Product Image -->
<div class="bg-gray-100 rounded-lg w-full flex justify-center mb-4">
<ProductImage
:product="product"
:dimmed="isOutOfStock"
img-class="max-w-full h-auto"
/>
</div>
<!-- Product Title -->
<div class="text-2xl font-bold mb-4">{{ product?.title }}</div>
<div class=" flex items-center justify-between mb-4 gap-4">
<!-- Product Price -->
<div class="text-xl font-semibold text-primary">
{{ usePrice((product?.price ?? 0) + (product?.cash_fee_buy ?? 0)) }}
</div>
<div class="flex-1">
<!-- Buy Button -->
<BasicButton
v-if="product?.show && product?.open_buy &&(product?.inventory || product?.inventory >0)"
class="w-full py-3 "
type="primary"
size="large"
@click="handleBuyClick"
>
خرید محصول
</BasicButton>
<div v-else-if="!product?.show" class="text-center text-gray-500 py-4">
این محصول در حال حاضر در دسترس نیست
</div>
<div v-else-if="!product?.open_buy" class="text-center text-gray-500 py-4">
خرید این محصول در حال حاضر امکان پذیر نیست
</div>
<div v-else-if="!product?.inventory || product?.inventory==0" class="text-center text-gray-500 py-4">
ناموجود
</div>
</div>
</div>
<!-- Product Description -->
<div v-if="product?.description" class="mb-6">
<div class="text-lg font-semibold mb-2">توضیحات محصول:</div>
<div class="text-base text-gray-700 whitespace-pre-line">{{ product?.description }}</div>
<!-- <div class="text-base text-gray-700 whitespace-pre-line">شمش طلای نقش برجسته ونوس ۱ گرمی انتخابی ظریف و ارزشمند برای سرمایه‌گذاری و هدیه است. این شمش از طلای خالص با عیار بالا ساخته شده و نقش برجسته‌ی الهه ونوس، نمادی از زیبایی و ظرافت، جلوه‌ای هنری و خاص به آن بخشیده است. وزن دقیق ۱ گرم، ابعاد مناسب و بسته‌بندی شکیل، این محصول را به گزینه‌ای ایده‌آل برای نگهداری ارزش، هدیه‌های خاص و کلکسیون‌های طلا تبدیل می‌کند. </div>-->
</div>
<!-- Similar Products -->
<div v-if="product?.similar?.length" class="mt-8">
<div class="text-lg font-semibold mb-4">محصولات مشابه</div>
<swiper
:slides-per-view="2.25"
:space-between="16"
class="similar-products-swiper"
>
<swiper-slide
v-for="item in product.similar"
:key="item.id"
>
<div
class="bg-white rounded-lg shadow p-4 cursor-pointer h-full"
@click="goToProduct(item.id)"
>
<!-- Image -->
<div class="bg-gray-100 rounded-md flex justify-center p-4 mb-2">
<ProductImage
:product="item"
:dimmed="!item.inventory || item.inventory === 0"
img-class="h-20 object-contain"
/>
</div>
<!-- Title -->
<div class="text-sm font-semibold mb-1 line-clamp-2">
{{ item.title }}
</div>
<!-- Price -->
<div class="text-sm text-primary font-bold mb-3">
{{ usePrice((item.price ?? 0) + (item.cash_fee_buy ?? 0)) }}
</div>
<span
v-if="item.inventory || item.inventory==0"
class="text-xs bg-gray-300 text-gray-600 px-1 py-0.5 rounded-md "
>
ناموجود
</span>
</div>
</swiper-slide>
</swiper>
</div>
</div>
</div>
</a-spin>
<!-- Basic Action Sheet for Buy -->
<BasicActionSheet placement="bottom" v-model:show="showFilter">
<div class="">
<indexGold v-if="product?.group_type == 'آبشده'" :ProductItem="product"></indexGold>
<DealProduct v-else :ProductItem="product" @close="showFilter = false"></DealProduct>
</div>
</BasicActionSheet>
</template>
<script setup lang="ts">
import {onMounted, onUnmounted, ref, computed, watch} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {getProductById, getProducts} from '@/api/products'
import {loading, getToken} from '@/utils'
import type {Product} from '@/models/products'
<script lang="ts" setup>
import { useDesktopBreakpoint } from '@/layouts/composables/useAppLayout'
import BasicActionSheet from '@/components/BasicPacks/BasicActionSheet.vue'
import indexGold from '@/views/base/gold/index.vue'
import DealProduct from '@/views/base/products/components/DealProduct.vue'
import {cloneDeep} from 'lodash'
import img from '@/assets/img/user_ly1.svg'
import {message} from 'ant-design-vue'
import BasicButton from '@/components/BasicPacks/BasicButton.vue'
import {usePrice} from '@/utils/usePrice'
import {
getLastPrices,
lastPrice,
stopPriceInterval
} from '@/utils/price'
import {Swiper, SwiperSlide} from 'swiper/vue'
import 'swiper/swiper-bundle.css'
import ProductImage from '@/components/ProductImage.vue'
const route = useRoute()
const router = useRouter()
const product = ref<Product>()
const showFilter = ref(false)
const productId = computed(() => {
const id = route.params.id
return typeof id === 'string' ? parseInt(id) : id
})
const isOutOfStock = computed(
() => !product.value?.inventory || product.value.inventory === 0
)
watch(
() => productId.value,
(newId, oldId) => {
if (newId && newId !== oldId) {
loadProduct()
window.scrollTo({top: 0, behavior: 'smooth'})
}
}
)
async function loadProduct() {
try {
loading.value = true
// const products = await getProducts()
const products = await getProductById(Number(productId.value))
const foundProduct = products
if (!foundProduct) {
message.error('محصول یافت نشد')
router.push({name: 'buyProduct'})
return
}
product.value = foundProduct
await initPrice()
} catch (e: any) {
console.log(e)
if (e?.response?.status === 401) {
message.warning('برای مشاهده محصولات، لطفا ابتدا وارد حساب کاربری خود شوید')
router.push({name: 'login'})
} else {
message.error('خطا در بارگذاری محصول')
}
} finally {
loading.value = false
}
}
watch(lastPrice, async () => {
// console.log(items);
if (lastPrice.value && product.value.similar) {
product.value.similar.forEach((val) => {
// console.log(lastPrice.value)
if (val.group_type == 'آبشده') {
val.price = lastPrice.value?.price_last
val.sellPrice = lastPrice.value?.sell
} else {
val.price = parseInt(val.amount * lastPrice.value?.price_last)
val.sellPrice = parseInt(val.amount * lastPrice.value?.sell)
// console.log(lastPrice.value?.price_last + "*" + val.amount + ' ' + val.price)
}
})
}
}, {deep: true})
async function initPrice() {
try {
await getLastPrices()
loading.value = true
if (lastPrice.value && product.value) {
if (product.value.group_type == 'آبشده') {
product.value.price = parseInt(lastPrice.value?.price_last)
product.value.sellPrice = parseInt(lastPrice.value?.sell)
} else {
product.value.price = parseInt(product.value.amount * lastPrice.value?.price_last)
product.value.sellPrice = parseInt(product.value.amount * lastPrice.value?.sell)
}
}
} catch (e: any) {
console.log(e)
} finally {
loading.value = false
}
}
function handleBuyClick() {
if (!product.value?.show) {
return
}
// // Check if user is logged in
// if (!getToken()) {
// message.warning('برای خرید یا فروش محصولات، لطفا ابتدا وارد حساب کاربری خود شوید')
// router.push({ name: 'login' })
// return
// }
//
showFilter.value = true
product.value = cloneDeep(product.value)
}
onMounted(() => {
loadProduct()
})
onUnmounted(() => {
stopPriceInterval()
})
function goToProduct(id: number) {
router.push({name: 'productDetail', params: {id}})
}
import { useProductDetailPage } from './composables/useProductDetailPage'
import DesktopProductDetailView from './desktop/DesktopProductDetailView.vue'
import MobileProductDetailView from './mobile/MobileProductDetailView.vue'
const isDesktop = useDesktopBreakpoint()
const { product, showFilter } = useProductDetailPage()
</script>
<style scoped>
.text-primary {
color: #d3a233;
}
.similar-products-swiper {
padding-bottom: 10px;
}
.similar-products-swiper :deep(.swiper-slide) {
height: auto;
.product-detail-page-root {
min-height: 100%;
height: 100%;
}
</style>
@@ -0,0 +1,104 @@
import { computed, inject, onMounted, onUnmounted, provide, ref, watch, type InjectionKey } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { cloneDeep } from 'lodash'
import { getProductById } from '@/api/products'
import { findProductInCatalog, getProductsCatalog } from '@/composables/useProductsCatalog'
import { getLastPrices, stopPriceInterval } from '@/utils/price'
import { getProductBuyPrice } from '@/utils/productPrice'
import { loading } from '@/utils'
import type { Product } from '@/models/products'
export interface ProductDetailPageContext {
product: ReturnType<typeof ref<Product | undefined>>
showFilter: ReturnType<typeof ref<boolean>>
isOutOfStock: ReturnType<typeof computed<boolean>>
handleBuyClick: () => void
goToProduct: (id: number) => void
getProductBuyPrice: typeof getProductBuyPrice
}
export const PRODUCT_DETAIL_PAGE_CONTEXT_KEY: InjectionKey<ProductDetailPageContext> =
Symbol('productDetailPageContext')
export function useProductDetailPage() {
const route = useRoute()
const router = useRouter()
const product = ref<Product>()
const showFilter = ref(false)
const productId = computed(() => {
const id = route.params.id
return typeof id === 'string' ? parseInt(id) : Number(id)
})
const isOutOfStock = computed(() => !product.value?.inventory || product.value.inventory === 0)
watch(productId, (newId, oldId) => {
if (newId && newId !== oldId) {
void loadProduct()
window.scrollTo({ top: 0, behavior: 'smooth' })
}
})
async function loadProduct() {
try {
loading.value = true
await getProductsCatalog()
let foundProduct = findProductInCatalog(Number(productId.value))
if (!foundProduct) foundProduct = await getProductById(Number(productId.value))
if (!foundProduct) {
message.error('محصول یافت نشد')
await router.push({ name: 'buyProduct' })
return
}
product.value = foundProduct
await getLastPrices()
} catch (e: any) {
if (e?.response?.status === 401) {
message.warning('برای مشاهده محصولات، لطفا ابتدا وارد حساب کاربری خود شوید')
await router.push({ name: 'login' })
} else {
message.error('خطا در بارگذاری محصول')
}
} finally {
loading.value = false
}
}
function handleBuyClick() {
if (!product.value?.show) return
showFilter.value = true
product.value = cloneDeep(product.value)
}
function goToProduct(id: number) {
router.push({ name: 'productDetail', params: { id } })
}
onMounted(() => {
void loadProduct()
})
onUnmounted(() => {
stopPriceInterval()
})
const context: ProductDetailPageContext = {
product,
showFilter,
isOutOfStock,
handleBuyClick,
goToProduct,
getProductBuyPrice,
}
provide(PRODUCT_DETAIL_PAGE_CONTEXT_KEY, context)
return context
}
export function useProductDetailPageContext() {
const context = inject(PRODUCT_DETAIL_PAGE_CONTEXT_KEY)
if (!context) throw new Error('useProductDetailPageContext must be used within useProductDetailPage')
return context
}
@@ -0,0 +1,113 @@
<template>
<div class="dinner product-detail-page">
<div class="dinner__container">
<DesktopPageTopbar :title="product?.title ?? 'جزئیات محصول'" show-back sticky />
<a-spin :spinning="loading">
<div v-if="product" class="dproduct-grid">
<div class="dinner-surface dproduct-gallery">
<ProductImage
:product="product"
:dimmed="isOutOfStock"
img-class="max-w-full max-h-[320px] object-contain"
/>
</div>
<div class="dproduct-info">
<div class="dinner-surface dproduct-info__panel">
<div class="dproduct-info__price-row">
<span class="dproduct-info__price">{{ usePrice(getProductBuyPrice(product)) }}</span>
<BasicButton
v-if="product.show && product.open_buy && product.inventory"
type="primary"
size="large"
@click="handleBuyClick"
>
خرید محصول
</BasicButton>
<div v-else-if="!product.show" class="text-gray-500">این محصول در حال حاضر در دسترس نیست</div>
<div v-else-if="!product.open_buy" class="text-gray-500">خرید این محصول در حال حاضر امکان پذیر نیست</div>
<div v-else class="text-gray-500">ناموجود</div>
</div>
</div>
<div v-if="product.description" class="dinner-surface dproduct-info__desc">
<h3 class="font-semibold mb-3">توضیحات محصول:</h3>
<div class="whitespace-pre-line">{{ product.description }}</div>
</div>
<div v-if="product.similar?.length" class="dinner-surface p-5">
<h3 class="font-semibold mb-4">محصولات مشابه</h3>
<div class="dproduct-similar-grid">
<article
v-for="item in product.similar"
:key="item.id"
class="dproduct-similar-card"
@click="goToProduct(item.id)"
>
<div class="dproduct-similar-card__image">
<ProductImage
:product="item"
:dimmed="!item.inventory"
img-class="h-20 object-contain"
/>
</div>
<div class="text-sm font-semibold line-clamp-2">{{ item.title }}</div>
<div class="text-sm text-primary font-bold">{{ usePrice(getProductBuyPrice(item)) }}</div>
</article>
</div>
</div>
</div>
</div>
</a-spin>
</div>
</div>
</template>
<script lang="ts" setup>
import BasicButton from '@/components/BasicPacks/BasicButton.vue'
import ProductImage from '@/components/ProductImage.vue'
import DesktopPageTopbar from '@/layouts/components/DesktopPageTopbar.vue'
import { loading } from '@/utils'
import { usePrice } from '@/utils/usePrice'
import { useProductDetailPageContext } from '../composables/useProductDetailPage'
const { product, isOutOfStock, handleBuyClick, goToProduct, getProductBuyPrice } = useProductDetailPageContext()
</script>
<style scoped>
.dproduct-info__panel {
padding: 20px;
}
.dproduct-similar-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 12px;
}
.dproduct-similar-card {
padding: 12px;
border: 1px solid rgba(15, 23, 42, 0.06);
border-radius: 12px;
cursor: pointer;
transition: box-shadow 0.15s ease;
&:hover {
box-shadow: 0 4px 12px rgba(15, 23, 42, 0.08);
}
&__image {
display: flex;
justify-content: center;
padding: 12px;
background: #f9fafb;
border-radius: 8px;
margin-bottom: 8px;
}
}
.text-primary {
color: #d3a233;
}
</style>
@@ -0,0 +1,92 @@
<template>
<div>
<div class="bottom-0 fixed top-0">
<img :src="img" alt="" class="w-inherit" :style="{ backgroundRepeat: 'repeat' }" />
</div>
<a-spin :spinning="loading">
<div class="!h-full overflow-y-scroll">
<div class="mx-5 pb-30 pt-5" style="color: #1b2b07">
<div class="bg-gray-100 rounded-lg w-full flex justify-center mb-4">
<ProductImage :product="product" :dimmed="isOutOfStock" img-class="max-w-full h-auto" />
</div>
<div class="text-2xl font-bold mb-4">{{ product?.title }}</div>
<div class="flex items-center justify-between mb-4 gap-4">
<div class="text-xl font-semibold text-primary">
{{ usePrice(getProductBuyPrice(product)) }}
</div>
<div class="flex-1">
<BasicButton
v-if="product?.show && product?.open_buy && product?.inventory"
class="w-full py-3"
type="primary"
size="large"
@click="handleBuyClick"
>
خرید محصول
</BasicButton>
<div v-else-if="!product?.show" class="text-center text-gray-500 py-4">
این محصول در حال حاضر در دسترس نیست
</div>
<div v-else-if="!product?.open_buy" class="text-center text-gray-500 py-4">
خرید این محصول در حال حاضر امکان پذیر نیست
</div>
<div v-else class="text-center text-gray-500 py-4">ناموجود</div>
</div>
</div>
<div v-if="product?.description" class="mb-6">
<div class="text-lg font-semibold mb-2">توضیحات محصول:</div>
<div class="text-base text-gray-700 whitespace-pre-line">{{ product.description }}</div>
</div>
<div v-if="product?.similar?.length" class="mt-8">
<div class="text-lg font-semibold mb-4">محصولات مشابه</div>
<swiper :slides-per-view="2.25" :space-between="16" class="similar-products-swiper">
<swiper-slide v-for="item in product.similar" :key="item.id">
<div class="bg-white rounded-lg shadow p-4 cursor-pointer h-full" @click="goToProduct(item.id)">
<div class="bg-gray-100 rounded-md flex justify-center p-4 mb-2">
<ProductImage
:product="item"
:dimmed="!item.inventory"
img-class="h-20 object-contain"
/>
</div>
<div class="text-sm font-semibold mb-1 line-clamp-2">{{ item.title }}</div>
<div class="text-sm text-primary font-bold mb-3">
{{ usePrice(getProductBuyPrice(item)) }}
</div>
</div>
</swiper-slide>
</swiper>
</div>
</div>
</div>
</a-spin>
</div>
</template>
<script lang="ts" setup>
import img from '@/assets/img/user_ly1.svg'
import BasicButton from '@/components/BasicPacks/BasicButton.vue'
import ProductImage from '@/components/ProductImage.vue'
import { loading } from '@/utils'
import { usePrice } from '@/utils/usePrice'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/swiper-bundle.css'
import { useProductDetailPageContext } from '../composables/useProductDetailPage'
const { product, isOutOfStock, handleBuyClick, goToProduct, getProductBuyPrice } = useProductDetailPageContext()
</script>
<style scoped>
.text-primary {
color: #d3a233;
}
.similar-products-swiper {
padding-bottom: 10px;
}
.similar-products-swiper :deep(.swiper-slide) {
height: auto;
}
</style>