-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
350 lines (305 loc) · 10.9 KB
/
app.js
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Function to load products and display them
async function loadProducts() {
try {
const productsContainer = document.querySelector(".products");
const response = await fetch("http://localhost:3000/coffee");
const products = await response.json();
console.log("Output: ", products);
products.forEach((product) => {
const productItem = document.createElement("div");
productItem.classList.add("product");
productItem.innerHTML = `
<img src="${product.image}" alt="${product.title}">
<div class="product-title">${product.title}</div>
<div class="product-price">$${product.price}</div>
<div class="product-quantity">In Storage: ${product.quantityInStorage}</div>
<button onclick="addToCart('${product._id}', '${product.title}', ${product.price})">Add to Cart</button>
`;
productsContainer.appendChild(productItem);
});
} catch (error) {
console.error("Error fetching products:", error);
}
}
// Function to toggle the cart panel
function toggleCart() {
const cartPanel = document.querySelector(".cart-panel");
cartPanel.classList.toggle("active");
// Calculate total price when opening the cart
calculateTotal();
}
// Function to add product to cart
function addToCart(productId, title, price) {
// Check if the product is already in the cart
const cartItems = document.querySelectorAll(".cart-item");
let found = false;
cartItems.forEach((item) => {
if (item.dataset.productId === productId) {
found = true;
let quantity = parseInt(item.dataset.quantity) + 1;
item.innerHTML = `${quantity}x ${title} - $${price * quantity}`;
item.dataset.quantity = quantity;
}
});
if (!found) {
// Create an object representing the product
const product = { _id: productId, title: title, price: price, quantity: 1 };
// Add the item to the cart panel
const cartContent = document.querySelector(".cart-content");
const cartItem = document.createElement("div");
cartItem.classList.add("cart-item");
cartItem.dataset.productId = productId;
cartItem.dataset.quantity = "1";
cartItem.innerHTML = `1x ${title} - $${price}`;
cartContent.appendChild(cartItem);
}
// Calculate total price whenever an item is added
calculateTotal();
}
// Function to calculate the total price of all items in the cart
function calculateTotal() {
const cartItems = document.querySelectorAll(".cart-item");
let totalPrice = 0;
cartItems.forEach((item) => {
const itemPrice = parseFloat(item.innerHTML.split("$")[1]); // Extract item price
totalPrice += itemPrice;
});
const cartPanel = document.querySelector(".cart-panel");
const totalElement = document.createElement("div");
totalElement.classList.add("total");
totalElement.innerHTML = `<strong>Total Price:</strong> $${totalPrice.toFixed(
2
)}`;
// Remove previous total price element before appending a new one
const existingTotal = document.querySelector(".total");
if (existingTotal) {
cartPanel.removeChild(existingTotal);
}
cartPanel.appendChild(totalElement);
}
// Function to clear the cart (remove all items)
function clearCart() {
const cartContent = document.querySelector(".cart-content");
cartContent.innerHTML = ""; // Clear all cart items
// Clear total price when cart is cleared
const cartPanel = document.querySelector(".cart-panel");
const existingTotal = document.querySelector(".total");
if (existingTotal) {
cartPanel.removeChild(existingTotal);
}
}
// Function to authenticate user credentials
function authenticate(username, password) {
return fetch("http://localhost:3000/credential")
.then((response) => response.json())
.then((credentials) => {
const foundUser = credentials.find(
(cred) => cred.username === username && cred.password === password
);
return foundUser ? true : false;
})
.catch((error) => {
console.error("Error fetching credentials:", error);
return false;
});
}
// Function to handle login form submission
function login(event) {
event.preventDefault();
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
authenticate(username, password).then((isAuthenticated) => {
if (isAuthenticated) {
// Store authentication status in localStorage
localStorage.setItem("loggedIn", "true");
localStorage.setItem("username", username);
window.location.href = "index.html"; // Redirect to main page on successful login
} else {
alert("Invalid credentials. Please try again.");
}
});
}
// Function to log out (clears authentication status and redirects to login page)
function logout() {
localStorage.removeItem("loggedIn");
window.location.href = "login.html";
}
// Function to check if user is logged in
function checkLogin() {
const isLoggedIn = localStorage.getItem("loggedIn");
if (!isLoggedIn || isLoggedIn !== "true") {
window.location.href = "login.html"; // Redirect to login page if not logged in
}
}
// Function to generate a random unique string to serve as purchase code
function generateRandomString(length) {
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
// Function to confirm purchase
async function confirmPurchase() {
const isLoggedIn = localStorage.getItem("loggedIn");
const storedUsername = localStorage.getItem("username");
if (!isLoggedIn || isLoggedIn !== "true" || !storedUsername) {
alert("Please login to confirm your purchase.");
return;
}
// Calculate the total price
calculateTotal();
const cartItems = document.querySelectorAll(".cart-item");
const purchaseDetails = [];
const cartProducts = [];
cartItems.forEach((item) => {
const productId = item.dataset.productId;
const quantity = parseInt(item.dataset.quantity);
const title = item.innerHTML.split("x")[1].trim().split("-")[0].trim();
const price = parseFloat(item.innerHTML.split("$")[1]);
purchaseDetails.push({ productId, title, quantity, price });
cartProducts.push({ productId, quantity });
});
try {
const response = await fetch("http://localhost:3000/coffee");
const products = await response.json();
for (const cartProduct of cartProducts) {
const product = products.find(
(prod) => prod._id === cartProduct.productId
);
if (!product) {
alert("Error: Product not found.");
return;
}
if (cartProduct.quantity > product.quantityInStorage) {
alert(
`The quantity of ${product.title} in your cart exceeds the available quantity in storage. Please update your cart.`
);
return;
}
}
const purchaseCode = generateRandomString(10);
const totalPrice = parseFloat(
document.querySelector(".total").textContent.split("$")[1]
);
const status = "Shipping soon";
const purchaseData = {
username: storedUsername,
purchaseCode: purchaseCode,
items: purchaseDetails,
totalPrice: totalPrice,
status: status,
};
sendPurchaseDataToServer(purchaseData);
} catch (error) {
console.error("Error confirming purchase:", error);
alert("There was an error confirming your purchase. Please try again.");
}
}
// Function to send purchase data to server using RESTful API
async function sendPurchaseDataToServer(data) {
try {
const response = await fetch("http://localhost:3000/purchase", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
const result = await response.json();
console.log("Purchase confirmed:", result);
const purchaseCode = data.purchaseCode;
alert(
`Purchase confirmed! Your purchase code is: ${purchaseCode}\nThank you for shopping with us.`
);
// After successful purchase, update the quantity in storage
await updateQuantityInStorage(data.items);
clearCart(); // Clear the cart after purchase confirmation
// Store purchase information in local storage
localStorage.setItem("lastPurchase", JSON.stringify(data));
// Reset the page after closing the alert
window.location.href = "orderStatus.html";
} catch (error) {
console.error("Error confirming purchase:", error);
alert("There was an error confirming your purchase. Please try again.");
}
}
async function updateQuantityInStorage(purchasedItems) {
for (const item of purchasedItems) {
try {
const product = await fetchProductData(item.productId);
const currentQuantityInStorage = parseFloat(product.quantityInStorage);
const purchasedQuantity = parseFloat(item.quantity);
if (!isNaN(currentQuantityInStorage) && !isNaN(purchasedQuantity)) {
const updatedQuantity = currentQuantityInStorage - purchasedQuantity;
// Update the quantity in storage for the purchased product
await updateProductQuantity(item.productId, updatedQuantity);
} else {
console.error(
`Error: Invalid quantity values for product ID ${item.productId}`
);
// Handle error scenario if needed
}
} catch (error) {
console.error(
`Error updating quantity for product ID ${item.productId}:`,
error
);
// Handle error scenario if needed
}
}
}
async function fetchProductData(productId) {
try {
const response = await fetch(`http://localhost:3000/coffee/${productId}`);
if (!response.ok) {
throw new Error("Failed to fetch product data");
}
const product = await response.json();
return product;
} catch (error) {
console.error("Error fetching product data:", error);
throw error; // Propagate the error to the caller if needed
}
}
async function updateProductQuantity(productId, updatedQuantity) {
try {
const updateResponse = await fetch(
`http://localhost:3000/coffee/${productId}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
quantityInStorage: updatedQuantity,
}),
}
);
if (!updateResponse.ok) {
throw new Error("Failed to update product quantity");
}
console.log(`Quantity updated for product ID ${productId}`);
} catch (error) {
console.error(
`Error updating quantity for product ID ${productId}:`,
error
);
throw error; // Propagate the error to the caller if needed
}
}
function switchToAdmin() {
window.location.href = "admin/adminLogin.html";
}
// Check login status when loading the main page
if (
window.location.pathname === "/index.html" ||
window.location.pathname === "/"
) {
checkLogin();
}
// Call the function to load products when the page loads
loadProducts();