1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
|
import { create } from 'zustand';
import { CartItem, CartProps } from '~/types/cart';
import { getUserCart } from '~/services/cart';
import {
syncCartWithCookie,
getCartDataFromCookie,
getSelectedItemsFromCookie,
forceResetAllSelectedItems,
} from '~/utils/cart';
interface Summary {
subtotal: number;
discount: number;
total: number;
tax: number;
grandTotal: number;
}
interface SyncResult {
cartData?: Record<string, any>;
selectedItems?: Record<number, boolean>;
needsUpdate: boolean;
}
interface State {
cart: CartProps | null;
isLoadCart: boolean;
summary: Summary;
}
interface Action {
loadCart: (userId: number) => Promise<void>;
updateCartItem: (updateCart: CartProps) => void;
forceResetSelection: () => void;
clearCart: () => void;
}
export const useCartStore = create<State & Action>((set, get) => ({
cart: null,
isLoadCart: false,
summary: {
subtotal: 0,
discount: 0,
total: 0,
tax: 0,
grandTotal: 0,
},
loadCart: async (userId: number): Promise<void> => {
if (get().isLoadCart) return;
set({ isLoadCart: true });
try {
const cart: CartProps = (await getUserCart(userId)) as CartProps;
// Sync with cookie data
const syncResult = syncCartWithCookie(cart) as SyncResult;
if (syncResult?.needsUpdate && cart.products) {
const selectedItems = getSelectedItemsFromCookie() as Record<
number,
boolean
>;
const updatedCart: CartProps = {
...cart,
products: cart.products.map((item) => ({
...item,
selected:
selectedItems[item.id] !== undefined
? selectedItems[item.id]
: item.selected,
})),
};
set({ cart: updatedCart });
} else {
set({ cart });
}
// Update summary
const summary = computeSummary(get().cart!);
set({ summary });
} catch (error) {
console.error('Failed to load cart:', error);
// Fallback to cookie data
await handleFallbackFromCookie();
} finally {
set({ isLoadCart: false });
}
},
updateCartItem: (updatedCart: CartProps): void => {
set({ cart: updatedCart });
syncCartWithCookie(updatedCart);
const summary = computeSummary(updatedCart);
set({ summary });
},
forceResetSelection: (): void => {
const { cart } = get();
if (!cart) return;
forceResetAllSelectedItems();
const updatedCart: CartProps = {
...cart,
products: cart.products.map((item) => ({ ...item, selected: false })),
};
set({ cart: updatedCart });
const summary = computeSummary(updatedCart);
set({ summary });
},
clearCart: (): void => {
set({
cart: null,
summary: {
subtotal: 0,
discount: 0,
total: 0,
tax: 0,
grandTotal: 0,
},
});
},
}));
// Helper function for cookie fallback
const handleFallbackFromCookie = async (): Promise<void> => {
try {
const cartData = getCartDataFromCookie() as Record<string, any>;
if (Object.keys(cartData).length === 0) return;
const products: CartItem[] = Object.values(cartData).map(
transformCookieItemToProduct
);
const fallbackCart: CartProps = {
product_total: products.length,
products,
};
useCartStore.setState({ cart: fallbackCart });
const summary = computeSummary(fallbackCart);
useCartStore.setState({ summary });
} catch (error) {
console.error('Cookie fallback failed:', error);
}
};
// Helper function to transform cookie item to product format
const transformCookieItemToProduct = (item: any): CartItem => ({
image_program: item.image_program || '',
cart_id: item.cart_id,
quantity: item.quantity,
selected: item.selected,
can_buy: true,
cart_type: item.cart_type,
id: item.id,
name: item.product?.name || item.program_line?.name || '',
stock: 0,
is_in_bu: false,
on_hand_qty: 0,
available_quantity: 0,
weight: 0,
attributes: [],
parent: {
id: 0,
name: '',
image: '',
},
price: item.price || {
price: 0,
discount_percentage: 0,
price_discount: 0,
},
manufacture: {
id: 0,
name: '',
},
has_flashsale: false,
subtotal: 0,
code: item.code,
image: item.image,
package_price: item.package_price,
});
const computeSummary = (cart: CartProps): Summary => {
if (!cart?.products) {
return { subtotal: 0, discount: 0, total: 0, grandTotal: 0, tax: 0 };
}
const PPN = parseFloat(process.env.NEXT_PUBLIC_PPN || '1.11');
let subtotal = 0;
let discount = 0;
for (const item of cart.products) {
if (!item.selected) continue;
const price =
item.cart_type === 'promotion'
? (item?.package_price || 0) * item.quantity
: item.price.price * item.quantity;
subtotal += price;
discount += price - item.price.price_discount * item.quantity;
}
const total = subtotal - discount;
// PERBAIKAN:
const tax = total * (PPN - 1);
const grandTotal = total + tax;
return { subtotal, discount, total, grandTotal, tax };
};
|