Files
ebook/store/useSelectedBook.ts
koziavin 925b6197f2
All checks were successful
Deploy Nuxt App / deploy (push) Successful in 3m59s
add. Closes #8
2025-06-22 08:53:02 +04:00

59 lines
1.6 KiB
TypeScript

import { defineStore } from 'pinia'
interface CartItem {
id: number
quantity: number
summary?: number
}
export const useSelectedBook = defineStore('selectedBook', {
state: () => ({
cartQuantities: [] as CartItem[],
}),
actions: {
increment(id: number) {
const item = this.cartQuantities.find((i) => i.id === id)
if (item && item.quantity < 1) {
item.quantity++
}
},
decrement(id: number) {
const item = this.cartQuantities.find((i) => i.id === id)
if (item) {
item.quantity--
}
},
reset(id: number) {
const idx = this.cartQuantities.findIndex((i) => i.id === id)
if (idx !== -1) {
this.cartQuantities.splice(idx, 1)
}
},
addToCart(id: number) {
if (!this.cartQuantities.find((i) => i.id === id)) {
this.cartQuantities.push({ id, quantity: 1 })
}
},
getQuantity(id: number) {
return this.cartQuantities.find((i) => i.id === id)?.quantity || 0
},
},
getters: {
getTotalPrice: (state) => (books: { id: number; price: number }[]) => {
const selected = state.cartQuantities.filter((i) => i.quantity > 0)
if (selected.length === 2) {
// Проверяем, что это две разные книги
const ids = selected.map((i) => i.id)
if (ids[0] !== ids[1]) {
return 936
}
}
// Обычная сумма
return selected.reduce((sum, item) => {
const book = books.find((b) => b.id === item.id)
return sum + (book ? book.price * item.quantity : 0)
}, 0)
},
},
})