Files
ghatreh_user/src/views/base/cart/index.vue
T
2026-06-13 14:03:52 +03:30

465 lines
15 KiB
Vue

<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>
</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>
</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'
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()
})
</script>
<style scoped>
.text-primary {
color: #d3a233;
}
@media screen and (min-width: 426px) {
.wrap-fix {
width: 426px;
margin: 0 auto;
}
}
</style>