Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master'
Browse files Browse the repository at this point in the history
  • Loading branch information
Apoorva64 committed Sep 25, 2024
2 parents 4cde7e9 + 4096964 commit d813371
Showing 1 changed file with 28 additions and 57 deletions.
85 changes: 28 additions & 57 deletions libs/ui/common/src/lib/commandsR/stores/cart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,67 +2,38 @@ import {create} from "zustand/index";

export interface CartsState {
carts: {[tableNumber: number]: {itemId: string, quantity: number}[]};
addItem: (tableNumber: number, itemId: string, quantity: number) => void;
removeItem: (itableNumber: number, itemId: string, quantity: number) => void;
updateItem: (itableNumber: number, itemId: string, quantity: number) => void;
resetCart: (tableNumber: number) => void;
}

export const useCarts = create<CartsState>((set) => ({
carts: {},
addItem: (tableNumber, itemId, quantity) => set((state) => {
const currentCart = state.carts[tableNumber] || [];

// Check if item exists
const itemIndex = currentCart.findIndex(
(element) => element.itemId === itemId
);

return {
carts: {
...state.carts,
[tableNumber]:
itemIndex !== -1
? currentCart.map((item, index) =>
index === itemIndex
? { ...item, quantity: item.quantity + quantity }
: item
)
: [...currentCart, { itemId, quantity }],
},
};
}),
removeItem: (tableNumber, itemId, quantity) =>
set((state) => {
const currentCart = state.carts[tableNumber] || [];

const itemIndex = currentCart.findIndex(
(element) => element.itemId === itemId
);

if (itemIndex === -1) return state;

const updatedCart = currentCart
.map((item, index) =>
index === itemIndex
? { ...item, quantity: item.quantity - quantity }
: item
)
.filter((item) => item.quantity > 0);

return {
carts: {
...state.carts,
[tableNumber]: updatedCart,
},
};
}),
resetCart: (tableNumber) =>
set((state) => ({
carts: {
...state.carts,
[tableNumber]: [],
},
})
),
updateItem: (tableNumber, itemId, quantity) => set((state) => {
const currentCart = state.carts[tableNumber] || [];

const itemIndex = currentCart.findIndex(element => element.itemId === itemId);

return {
carts: {
...state.carts,
tableNumber:
(itemIndex === -1) ? [...currentCart, {itemId, quantity}].filter(element => element.quantity > 0)
: currentCart.map(element => {
if (element.itemId === itemId) {
element.quantity = quantity
}
return element
}).filter(element => element.quantity > 0)
}
}
}),
resetCart: (tableNumber) =>
set((state) => ({
carts: {
...state.carts,
[tableNumber]: [],
},
})
),
})
);

0 comments on commit d813371

Please sign in to comment.