1404/11/08-store style

This commit is contained in:
2026-01-28 11:17:48 +03:30
parent 1d6f342ff1
commit 00c2e38ab9
23 changed files with 2047 additions and 127 deletions
+109
View File
@@ -0,0 +1,109 @@
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import type { CartItem } from '@/models/cart'
import type { Product } from '@/models/products'
const CART_STORAGE_KEY = 'ghatre_cart'
export const useCartStore = defineStore('cart', () => {
const cartItems = ref<CartItem[]>([])
// Load cart from localStorage on initialization
function loadCartFromStorage() {
try {
const stored = localStorage.getItem(CART_STORAGE_KEY)
if (stored) {
cartItems.value = JSON.parse(stored)
}
} catch (e) {
console.error('Error loading cart from storage:', e)
cartItems.value = []
}
}
// Save cart to localStorage
function saveCartToStorage() {
try {
localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(cartItems.value))
} catch (e) {
console.error('Error saving cart to storage:', e)
}
}
// Initialize cart from storage
loadCartFromStorage()
// Add item to cart
function addToCart(
product: Product,
quantity: number,
method: 'cash' | 'gold',
gateway: boolean,
goldVazn?: number,
goldCash: number = 0
) {
const itemId = `${Date.now()}_${product.id}`
const price = (product.price ?? 0) + (product.cash_fee_buy ?? 0)
const totalPrice = price * quantity
const cartItem: CartItem = {
id: itemId,
product: { ...product },
quantity,
method,
gateway,
goldVazn,
goldCash,
price,
totalPrice,
addedAt: Date.now()
}
cartItems.value.push(cartItem)
saveCartToStorage()
}
// Remove item from cart
function removeFromCart(itemId: string) {
const index = cartItems.value.findIndex(item => item.id === itemId)
if (index !== -1) {
cartItems.value.splice(index, 1)
saveCartToStorage()
}
}
// Clear cart
function clearCart() {
cartItems.value = []
saveCartToStorage()
}
// Get cart items
function getCartItems(): CartItem[] {
return cartItems.value
}
// Computed: Total price
const totalPrice = computed(() => {
return cartItems.value.reduce((sum, item) => sum + item.totalPrice, 0)
})
// Computed: Item count
const itemCount = computed(() => {
return cartItems.value.length
})
return {
cartItems,
addToCart,
removeFromCart,
clearCart,
getCartItems,
totalPrice,
itemCount,
loadCartFromStorage,
saveCartToStorage
}
})