-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
1685 lines (1577 loc) · 74.3 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
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//jshint esversion:6
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const md5 = require('md5');
const mongoose = require("mongoose");
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const { Console } = require('console');
const { verify } = require('crypto');
const stripe = require("stripe")(process.env.STRIPE_PRIVATE_KEY)
const nodemailer = require("nodemailer");
const needle = require('needle');
const { get } = require('http');
const app = express();
//OpenAI setup
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.GPT_KEY,
});
const openai = new OpenAIApi(configuration);
//middleware
app.use(session({
secret: toString(process.env.MYSECRET),
resave: false,
saveUninitialized: true
}));
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.json());
// app.use(bodyParser.urlencoded({ extended: true }));
const PORT = process.env.PORT || 80;
const GPTkey = process.env.GPT_KEY;
app.use(express.static("public"));
app.set('view engine', 'ejs');
let usersId = 10000;
let productId = 720000;
let bulkOrderId = 10;
let adminPassKeyHash = md5((process.env.ADMIN_PLAIN));
//Twilio Client Initialisation
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
// NodeMailer Initialisation
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
user: process.env.EMAIL_ID,
pass: process.env.EMAIL_KEY
},
});
//Mongoose initialisations
mongoose.set('strictQuery', true);
const dbURL = process.env.DBURL;
mongoose.connect(dbURL);
const ProductSchema = new mongoose.Schema({
ProductId: Number,
Variety: String,
ProductName: String,
Description: String,
cost: Number,
imageURL: String,
SellerName: String,
SellerAddress: String,
link: String,
Mobile: Number,
emailId: String,
Quantity: Number,
OtherName: String
});
const NewProduct = mongoose.model('NewProduct', ProductSchema);
const UserSchema = new mongoose.Schema({
usersId: Number,
userName: String,
age: Number,
status: String,
Location: String,
Occupation: String,
mobileNo: Number,
emailId: String,
password: String
});
const User = mongoose.model('User', UserSchema);
const DeviceSchema = new mongoose.Schema({
userId: Number,
deviceName: String,
Location: String,
deviceType: String,
Link: String
});
const Device = mongoose.model('Device', DeviceSchema);
const PaymentSchema = new mongoose.Schema({
SellerName: String,
SellerEmail: String,
SellerMobile: Number,
BuyerName: String,
BuyerEmail: String,
BuyerMobile: Number,
SellerNotifiedStatus: String,
ProductId: Number,
ProductName: String,
cost: Number,
Quantity: Number
});
const Payment = mongoose.model("Payment", PaymentSchema);
const costOfComponentSchema = new mongoose.Schema({
esp32: Number,
esp8266: Number,
moisture: Number,
temperature: Number,
solar: Number,
jumpers: Number,
serviceCharge: Number
});
const costOfComponent = mongoose.model('costOfComponent', costOfComponentSchema);
const BulkOrderSchema = new mongoose.Schema({
OrderId: Number,
SellerId: Number,
BuyerId: Number,
Status: String,
ProductId: Number,
BidAmount: Number,
MarketPrice: Number,
Quantity: Number
});
const BulkOrder = mongoose.model("BulkOrder", BulkOrderSchema);
//For server side Caching of Advices by Open Ai
const CropAdviseSchema = new mongoose.Schema({
location: String,
Advice: String
});
const CropAdvice = mongoose.model("CropAdvice", CropAdviseSchema);
const FraudReportSchema = new mongoose.Schema({
ItemId: Number,
ReporterID: Number,
Description: String,
Status: String
});
const FraudReport = mongoose.model("FraudReport", FraudReportSchema);
//Testing Purpose
const DummySchema = new mongoose.Schema({
item: Number,
name: String
});
const Dummy = mongoose.model("Dummy", DummySchema);
// Structures for adding new elements as per their Schemas
// var newEntry = new NewProduct({
// ProductId: 225, ProductName: "String",Variety: "Normal", Description: "ajlfsdkj asodijf;masd lj aosdjf asdjf jjw oirj", cost: 500, imageURL: "String", SellerName: "String", SellerAddress: "String", Mobile: 9515306769, emailId:"[email protected]", Quantity:25
// });
// newEntry.save();
// var newDevice = new Device({
// userId: req.user.usersId,
// deviceName: req.user.userName,
// Location: req.user.Location,
// deviceType: req.user.deviceType,
// Link: "https://thingspeak.com/channels/2065077/charts/1?bgcolor=%23ffffff&color=%23d62020&dynamic=true&results=60&type=line&update=15",
// });
// newDevice.save();
// "https://thingspeak.com/channels/2065077/charts/2?bgcolor=%23ffffff&color=%23d62020&dynamic=true&results=60&type=line&update=15",
// "https://thingspeak.com/channels/2065077/charts/3?bgcolor=%23ffffff&color=%23d62020&dynamic=true&results=60&type=line&update=15",
// "https://thingspeak.com/channels/2065077/charts/4?bgcolor=%23ffffff&color=%23d62020&dynamic=true&results=60&type=line&update=15"
// const SampleTransaction = new Payment({
// SellerName: "Sanjay Kumar",
// SellerEmail: "[email protected]",
// SellerMobile: 9515306769,
// BuyerName: "Durga Prasad",
// BuyerEmail: "[email protected]",
// BuyerMobile: 7893924278,
// SellerNotifiedStatus: "No",
// ProductId: 7200016,
// ProductName: "Apple",
// cost: 40,
// Quantity: 5
// });
// SampleTransaction.save();
// var costEntry = new costOfComponent({
// esp32: 450,
// esp8266: 320,
// moisture: 90,
// temperature: 70,
// solar: 210,
// jumpers: 2,
// serviceCharge: 200
// });
// costEntry.save();
// Updating Ids with the last ID's so that Id's will not get repeated even if the server is restarted.
async function updateIds() {
try {
let LastProduct = await NewProduct.findOne({}).sort({ field: 'asc', _id: -1 }).limit(1);
let LastUser = await User.findOne({}).sort({ field: 'asc', _id: -1 }).limit(1);
let LastBulk = await BulkOrder.findOne({}).sort({ field: 'asc', _id: -1 }).limit(1);
// console.log(LastProduct.ProductId);
// console.log(LastUser.usersId);
if (LastProduct != null)
productId = LastProduct.ProductId;
if (LastUser != null)
usersId = LastUser.usersId;
if (LastBulk != null)
bulkOrderId = LastBulk.OrderId;
}
catch (err) {
console.log(err);
}
}
updateIds();
// Passport.js initialisations
app.use(passport.initialize());
app.use(passport.session());
//Serialising user
passport.serializeUser(function (user, done) {
done(null, user.id);
});
//Deserialising user
passport.deserializeUser(async (id, done) => {
const USER = await User.findById(id);
done(null, USER);
});
passport.use(new localStrategy({
usernameField: 'emailId',
passwordField: 'password'
},
function (username, password, done) {
async function executer1() {
let user = [];
try {
user = await User.findOne({ emailId: username });
}
catch (err) {
return done(err);
}
function executer2(user) {
// if (err) return done(err);
if (!user) return done(null, false, { message: "Incorrect username" });
if (user.status == "Blocked") {
return done(null, false, { message: "User Blocked." });
}
bcrypt.compare(password, user.password, function (err, res) {
if (err) return done(err);
if (res === false) return done(null, false, { message: "Incorrect password" });
return done(null, user);
});
}
executer2(user);
}
executer1();
}
));
// Checking whether the user is logged in or not
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect('/login');
}
//Checking whether the user is Admin or Not
function isAdmin(req, res, next) {
if (req.isAuthenticated() && req.user.usersId == process.env.ADMIN_ID) return next();
res.redirect('/market');
}
// Checking whether the user is logged out or not
function isLoggedOut(req, res, next) {
if (!req.isAuthenticated()) return next();
res.redirect('/market');
}
//Get routes Start
app.get("/", function (req, res) {
// res.sendFile(__dirname + "/index.html");
let temp = "Login👤";
if (req.isAuthenticated()) {
// console.log(req.user.userName);
temp = req.user.userName
}
res.render("index", { name: temp });
});
app.get("/login", isLoggedOut, function (req, res) {
res.render("login", { error: req.query.error });
});
app.get("/userRegister", function (req, res) {
res.render("getMobile", { error: req.query.error })
// res.render("register", {});
});
app.get("/market", isLoggedIn, function (req, res) {
async function getCheapCosts() {
let data = await NewProduct.aggregate([
{
$group: {
_id: "$ProductName",
minPrice: { $min: '$cost' }
}
}
]).sort({ _id: 1 });
const myData = data.reduce((acc, item) => {
acc[item._id] = item.minPrice;
return acc;
}, {});
// console.log(myData.Apple);
res.render("marketIntro", { bestDeals: myData });
}
getCheapCosts();
});
app.get("/market/:productName", isLoggedIn, function (req, res) {
// console.log(req.params);
// console.log(req.query);
let myProductData = [];
async function getParticularProduct() {
let pictures = ["Products", "Products1", "Products2"];
if (req.query.sort == "PriceLowToHigh")
myProductData = await NewProduct.find({ ProductName: req.params.productName }).sort({ 'cost': 1 });
else if (req.query.sort == "PriceHighToLow")
myProductData = await NewProduct.find({ ProductName: req.params.productName }).sort({ 'cost': -1 });
else if (req.query.sort == "LatestFirst")
myProductData = await NewProduct.find({ ProductName: req.params.productName }).sort({ 'ProductId': -1 });
else if (req.query.sort == "OldestFirst")
myProductData = await NewProduct.find({ ProductName: req.params.productName }).sort({ 'ProductId': 1 });
else
myProductData = await NewProduct.find({ ProductName: req.params.productName });
// res.send(myProductData);
// console.log(myProductData);
res.render("mainMarket", {
productList: myProductData,
sortingKey: req.query.sort,
myPictures: pictures
});
}
getParticularProduct();
});
app.get("/logout", isLoggedIn, function (req, res) {
req.logout(req.user, err => {
if (err) return next(err);
res.redirect("/");
});
});
app.get("/newProduct", isLoggedIn, function (req, res) {
async function sendResponse() {
let userSensors = await Device.find({ userId: req.user.usersId, deviceType: "Trendline" });
res.render("productEntry", { sensors: userSensors });
}
sendResponse();
});
app.get("/myProducts", isLoggedIn, function (req, res) {
async function getMyProducts() {
let pictures = ["Products", "Products1", "Products2"];
let myProductData = await NewProduct.find({ Mobile: req.user.mobileNo }).sort({ 'ProductName': 1 });
// res.send(myProductData);
// console.log(myProductData);
res.render("customerProductsView", {
name: req.user.userName,
productList: myProductData,
myPictures: pictures
});
}
getMyProducts();
});
app.get("/productDetail/:pID", isLoggedIn, function (req, res) {
// console.log(req.params.SellerMobile);
// console.log(req.params.pID);
async function getSellerDetails() {
let mySellerData = await NewProduct.findOne({ ProductId: req.params.pID });
if (mySellerData != null) {
res.render("productDetails", {
name: req.user.userName,
sellerData: mySellerData
});
}
else
res.redirect("/messageRoute?Message=Sorry Product already SOLD out.");
}
getSellerDetails();
});
app.get("/messageRoute", function (req, res) {
res.render("message", { redirectTo: "/market", myMessage: req.query.Message });
});
app.get("/IOT", isLoggedIn, function (req, res) {
async function getDeviceData() {
let realTime = await Device.find({ userId: req.user.usersId, deviceType: "Realtime" });
let trendLine = await Device.find({ userId: req.user.usersId, deviceType: "Trendline" });
// console.log(devicesInfo);
if (realTime != null && trendLine != null)
res.render("agriIOT", { realtimeDevices: realTime, trendlineDevices: trendLine });
else if (trendLine == null)
res.render("agriIOT", { realtimeDevices: realTime, trendlineDevices: [] });
else if (realTime == null)
res.render("agriIOT", { realtimeDevices: [], trendlineDevices: trendLine });
else
res.render("agriIOT", { realtimeDevices: [], trendlineDevices: [] });
}
getDeviceData();
});
app.get("/success", isLoggedIn, function (req, res) {
let mySellerData = "";
async function insertPayment() {
// console.log(req.query.Pid);
mySellerData = await NewProduct.findOne({ ProductId: req.query.Pid });
// console.log(mySellerData);
if (mySellerData != null) {
const MyTransaction = new Payment({
SellerName: mySellerData.SellerName,
SellerEmail: mySellerData.emailId,
SellerMobile: mySellerData.Mobile,
BuyerName: req.user.userName,
BuyerEmail: req.user.emailId,
BuyerMobile: req.user.mobileNo,
SellerNotifiedStatus: "No",
ProductId: mySellerData.ProductId,
ProductName: mySellerData.ProductName,
cost: mySellerData.cost,
Quantity: req.query.quant,
});
// console.log(MyTransaction);
MyTransaction.save();
}
else
res.send("Sorry :( product already SOLD. Please refresh the market page.");
}
async function reduceStock() {
let oldData = await NewProduct.findOne({ ProductId: req.query.Pid });
let newQuant = oldData.Quantity - req.query.quant;
await NewProduct.updateOne({ ProductId: req.query.Pid }, { Quantity: newQuant });
let updated = await NewProduct.findOne({ ProductId: req.query.Pid });
// console.log(updated);
if (updated.Quantity <= 0) {
await NewProduct.deleteOne({ ProductId: req.query.Pid });
}
}
async function notifySeller() {
mySellerData = await NewProduct.findOne({ ProductId: req.query.Pid });
let info = await transporter.sendMail({
from: `"Manager of Sales" <${process.env.EMAIL_ID}>`,
to: mySellerData.emailId,
subject: `✅ You received order for Product with Product Id : ${mySellerData.ProductId}`,
html: `
<div style="display: flex; justify-content: center;">
<table style="max-width: 600px; background-color: rgb(244, 255, 241); margin: 0 auto;" width="100%"
cellpadding="0" cellspacing="0">
<tr>
<td style="background-color: #00a033; text-align: center;">
<img style="max-width: 100%;" src="https://i.ibb.co/rZnQ8Hn/agri1.jpg" alt="">
</td>
</tr>
<tr style="text-align: center;">
<td>
<img style="height: 50px;margin-top:30px;" src="https://s11.gifyu.com/images/croppedTitle.gif">
</td>
</tr>
<tr>
<td style="padding: 20px; text-align: center; font-size: 24px; font-weight: bold; color: #015f11;">
You received an order for your product.</td>
</tr>
<tr>
<td style="padding: 20px; text-align: justify; font-size: 16px; color: #3d5d36;">
<h4>Hello dear ${mySellerData.SellerName},</h4>
<p>Greetings of the day,
<br><br> This email is to inform you that you have received
an order for ${mySellerData.ProductName}(s) with a quantity
requirement of ${req.query.quant} Kg(s). <br>Payment for the same has been processed. You can find
more details in this email
or you can visit our Fruitful app to know more.
</p>
</td>
</tr>
<tr>
<td style="padding: 20px; text-align: justify; font-size: 16px; color: #3d5d36;">
Here are the details for your order. To know more please visit our portal.
<table style="margin: 10px; margin-left: 20px;">
<tr>
<td>
Customer Name
</td>
<td>
:
</td>
<td>
${req.user.userName}
</td>
</tr>
<tr>
<td>
Customer Email
</td>
<td>
:
</td>
<td>
${req.user.emailId}
</td>
</tr>
<tr>
<td>
Customer Mobile.no
</td>
<td>
:
</td>
<td>
${req.user.mobileNo}
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="padding: 20px; text-align: center;">
<a href=${process.env.SERVER_URL}
style="display: inline-block; background-color: #66cc33; color: #ffffff; padding: 10px 20px; text-decoration: none; border-radius: 5px;">Visit
Now</a>
</td>
</tr>
<tr>
<td
style="background-color: #3d5d36; text-align: center; padding: 6px; color: #ffffff; font-size: 14px;">
© 2023 FruitFul Technologies. All rights reserved.
</td>
</tr>
</table>
</div>
`,
});
// console.log(info.messageId);
}
async function notifyUser() {
mySellerData = await NewProduct.findOne({ ProductId: req.query.Pid });
let info = await transporter.sendMail({
from: `"Manager of Sales" <${process.env.EMAIL_ID}>`,
to: req.user.emailId,
subject: `✅ Your order for Product ${mySellerData.ProductName} is successful`,
html: `<div style="display: flex; justify-content: center;">
<table style="max-width: 600px; background-color: rgb(244, 255, 241); margin: 0 auto;" width="100%" cellpadding="0"
cellspacing="0">
<tr>
<td style="background-color: #00a033; text-align: center;">
<img style="max-width: 100%;" src="https://i.ibb.co/rZnQ8Hn/agri1.jpg" alt="">
</td>
</tr>
<tr style="text-align: center;">
<td>
<img style="height: 50px;margin-top:30px;" src="https://s11.gifyu.com/images/croppedTitle.gif" draggable="false">
</td>
</tr>
<tr>
<td style="padding: 10px; text-align: center; font-size: 24px; font-weight: bold; color: #015f11;">
Thanks for ordering ${mySellerData.ProductName}.</td>
</tr>
<tr>
<td style="padding: 20px;padding-top: 0; text-align: justify; font-size: 16px; color: #3d5d36;">
<h4>Hello dear ${req.user.userName},</h4>
<p>Greetings of the day,
<br><br> We have received your order for ${mySellerData.ProductName}. Payment for the same is successful.
You will get the delivery details by the seller soon.
<br>
<br>
With Regards,<br>
Fruitful.
</p>
</td>
</tr>
<tr>
<td style="background-color: #3d5d36; text-align: center; padding: 6px; color: #ffffff; font-size: 14px;">
© 2023 FruitFul Technologies. All rights reserved.
</td>
</tr>
</table>
</div>
`,
});
// console.log(info.messageId);
}
reduceStock();
insertPayment();
notifySeller();
notifyUser();
res.render("message", { redirectTo: "/market", myMessage: "Your payment is successful." });
});
app.get("/cancel", isLoggedIn, function (req, res) {
res.render("message", { redirectTo: "/market", myMessage: "Your payment is cancelled." });
});
app.get("/success-iot", isLoggedIn, function (req, res) {
async function notifyAdmin() {
let info = await transporter.sendMail({
from: `"Manager of Sales" <${process.env.EMAIL_ID}>`,
to: process.env.EMAIL_ID,
subject: `${req.user.userName} is requesting for IOT kit.`,
html: `<div style="display: flex; justify-content: center;">
<table style="max-width: 600px; background-color: rgb(244, 255, 241); margin: 0 auto;" width="100%" cellpadding="0"
cellspacing="0">
<tr>
<td style="background-color: #00a033; text-align: center;">
<img style="max-width: 100%;" src="https://i.ibb.co/rZnQ8Hn/agri1.jpg" alt="">
</td>
</tr>
<tr style="text-align: center;">
<td>
<img style="height: 50px;margin-top:30px;" src="https://s11.gifyu.com/images/croppedTitle.gif" draggable="false">
</td>
</tr>
<tr>
<td style="padding: 10px; text-align: center; font-size: 24px; font-weight: bold; color: #015f11;">
IOT kit request has been generated.</td>
</tr>
<tr>
<td style="padding: 20px;padding-top: 0; text-align: justify; font-size: 16px; color: #3d5d36;">
<h4>Hello dear admin,</h4>
<p>Greetings of the day,
<br><br> We received an order from ${req.user.userName} for
IOT kit for his farm. He has paid an amount of total ₹${req.query.amount}/-. Please contact the customer and
follow up the procedure as quickly as possible. Below are the details of the payment for your reference.
<br>Payment for the same has been successfully processed.
</p>
</td>
</tr>
<tr>
<td style="padding: 20px;padding-top: 0; text-align: justify; font-size: 16px; color: #3d5d36;">
Here are the details for the order.
<table style="margin: 10px; margin-left: 20px;">
<tr>
<td>
Customer Name
</td>
<td>
:
</td>
<td>
${req.user.userName}
</td>
</tr>
<tr>
<td>
Customer Mobile.no
</td>
<td>
:
</td>
<td>
${req.user.mobileNo}
</td>
</tr>
<tr>
<td>
Amount paid
</td>
<td>
:
</td>
<td>
₹${req.query.amount}/-
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="background-color: #3d5d36; text-align: center; padding: 6px; color: #ffffff; font-size: 14px;">
© 2023 FruitFul Technologies. All rights reserved.
</td>
</tr>
</table>
</div>
`,
});
// console.log(info.messageId);
}
async function notifyUser() {
let info = await transporter.sendMail({
from: `"Manager of Sales" <${process.env.EMAIL_ID}>`,
to: req.user.emailId,
subject: `✅Your request for IOT kit is successful.`,
html: `<div style="display: flex; justify-content: center;">
<table style="max-width: 600px; background-color: rgb(244, 255, 241); margin: 0 auto;" width="100%" cellpadding="0"
cellspacing="0">
<tr>
<td style="background-color: #00a033; text-align: center;">
<img style="max-width: 100%;" src="https://i.ibb.co/rZnQ8Hn/agri1.jpg" alt="">
</td>
</tr>
<tr style="text-align: center;">
<td>
<img style="height: 50px;margin-top:30px;" src="https://s11.gifyu.com/images/croppedTitle.gif" draggable="false">
</td>
</tr>
<tr>
<td style="padding: 10px; text-align: center; font-size: 24px; font-weight: bold; color: #015f11;">
Thanks for your IOT-kit order.</td>
</tr>
<tr>
<td style="padding: 20px;padding-top: 0; text-align: justify; font-size: 16px; color: #3d5d36;">
<h4>Hello dear ${req.user.userName},</h4>
<p>Greetings of the day,
<br><br> We have received your order for
IOT kit. Payment for ₹${req.query.amount}/- is successful. Our execution team will contact you soon.
<br>
<br>
With Regards,<br>
Fruitful.
</p>
</td>
</tr>
<tr>
<td style="background-color: #3d5d36; text-align: center; padding: 6px; color: #ffffff; font-size: 14px;">
© 2023 FruitFul Technologies. All rights reserved.
</td>
</tr>
</table>
</div>
`,
});
// console.log(info.messageId);
}
notifyAdmin();
notifyUser();
res.render("message", { redirectTo: "/market", myMessage: "Your payment is successful and our admin will contact you soon." });
});
app.get("/ordersReceived", isLoggedIn, function (req, res) {
let receivedOrders = "";
async function getUserOrders() {
let pictures = ["Products", "Products1", "Products2"];
receivedOrders = await Payment.find({ SellerMobile: req.user.mobileNo, SellerNotifiedStatus: "No" }).sort({ _id: -1 });
// res.send(receivedOrders);
// console.log(receivedOrders);
res.render("receivedOrders", {
name: req.user.userName,
productList: receivedOrders,
myPictures: pictures
});
}
getUserOrders();
});
app.get("/myOrders", isLoggedIn, function (req, res) {
let myOrders = "";
async function getMyOrders() {
let pictures = ["Products", "Products1", "Products2"];
myOrders = await Payment.find({ BuyerMobile: req.user.mobileNo }).sort({ _id: -1 });
// res.send(myOrders);
// console.log(myOrders);
res.render("myOrders", {
name: req.user.userName,
productList: myOrders,
myPictures: pictures
});
}
getMyOrders();
});
app.get("/admin/:passKeyHash", isLoggedIn, function (req, res) {
// console.log(parseInt(process.env.ADMIN_ID));
// console.log((req.user.usersId));
// console.log(((process.env.ADMIN_EMAIL)));
// console.log((req.user.emailId));
if (parseInt(process.env.ADMIN_ID) == (req.user.usersId) && (process.env.ADMIN_EMAIL) == (req.user.emailId)) {
// console.log(md5((process.env.ADMIN_PLAIN)));
// console.log(req.params.passKeyHash);
if (req.params.passKeyHash == adminPassKeyHash) {
// console.log(req.params.passKeyHash);
// console.log("Admin accessed - Now");
res.render("adminMainPage", { passKeyHash: adminPassKeyHash });
}
else {
console.log(`Admin used password = ${req.params.passKeyHash} and failed to login`);
res.send(`Wrong Passkey ${req.params.passKeyHash}`);
}
}
else {
async function notifyAdmin() {
let info = await transporter.sendMail({
from: `"Manager of Sales" <${process.env.EMAIL_ID}>`,
to: process.env.EMAIL_ID,
subject: `🛑🛑 Someone trying to get into the Admin portal.`,
html: `
<div style="display: flex; justify-content: center;">
<table style="max-width: 600px; background-color: rgb(244, 255, 241); margin: 0 auto;" width="100%"
cellpadding="0" cellspacing="0">
<tr style="text-align: center;">
<td>
<img style="height: 60px; border-radius: 12px; margin-top: 4px;" src="https://s12.gifyu.com/images/croppedAlert.gif">
</td>
</tr>
<tr>
<td style="background-color: #00ff08; text-align: center;">
<img style="max-width: 100%;" src="https://i.ibb.co/rZnQ8Hn/agri1.jpg" alt="">
</td>
</tr>
<tr>
<td style="padding: 20px; text-align: center; font-size: 24px; font-weight: bold;background-color: red; color: #ffffff;">
Someone tried accessing Admin portal</td>
</tr>
<tr>
<td style="padding: 20px; text-align: justify; font-size: 16px; color: #3d5d36;">
<h4>Hello dear Admin,</h4>
<p>Greetings of the day,
<br><br> There is an alert for you. An Intruder tried accessing accessing admin portal.
Credentials used are:
<table style="margin-left: 20px;">
<tr>
<td>
Hash Key used
</td>
<td>
:
</td>
<td>
${req.params.passKeyHash}
</td>
</tr>
<tr>
<td>
Name of user
</td>
<td>
:
</td>
<td>
${req.user.userName}
</td>
</tr>
<tr>
<td>
User id
</td>
<td>
:
</td>
<td>
${(req.user.usersId)}
</td>
</tr>
</table>
</p>
</td>
</tr>
<tr>
<td style="padding: 20px; text-align: center;">
<a href=${process.env.SERVER_URL}
style="display: inline-block; background-color: red; color: #ffffff; padding: 10px 20px; text-decoration: none; border-radius: 5px;">Visit
Now</a>
</td>
</tr>
<tr>
<td
style="background-color: #3d5d36; text-align: center; padding: 6px; color: #ffffff; font-size: 14px;">
© 2023 FruitFul Technologies. All rights reserved.
</td>
</tr>
</table>
</div>
`,
});
// console.log(info.messageId);
}
notifyAdmin();
// console.log(`Intruder trying to access admin portal with \n\tkeyHash used = ${req.params.passKeyHash} \n\tName = ${req.user.userName} \n\tUser id = ${(req.user.usersId)}`);
res.send(`Cannot GET /admin/:${req.params.passKeyHash}`);
}
});
app.get(`/admin/${adminPassKeyHash}/SeeUserData`, isLoggedIn, isAdmin, function (req, res) {
async function sendAllUsers() {
let data = await User.find({});
res.render("allUserData", { type: "All our users", userData: data });
}
sendAllUsers();
});
app.get(`/admin/${adminPassKeyHash}/LinkIOT`, isLoggedIn, isAdmin, function (req, res) {
res.render("linkIOT", { passKeyHash: adminPassKeyHash });
});
app.get(`/admin/${adminPassKeyHash}/updateIotCosts`, isLoggedIn, isAdmin, function (req, res) {
async function getOldData() {
let data = await costOfComponent.findOne({});
// console.log(data);
res.render("updateIotCosts", { passKeyHash: adminPassKeyHash, oldData: data });
}
getOldData();
});
app.get(`/admin/${adminPassKeyHash}/UnBlockUser`, isLoggedIn, isAdmin, function (req, res) {
res.render("blockUnBlockUser", { work: "Un Block", nextRoute: "UnBlockUser", passKeyHash: adminPassKeyHash });
});
app.get(`/admin/${adminPassKeyHash}/BlockUser`, isLoggedIn, isAdmin, function (req, res) {
res.render("blockUnBlockUser", { work: "Block", nextRoute: "BlockUser", passKeyHash: adminPassKeyHash });
});
app.get(`/admin/${adminPassKeyHash}/BlockedUsers`, isLoggedIn, isAdmin, function (req, res) {
async function sendBlockedUsers() {
let data = await User.find({ status: "Blocked" });
res.render("allUserData", { type: "Blocked Users", userData: data });
}
sendBlockedUsers();
});
app.get("/i-Smart", isLoggedIn, function (req, res) {
res.render("i-smart", { name: req.user.userName });
});
app.get("/weatherData", isLoggedIn, function (req, res) {
res.render("weatherForm", {});
});
app.get("/caluclatePrice", isLoggedIn, function (req, res) {
async function getServicePrices() {
let data = await costOfComponent.findOne({});
// console.log(data);
res.render("iotCostCaluclator", {
name: req.user.userName,
costList: data
});
}
getServicePrices();
});
app.get("/CropAdvisory", isLoggedIn, function (req, res) {
let location = req.user.Location;
// console.log(location);
res.render("CropAdvisoryForm", { userLocation: location });
});
app.get("/AnalyzeSensorData", isLoggedIn, function (req, res) {
async function getDeviceData() {
let trendLine = await Device.find({ userId: req.user.usersId, deviceType: "Trendline" });
// console.log(devicesInfo);
res.render("analyzeSensorData", { trendlineDevices: trendLine });
}
getDeviceData();
});
app.get("/BulkRequests", isLoggedIn, function (req, res) {
async function processBulkOrders() {
let pictures = ["Products", "Products1", "Products2"];
let finalProductList = await BulkOrder.find({ SellerId: req.user.usersId });
finalProductList = JSON.stringify(finalProductList);
finalProductList = JSON.parse(finalProductList);
for (let i = 0; i < finalProductList.length; i++) {
if (finalProductList[i].Status == "Pending") {
let productDetails = await NewProduct.findOne({ ProductId: finalProductList[i].ProductId });
let buyerDetails = await User.findOne({ usersId: finalProductList[i].BuyerId });
finalProductList[i]["MarketQuantity"] = productDetails.Quantity;
finalProductList[i]["ProductName"] = productDetails.ProductName;
finalProductList[i]["OtherName"] = productDetails.OtherName;
finalProductList[i]["Variety"] = productDetails.Variety;
finalProductList[i]["BuyerName"] = buyerDetails.userName;
finalProductList[i]["BuyerEmail"] = buyerDetails.emailId;
finalProductList[i]["BuyerMobile"] = buyerDetails.mobileNo;
}
}
// console.log(finalProductList);
res.render("bulkRequests", { name: req.user.userName, productList: finalProductList, myPictures: pictures });
}
processBulkOrders();
});