-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
533 lines (421 loc) · 15.2 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
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
const express = require('express');
const mysql = require('mysql');
const app = express();
const port = 3000;
const bodyParser = require('body-parser');
const session = require('express-session');
// app.use(session({
// secret : 'webslesson',
// resave : true,
// saveUninitialized : true
// }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use(session({
secret : 'webslesson',
resave : true,
saveUninitialized : true
}));
// MySQL database connection configuration
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'inventory',
insecureAuth: true,
});
// Connect to the MySQL database
db.connect((err) => {
if (err) {
console.error('Error connecting to MySQL database: ' + err.stack);
return;
}
console.log('Connected to MySQL database as id ' + db.threadId);
});
// Define a route to fetch data from MySQL
app.get('/', function(req, res, next) {
res.render('login', { title: 'Express', session : req.session });
});
app.get('/dashboard', (req, res) => {
let sql1 = 'SELECT SUM(amount) AS TotalAmount FROM orders';
let sql3 = 'SELECT COUNT(pid) AS NumberOfProducts FROM product';
let sql2 = 'SELECT COUNT(orderid) AS NumberOforders FROM orders';
let sql4 = 'SELECT SUM(price) AS TotalItemsOrdered FROM product';
let query1 = db.query(sql1,(err1,rows1,fields1)=>{
if(!err1){
tot_sales=rows1
}
});
let query2 = db.query(sql2,(err2,rows2,fields2)=>{
if(!err2){
nof_ord=rows2
}
});
let query4 = db.query(sql4,(err4,rows4,fields4)=>{
if(!err4){
stk_val=rows4
}
});
let query3= db.query(sql3, (err3, rows3, fields3)=>{
// res.render('index1.ejs', { products: [] });
// Render the index.ejs page with an empty array initially
if(!err3){
ord_num = rows3
console.log('Fetched total no. of orders from ordersdb')
res.render('index1.ejs',{
tot_sales:tot_sales,
nof_ord:nof_ord,
ord_num:rows3,
stk_val:stk_val
});
}
});
})
app.post('/login', function(request, response, next){
var user_email_address = request.body.user_email_address;
var user_password = request.body.user_password;
if(user_email_address && user_password)
{
query = `
SELECT * FROM user_login
WHERE user_email = "${user_email_address}"
`;
db.query(query, function(error, data){
if(data.length > 0)
{
for(var count = 0; count < data.length; count++)
{
console.log((data[count].user_password));
if(data[count].user_password == user_password)
{
request.session.user_id = data[count].user_id;
response.redirect("/dashboard");
}
else
{
response.redirect("/dashboard");
}
}
}
else
{
response.send('Incorrect Email Address');
}
response.end();
});
}
else
{
response.send('Please Enter Email Address and Password Details');
response.end();
}
});
app.get('/index', (req, res) => {
res.render('index', { products: [] }); // Render the index.ejs page with an empty array initially
})
app.get('/product', (req, res) => {
res.render('product', { products: [] }); // Render the index.ejs page with an empty array initially
})
app.post('/addProduct', (req, res) => {
const productName = req.body.productName;
const productPrice = req.body.productPrice;
const productId = req.body.productId;
const productDescription = req.body.productDescription;
const productQuantity = req.body.productQuantity;
const categoryId = req.body.categoryId;
const suppliersId = req.body.suppliersId;
const query = 'INSERT INTO product (pid,pname,pdesc,price,quantity,categoryId,suppliersId) VALUES (?, ?,?,?,?,?,?)';
db.query(query, [productId,productName,productDescription, productPrice,productQuantity,categoryId,suppliersId], (err, results) => {
if (err) {
console.error('Error executing MySQL query: ' + err.stack);
res.status(500).send('Error adding product');
return;
}
// After adding the product, fetch the updated list of products
const searchQuery = 'SELECT * FROM product';
db.query(searchQuery, (err, products) => {
if (err) {
console.error('Error executing MySQL query: ' + err.stack);
res.status(500).send('Error fetching products');
return;
}
// Render the index page with the updated list of products
res.render('index', { message: 'Product Management', products:[] });
});
});
});
app.post('/editProduct', (req, res) => {
const productName = req.body.productName;
const productPrice = req.body.productPrice;
const productId = req.body.productId;
const productDescription = req.body.productDescription;
const productQuantity = req.body.productQuantity;
const categoryId = req.body.categoryId;
const suppliersId = req.body.suppliersId;
const query = 'update product set pname= ? ,pdesc= ?,price= ?,quantity=?,categoryId=?,suppliersId=? where pid=?';
db.query(query, [productName,productDescription, productPrice,productQuantity,categoryId,suppliersId,productId], (err, results) => {
if (err) {
console.error('Error executing MySQL query: ' + err.stack);
res.status(500).send('Error adding product');
return;
}
// After adding the product, fetch the updated list of products
const searchQuery = 'SELECT * FROM product';
db.query(searchQuery, (err, products) => {
if (err) {
console.error('Error executing MySQL query: ' + err.stack);
res.status(500).send('Error fetching products');
return;
}
// Render the index page with the updated list of products
res.render('index', { message: 'Product Management', products:[] });
});
});
});
app.post('/search', (req, res) => {
const productId = req.body.productId;
const query = 'SELECT * FROM product WHERE pid = ?';
db.query(query, [productId], (err, results) => {
if (err) {
console.error('Error executing MySQL query: ' + err.stack);
res.status(500).send('Error searching for product');
return;
}
res.render('index', { products: results });
});
});
// app.get('/viewproduct', (req, res) => {
// res.render('viewproduct', { suppliers: [] }); // Render the index.ejs page with an empty array initially
// });
app.get('/viewproduct',(req,res) =>{
let sql = 'SELECT * FROM product limit 25';
let query = db.query(sql, (err, rows, fields)=>{
if(!err){
let sql1 = 'SELECT * FROM product'
let query1 = db.query(sql1, (err1, rows1, fields1)=>{
if(!err1){
let sql2 = 'SELECT * FROM categories'
let query2 = db.query(sql2, (err2, rows2, fields2)=>{
if(!err2){
res.render('viewproduct.ejs',{
all_stocks:rows, brands:rows1, categories:rows2, display_content:'None', filter_type:'None', filter_name:'None'
});
}
else
console.log(err2)
})
}
else
console.log(err1)
})
}
else
console.log(err);
});
})
app.post('/addcategory',(req,res) => {
let sql = `INSERT INTO categorydb(Category) VALUES ('${req.body.new}') `
let query = mysqlConnection.query(sql, (err, rows, fields) => {
if(!err)
{
res.redirect('/categories')
}
else
console.log(err)
})
})
app.post('/submitstock',(req, res) => {
console.log(req.body)
var request1 = req.body
var date_format = new Date();
var transaction_date = date_format.getDate()+ '/'+ (parseInt(date_format.getMonth()+1)).toString() +'/'+date_format.getFullYear()
console.log((parseInt(date_format.getMonth()+1)).toString())
var transaction_time = date_format.getHours() + ':' + date_format.getMinutes() + ':' + date_format.getSeconds()
let new_req = {};
for (i in request1){
if(i.includes("number") || i.includes("total")){
delete i
}
else
new_req[i] = request1[i]
}
const data = Object.entries(new_req).reduce((carry, [key, value]) => {
const [text] = key.split(/\d+/);
const index = key.substring(text.length) - 1;
if (!Array.isArray(carry[index])) carry[index] = [];
carry[index].push(value);
return carry;
}, []);
// for (let i = 0; i < data.length; i++) {
// data[i].push(transaction_date);
// data[i].push(transaction_time);
// data[i].push(date_format.getDate())
// data[i].push(date_format.getMonth() + 1)
// data[i].push(date_format.getFullYear())
// }
let sql = `INSERT INTO product (pid,pname,pdesc,price,quantity,categoryId,suppliersId) VALUES ? `
let query = db.query(sql,[ data], (err, rows, fields)=>{
if(!err)
{
console.log('Successfully inserted values')
res.redirect('/viewproduct')
}
else
console.log(err);
});
})
app.get('/stocks',(req,res)=>{
let sql2 = 'SELECT * FROM categories'
let query2 = db.query(sql2, (err2, rows2, fields2)=>{
if(!err2){
res.render('stocks.ejs',{
categories:rows2, display_content:'None', filter_type:'None', filter_name:'None'
});
}
else
console.log(err2)
})
// res.render('stocks', { products:[] });
})
app.post('/viewproducts', (req, res) => {
let sql = 'SELECT * FROM product limit 25';
let query = db.query(sql, (err, rows, fields)=>{
if(!err){
let sql1 = 'SELECT * FROM product'
let query1 = db.query(sql1, (err1, rows1, fields1)=>{
if(!err1){
let sql2 = 'SELECT * FROM categories'
let query2 = db.query(sql2, (err2, rows2, fields2)=>{
if(!err2){
var selected_item = req.body['exampleRadios']
if(selected_item == 'brand'){
var brand_name = req.body['selected_brand']
console.log(brand_name)
let sql3 = `SELECT * FROM product WHERE pname='${brand_name}'`
let query3 = db.query(sql3, (err3, rows3, fields3)=>{
if(!err3){
console.log(brand_name)
console.log(rows3);
res.render('viewproduct.ejs',{
all_stocks:rows, brands:rows1, categories:rows2, display_content:rows3, filter_type:'brand', filter_name:brand_name
});
}
else
console.log(err3)
})
}
if(selected_item == 'category'){
var category_name = req.body['selected_category']
let sql3 = `select * from product p where p.categoryId=(SELECT categoryId FROM categories WHERE categoryname='${category_name}')`
let query3 = db.query(sql3, (err3, rows3, fields3)=>{
if(!err3){
console.log(rows3);
res.render('viewproduct.ejs',{
all_stocks:rows, brands:rows1, categories:rows2, display_content:rows3, filter_type:'category', filter_name:category_name
});
}
else
console.log(err3)
})
}
}
else
console.log(err2)
})
}
else
console.log(err1)
})
}
else
console.log(err);
});
})
app.post('/allProducts', (req, res) => {
const productId = req.body.productId;
const query = 'SELECT * FROM product limit 25';
db.query(query, (err, results) => {
if (err) {
console.error('Error executing MySQL query: ' + err.stack);
res.status(500).send('Error searching for product');
return;
}
res.render('index', { products: results });
});
});
app.get('/supplier', (req, res) => {
res.render('supplier', { suppliers: [] }); // Render the index.ejs page with an empty array initially
});
app.post('/supplier', (req, res) => {
const supplierId = req.body.supplierId;
const query = 'SELECT * FROM suppliers WHERE suppliersId = ?';
const query1 = 'select * from product where suppliersId=?';
db.query(query, [supplierId], (err, results) => {
if (err) {
console.error('Error executing MySQL query: ' + err.stack);
res.status(500).send('Error searching for product');
return;
}
db.query(query1, [supplierId], (err, products) => {
if (err) {
console.error('Error executing MySQL query: ' + err.stack);
res.status(500).send('Error searching for product');
return;
}
res.render('supplier', { suppliers: results ,products: products});
});
});
});
app.post('/allsuppliers', (req, res) => {
const query = 'SELECT * FROM suppliers limit 25';
db.query(query, (err, results) => {
if (err) {
console.error('Error executing MySQL query: ' + err.stack);
res.status(500).send('Error searching for product');
return;
}
res.render('supplier', { suppliers: results, products:[] });
});
});
app.post('/allorders', (req, res) => {
const query = 'SELECT * FROM orders limit 25';
db.query(query, (err, results) => {
if (err) {
console.error('Error executing MySQL query: ' + err.stack);
res.status(500).send('Error searching for product');
return;
}
res.render('order', { orders: results , products: [], order:[]});
});
});
app.get('/order', (req, res) => {
res.render('order', { orders: [], products: [],order: [] });
});
app.post('/searchOrder', (req, res) => {
const orderId = req.body.orderId;
console.log(orderId);
const orderQuery = 'SELECT * FROM orders WHERE orderid = ?';
db.query(orderQuery, [orderId], (err, orderResults) => {
if (err) {
console.error('Error executing MySQL query: ' + err.stack);
res.status(500).send('Error searching for order');
return;
}
const order= orderResults[0];
const productsQuery = 'SELECT * FROM product p JOIN contains c ON p.pid = c.pid WHERE c.orderid = ?';
db.query(productsQuery, [orderId], (err, productResults) => {
if (err) {
console.error('Error executing MySQL query: ' + err.stack);
res.status(500).send('Error fetching products for order');
return;
}
const products = productResults || [];
res.render('order', { order, products, orders : [] });
});
});
});
// Start the Express server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});