-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1360 lines (1079 loc) · 39.1 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
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
const conn = require('./connection');
const express = require('express');
const session = require('express-session');
const bodyParser = require("body-parser");
const e = require('express');
const app = express();
const mongoose = require("mongoose");
const User = require("./models/user");
const SubscriptionPlan = require("./models/subplan");
const BusinessCard = require("./models/bcard");
const cardt = require("./models/card");
const temp = require("./models/templates");
const cpages = require("./models/custompages");
const mcompany = require("./models/company");
const emp = require("./models/employee");
const bcrypt = require("bcrypt");
const path = require('path');
const adminModel = require('./models/admin');
const multer = require('multer');
const Image = require('./models/image');
const LogModel = require('./models/logModel');
const { ObjectId } = require('mongodb');
const AWS = require('aws-sdk');
const dotenv = require('dotenv');
dotenv.config();
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use('/public', express.static(__dirname + "/public"));
const fs = require('fs');
const defaultSessionSecret = 'mydefaultsecretkey';
app.use(session({
secret: defaultSessionSecret,
resave: false,
saveUninitialized: true
}));
AWS.config.update({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION
});
const s3 = new AWS.S3();
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
app.get('/', function (req, res) {
res.render('landing/index');
});
app.get('/login', async (req, res) => {
res.render('login/login');
}
);
app.get('/register', async (req, res) => {
res.render('register/register');
}
);
app.get('/about', function (req, res) {
res.render('/views/about/about.ejs');
});
app.get('/contact', function (req, res) {
res.render('/views/contact/contact.ejs');
}
);
app.listen(8000, function () {
console.log('Server started at port 8000');
})
// Log Model
const logModel = new LogModel();
// Middleware for logging route access
app.use(async (req, res, next) => {
const routeAccessDetails = {
method: req.method,
path: req.path,
query: req.query,
params: req.params,
};
await logModel.logEvent('route_access', routeAccessDetails);
next();
});
// Displaying all the logs
app.get('/_logs', async (req, res) => {
try {
const logs = await logModel.getAllLogs();
console.log(logs);
res.json(logs);
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
app.get('/admin', async (req, res) => {
try {
const admin = await adminModel.findOne({ username: 'admins', password: 'admin' });
if (admin) {
// If the admin credentials are found, render the admin dashboard using EJS
res.render('admin/index');
} else {
// If admin credentials are not found, serve the login page from the admin folder using EJS
res.render('admin/login');
}
} catch (error) {
// Handle any errors, e.g., display an error page or redirect to login
console.error(error);
res.redirect('/');
}
});
app.post('/admin', async (req, res) => {
try {
const { username, password } = req.body;
const user = await adminModel.findOne({ username });
if (!user) {
res.send("User does not exist");
} else if (password === user.password) {
res.render('admin/index');
} else {
res.send("Invalid password");
}
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
app.get('/index',async(req,res)=>{
res.render('admin/index');
});
app.get('/subscription',async (req, res) =>{
const subscriptionPlans = await SubscriptionPlan.find();
res.render('admin/subscription', { subscriptionPlans });
});
app.post('/subscription', async (req, res) => {
try {
const { name, price, duration } = req.body;
const subscriptionPlan = new Subplan1({ name, price, duration });
await subscriptionPlan.save();
res.redirect('/subscription');
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
app.post('/edit-subscription', async (req, res) => {
try {
const { name, price, duration } = req.body;
await SubscriptionPlan.findByIdAndUpdate(req.params.id, { name, price, duration });
res.redirect('/subscription');
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
// getting subscription details
app.get('/add-subscription', async (req, res) => {
try {
res.render('admin/add-subscription');
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
//add subscription plan
app.post('/add-subscription', async (req, res) => {
try {
const { name, price, featureNames } = req.body;
if (!name || !price || !featureNames || !Array.isArray(featureNames)) {
return res.status(400).json({ error: 'Invalid data format' });
}
const newSubscriptionPlan = new SubscriptionPlan({
name,
price,
features: featureNames,
});
await newSubscriptionPlan.save();
const subscriptionPlans = await SubscriptionPlan.find();
res.render('admin/subscription', { subscriptionPlans });
} catch (error) {
console.error('Error adding subscription plan:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.get('/edit-subscription/:id', async (req, res) => {
try {
const plan = await SubscriptionPlan.findById(req.params.id);
if (!plan) {
return res.status(404).send('Subscription plan not found');
}
res.render('admin/edit-subscription', { plan });
} catch (error) {
console.error('Error fetching subscription plan:', error);
res.status(500).send('Internal Server Error');
}
});
app.post('/edit-subscription/:id', async (req, res) => {
const planId = req.params.id;
try {
const existingPlan = await SubscriptionPlan.findById(planId);
if (!existingPlan) {
return res.status(404).json({ error: 'Subscription plan not found' });
}
const { name, price, existingFeatures } = req.body;
const updatedFeatures = existingFeatures.split(',');
existingPlan.name = name;
existingPlan.price = price;
existingPlan.features = updatedFeatures;
await existingPlan.save();
const subscriptionPlans = await SubscriptionPlan.find();
res.render('admin/subscription', { subscriptionPlans });
} catch (error) {
console.error('Error updating subscription plan:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.get('/add-user', async (req, res) => {
try {
// Fetch subscription plans, card types, and templates from the database
const subscriptionPlans = await SubscriptionPlan.find();
const cardTypes = await cardt.find();
const templates = await temp.find();
res.render('admin/add-user', { subscriptionPlans, cardTypes, templates });
} catch (error) {
console.error('Error fetching data for user form:', error);
res.status(500).send('Internal Server Error');
}
});
app.post('/add-card', async (req, res) => {
const mobileNumber = req.body.phoneNumber; // Get the entered mobile number
try {
// Check if the user already exists based on the mobile number
const existingUser = await User.findOne({ number: mobileNumber });
console.log(existingUser);
if (existingUser) {
// If the user exists, you can redirect to the add-card page or perform necessary actions
const subscriptionPlans = await SubscriptionPlan.find();
const cardTypes = await cardt.find();
const templates = await temp.find();
res.render('admin/add-card', { existingUser, subscriptionPlans, cardTypes, templates });
// Redirect to the add-card page with the user ID
} else {
// If the user doesn't exist, you can handle it as needed, such as displaying an error message
res.send('User not found. Please register.');
}
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
app.post('/update-cards', async (req, res) => {
const { username, email, number, subscriptionPlan, occassion, cardType, template } = req.body
console.log(req.body);
try {
// Find the user by mobile number
const user = await User.findOne({ number: number });
if (!user) {
return res.status(404).send('User not found');
}
// Push the new card details and subscription plan to the user's selectedItems array
const newSelectedItem = {
occasion:occassion,
cardType: cardType,
template: template,
subscriptionPlan: {
plan: subscriptionPlan,
},
// Add other necessary fields for the new item
};
// Push the new item to the selectedItems array
user.selectedItems.push(newSelectedItem);
// Save the updated user object
await user.save();
const users1 = await fetchUserData();
res.render('admin/user', { users1 });
} catch (error) {
console.error('Error adding card:', error);
return res.status(500).send('Internal Server Error');
}
});
app.get('/user-details', async (req, res) => {
try {
// Your logic for fetching subscription plan data if needed
// const subscriptionPlan = await Subplan1.findById(req.params.id);
res.render('admin/user-details');
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
const fetchUserData = async () => {
try {
const users = await User.find()
.populate({
path: 'selectedItems.subscriptionPlan.plan',
model: 'SubscriptionPlan',
select: 'name',
})
.populate({
path: 'selectedItems.cardType',
model: 'CardType',
select: 'name',
})
.populate({
path: 'selectedItems.template',
model: 'Template',
select: 'name',
});
return users;
} catch (error) {
throw error;
}
};
app.get('/user', async (req, res) => {
try {
const users1 = await fetchUserData();
res.render('admin/user', { users1 });
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
app.get('/get-cards/:userId', async (req, res) => {
try {
const userId = req.params.userId;
const user = await User.findById(userId)
.populate({
path: 'selectedItems.subscriptionPlan.plan',
model: 'SubscriptionPlan',
select: 'name',
})
.populate({
path: 'selectedItems.cardType',
model: 'CardType',
select: 'name',
});
console.log(user);
res.json({ cards: user.selectedItems });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
//card deletion code
app.post('/delete-card/:userId', async (req, res) => {
try {
const userId = req.params.userId;
const cardId = req.body.cardId;
const businessCard = await BusinessCard.findByIdAndDelete(cardId);
if (businessCard) {
const s3 = new AWS.S3();
const deleteObject = async (objectKey) => {
const decodedObjectKey = decodeURIComponent(objectKey);
const key1 = decodedObjectKey.split('.com/')[1];
const params = {
Bucket: process.env.S3_BUCKET_NAME,
Key: key1, // Specify the folder path
};
try {
await s3.deleteObject(params).promise();
console.log(`Object deleted successfully: ${key1}`);
} catch (error) {
console.error(`Error deleting object: ${key1}`, error);
throw error;
}
};
await deleteObject(businessCard.Image);
await deleteObject(businessCard.bgImg);
}
await User.findByIdAndUpdate(userId, {
$pull: { selectedItems: { _id: cardId } }
});
const users1 = await fetchUserData();
res.render('admin/user', { users1 }); // Redirect to home or any desired route
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.get('/user-grid', async (req, res) => {
try {
// Your logic for fetching subscription plan data if needed
// const subscriptionPlan = await Subplan1.findById(req.params.id);
res.render('admin/user-grid');
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
app.get("/delete/:id",async(req,res)=>{
let planid = req.params.id;
try {
if (!ObjectId.isValid(planid)) {
return res.status(400).json({ error: 'Invalid ObjectId' });
}
const deletedPlan = await SubscriptionPlan.findByIdAndDelete(planid);
const subscriptionPlans = await SubscriptionPlan.find();
if (!deletedPlan) {
return res.status(404).json({ error: 'Subscription plan not found' });
}
res.render('admin/subscription', { subscriptionPlans });
} catch (error) {
console.error('Error deleting subscription plan:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
// app.post('/add-user', async (req, res) => {
// try {
// const { username, email, number, subscriptionPlan, occasion, cardType, template } = req.body;
// console.log(req.body);
// // Create a new user
// const Plan = new ObjectId(subscriptionPlan);
// const card = new ObjectId(cardType);
// const temp = new ObjectId(template);
// const newUser = new User({
// username,
// email,
// number,
// selectedItems: [
// {
// occasion,
// cardType: card,
// template: temp,
// subscriptionPlan: {
// plan: Plan,
// },
// },
// ],
// });
// // Save the user to the database
// const savedUser = await newUser.save();
// // Redirect to the edit page for the newly created user
// res.redirect(`/template1?userId=${savedUser._id}`);
// } catch (error) {
// console.error('Error creating user:', error);
// res.status(500).send('Internal Server Error');
// }
// });
app.get('/imageupload', async (req, res) => {
try {
const data = await Image.find({});
res.render('admin/image', { items: data });
} catch (err) {
console.error(err);
res.status(500).send('Internal Server Error');
}
});
// app.post('/imageupload', upload.single('image'), async (req, res) => {
// try {
// const obj = {
// name: req.body.name,
// desc: req.body.desc,
// img: {
// data: await fs.readFileAsync(path.join(__dirname, 'uploads', req.file.filename)),
// contentType: 'image/png',
// },
// };
// await Image.create(obj);
// res.redirect('/');
// } catch (err) {
// console.error(err);
// res.status(500).send('Internal Server Error');
// }
// });
app.post('/add-user', async (req, res) => {
try {
// ... (validate and sanitize user input)
// Extract selected values
const subscriptionPlanId = req.body.subscriptionPlan;
const templateId = req.body.template;
const cardTypeId = req.body.cardType;
// Create a new user
const newUser = new User({
username: req.body.username,
email: req.body.email,
number: req.body.number,
selectedItems: [
{
occasion: req.body.occassion,
cardType: cardTypeId,
template: templateId,
subscriptionPlan: {
plan: subscriptionPlanId,
expiresAt: req.body.expiresAt,
},
},
],
});
// Save the user to the database
const savedUser = await newUser.save();
// Redirect to the template page with selected values as query parameters
const users1 = await fetchUserData();
res.render('admin/user', { users1 });
} catch (error) {
// Handle errors
console.error(error);
res.status(500).send('Internal Server Error');
}
});
app.get('/edit-user/:userId', async (req, res) => {
try {
const userId = req.params.userId;
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const subscriptionPlans = await SubscriptionPlan.find();
const cardTypes = await cardt.find();
const templates = await temp.find();
res.render('admin/edit-user', { user,subscriptionPlans, cardTypes, templates });
} catch (error) {
console.error('Error fetching user for editing:', error);
res.status(500).send('Internal Server Error');
}
});
app.post('/edit-user/:userId', async (req, res) => {
const userId = req.params.userId;
try {
// Retrieve the user by ID
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
// Update user fields
user.username = req.body.username;
user.email = req.body.email;
user.number = req.body.number;
// Clear existing selectedItems array
user.selectedItems = [];
// Get the number of selectedItems from the hidden field
const selectedItemsCount = parseInt(req.body.selectedItemsCount, 10);
// Iterate over form fields to reconstruct selectedItems array
for (let index = 0; index < selectedItemsCount; index++) {
user.selectedItems.push({
occasion: req.body[`occasion_${index}`],
cardType: new ObjectId(req.body[`cardType_${index}`]),
template: new ObjectId(req.body[`template_${index}`]),
subscriptionPlan: {
plan: new ObjectId(req.body[`subscriptionPlan_${index}`]),
},
// Add other fields if needed
});
}
// Save the updated user to the database
const updatedUser = await user.save();
// Redirect to the user listing page or any other page after successful update
const users1 = await fetchUserData();
res.render('admin/user', { users1 });
} catch (error) {
console.error('Error updating user:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/template1', (req, res) => {
// Retrieve fixed values from query parameters
const subscriptionPlanId = req.query.subscriptionPlan;
const templateId = req.query.template;
const cardTypeId = req.query.cardType;
// Render the template.ejs file with fixed values
res.render('template1', { subscriptionPlanId, templateId, cardTypeId });
});
app.post('/template1', async (req, res) => {
try {
const { name, email, number, subscriptionPlan, occasion, cardType, template } = req.body;
console.log(req.body);
// Create a new user
const Plan = new ObjectId(subscriptionPlan);
const card = new ObjectId(cardType);
const temp = new ObjectId(template);
const newBusinnessCard = new BusinessCard({
username,
email,
number,
selectedItems: [
{
occasion,
cardType: card,
template: temp,
subscriptionPlan: {
plan: Plan,
},
},
],
});
// Save the user to the database
const savedUser = await newUser.save();
// Redirect to the edit page for the newly created user
res.redirect(`/template1?userId=${savedUser._id}`);
} catch (error) {
console.error('Error creating user:', error);
res.status(500).send('Internal Server Error');
}
}
);
app.post('/generate-card/:userid', async (req, res) => {
try {
const cardId = req.body.cardId;
const userId = req.params.userid;
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
// Find the selected item with the given cardId
const selectedItem = user.selectedItems.find(item => item._id.toString() === cardId);
if (!selectedItem) {
return res.status(404).json({ error: 'Selected item not found' });
}
const template = await temp.findById(selectedItem.template);
if (!template) {
return res.status(404).json({ error: 'Template not found' });
}
const templateName = template.name;
res.render(`admin/${templateName}`,{user,selectedItem});
} catch (error) {
console.error('Error generating card:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/cardlist', async (req, res) => {
try {
const users1 = await fetchUserData();
res.render('admin/cardlist', { users1 });
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
app.post('/businesscard/:userId', upload.fields([
{ name: 'Image', maxCount: 1 },
{ name: 'bgImage', maxCount: 1 }
]), async (req, res) => {
try {
const userId = req.params.userId;
const selectedItems = req.body.selectedItems;
const selectedItemsObject = JSON.parse(selectedItems);
const businessid = selectedItemsObject._id;
const subscriptionPlan = selectedItemsObject.subscriptionPlan || {};
const plan = subscriptionPlan.plan || '';
const templateId = selectedItemsObject.template;
const cardid = selectedItemsObject.cardType;
const occasion = selectedItemsObject.occasion;
const template = await temp.findById(templateId).lean();
// Extract the files from req.files
const images = req.files['Image'] ? req.files['Image'][0] : null;
const bgImage = req.files['bgImage'] ? req.files['bgImage'][0] : null;
const templateFields = template.fields && template.fields.map(field => ({
fieldName: field.name,
fieldValue: req.body[field.name] || '',
}));
const uploadToS3 = async (file, folder, filenamePrefix) => {
const key = `${userId}_${cardid}_${templateId}_${plan}_${occasion}_${filenamePrefix}`;
const s3Params = {
Bucket: process.env.S3_BUCKET_NAME,
Key: `${folder}/${key}`,
Body: file.buffer,
ContentType: file.mimetype,
};
const s3UploadResponse = await s3.upload(s3Params).promise();
return s3UploadResponse.Location;
};
const image1Url = images ? await uploadToS3(images, 'cards_img', 'image') : null;
const image2Url = bgImage ? await uploadToS3(bgImage, 'cards_img', 'bgimage') : null;
console.log(templateFields);
const filter = {
user: userId,
selectedCardType: cardid,
selectedTemplate: templateId,
selectedSubscriptionPlan: plan,
_id: businessid
};
const update = {
user: userId,
selectedCardType: cardid,
selectedTemplate: templateId,
selectedSubscriptionPlan: plan,
templateFields: templateFields,
Image: image1Url,
bgImg: image2Url,
bgColor: req.body.bgColor || '',
};
const options = {
upsert: true, // Creates a new document if no documents match the filter
new: true, // Returns the modified document if found or the upserted document if created
};
const savedBusinessCard = await BusinessCard.findOneAndUpdate(filter, update, options);
console.log(savedBusinessCard);
const users1 = await fetchUserData();
res.render('admin/user', { users1 });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/delete-user/:userId', async (req, res) => {
const userId = req.params.userId;
try {
// Find the user by ID and remove them
const deletedUser = await User.findOneAndDelete({ _id: userId });;
if (!deletedUser) {
return res.status(404).json({ error: 'User not found' });
}
const users1 = await fetchUserData();
res.render('admin/user', { users1 });
} catch (error) {
console.error('Error deleting user:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
function mapFields(formData, section) {
const fieldNames = formData[`${section}Names`] || [];
const fieldValues = formData[`${section}Values`] || [];
const textColors = formData[`${section}TextColors`] || [];
const textStyles = formData[`${section}TextStyles`] || [];
const textSizes = formData[`${section}TextSizes`] || [];
return fieldNames.map((name, idx) => {
const fieldObj = {
fieldName: name,
value: fieldValues[idx] || '',
textColor: textColors[idx] || '',
textStyle: textStyles[idx] || '',
textSize: textSizes[idx] || '',
};
// Additional fields based on section
if (section === 'contactField') {
fieldObj.icon = formData[`${section}Icons`] ? formData[`${section}Icons`][idx] : '';
}
return fieldObj;
});
}
app.post('/custompage/:id',upload.fields([{ name: 'image', maxCount: 1 }]),async(req,res)=>
{
try{
const formData = req.body;
const imageFile = req.files['image'][0];
const basicInformationFields = mapFields(formData, 'field');
const contactInfoFields = mapFields(formData, 'contactField');
const socialMediaFields = mapFields(formData, 'socialField');
const buttons = [];
// Iterate over the button fields in the form data
for (let i = 0; i < formData.buttonFieldNames.length; i++) {
const button = {
fieldName: formData.buttonFieldNames[i],
value: formData.buttonValues[i],
textStyle: formData.buttonTextStyles[i],
buttonColor: formData.buttonColors[i],
buttonSize: formData.buttonSizes[i],
};
buttons.push(button);
}
const uniqueid = new ObjectId();
const key = `${uniqueid}_${req.params.id}`;
const params = {
Bucket: process.env.S3_BUCKET_NAME,
Key: `custompages_img/${key}`,
Body: file.buffer,
ContentType: file.mimetype
};
const s3UploadResponse = await s3.upload(params).promise();
const logoUrl = s3UploadResponse.Location;
// Save the image to MongoDB
const customizablePage = new cpages({
_id: uniqueid,
user: req.params.id,
image: logoUrl,
imageSize: formData.imageSize,
basicInformationFields:basicInformationFields,
contactInfoFields:contactInfoFields,
additionalButtons: buttons,
socialMediaFields:socialMediaFields,
});
// Save the data to MongoDB
await customizablePage.save();
console.log(customizablePage);
res.status(201).send('Form submitted successfully!');
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
app.get('/add-company',async(req,res)=>{
res.render('admin/add-company');
});
app.post('/company-details', upload.single('logo'),async(req, res) => {
const { name, cname, cnum, cmail } = req.body;
console.log(req.body);
const file = req.file;