1405/03/09-fix bug in transactions & cart

This commit is contained in:
2026-05-30 16:13:21 +03:30
parent 53a3e2f61a
commit bf34d0fba0
5 changed files with 184 additions and 141 deletions
+58 -1
View File
@@ -2,6 +2,8 @@ import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import type { CartItem } from '@/models/cart'
import type { Product } from '@/models/products'
import type { Price } from '@/models/home'
import { getProducts } from '@/api/products'
const CART_STORAGE_KEY = 'ghatre_cart'
@@ -93,6 +95,58 @@ export const useCartStore = defineStore('cart', () => {
return cartItems.value.length
})
function syncProductsFromServer(serverProducts: Product[]): number {
const productMap = new Map(serverProducts.map(p => [p.id, p]))
const beforeCount = cartItems.value.length
cartItems.value = cartItems.value
.filter(item => productMap.has(item.product.id))
.map(item => ({
...item,
product: { ...productMap.get(item.product.id)! }
}))
if (cartItems.value.length > 0 || beforeCount > 0) {
saveCartToStorage()
}
return beforeCount - cartItems.value.length
}
function recalculateCartPrices(lastPrice: Price) {
if (!lastPrice || cartItems.value.length === 0) return
cartItems.value.forEach((item) => {
const product = item.product
let newPrice = 0
if (product.group_type == 'آبشده') {
newPrice = lastPrice.price_last ?? 0
} else {
newPrice = product.amount * (lastPrice.price_last ?? 0)
}
product.price = newPrice
product.sellPrice = product.amount * (lastPrice.sell ?? 0)
item.price = newPrice + (product.cash_fee_buy ?? 0)
item.totalPrice = parseInt(String(item.price * item.quantity))
})
saveCartToStorage()
}
async function refreshCartFromServer(): Promise<number> {
if (cartItems.value.length === 0) return 0
try {
const serverProducts: Product[] = await getProducts()
return syncProductsFromServer(serverProducts)
} catch (e) {
console.error('Error refreshing cart from server:', e)
return 0
}
}
return {
cartItems,
addToCart,
@@ -102,7 +156,10 @@ export const useCartStore = defineStore('cart', () => {
totalPrice,
itemCount,
loadCartFromStorage,
saveCartToStorage
saveCartToStorage,
syncProductsFromServer,
recalculateCartPrices,
refreshCartFromServer
}
})