Files
ghatreh_user/src/views/base/cart/index.vue
T

469 lines
15 KiB
Vue
Raw Normal View History

2026-01-28 11:17:48 +03:30
<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>
2026-04-09 13:58:37 +03:30
<GoldLoading v-model:show="infoVisible" title=""/>
2026-01-28 11:17:48 +03:30
<div class="px-5 pt-26 pb-30">
<!-- Empty Cart Message -->
<div v-if="cartStore.itemCount === 0" class="flex flex-col items-center justify-center h-[60vh]">
2026-04-09 13:58:37 +03:30
<div class="text-gray-500 text-lg font-semibold mb-4">سبد خرید شما خالی است</div>
<BasicButton type="primary" @click="$router.push({ name: 'buyProduct' })">
مشاهده محصولات
</BasicButton>
</div>
2026-01-28 11:17:48 +03:30
2026-04-09 13:58:37 +03:30
<!-- Cart Items -->
<div v-else>
<div class="space-y-4 mb-20">
<div
2026-01-28 11:17:48 +03:30
v-for="item in cartStore.cartItems"
:key="item.id"
class="bg-white rounded-lg border border-gray-200 p-4 shadow-sm"
2026-04-09 13:58:37 +03:30
>
<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]">
<img
2026-01-31 10:19:21 +03:30
:src="getProductImage(item.product)"
2026-01-28 11:17:48 +03:30
class="max-w-full max-h-full object-contain"
alt=""
2026-04-09 13:58:37 +03:30
/>
</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>
2026-01-28 11:17:48 +03:30
</div>
2026-04-09 13:58:37 +03:30
<div class="flex items-center justify-between mt-2">
<div class="text-primary font-bold">
{{ usePrice(item.totalPrice) }}
2026-01-28 11:17:48 +03:30
</div>
2026-04-09 13:58:37 +03:30
<BasicIcon
2026-01-28 11:17:48 +03:30
icon="vuesax-linear:trash"
class="text-red-500 cursor-pointer"
@click.stop="handleRemoveItem(item.id)"
2026-04-09 13:58:37 +03:30
/>
2026-01-28 11:17:48 +03:30
</div>
</div>
</div>
</div>
2026-04-09 13:58:37 +03:30
</div>
2026-01-28 11:17:48 +03:30
2026-04-09 13:58:37 +03:30
<!-- Total and Checkout -->
<div class="fixed bottom-20 left-0 right-0 bg-white border-t border-gray-200 p-4 shadow-lg z-1">
<div class="flex justify-between items-center mb-4">
<div class="text-lg font-semibold">مجموع:</div>
<div class="flex flex-col gap-2 ">
2026-01-28 11:17:48 +03:30
<div class="text-primary font-bold text-xl">
2026-04-09 13:58:37 +03:30
{{ usePrice(displaytotalPrice) }}
2026-01-28 11:17:48 +03:30
</div>
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
</div>
2026-04-09 13:58:37 +03:30
<div class="!text-primary font-bold text-xs line-through cursor-pointer "
v-if="discountInfo?.amount>0"
@click="showDiscountModal=true">
{{ usePrice(totalPrice) }}
</div>
<div v-else
class="!text-primary font-bold text-xs underline-solid underline cursor-pointer"
@click="showDiscountModal=true">
کد تخفیف دارم
</div>
</div>
<BasicButton
2026-01-28 11:17:48 +03:30
class="w-full py-3"
type="primary"
size="large"
@click="handleCheckout"
2026-04-09 13:58:37 +03:30
>
تسویه حساب
</BasicButton>
2026-01-28 11:17:48 +03:30
</div>
</div>
2026-04-09 13:58:37 +03:30
</div>
2026-01-28 11:17:48 +03:30
</div>
2026-04-09 13:58:37 +03:30
<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>
2026-04-11 18:00:05 +03:30
<div class="font-bold text-xs mt-3">
*حساس به حروف بزرگ و کوچک
</div>
2026-04-09 13:58:37 +03:30
</div>
</AModal>
2026-01-28 11:17:48 +03:30
</template>
<script setup lang="ts">
2026-04-09 13:58:37 +03:30
import {ref, onMounted, onUnmounted, watch, computed} from 'vue'
import {useCartStore} from '@/store/cartStore'
import {usePrice, usePriceWithoutType} from '@/utils/usePrice'
2026-01-28 11:17:48 +03:30
import BasicButton from '@/components/BasicPacks/BasicButton.vue'
import BasicIcon from '@/components/BasicPacks/BasicIcon.vue'
2026-04-09 13:58:37 +03:30
import {message, Modal} from 'ant-design-vue'
2026-01-28 11:17:48 +03:30
import img from '@/assets/img/user_ly1.svg'
import {
getLastPrices,
lastPrice,
stopPriceInterval,
setIntervalGetLastPrice
} from '@/utils/price'
2026-04-09 13:58:37 +03:30
import {checkoutCart} from '@/api/card'
2026-01-28 11:17:48 +03:30
import router from '@/router'
2026-04-09 13:58:37 +03:30
import {useWalletStore} from '@/store/walletStore'
import {useFundUserStore} from '@/store/fundStore'
import type {Price} from '@/models/home'
import type {Order} from '@/models/order'
2026-01-28 11:17:48 +03:30
// Image imports
import defaultImg from '@/assets/img/defaultAbshodeh.svg'
import goyImg from '@/assets/img/goyImg.svg'
import mokaabImg from '@/assets/img/mokaabImg.svg'
import sekkeImg from '@/assets/img/sekkeImg.svg'
import parsianImg from '@/assets/img/parsianImg.svg'
import venusImg from '@/assets/img/venousImg.svg'
2026-04-09 13:58:37 +03:30
import {loading, getToken} from '@/utils'
2026-01-28 11:17:48 +03:30
import GoldLoading from '@/components/GoldLoading.vue'
2026-04-09 13:58:37 +03:30
import {registerCodeDiscount} from "@/api/giftCard";
2026-01-28 11:17:48 +03:30
const cartStore = useCartStore()
const walletStore = useWalletStore()
const fundStore = useFundUserStore()
const infoVisible = ref(false)
2026-04-09 13:58:37 +03:30
const showDiscountModal = ref(false)
const discountCode = ref<string>('')
const discountInfo = ref()
let totalPriceWithDiscount = 0
2026-01-28 11:17:48 +03:30
const price = computed((): Price => <Price>lastPrice.value ?? 0)
// Watch for price updates and update cart items
watch(lastPrice, () => {
if (lastPrice.value && cartStore.cartItems.length > 0) {
cartStore.cartItems.forEach((item) => {
const product = item.product
let newPrice = 0
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
if (product.group_type == 'آبشده') {
newPrice = lastPrice.value?.price_last ?? 0
} else {
newPrice = product.amount * (lastPrice.value?.price_last ?? 0)
}
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// Update product price
product.price = newPrice
product.sellPrice = product.amount * (lastPrice.value?.sell ?? 0)
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// Update item price and total price
item.price = newPrice + (product.cash_fee_buy ?? 0)
2026-02-08 13:37:10 +03:30
item.totalPrice = parseInt(item.price * item.quantity)
2026-01-28 11:17:48 +03:30
})
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// Save updated prices to storage
cartStore.saveCartToStorage()
}
2026-04-09 13:58:37 +03:30
}, {deep: true, immediate: false})
2026-01-28 11:17:48 +03:30
// Computed total price that updates with price changes
const totalPrice = computed(() => {
2026-02-08 13:37:10 +03:30
return parseInt(cartStore.cartItems.reduce((sum, item) => sum + item.totalPrice, 0))
2026-01-28 11:17:48 +03:30
})
2026-04-09 13:58:37 +03:30
const displaytotalPrice = computed(() => {
if (discountInfo.value?.amount > 0) {
return (totalPrice.value - (totalPrice.value * discountInfo.value?.amount)).toFixed(0)
} else
return totalPrice.value
})
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
}
}
2026-01-28 11:17:48 +03:30
2026-01-31 10:19:21 +03:30
function getProductImage(product: any) {
// Check if product has file field from server with src property
if (product?.file?.src) {
return product.file.src
}
2026-04-09 13:58:37 +03:30
2026-01-31 10:19:21 +03:30
// Fallback to local images based on group_type if file is empty or doesn't exist
const type = product?.group_type
2026-01-28 11:17:48 +03:30
switch (type) {
case 'گوی':
return goyImg
case 'مکعب':
return mokaabImg
case 'سکه':
return sekkeImg
case 'شمش ونوس':
return venusImg
case 'سکه پارسیان':
return parsianImg
default:
return defaultImg
}
}
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('برای تسویه حساب، لطفا ابتدا وارد حساب کاربری خود شوید')
2026-04-09 13:58:37 +03:30
await router.push({name: 'login'})
2026-01-28 11:17:48 +03:30
return
}
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
if (cartStore.itemCount === 0) {
message.warning('سبد خرید شما خالی است')
return
}
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
if (!lastPrice.value) {
message.error('لطفا منتظر بمانید تا قیمت‌ها بارگذاری شوند')
return
}
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// Check wallet balance for cash method items (without gateway)
2026-04-09 13:58:37 +03:30
let cashItemsTotal = cartStore.cartItems
.filter(item => item.method === 'cash' && !item.gateway)
.reduce((sum, item) => parseInt(sum + item.totalPrice), 0)
2026-01-28 11:17:48 +03:30
if (cashItemsTotal > 0) {
// Ensure wallet info is loaded
2026-04-09 13:58:37 +03:30
if (discountInfo.value.amount>0){
cashItemsTotal=cashItemsTotal-cashItemsTotal*discountInfo.value.amount
}
2026-01-28 11:17:48 +03:30
if (!walletStore.walletInfo) {
await walletStore.getMyWallet()
}
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
if (!walletStore.walletInfo?.cash || cashItemsTotal > walletStore.walletInfo.cash) {
message.error('موجودی کیف پول شما ناکافی است')
return
}
}
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// Check gold balance for gold method items
const goldItemsTotal = cartStore.cartItems
2026-04-09 13:58:37 +03:30
.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)
2026-01-28 11:17:48 +03:30
if (goldItemsTotal > 0) {
// Ensure wallet info is loaded
if (!walletStore.walletInfo) {
await walletStore.getMyWallet()
}
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
if (!walletStore.walletInfo?.gold || goldItemsTotal > walletStore.walletInfo.gold) {
message.error('موجودی کیف طلا شما ناکافی است')
return
}
}
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
try {
loading.value = true
infoVisible.value = true
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// Prepare orders array with same structure as createOrder for each product
const orders: Order[] = cartStore.cartItems.map(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)
}
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
return {
direction: 1, // 1 for buy (cart items are always buy orders)
price: productPrice,
2026-02-09 13:43:02 +03:30
amount: product.amount,
2026-01-28 11:17:48 +03:30
gateway: item.gateway,
product_id: product.id,
method: item.method,
2026-04-09 13:58:37 +03:30
number: item.quantity,
discount_code:discountInfo.value.code
2026-01-28 11:17:48 +03:30
}
})
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// Call checkoutCart API with orders array
const data = await checkoutCart(orders)
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// 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
}
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// If returnUrl exists, redirect to gateway and stop execution
if (returnUrl) {
window.location.href = returnUrl
return // Stop execution here
}
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// If no gateway, continue with normal flow
await walletStore.getMyWallet()
cartStore.clearCart()
2026-04-09 13:58:37 +03:30
await router.push({name: 'transactions'})
2026-01-28 11:17:48 +03:30
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()
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// Update prices for all cart items
if (lastPrice.value && cartStore.cartItems.length > 0) {
cartStore.cartItems.forEach((item) => {
const product = item.product
let newPrice = 0
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
if (product.group_type == 'آبشده') {
newPrice = lastPrice.value?.price_last ?? 0
} else {
newPrice = product.amount * (lastPrice.value?.price_last ?? 0)
}
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// Update product price
product.price = newPrice
product.sellPrice = product.amount * (lastPrice.value?.sell ?? 0)
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// Update item price and total price
item.price = newPrice + (product.cash_fee_buy ?? 0)
2026-04-09 13:58:37 +03:30
item.totalPrice = parseInt(item.price * item.quantity)
2026-01-28 11:17:48 +03:30
})
2026-04-09 13:58:37 +03:30
2026-01-28 11:17:48 +03:30
// Save updated prices to storage
cartStore.saveCartToStorage()
}
} catch (e: any) {
console.log(e)
}
}
onMounted(async () => {
// Load cart from storage if needed
cartStore.loadCartFromStorage()
await initPrice()
})
onUnmounted(() => {
stopPriceInterval()
})
</script>
<style scoped>
.text-primary {
color: #d3a233;
}
@media screen and (min-width: 426px) {
.wrap-fix {
width: 426px;
margin: 0 auto;
}
}
</style>