-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcart.html
306 lines (281 loc) · 12.9 KB
/
cart.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MyBookPal</title>
<script src="listAllBooks.js"></script>
<link rel="stylesheet" href="listAllBooks.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
</head>
<body>
<header>
<div class="brand">MyBookPal</div>
<nav>
<ul class="nav-menu">
<li><a href="./listAllBooks.html" class="books-icon">Books</a></li>
<!--
<li><a href="#ebooks" class="ebooks-icon"></a></li>
<li><a href="#audiobooks" class="audiobooks-icon">Audiobooks</a></li>
<li><a href="#bestsellers" class="bestsellers-icon">Bestsellers</a></li>
<li><a href="#comingsoon" class="comingsoon-icon">Coming Soon</a></li>
-->
<li class="dropdown">
<a href="#" class="bookLending-icon">BookLending</a>
<div class="dropdown-content">
<a href="listAllLendingBooks.html" id="borrowBookOption">Borrow a book</a>
<a href="returnBook.html" id="returnBookOption">Return a book</a>
<a href="MyBorrowedBooks.html" id="myBorrowedBooksOption">My borrowed books</a>
</div>
</li>
<li><a href="selling.html" class="books-icon">Selling Books</a></li>
<li class="dropdown">
<a href="#" class="bookLending-icon">Subscriptions</a>
<div class="dropdown-content">
<a href="subscribeBook.html" id="borrowBookOption">Subscribe to a book</a>
<a href="unsubscribeBook.html" id="returnBookOption">Unsubscribe</a>
</div>
</li>
<!-- ?id=${userId} -->
<li><a href="./wallet.html?id=1" class="Wallet_icon">Wallet</a></li>
<li><a href="./cart.html?id=1" class="cart-icon"><i class="fa fa-opencart" style="padding:3px;"></i>Cart</a></li>
<li><a href="./purchasehistory.html?id=1" class="Wallet_icon">Purchase History</a></li>
</ul>
</nav>
<ul class="user-menu">
<!-- <li class="home-button"><a href="listAllBooks.html" class="home-icon">Home</a></li> -->
<li class="dropdown">
<a href="#account" class="account-icon"><i class="fa fa-user" style="padding:3px;"></i>My Account</a>
<div class="dropdown-content">
<a href="#" id="borrowBookOption">Update Account</a>
<a href="listNotificationPreferences.html" id="borrowBookOption">Settings</a>
<a href="./public/index.html" id="borrowBookOption">Contact Us</a>
<a href="./public/index.html" id="borrowBookOption">FAQ</a>
<a href="login.html" id="borrowBookOption">Logout</a>
<a href="login.html" id="borrowBookOption">Sign In</a>
</div>
</li>
</ul>
</header>
<div class="search-bar">
<input type="text" id="searchInput" placeholder="Search for books">
<button><i class="fa fa-search"></i></button>
<button><a style="color: aliceblue;" href="./listAllBooks.html"><i class="fa fa-refresh"></i></a></button>
</div>
<div class="container">
<table id="cart">
<thead>
<tr>
<th class="third">Product</th>
<th class="second">Quantity</th>
<th class="fourth">Total</th>
<th class="fifth"> </th>
<th class="sixth"> </th>
</tr>
</thead>
<tbody id="cartDetails"></tbody>
<tr class="totalprice">
<td class="light">Total:</td>
<td colspan="2"> </td>
<td colspan="2"><span class="thick">$225.45</span></td>
</tr>
<tr class="walletamount">
<td class="light">Amount in Wallet:</td>
<td colspan="2"> </td>
<td colspan="2"><span class="thick">$225.45</span></td>
</tr>
<tr class="checkoutrow">
<td colspan="5" class="checkout-wallet-container">
<button id="submitbtn">Purchase Now!</button>
<button id="walletbtn">Go to Wallet</button>
</td>
</tr>
</table>
</div>
<script>
const serverURL = 'http://localhost:3000';
const userId = 1;
// Display cart details on page load
document.addEventListener("DOMContentLoaded", function () {
//write the redirection code here -> whenever cart is clicked, we should get the userid here
displayCartDetails(userId);
document.querySelector('#cartDetails').addEventListener('click', function(event) {
if (event.target.closest('.remove')) {
removeItem(event.target.closest('.remove'));
}
});
document.getElementById('submitbtn').addEventListener('click', function () {
purchaseNow(userId);
});
document.getElementById('walletbtn').addEventListener('click', function () {
redirectTowalletPage(userId);
})
});
// Function to fetch cart details
async function fetchCartDetails(userId) {
try {
const response = await fetch(`${serverURL}/view_cart?id=${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching cart details:', error.message);
throw error;
}
}
// Function to fetch book details
async function fetchBookDetails(bookId) {
try {
const response = await fetch(`${serverURL}/get_book_details?id=${bookId}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching book details:', error.message);
throw error;
}
}
// Function to display cart details on the page
async function displayCartDetails(userId) {
try {
const cartDetails = await fetchCartDetails(userId);
const tbody = document.getElementById('cartDetails');
const totalRow = document.querySelector('.totalprice');
const walletRow = document.querySelector('.walletamount');
tbody.innerHTML = '';
if (cartDetails.length > 0) {
let finalCartValue = 0;
for (const item of cartDetails) {
const bookDetails = await fetchBookDetails(item.BookID);
const totalPrice = item.Quantity * bookDetails[0].Price;
finalCartValue += totalPrice;
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${bookDetails[0].Title}</td>
<td><input type="number" value="${item.Quantity}" min="0" max="99" class="qtyinput" onchange="updateQuantity(this)"></td>
<td>${totalPrice.toFixed(2)}</td>
<td><span class="remove" data-book-id="${bookDetails[0].BookID}" onclick="removeItem(this)"><img src="https://i.imgur.com/h1ldGRr.png" alt="Remove"></span></td>
`;
tbody.appendChild(tr);
}
totalRow.classList.remove('hidden');
walletRow.classList.remove('hidden');
document.querySelector('.totalprice td span.thick').innerText = `$${finalCartValue.toFixed(2)}`;
const walletResponse = await fetch(`${serverURL}/wallet_balance?id=${userId}`);
const walletData = await walletResponse.json();
const walletAmount = parseFloat(walletData.balance);
document.querySelector('.walletamount td span.thick').innerText = `$${walletAmount.toFixed(2)}`;
} else {
totalRow.classList.add('hidden');
walletRow.classList.add('hidden');
}
} catch (error) {
console.error('Error fetching cart details:', error);
}
}
function getBookIdFromRow(row) {
const bookId = row.querySelector('.remove').getAttribute('data-book-id');
console.log('This is the bookid', bookId);
return bookId;
}
// Function to remove an item from the cart
async function removeItem(element) {
const row = element.closest('tr');
const bookId = getBookIdFromRow(row);
try {
const response = await fetch(`${serverURL}/delete_item_from_cart?userId=${userId}&bookId=${bookId}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
row.parentNode.removeChild(row);
updateTotalPrice(userId);
} catch (error) {
console.error('Error removing item from cart:', error);
}
}
async function updateTotalPrice(userId) {
try {
const cartDetails = await fetchCartDetails(userId);
let finalCartValue = 0;
for (const item of cartDetails) {
const bookDetails = await fetchBookDetails(item.BookID);
finalCartValue += item.Quantity * bookDetails[0].Price;
}
document.querySelector('.totalprice td span.thick').innerText = `$${finalCartValue.toFixed(2)}`;
} catch (error) {
console.error('Error updating total price:', error);
}
}
async function purchaseNow(userId) {
try {
// Fetch the cart details to include in the purchase request
const cartDetails = await fetchCartDetails(userId);
// Check if the cart is not empty
if (cartDetails.length === 0) {
alert('Cart is empty. Add items to the cart before purchasing.');
return;
}
// Prepare the purchase request body
const requestBody = JSON.stringify(cartDetails.map(item => ({
UserID: userId,
BookID: item.BookID,
Quantity: item.Quantity
})));
// Make a request to the backend to initiate the purchase
const response = await fetch(`${serverURL}/purchase_product`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: requestBody,
});
// Check if the response status is in the success range (200-299)
if (response.status >= 200 && response.status < 300) {
// If the purchase is successful, update the UI or perform any necessary actions
console.log('Purchase successful!');
// Optionally, you can clear the cart and update the displayed cart details
displayCartDetails(userId);
// Redirect to the purchase history page with the user ID
redirectToPurchaseHistory(userId);
} else {
// Handle specific error messages from the backend
const responseData = await response.json();
if (responseData.error) {
// Alert for specific error messages
alert(responseData.error);
} else {
// For unexpected errors, display a generic error message
throw new Error(`HTTP error! Status: ${response.status}`);
}
}
} catch (error) {
// Log the detailed error information to the console
console.error('Error during purchase:', error);
// Display a more specific error message based on the type of error
if (error instanceof TypeError) {
alert('Error during purchase: There was a type error. Please check your code.');
} else if (error instanceof SyntaxError) {
alert('Error during purchase: There was a syntax error in your code.');
} else {
// For unexpected errors, display a generic error message
alert('Error during purchase: Something went wrong. Please try again.');
}
}
}
// Function to redirect to another page with the user ID
function redirectToPurchaseHistory(userId) {
const redirectURL = `purchasehistory.html?id=${userId}`;
window.location.href = redirectURL;
}
function redirectTowalletPage(userId) {
const redirectURL = `wallet.html?id=${userId}`;
window.location.href = redirectURL;
}
</script>
</body>
</html>