WIP: cart

This commit is contained in:
Nikita Kiselev
2025-07-22 00:27:40 +03:00
parent ce2c9e374d
commit 626ee6ecb0
10 changed files with 165 additions and 37 deletions

View File

@@ -1,43 +1,69 @@
import {defineStore} from "pinia";
import md5 from 'crypto-js/md5';
import ftch from "@/utils/ftch.js";
export const useCartStore = defineStore('cart', {
state: () => ({
items: [],
isLoading: false,
}),
actions: {
getProduct(productId) {
return this.items.find(item => parseInt(item.productId) === parseInt(productId)) ?? null;
getItem(rowId) {
return this.items.find(item => item.rowId === rowId) ?? null;
},
hasProduct(productId) {
return this.getProduct(productId) !== null;
hasItem(rowId) {
return this.getItem(rowId) !== null;
},
addProduct(productId, productName, price, quantity = 1, options = []) {
this.items.push({
async addProduct(productId, productName, price, quantity = 1, options = []) {
const rowId = this.generateRowId(productId, options);
const item = {
rowId: rowId,
productId: productId,
productName: productName,
price: price,
quantity: quantity,
options: options,
});
options: JSON.parse(JSON.stringify(options)), // ← 💥 глубокая копия!
};
this.items.push(item);
return rowId;
},
removeProduct(productId) {
this.items.splice(this.items.indexOf(productId), 1);
removeItem(rowId) {
this.items.splice(this.items.indexOf(rowId), 1);
},
getQuantity(productId) {
if (this.hasProduct(productId)) {
return this.getProduct(productId).quantity;
getQuantity(rowId) {
if (this.hasItem(rowId)) {
return this.getItem(rowId).quantity;
}
return 0;
},
setQuantity(productId, quantity) {
this.getProduct(productId).quantity = quantity;
}
setQuantity(rowId, quantity) {
this.getItem(rowId).quantity = quantity;
},
generateRowId(productId, options) {
return md5(productId + JSON.stringify(options)).toString();
},
async checkout() {
try {
this.isLoading = true;
const {data} = await ftch('checkout', null, this.items);
this.items = data;
} catch (e) {
console.error(e);
} finally {
this.isLoading = false;
}
},
},
});