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
@@ -0,0 +1,309 @@
import { computed, inject, onMounted, onUnmounted, provide, ref, watch, type InjectionKey } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { useCartStore } from '@/store/cartStore'
import { useWalletStore } from '@/store/walletStore'
import { useWalletAssets } from '@/composables/useWalletAssets'
import { checkoutCart } from '@/api/card'
import { registerCodeDiscount } from '@/api/giftCard'
import { getProductBaseBuyPrice } from '@/utils/productPrice'
import { subscribeProductListStream } from '@/utils/productStreamBridge'
import {
getLastPrices,
lastPrice,
startLastPricePolling,
stopPriceInterval,
} from '@/utils/price'
import {
priceSocketConnected,
priceStreamLifecycle,
priceWssEnabled,
shouldUsePricePolling,
} from '@/utils/priceSocketState'
import { getToken, loading } from '@/utils'
import router from '@/router'
import type { Price } from '@/models/home'
import type { Order } from '@/models/order'
import type { Product } from '@/models/products'
export interface CartPageContext {
cartStore: ReturnType<typeof useCartStore>
loading: typeof loading
infoVisible: ReturnType<typeof ref<boolean>>
showDiscountModal: ReturnType<typeof ref<boolean>>
discountCode: ReturnType<typeof ref<string>>
discountInfo: ReturnType<typeof ref<any>>
price: ReturnType<typeof computed<Price>>
totalPrice: ReturnType<typeof computed<number>>
displaytotalPrice: ReturnType<typeof computed<number | string>>
discountPercentLabel: ReturnType<typeof computed<string>>
formatWeight: (weight?: number) => string
handleRemoveItem: (itemId: string) => void
handleCheckout: () => Promise<void>
submitDiscount: () => Promise<void>
removeDiscount: () => void
}
export const CART_PAGE_CONTEXT_KEY: InjectionKey<CartPageContext> = Symbol('cartPageContext')
export function useCartPage() {
const cartStore = useCartStore()
const walletStore = useWalletStore()
const { loadWalletAssets } = useWalletAssets()
const infoVisible = ref(false)
const showDiscountModal = ref(false)
const discountCode = ref('')
const discountInfo = ref<any>()
let cartRefreshInterval: ReturnType<typeof setInterval> | undefined
let unsubscribeProductStream: (() => void) | undefined
const price = computed((): Price => <Price>lastPrice.value ?? 0)
function syncCartFromProducts(products: Product[]) {
if (cartStore.itemCount === 0) return
const removedCount = cartStore.syncProductsFromServer(products)
cartStore.updateCartItemPrices()
if (removedCount > 0) {
message.warning(`${removedCount} محصول از سبد خرید حذف شد (دیگر در دسترس نیست)`)
}
}
watch(lastPrice, () => {
if (lastPrice.value && cartStore.itemCount > 0) {
cartStore.updateCartItemPrices()
}
}, { deep: true, immediate: false })
const totalPrice = computed(() =>
parseInt(String(cartStore.cartItems.reduce((sum, item) => sum + item.totalPrice, 0)))
)
const displaytotalPrice = computed(() => {
if (discountInfo.value?.amount > 0) {
return (totalPrice.value - totalPrice.value * discountInfo.value.amount).toFixed(0)
}
return totalPrice.value
})
const discountPercentLabel = computed(() => {
const amount = Number(discountInfo.value?.amount ?? 0)
if (amount <= 0) return ''
return `${Math.round(amount * 100)}٪`
})
function removeDiscount() {
discountInfo.value = undefined
discountCode.value = ''
message.success('کد تخفیف حذف شد')
}
async function submitDiscount() {
try {
loading.value = true
const temp = await registerCodeDiscount(discountCode.value)
discountInfo.value = temp.giftcard
message.success('کد تخفیف با موفقیت اعمال شد')
showDiscountModal.value = false
} finally {
loading.value = false
}
}
function formatWeight(weight?: number) {
if (!weight) return ''
if (weight < 1) {
const sot = weight * 1000
return sot < 1 ? '1 سوت' : `${Math.round(sot)} سوت`
}
return `${weight} گرم`
}
function handleRemoveItem(itemId: string) {
Modal.confirm({
title: 'حذف از سبد خرید',
content: 'آیا از حذف این آیتم از سبد خرید اطمینان دارید؟',
okText: 'تایید',
okType: 'danger',
centered: true,
cancelText: 'انصراف',
onOk() {
cartStore.removeFromCart(itemId)
message.success('آیتم از سبد خرید حذف شد')
},
})
}
async function handleCheckout() {
if (!getToken()) {
message.warning('برای تسویه حساب، لطفا ابتدا وارد حساب کاربری خود شوید')
await router.push({ name: 'login' })
return
}
if (cartStore.itemCount === 0) {
message.warning('سبد خرید شما خالی است')
return
}
if (!lastPrice.value) {
message.error('لطفا منتظر بمانید تا قیمت‌ها بارگذاری شوند')
return
}
let cashItemsTotal = cartStore.cartItems
.filter((item) => item.method === 'cash' && !item.gateway)
.reduce((sum, item) => parseInt(String(sum + item.totalPrice)), 0)
if (cashItemsTotal > 0) {
if (discountInfo.value?.amount > 0) {
cashItemsTotal -= cashItemsTotal * discountInfo.value.amount
}
if (!walletStore.walletInfo) await walletStore.getMyWallet()
if (!walletStore.walletInfo?.cash || cashItemsTotal > walletStore.walletInfo.cash) {
message.error('موجودی کیف پول شما ناکافی است')
return
}
}
const goldItemsTotal = cartStore.cartItems
.filter((item) => item.method === 'gold')
.reduce((sum, item) => sum + (item.goldVazn ? item.goldVazn * item.quantity : 0), 0)
if (goldItemsTotal > 0) {
if (!walletStore.walletInfo) await walletStore.getMyWallet()
if (!walletStore.walletInfo?.gold || goldItemsTotal > walletStore.walletInfo.gold) {
message.error('موجودی کیف طلا شما ناکافی است')
return
}
}
try {
infoVisible.value = true
const orders: Order[] = cartStore.cartItems.map((item) => ({
direction: 1,
price: getProductBaseBuyPrice(item.product),
amount: item.product.amount,
gateway: item.gateway,
product_id: item.product.id,
method: item.method,
number: item.quantity,
discount_code: discountInfo.value?.code,
}))
const data = await checkoutCart(orders)
let returnUrl: string | null = null
if (Array.isArray(data)) {
const itemWithReturnUrl = data.find((item) => item?.returnUrl)
if (itemWithReturnUrl?.returnUrl) returnUrl = itemWithReturnUrl.returnUrl
} else if (data?.returnUrl) {
returnUrl = data.returnUrl
}
if (returnUrl) {
window.location.href = returnUrl
return
}
await walletStore.getMyWallet()
cartStore.clearCart()
await router.push({ name: 'transactions' })
message.success('سفارشات شما با موفقیت ثبت شد')
await loadWalletAssets(true)
} catch (e) {
console.error('Error in checkout:', e)
message.error('خطا در ثبت سفارش. لطفا دوباره تلاش کنید.')
} finally {
loading.value = false
infoVisible.value = false
}
}
async function initPrice() {
try {
if (shouldUsePricePolling()) await getLastPrices()
startLastPricePolling()
cartStore.updateCartItemPrices()
} catch (e) {
console.log(e)
}
}
async function refreshCart() {
const removedCount = await cartStore.refreshCartFromServer()
if (removedCount > 0) {
message.warning(`${removedCount} محصول از سبد خرید حذف شد (دیگر در دسترس نیست)`)
}
}
function startCartRefreshPolling() {
if (cartRefreshInterval || !shouldUsePricePolling()) return
cartRefreshInterval = setInterval(() => {
if (shouldUsePricePolling()) void refreshCart()
}, 10000)
}
function stopCartRefreshPolling() {
if (cartRefreshInterval) {
clearInterval(cartRefreshInterval)
cartRefreshInterval = undefined
}
}
function syncCartRefreshPolling() {
if (shouldUsePricePolling()) startCartRefreshPolling()
else stopCartRefreshPolling()
}
watch(
() => [priceWssEnabled.value, priceSocketConnected.value, priceStreamLifecycle.value] as const,
() => {
syncCartRefreshPolling()
if (shouldUsePricePolling() && cartStore.itemCount > 0) void refreshCart()
},
)
onMounted(async () => {
cartStore.loadCartFromStorage()
unsubscribeProductStream = subscribeProductListStream(syncCartFromProducts)
loading.value = true
try {
await initPrice()
if (shouldUsePricePolling()) await refreshCart()
syncCartRefreshPolling()
} finally {
loading.value = false
}
})
onUnmounted(() => {
unsubscribeProductStream?.()
unsubscribeProductStream = undefined
stopCartRefreshPolling()
stopPriceInterval()
})
const context: CartPageContext = {
cartStore,
loading,
infoVisible,
showDiscountModal,
discountCode,
discountInfo,
price,
totalPrice,
displaytotalPrice,
discountPercentLabel,
formatWeight,
handleRemoveItem,
handleCheckout,
submitDiscount,
removeDiscount,
}
provide(CART_PAGE_CONTEXT_KEY, context)
return context
}
export function useCartPageContext() {
const context = inject(CART_PAGE_CONTEXT_KEY)
if (!context) throw new Error('useCartPageContext must be used within useCartPage')
return context
}
@@ -0,0 +1,184 @@
<template>
<div class="dinner cart-page">
<div class="dinner__container">
<DesktopPageTopbar title="سبد خرید" show-back>
<template #trailing>
<div v-if="price" class="dcart-header-price number-ltr">
<span class="dcart-header-price__label">قیمت خرید از کشکول گلد:</span>
<strong>{{ usePriceWithoutType(price?.price_last ?? 0) }}</strong>
<span>ریال</span>
</div>
</template>
</DesktopPageTopbar>
<GoldLoading v-model:show="infoVisible" title="" />
<template v-if="loading">
<TransactionSkeleton v-for="i in 3" :key="i" class="mt-4" />
</template>
<div v-else-if="cartStore.itemCount === 0" class="dinner-surface dcart-empty">
<p>سبد خرید شما خالی است</p>
<BasicButton type="primary" @click="router.push({ name: 'buyProduct' })">مشاهده محصولات</BasicButton>
</div>
<div v-else class="dcart-grid">
<div class="dcart-items">
<article v-for="item in cartStore.cartItems" :key="item.id" class="dcart-item">
<div class="dcart-item__image">
<ProductImage :product="item.product" img-class="max-w-full max-h-full object-contain" />
</div>
<div class="dcart-item__main">
<h3 class="dcart-item__title">{{ item.product.title }}</h3>
<p class="dcart-item__meta">
روش پرداخت: {{ item.method === 'cash' ? 'نقدی' : 'طلایی' }}
<span v-if="item.method === 'cash' && item.gateway"> (با درگاه)</span>
</p>
<p class="dcart-item__meta">
تعداد: {{ item.quantity }} عدد
<span v-if="item.goldVazn"> | وزن: {{ formatWeight(item.goldVazn) }}</span>
</p>
<div class="dcart-item__footer">
<span class="dcart-item__price">{{ usePrice(item.totalPrice) }}</span>
<BasicIcon
icon="vuesax-linear:trash"
class="text-red-500 cursor-pointer"
@click.stop="handleRemoveItem(item.id)"
/>
</div>
</div>
</article>
</div>
<aside class="dinner-surface dcart-summary">
<h2 class="dcart-summary__title">خلاصه سفارش</h2>
<div
v-if="discountInfo?.amount > 0"
class="dcart-summary__discount"
>
<div>
<span>کد تخفیف: </span>
<strong>{{ discountInfo.code }}</strong>
<div class="text-xs text-green-600">{{ discountPercentLabel }} تخفیف اعمال شد</div>
</div>
<button type="button" class="dcart-summary__remove-discount" @click="removeDiscount">
<BasicIcon icon="vuesax-linear:close-circle" size="18" />
حذف
</button>
</div>
<div class="dcart-summary__row">
<span>مجموع:</span>
<div class="text-left">
<div class="dcart-summary__total">{{ usePrice(displaytotalPrice) }}</div>
<div v-if="discountInfo?.amount > 0" class="text-xs text-gray-400 line-through">
{{ usePrice(totalPrice) }}
</div>
</div>
</div>
<button
v-if="!discountInfo?.amount"
type="button"
class="dcart-summary__discount-link"
@click="showDiscountModal = true"
>
کد تخفیف دارم
</button>
<BasicButton class="w-full" type="primary" size="large" @click="handleCheckout">
تسویه حساب
</BasicButton>
</aside>
</div>
</div>
</div>
</template>
<script lang="ts" setup>
import router from '@/router'
import BasicButton from '@/components/BasicPacks/BasicButton.vue'
import BasicIcon from '@/components/BasicPacks/BasicIcon.vue'
import GoldLoading from '@/components/GoldLoading.vue'
import ProductImage from '@/components/ProductImage.vue'
import TransactionSkeleton from '@/components/TransactionSkeleton.vue'
import DesktopPageTopbar from '@/layouts/components/DesktopPageTopbar.vue'
import { usePrice, usePriceWithoutType } from '@/utils/usePrice'
import { useCartPageContext } from '../composables/useCartPage'
const {
cartStore,
loading,
infoVisible,
showDiscountModal,
discountInfo,
price,
totalPrice,
displaytotalPrice,
discountPercentLabel,
formatWeight,
handleRemoveItem,
handleCheckout,
removeDiscount,
} = useCartPageContext()
</script>
<style scoped>
.dcart-header-price {
display: flex;
align-items: baseline;
gap: 6px;
font-size: 13px;
color: #6b7280;
strong {
font-size: 16px;
color: #111827;
}
}
.dcart-empty {
padding: 48px 24px;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
color: #6b7280;
}
.dcart-summary__discount {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
padding: 12px;
border-radius: 10px;
background: rgba(167, 43, 119, 0.06);
font-size: 13px;
}
.dcart-summary__remove-discount {
display: inline-flex;
align-items: center;
gap: 4px;
border: none;
background: transparent;
color: #ef4444;
font-size: 12px;
cursor: pointer;
font-family: inherit;
}
.dcart-summary__discount-link {
border: none;
background: transparent;
color: @App-primary-color;
font-size: 13px;
text-decoration: underline;
cursor: pointer;
font-family: inherit;
text-align: center;
}
</style>
+26 -453
View File
@@ -1,464 +1,37 @@
<template>
<div>
<div class="absolute inset-0 bg-cover bg-center opacity-60 z--1" :style="{ backgroundImage: `url(${img})` }"></div>
<div class="bg-white drop-shadow z-[1999] wrap-fix">
<div class="py-3 px-3 font-bold flex items-center justify-between">
<div>سبد خرید</div>
<!-- Price Display in Header -->
<div v-if="price" class="flex gap-1 items-center text-xs flex-1 justify-end">
<span class="text-gray-600 text-xs">قیمت خرید از کشکول گلد:</span>
<div class="font-bold text-base" style="font-family: iran-sans; direction: ltr">
{{ usePriceWithoutType(price?.price_last ?? 0) }}
</div>
<span class="text-xs">ریال</span>
</div>
<div class="cart-page-root">
<DesktopCartView v-show="isDesktop" />
<MobileCartView v-show="!isDesktop" />
<AModal
v-model:visible="showDiscountModal"
ok-text="اعمال کد تخفیف"
cancel-text="انصراف"
@ok="submitDiscount"
@cancel="showDiscountModal = false"
>
<div class="p-5">
<div>کد تخفیف</div>
<AInput v-model:value="discountCode" />
<div class="font-bold text-xs mt-3">*حساس به حروف بزرگ و کوچک</div>
</div>
</div>
<GoldLoading v-model:show="infoVisible" title=""/>
<div class="px-5 pt-26 pb-30" :class="loading ? 'h-[60vh]' : ''">
<template v-if="loading">
<TransactionSkeleton v-for="i in 3" :key="i" class="mt-4" />
</template>
<template v-else>
<!-- Empty Cart Message -->
<div v-if="cartStore.itemCount === 0" class="flex flex-col items-center justify-center h-[60vh]">
<div class="text-gray-500 text-lg font-semibold mb-4">سبد خرید شما خالی است</div>
<BasicButton type="primary" @click="$router.push({ name: 'buyProduct' })">
مشاهده محصولات
</BasicButton>
</div>
<!-- Cart Items -->
<div v-else>
<div class="space-y-4 mb-20">
<div
v-for="item in cartStore.cartItems"
:key="item.id"
class="bg-white rounded-lg border border-gray-200 p-4 shadow-sm"
>
<div class="flex gap-4">
<!-- Product Image -->
<div class="bg-gray-100 rounded-lg flex justify-center items-center p-1 min-w-[80px] h-[80px]">
<ProductImage
:product="item.product"
img-class="max-w-full max-h-full object-contain"
/>
</div>
<!-- Product Info -->
<div class="flex-1 flex flex-col justify-between">
<div>
<div class="text-base font-semibold mb-1">{{ item.product.title }}</div>
<!-- <div class="text-xs text-gray-500 mb-2">-->
<!-- {{ getProductAmount(item.product.amount) }}-->
<!-- </div>-->
<div class="text-xs text-gray-500 mb-2">
روش پرداخت: {{ item.method === 'cash' ? 'نقدی' : 'طلایی' }}
<span v-if="item.method === 'cash' && item.gateway" class="mr-2">(با درگاه)</span>
</div>
<div class="text-xs text-gray-500">
تعداد: {{ item.quantity }} عدد
<span v-if="item.goldVazn" class="mr-2">| وزن: {{ formatWeight(item.goldVazn) }}</span>
</div>
</div>
<div class="flex items-center justify-between mt-2">
<div class="text-primary font-bold">
{{ usePrice(item.totalPrice) }}
</div>
<BasicIcon
icon="vuesax-linear:trash"
class="text-red-500 cursor-pointer"
@click.stop="handleRemoveItem(item.id)"
/>
</div>
</div>
</div>
</div>
</div>
<!-- Total and Checkout -->
<div class=" flex justify-center fixed bottom-20 left-0 right-0 z-1">
<div class="md:w-[426px] w-full bg-white border-t border-gray-200 p-4 shadow-lg">
<div
v-if="discountInfo?.amount > 0"
class="mb-3 flex items-center justify-between rounded-lg bg-purple-50 px-3 py-2"
>
<div class="flex flex-col gap-0.5 text-sm">
<div class="flex items-center gap-2">
<span class="text-gray-600">کد تخفیف:</span>
<span class="font-semibold">{{ discountInfo.code }}</span>
</div>
<div class="text-xs text-green-600">
{{ discountPercentLabel }} تخفیف اعمال شد
</div>
</div>
<button
type="button"
class="flex items-center gap-1 text-xs text-red-500"
@click="removeDiscount"
>
<BasicIcon icon="vuesax-linear:close-circle" size="18" />
<span>حذف</span>
</button>
</div>
<div class="flex justify-between items-center mb-4">
<div class="text-lg font-semibold">مجموع:</div>
<div class="flex flex-col items-end gap-1">
<div class="text-primary font-bold text-xl">
{{ usePrice(displaytotalPrice) }}
</div>
<div
v-if="discountInfo?.amount > 0"
class="text-xs text-gray-400 line-through"
>
{{ usePrice(totalPrice) }}
</div>
</div>
</div>
<div
v-if="!discountInfo?.amount"
class="mb-3 text-center"
>
<span
class="text-xs text-primary underline cursor-pointer"
@click="showDiscountModal = true"
>
کد تخفیف دارم
</span>
</div>
<BasicButton
class="w-full py-3"
type="primary"
size="large"
@click="handleCheckout"
>
تسویه حساب
</BasicButton>
</div>
</div>
</div>
</template>
</div>
</AModal>
</div>
<AModal v-model:visible="showDiscountModal" ok-text="اعمال کد تخفیف" cancel-text="انصراف" @ok="submitDiscount"
@cancel="showDiscountModal=false">
<div class="p-5">
<div>کد تخفیف</div>
<AInput v-model:value="discountCode"></AInput>
<div class="font-bold text-xs mt-3">
*حساس به حروف بزرگ و کوچک
</div>
</div>
</AModal>
</template>
<script setup lang="ts">
import {ref, onMounted, onUnmounted, watch, computed} from 'vue'
import {useCartStore} from '@/store/cartStore'
import {usePrice, usePriceWithoutType} from '@/utils/usePrice'
import BasicButton from '@/components/BasicPacks/BasicButton.vue'
import BasicIcon from '@/components/BasicPacks/BasicIcon.vue'
import {message, Modal} from 'ant-design-vue'
import img from '@/assets/img/user_ly1.svg'
import {
getLastPrices,
lastPrice,
stopPriceInterval,
setIntervalGetLastPrice
} from '@/utils/price'
import {checkoutCart} from '@/api/card'
import router from '@/router'
import {useWalletStore} from '@/store/walletStore'
import {useFundUserStore} from '@/store/fundStore'
import type {Price} from '@/models/home'
import type {Order} from '@/models/order'
<script lang="ts" setup>
import { useDesktopBreakpoint } from '@/layouts/composables/useAppLayout'
import { useCartPage } from './composables/useCartPage'
import DesktopCartView from './desktop/DesktopCartView.vue'
import MobileCartView from './mobile/MobileCartView.vue'
import {loading, getToken} from '@/utils'
import GoldLoading from '@/components/GoldLoading.vue'
import TransactionSkeleton from '@/components/TransactionSkeleton.vue'
import ProductImage from '@/components/ProductImage.vue'
import {registerCodeDiscount} from "@/api/giftCard";
const cartStore = useCartStore()
const walletStore = useWalletStore()
const fundStore = useFundUserStore()
const infoVisible = ref(false)
const showDiscountModal = ref(false)
const discountCode = ref<string>('')
const discountInfo = ref()
let totalPriceWithDiscount = 0
const price = computed((): Price => <Price>lastPrice.value ?? 0)
// Watch for price updates and update cart items
watch(lastPrice, () => {
if (lastPrice.value) {
cartStore.recalculateCartPrices(lastPrice.value)
}
}, {deep: true, immediate: false})
// Computed total price that updates with price changes
const totalPrice = computed(() => {
return parseInt(cartStore.cartItems.reduce((sum, item) => sum + item.totalPrice, 0))
})
const displaytotalPrice = computed(() => {
if (discountInfo.value?.amount > 0) {
return (totalPrice.value - (totalPrice.value * discountInfo.value?.amount)).toFixed(0)
} else
return totalPrice.value
})
const discountPercentLabel = computed(() => {
const amount = Number(discountInfo.value?.amount ?? 0)
if (amount <= 0) return ''
return `${Math.round(amount * 100)}٪`
})
function removeDiscount() {
discountInfo.value = undefined
discountCode.value = ''
message.success('کد تخفیف حذف شد')
}
async function submitDiscount() {
try {
loading.value = true
const temp = await registerCodeDiscount(discountCode.value)
discountInfo.value = temp.giftcard
message.success('کد تخفیف با موفقیت اعمال شد')
showDiscountModal.value = false
} catch (e) {
} finally {
loading.value = false
}
}
function getProductAmount(amount?: number) {
if (!amount) return ''
if (amount < 1) {
// کمتر از 1 گرم را به سوت تبدیل کن (مشابه ProductItem)
const sot = amount * 1000
// اگر نتیجه کمتر از 1 شد، حداقل 1 نمایش بده
if (sot < 1) {
return `1 سوت`
}
// در غیر این صورت، عدد را به عدد صحیح گرد کن
return `${Math.round(sot)} سوت`
}
return `${amount} گرم`
}
function formatWeight(weight?: number) {
if (!weight) return ''
if (weight < 1) {
// کمتر از 1 گرم را به سوت تبدیل کن
const sot = weight * 1000
// اگر نتیجه کمتر از 1 شد، حداقل 1 نمایش بده
if (sot < 1) {
return `1 سوت`
}
// در غیر این صورت، عدد را به عدد صحیح گرد کن
return `${Math.round(sot)} سوت`
}
return `${weight} گرم`
}
function handleRemoveItem(itemId: string) {
Modal.confirm({
title: 'حذف از سبد خرید',
content: 'آیا از حذف این آیتم از سبد خرید اطمینان دارید؟',
okText: 'تایید',
okType: 'danger',
centered: true,
cancelText: 'انصراف',
onOk() {
cartStore.removeFromCart(itemId)
message.success('آیتم از سبد خرید حذف شد')
}
})
}
async function handleCheckout() {
// Check if user is logged in
if (!getToken()) {
message.warning('برای تسویه حساب، لطفا ابتدا وارد حساب کاربری خود شوید')
await router.push({name: 'login'})
return
}
if (cartStore.itemCount === 0) {
message.warning('سبد خرید شما خالی است')
return
}
if (!lastPrice.value) {
message.error('لطفا منتظر بمانید تا قیمت‌ها بارگذاری شوند')
return
}
// Check wallet balance for cash method items (without gateway)
let cashItemsTotal = cartStore.cartItems
.filter(item => item.method === 'cash' && !item.gateway)
.reduce((sum, item) => parseInt(sum + item.totalPrice), 0)
if (cashItemsTotal > 0) {
// Ensure wallet info is loaded
if (discountInfo.value?.amount && discountInfo.value?.amount>0){
cashItemsTotal=cashItemsTotal-cashItemsTotal*discountInfo.value?.amount
}
if (!walletStore.walletInfo) {
await walletStore.getMyWallet()
}
if (!walletStore.walletInfo?.cash || cashItemsTotal > walletStore.walletInfo.cash) {
message.error('موجودی کیف پول شما ناکافی است')
return
}
}
// Check gold balance for gold method items
const goldItemsTotal = cartStore.cartItems
.filter(item => item.method === 'gold')
.reduce((sum, item) => {
// Calculate total gold weight needed
const goldWeight = item.goldVazn ? item.goldVazn * item.quantity : 0
return sum + goldWeight
}, 0)
if (goldItemsTotal > 0) {
// Ensure wallet info is loaded
if (!walletStore.walletInfo) {
await walletStore.getMyWallet()
}
if (!walletStore.walletInfo?.gold || goldItemsTotal > walletStore.walletInfo.gold) {
message.error('موجودی کیف طلا شما ناکافی است')
return
}
}
try {
infoVisible.value = true
// Prepare orders array with same structure as createOrder for each product
const orders: Order[] = cartStore.cartItems.map(item => {
console.log(item)
const product = item.product
// Calculate price similar to createOrder (buy price)
let productPrice = 0
if (product.group_type == 'آبشده') {
productPrice = lastPrice.value?.price_last ?? 0
} else {
productPrice = (product.amount ?? 0) * (lastPrice.value?.price_last ?? 0)
}
return {
direction: 1, // 1 for buy (cart items are always buy orders)
price: productPrice,
amount: product.amount,
gateway: item.gateway,
product_id: product.id,
method: item.method,
number: item.quantity,
discount_code:discountInfo.value?.code
}
})
// Call checkoutCart API with orders array
const data = await checkoutCart(orders)
// Check for returnUrl (gateway payment)
let returnUrl = null
if (Array.isArray(data)) {
const itemWithReturnUrl = data.find(item => item?.returnUrl)
if (itemWithReturnUrl?.returnUrl) {
returnUrl = itemWithReturnUrl.returnUrl
}
} else if (data?.returnUrl) {
returnUrl = data.returnUrl
}
// If returnUrl exists, redirect to gateway and stop execution
if (returnUrl) {
window.location.href = returnUrl
return // Stop execution here
}
// If no gateway, continue with normal flow
await walletStore.getMyWallet()
cartStore.clearCart()
await router.push({name: 'transactions'})
message.success('سفارشات شما با موفقیت ثبت شد')
await fundStore.getMyFund()
} catch (e: any) {
console.error('Error in checkout:', e)
message.error('خطا در ثبت سفارش. لطفا دوباره تلاش کنید.')
} finally {
loading.value = false
infoVisible.value = false
}
}
async function initPrice() {
try {
await getLastPrices()
await setIntervalGetLastPrice()
if (lastPrice.value) {
cartStore.recalculateCartPrices(lastPrice.value)
}
} catch (e: any) {
console.log(e)
}
}
async function refreshCart() {
const removedCount = await cartStore.refreshCartFromServer()
if (removedCount > 0) {
message.warning(`${removedCount} محصول از سبد خرید حذف شد (دیگر در دسترس نیست)`)
}
if (lastPrice.value) {
cartStore.recalculateCartPrices(lastPrice.value)
}
}
onMounted(async () => {
cartStore.loadCartFromStorage()
loading.value = true
try {
await initPrice()
await refreshCart()
const refreshCartInfo=setInterval(async () => {
await refreshCart()
// await getUpPrice()
}, 10000)
} finally {
loading.value = false
}
})
onUnmounted(() => {
stopPriceInterval()
})
const isDesktop = useDesktopBreakpoint()
const { showDiscountModal, discountCode, submitDiscount } = useCartPage()
</script>
<style scoped>
.text-primary {
color: #d3a233;
}
@media screen and (min-width: 426px) {
.wrap-fix {
width: 426px;
margin: 0 auto;
}
.cart-page-root {
min-height: 100%;
height: 100%;
}
</style>
@@ -0,0 +1,142 @@
<template>
<div>
<div class="absolute inset-0 bg-cover bg-center opacity-60 z--1" :style="{ backgroundImage: `url(${img})` }" />
<div class="bg-white drop-shadow z-[1999] wrap-fix">
<div class="py-3 px-3 font-bold flex items-center justify-between">
<div>سبد خرید</div>
<div v-if="price" class="flex gap-1 items-center text-xs flex-1 justify-end">
<span class="text-gray-600 text-xs">قیمت خرید از کشکول گلد:</span>
<div class="font-bold text-base" style="font-family: iran-sans; direction: ltr">
{{ usePriceWithoutType(price?.price_last ?? 0) }}
</div>
<span class="text-xs">ریال</span>
</div>
</div>
</div>
<GoldLoading v-model:show="infoVisible" title="" />
<div class="px-5 pt-26 pb-30" :class="loading ? 'h-[60vh]' : ''">
<template v-if="loading">
<TransactionSkeleton v-for="i in 3" :key="i" class="mt-4" />
</template>
<template v-else>
<div v-if="cartStore.itemCount === 0" class="flex flex-col items-center justify-center h-[60vh]">
<div class="text-gray-500 text-lg font-semibold mb-4">سبد خرید شما خالی است</div>
<BasicButton type="primary" @click="router.push({ name: 'buyProduct' })">مشاهده محصولات</BasicButton>
</div>
<div v-else>
<div class="space-y-4 mb-20">
<div
v-for="item in cartStore.cartItems"
:key="item.id"
class="bg-white rounded-lg border border-gray-200 p-4 shadow-sm"
>
<div class="flex gap-4">
<div class="bg-gray-100 rounded-lg flex justify-center items-center p-1 min-w-[80px] h-[80px]">
<ProductImage :product="item.product" img-class="max-w-full max-h-full object-contain" />
</div>
<div class="flex-1 flex flex-col justify-between">
<div>
<div class="text-base font-semibold mb-1">{{ item.product.title }}</div>
<div class="text-xs text-gray-500 mb-2">
روش پرداخت: {{ item.method === 'cash' ? 'نقدی' : 'طلایی' }}
<span v-if="item.method === 'cash' && item.gateway" class="mr-2">(با درگاه)</span>
</div>
<div class="text-xs text-gray-500">
تعداد: {{ item.quantity }} عدد
<span v-if="item.goldVazn" class="mr-2">| وزن: {{ formatWeight(item.goldVazn) }}</span>
</div>
</div>
<div class="flex items-center justify-between mt-2">
<div class="text-primary font-bold">{{ usePrice(item.totalPrice) }}</div>
<BasicIcon
icon="vuesax-linear:trash"
class="text-red-500 cursor-pointer"
@click.stop="handleRemoveItem(item.id)"
/>
</div>
</div>
</div>
</div>
</div>
<div class="flex justify-center fixed bottom-20 left-0 right-0 z-1">
<div class="md:w-[426px] w-full bg-white border-t border-gray-200 p-4 shadow-lg">
<div
v-if="discountInfo?.amount > 0"
class="mb-3 flex items-center justify-between rounded-lg bg-purple-50 px-3 py-2"
>
<div class="flex flex-col gap-0.5 text-sm">
<div class="flex items-center gap-2">
<span class="text-gray-600">کد تخفیف:</span>
<span class="font-semibold">{{ discountInfo.code }}</span>
</div>
<div class="text-xs text-green-600">{{ discountPercentLabel }} تخفیف اعمال شد</div>
</div>
<button type="button" class="flex items-center gap-1 text-xs text-red-500" @click="removeDiscount">
<BasicIcon icon="vuesax-linear:close-circle" size="18" />
<span>حذف</span>
</button>
</div>
<div class="flex justify-between items-center mb-4">
<div class="text-lg font-semibold">مجموع:</div>
<div class="flex flex-col items-end gap-1">
<div class="text-primary font-bold text-xl">{{ usePrice(displaytotalPrice) }}</div>
<div v-if="discountInfo?.amount > 0" class="text-xs text-gray-400 line-through">
{{ usePrice(totalPrice) }}
</div>
</div>
</div>
<div v-if="!discountInfo?.amount" class="mb-3 text-center">
<span class="text-xs text-primary underline cursor-pointer" @click="showDiscountModal = true">
کد تخفیف دارم
</span>
</div>
<BasicButton class="w-full py-3" type="primary" size="large" @click="handleCheckout">
تسویه حساب
</BasicButton>
</div>
</div>
</div>
</template>
</div>
</div>
</template>
<script lang="ts" setup>
import router from '@/router'
import img from '@/assets/img/user_ly1.svg'
import BasicButton from '@/components/BasicPacks/BasicButton.vue'
import BasicIcon from '@/components/BasicPacks/BasicIcon.vue'
import GoldLoading from '@/components/GoldLoading.vue'
import ProductImage from '@/components/ProductImage.vue'
import TransactionSkeleton from '@/components/TransactionSkeleton.vue'
import { usePrice, usePriceWithoutType } from '@/utils/usePrice'
import { useCartPageContext } from '../composables/useCartPage'
const {
cartStore,
loading,
infoVisible,
showDiscountModal,
discountInfo,
price,
totalPrice,
displaytotalPrice,
discountPercentLabel,
formatWeight,
handleRemoveItem,
handleCheckout,
removeDiscount,
} = useCartPageContext()
</script>
<style scoped>
.text-primary {
color: #d3a233;
}
</style>