-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
318 lines (263 loc) · 8.68 KB
/
Copy pathdatabase.js
File metadata and controls
318 lines (263 loc) · 8.68 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// ==================== API CONFIGURATION ====================
const API_URL = 'http://localhost:3000/api';
// ==================== HELPER FUNCTIONS ====================
// Get current user from localStorage
const getCurrentUser = () => {
const userStr = localStorage.getItem('surron_current_user');
return userStr ? JSON.parse(userStr) : null;
};
// Set current user to localStorage
const setCurrentUser = (user) => {
localStorage.setItem('surron_current_user', JSON.stringify(user));
};
// Remove current user from localStorage
const removeCurrentUser = () => {
localStorage.removeItem('surron_current_user');
};
// Generic API call function
const apiCall = async (endpoint, options = {}) => {
try {
const response = await fetch(`${API_URL}${endpoint}`, {
headers: {
'Content-Type': 'application/json',
...options.headers
},
...options
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Request failed');
}
return data;
} catch (error) {
console.error('API Error:', error);
throw error;
}
};
// ==================== DATABASE OBJECT ====================
const DB = {
// ==================== AUTH ====================
async register(username, email, password) {
const result = await apiCall('/auth/register', {
method: 'POST',
body: JSON.stringify({ username, email, password })
});
if (result.success && result.data.user) {
setCurrentUser(result.data.user);
}
return result;
},
async login(username, password) {
const result = await apiCall('/auth/login', {
method: 'POST',
body: JSON.stringify({ username, password })
});
if (result.success && result.data.user) {
setCurrentUser(result.data.user);
}
return result;
},
logout() {
removeCurrentUser();
},
getCurrentUser() {
return getCurrentUser();
},
// ==================== PRODUCTS ====================
async getAllProducts(category = null, search = null) {
try {
let url = '/products';
const params = new URLSearchParams();
if (category && category !== 'All') {
params.append('category', category);
}
if (search) {
params.append('search', search);
}
if (params.toString()) {
url += `?${params.toString()}`;
}
const result = await apiCall(url);
return result.success ? result.data : [];
} catch (error) {
console.error('Get products error:', error);
return [];
}
},
async getProduct(id) {
try {
const result = await apiCall(`/products/${id}`);
return result.success ? result.data : null;
} catch (error) {
console.error('Get product error:', error);
return null;
}
},
async createProduct(productData) {
return await apiCall('/products', {
method: 'POST',
body: JSON.stringify(productData)
});
},
async updateProduct(id, productData) {
return await apiCall(`/products/${id}`, {
method: 'PUT',
body: JSON.stringify(productData)
});
},
async deleteProduct(id) {
return await apiCall(`/products/${id}`, {
method: 'DELETE'
});
},
// ==================== CART ====================
async getCart() {
try {
const user = getCurrentUser();
if (!user) return { items: [] };
const result = await apiCall(`/cart/${user.id}`);
// Get full product details for cart items
if (result.success && result.data.items.length > 0) {
const cartItems = [];
for (const item of result.data.items) {
const product = await this.getProduct(item.productId);
if (product) {
cartItems.push({
...product,
quantity: item.quantity
});
}
}
return { ...result.data, items: cartItems };
}
return result.success ? result.data : { items: [] };
} catch (error) {
console.error('Get cart error:', error);
return { items: [] };
}
},
async addToCart(productId, quantity = 1) {
const user = getCurrentUser();
if (!user) {
throw new Error('Нэвтрэх шаардлагатай');
}
return await apiCall(`/cart/${user.id}/add`, {
method: 'POST',
body: JSON.stringify({ productId, quantity })
});
},
async updateCartItem(productId, quantity) {
const user = getCurrentUser();
if (!user) {
throw new Error('Нэвтрэх шаардлагатай');
}
return await apiCall(`/cart/${user.id}/update`, {
method: 'PUT',
body: JSON.stringify({ productId, quantity })
});
},
async removeFromCart(productId) {
const user = getCurrentUser();
if (!user) {
throw new Error('Нэвтрэх шаардлагатай');
}
return await apiCall(`/cart/${user.id}/remove/${productId}`, {
method: 'DELETE'
});
},
async clearCart() {
const user = getCurrentUser();
if (!user) {
throw new Error('Нэвтрэх шаардлагатай');
}
return await apiCall(`/cart/${user.id}/clear`, {
method: 'DELETE'
});
},
// ==================== ORDERS ====================
async createOrder(items, totalAmount, shippingAddress = {}) {
const user = getCurrentUser();
if (!user) {
throw new Error('Нэвтрэх шаардлагатай');
}
// Format items for order
const orderItems = items.map(item => ({
productId: item.id,
name: item.name,
price: item.price,
quantity: item.quantity,
image: item.image
}));
return await apiCall('/orders', {
method: 'POST',
body: JSON.stringify({
userId: user.id,
items: orderItems,
totalAmount,
shippingAddress
})
});
},
async getAllOrders() {
try {
const user = getCurrentUser();
if (!user) return [];
const params = new URLSearchParams({
userId: user.id,
role: user.role
});
const result = await apiCall(`/orders?${params.toString()}`);
return result.success ? result.data : [];
} catch (error) {
console.error('Get orders error:', error);
return [];
}
},
async getOrder(id) {
try {
const result = await apiCall(`/orders/${id}`);
return result.success ? result.data : null;
} catch (error) {
console.error('Get order error:', error);
return null;
}
},
async updateOrderStatus(id, status) {
return await apiCall(`/orders/${id}/status`, {
method: 'PUT',
body: JSON.stringify({ status })
});
},
async getDashboardStats() {
try {
const result = await apiCall('/orders/stats/dashboard');
return result.success ? result.data : {
totalOrders: 0,
pendingOrders: 0,
totalRevenue: 0,
productCount: 0
};
} catch (error) {
console.error('Get stats error:', error);
return {
totalOrders: 0,
pendingOrders: 0,
totalRevenue: 0,
productCount: 0
};
}
},
// ==================== HELPER METHODS ====================
getCategories() {
return ['All', 'Electronics', 'Battery', 'Suspension', 'Brakes', 'Wheels', 'Accessories'];
},
// Compatibility method for cart badge
async getCartCount() {
const cart = await this.getCart();
return cart.items.reduce((total, item) => total + item.quantity, 0);
}
};
// Export for use in other files
if (typeof module !== 'undefined' && module.exports) {
module.exports = DB;
}