-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
718 lines (621 loc) · 20.7 KB
/
index.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
import express from "express";
import bodyParser from "body-parser";
import { dirname } from "path";
import { fileURLToPath } from "url";
import path from "path";
import mysql from "mysql2";
//import { v4 as uuidv4 } from 'uuid';
import stripe from 'stripe';
const __dirname = dirname(fileURLToPath(import.meta.url));
const app = express();
const port = 3000;
const router = express.Router();
app.use(express.json());
app.set("view engine", "ejs");
const PUBLISHABLE_KEY="pk_test_51OJtuIJKeBRiVd9Q77K37puMcCb8YmmDOBDnpgWPS4LKZb8l4lPGsSs7efvMhXWQesYI9EGJojJjWFZ7oswVgYqk00awcJYVXY"
const SECRET_KEY="sk_test_51OJtuIJKeBRiVd9Q4vvWtKr2qncPZ2RABm3QXFORcqNlkLXVTbxgqlPtc6bPXDjxn23oRVBurOjSvlXBVrZQLPWo00c9lVmdQN"
const stripeInstance = stripe(SECRET_KEY);
// MySQL Connection Configuration
let globalEmail;
const connection = mysql.createConnection({
host: 'localhost',
user: 'myuser',
password: 'abc123',
database: 'store'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL:', err);
return;
}
console.log('Connected to MySQL');
});
// Handle MySQL disconnection event
connection.on('end', () => {
console.log('Disconnected from MySQL');
});
// Serve static files
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
// Serve login page by default
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "/public/home.html"));
});
console.log("working");
app.post("/test", (req, res) => {
// Retrieve user data from the form
const {fullname, email, password, date, gender,address,phone } = req.body;
// Log the data to the console
console.log("Data received from the login form:");
console.log("Full Name:", fullname);
console.log("Email:", email);
console.log("Password:", password);
console.log("Date:", date);
console.log("Gender:", gender);
console.log('Address:', address);
console.log('Phone:', phone);
// Check if the email already exists
const checkEmailQuery = "SELECT COUNT(*) AS emailCount FROM Users WHERE Email = ?";
connection.query(checkEmailQuery, [email], (err, results) => {
if (err) {
console.error("Error checking email:", err);
res.status(500).send("Internal Server Error");
return;
}
const emailCount = results[0].emailCount;
if (emailCount > 0) {
// Email already exists, send a message to the user
res.status(400).send("You are already a member. Please login.");
} else {
// Email doesn't exist, proceed to insert the new user
// Query to get the maximum existing User_ID
const getMaxUserIdQuery = "SELECT MAX(CAST(SUBSTRING(User_ID, 2) AS SIGNED)) AS maxUserId FROM Users";
connection.query(getMaxUserIdQuery, (err, results) => {
if (err) {
console.error("Error getting max user ID:", err);
res.status(500).send("Internal Server Error");
return;
}
// Generate the new User_ID by incrementing the maxUserId
const maxUserId = results[0].maxUserId || 1000;
const newUserId = `U${maxUserId + 1}`;
// Insert user data into the Users table
const insertUserQuery = `
INSERT INTO Users (User_ID, Username, Passwords, Email, First_name, Last_name, Address, Phone_number)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`;
connection.query(
insertUserQuery,
[newUserId, fullname, password, email, fullname,"",address,phone], // You might want to modify this depending on your actual database schema
(err, results) => {
if (err) {
console.error("Error inserting user data:", err);
res.status(500).send("Internal Server Error");
return;
}
console.log("User data inserted successfully!");
// Redirect the user to the home page or perform any other necessary action
res.sendFile(path.join(__dirname, "home.html"));
}
);
});
}
});
});
//newsletter subscribe
app.post("/signup", (req, res) => {
const email = req.body.email;
// Insert the email into the 'promotions' table
connection.query('INSERT INTO Promotions (email) VALUES (?)', [email], (error, results) => {
if (error) {
return res.status(500).json({ error: 'Error inserting data into the database' });
}
// Send a success message as JSON response
res.status(200).json({ message: 'Successfully subscribed to the newsletter' });
});
});
// Handle login form submission
app.post("/t1", (req, res) => {
// Retrieve user data from the form
const { email, password } = req.body;
globalEmail = email;
// Query to check if the email exists in the Users table
const checkEmailQuery = "SELECT * FROM Users WHERE Email = ?";
connection.query(checkEmailQuery, [email], (err, results) => {
if (err) {
console.error("Error checking email:", err);
res.status(500).send("Internal Server Error");
return;
}
console.log(results);
// Check if the email exists
if (results.length === 0) {
console.log("Email not found");
res.status(404).send("Email not found");
return;
}
// Email exists, check the password
const storedPassword = results[0].Passwords;
const userId = results[0].User_ID;
if (password === storedPassword) {
// Passwords match, fetch username and product information from Users and Orders tables
const fetchUserDataQuery = "SELECT Username FROM Users WHERE User_ID = ?";
connection.query(fetchUserDataQuery, [userId], (err, userResults) => {
if (err) {
console.error("Error fetching user information:", err);
res.status(500).send("Internal Server Error");
return;
}
// Check if the user with the specified User_ID exists
if (userResults.length === 0) {
console.error("User not found");
res.status(500).send("Internal Server Error");
return;
}
// Extract the username from the results
const username = userResults[0].Username;
console.log(username);
// Fetch product information from the Orders table
const fetchProductQuery = "SELECT product_name, product_image FROM Orders WHERE User_user_id = ?";
connection.query(fetchProductQuery, [userId], (err, productResults) => {
if (err) {
console.error("Error fetching product information:", err);
res.status(500).send("Internal Server Error");
return;
}
// Transform product results to productData
const productData = productResults.map(product => ({
productName: product.product_name,
productImage: product.product_image
}));
// Render a new HTML page and pass the username and productData to it
res.render('home2', { username, productData });
});
});
} else {
// Passwords don't match
console.log("Incorrect password");
res.status(401).send("Incorrect password");
}
});
});
app.get("/product1",function(request,response,next){
var query="Select * from Products where Product_ID=1001";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
// app.get("/home2.ejs",function (req, res) {
// res.render(path.join(__dirname, "/views/home2.ejs"));
// });
// bilal said cooment in incase
// Handle login form submission
// app.post("/t1", (req, res) => {
// // Retrieve user data from the form
// const { email, password } = req.body;
// // Query to check if the email exists in the Users table
// const checkEmailQuery = "SELECT * FROM Users WHERE Email = ?";
// connection.query(checkEmailQuery, [email], (err, results) => {
// if (err) {
// console.error("Error checking email:", err);
// res.status(500).send("Internal Server Error");
// return;
// }
// console.log(results);
// // Check if the email exists
// if (results.length === 0) {
// console.log("Email not found");
// res.status(404).send("Email not found");
// return;
// }
// // Email exists, check the password
// const storedPassword = results[0].Passwords;
// const userId = results[0].User_ID;
// if (password === storedPassword) {
// // Passwords match, fetch username and product information from Users and Orders tables
// const fetchUserDataQuery = "SELECT Username FROM Users WHERE User_ID = ?";
// connection.query(fetchUserDataQuery, [userId], (err, userResults) => {
// if (err) {
// console.error("Error fetching user information:", err);
// res.status(500).send("Internal Server Error");
// return;
// }
// // Check if the user with the specified User_ID exists
// if (userResults.length === 0) {
// console.error("User not found");
// res.status(500).send("Internal Server Error");
// return;
// }
// // Extract the username from the results
// const username = userResults[0].Username;
// console.log(username);
// // Fetch product information from the Orders table
// const fetchProductQuery = "SELECT product_name, product_image FROM Orders WHERE User_user_id = ?";
// connection.query(fetchProductQuery, [userId], (err, productResults) => {
// if (err) {
// console.error("Error fetching product information:", err);
// res.status(500).send("Internal Server Error");
// return;
// }
// // Transform product results to productData
// const productData = productResults.map(product => ({
// productName: product.product_name,
// productImage: product.product_image
// }));
// // Render a new HTML page and pass the username and productData to it
// res.render('productPage', { username, productData });
// });
// });
// } else {
// // Passwords don't match
// console.log("Incorrect password");
// res.status(401).send("Incorrect password");
// }
// });
// app.get("/product1",function (req, res) {
// });
app.get("/productpage", (req, res) => {
// Retrieve user data from the form
// Query to check if the email exists in the Users table
const checkEmailQuery = "SELECT * FROM Users WHERE Email = ?";
connection.query(checkEmailQuery, [globalEmail], (err, results) => {
if (err) {
console.error("Error checking email:", err);
res.status(500).send("Internal Server Error");
return;
}
console.log(results);
// Check if the email exists
if (results.length === 0) {
console.log("Email not found");
res.status(404).send("Email not found");
return;
}
// Email exists, check the password
const userId = results[0].User_ID;
// Passwords match, fetch username and product information from Users and Orders tables
const fetchUserDataQuery = "SELECT Username FROM Users WHERE User_ID = ?";
connection.query(fetchUserDataQuery, [userId], (err, userResults) => {
if (err) {
console.error("Error fetching user information:", err);
res.status(500).send("Internal Server Error");
return;
}
// Check if the user with the specified User_ID exists
if (userResults.length === 0) {
console.error("User not found");
res.status(500).send("Internal Server Error");
return;
}
// Extract the username from the results
const username = userResults[0].Username;
console.log(username);
// Fetch product information from the Orders table
const fetchProductQuery = "SELECT product_name, product_image FROM Orders WHERE User_user_id = ?";
connection.query(fetchProductQuery, [userId], (err, productResults) => {
if (err) {
console.error("Error fetching product information:", err);
res.status(500).send("Internal Server Error");
return;
}
// Transform product results to productData
const productData = productResults.map(product => ({
productName: product.product_name,
productImage: product.product_image
}));
// Render a new HTML page and pass the username and productData to it
res.render('productpage', { username, productData });
});
});
});
});
app.get("/home2.ejs",function(request,response,next){
var query="Select * from Products where Product_ID=1001";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('home2',{username:'bilal'});
}
});
});
console.log("eokokfds");
app.get("/product",function(request,response,next){
var query="Select * from Products where Product_ID=2312";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
//products ejs
app.get("/productm1",function(request,response,next){
var query="Select * from Products where Product_ID=1001";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
//console.log()
response.render('1001',{sampleData:data});
}
});
});
app.get("/productm2",function(request,response,next){
var query="Select * from Products where Product_ID=1002";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productm3",function(request,response,next){
var query="Select * from Products where Product_ID=1003";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productm4",function(request,response,next){
var query="Select * from Products where Product_ID=1004";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productm5",function(request,response,next){
var query="Select * from Products where Product_ID=1005";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productm6",function(request,response,next){
var query="Select * from Products where Product_ID=1006";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productm6",function(request,response,next){
var query="Select * from Products where Product_ID=1006";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productm7",function(request,response,next){
var query="Select * from Products where Product_ID=1007";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productm8",function(request,response,next){
var query="Select * from Products where Product_ID=1008";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productf1",function(request,response,next){
var query="Select * from Products where Product_ID=1009";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productf2",function(request,response,next){
var query="Select * from Products where Product_ID=1010";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productf3",function(request,response,next){
var query="Select * from Products where Product_ID=1011";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productf4",function(request,response,next){
var query="Select * from Products where Product_ID=1012";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productf5",function(request,response,next){
var query="Select * from Products where Product_ID=1013";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productf6",function(request,response,next){
var query="Select * from Products where Product_ID=1014";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productf7",function(request,response,next){
var query="Select * from Products where Product_ID=1015";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/productf8",function(request,response,next){
var query="Select * from Products where Product_ID=1016";
connection.query(query,function(error,data){
if(error){
throw error;
}
else{
response.render('1001',{sampleData:data});
}
});
});
app.get("/get_payment", (req, res) => {
const amount = req.query.amount;
// Fetch the username from the Users table (replace 'userId' with the actual user ID)
const userId = 'U1001'; // Replace with the actual user ID; you might get this from the user's session
const fetchUsernameQuery = "SELECT Username FROM Users WHERE User_ID = ?";
connection.query(fetchUsernameQuery, [userId], (err, results) => {
if (err) {
console.error("Error fetching username:", err);
res.status(500).send("Internal Server Error");
return;
}
const username = results.length > 0 ? results[0].Username : "DefaultUsername";
res.render('payment', {
key: PUBLISHABLE_KEY,
amount: amount,
username: username // Pass the username variable to the template
});
});
});
app.post('/payment',(req,res)=>{
stripeInstance.customers.create({
email:req.body.stripeEmail,
source:req.body.stripeToken,
name:'bilal',
address:{
line1:'kyu bataon',
postal_code:'4522',
city:'Karachi',
state:'fast',
country:'india'
}
})
.then((customer)=>{
return stripeInstance.charges.create({
amount:7000,
description:'One tshirt',
currency:'USD',
customer:customer.id
})
})
.then((charge)=>{
res.send("success")
})
.catch((err)=>{
res.send(err)
})
})
let orderIdCounter = 0; // Counter to generate sequential order IDs
app.post('/checkout', (req, res) => {
const userId = 'U1001'; // Replace with the actual user ID; you might get this from the user's session
// Extract order items from the request body
const orderItems = req.body.orderItems;
// Process each order item
const promises = orderItems.map(item => {
return new Promise((resolve, reject) => {
const { productName, productImage, subtotal } = item;
// Increment the order ID counter
orderIdCounter++;
// Insert order items into the Orders table
const numericTotalAmount = parseFloat(subtotal.replace('$', ''));
const insertOrderQuery = `
INSERT INTO Orders (Order_ID, Order_Date, Total_Amount, Order_Status, User_user_id, product_name, product_image)
VALUES (?, ?, ?, ?, ?, ?, ?)
`;
connection.query(
insertOrderQuery,
[orderIdCounter, '2023-01-01', numericTotalAmount, 'Success', userId, productName, productImage],
(err, results) => {
if (err) {
console.error("Error inserting order item:", err);
reject(err);
} else {
resolve(results);
}
}
);
});
});
// Wait for all promises to resolve before sending the response
Promise.all(promises)
.then(() => {
res.json({ success: true });
})
.catch(error => {
console.error("Error inserting order items:", error);
res.status(500).json({ error: 'Internal Server Error' });
});
});
// Wait for all promises to resolve before sending the response
app.use("/api", router);
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});