-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
2671 lines (2263 loc) · 92.1 KB
/
server.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 express= require("express");
const cors = require("cors");
const router = express.Router();
const mongoose = require("mongoose");
const multer=require("multer");
const { type } = require("os");
const bcrypt = require('bcryptjs');
const dotenv = require('dotenv');
const { error } = require("console");
const jwt = require('jsonwebtoken');
const nodemailer=require('nodemailer');
const { inflate } = require("zlib");
const { truncate } = require("fs");
dotenv.config()
// email Config
const transporter = nodemailer.createTransport({
service: "gmail",
auth:{
user:process.env.EMAIL,
pass:process.env.PASSWORD
}
})
const path = require('path');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname));
}
});
const upload = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname));
}
}),
fileFilter: (req, file, cb) => {
const filetypes = /jpeg|jpg|png|pdf/;
const mimetype = filetypes.test(file.mimetype);
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
if (mimetype && extname) {
return cb(null, true);
}
cb(new Error('Invalid file type'));
}
});
const app =express();
app.use(express.json());
// // Define allowed origins
// const allowedOrigins = [
// 'https://frontend-fge2.vercel.app',
// 'https://frontend-theta-mocha-38.vercel.app',
// 'https://ornnova.com/HR'
// ];
// // Configure CORS options
// const corsOptions = {
// origin: function (origin, callback) {
// // Check if the origin is allowed
// if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
// callback(null, true);
// } else {
// callback(new Error('Not allowed by CORS'));
// }
// },
// credentials: true, // Allow cookies to be sent
// };
const allowedOrigins = [
'https://frontend-fge2.vercel.app',
'https://frontend-theta-mocha-38.vercel.app',
'https://ornnova.com' // Correct domain
];
const corsOptions = {
origin: function (origin, callback) {
if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
callback(null, true); // If origin is allowed, continue the request
} else {
callback(new Error('Not allowed by CORS')); // Block the request
}
},
credentials: true, // Allow cookies to be sent
};
app.use(cors(corsOptions)); // Apply the CORS middleware
app.use("/www", express.static("uploads"));
// app.use('/uploads', express.static('uploads'));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.listen(process.env.PORT,()=>{
console.log("Listening to Port 7993");
});
let ConnectedtoMDB= async()=>{
try{
await mongoose.connect("mongodb+srv://bgopisrinivas:[email protected]/HRManagment");
console.log("Succesfully Connected to MDB ✅");
}catch{
console.log("Failed to Connect to MDB ❌");
}
}
ConnectedtoMDB();
let userSchema = new mongoose.Schema({
EmpCode: {
type: String,
required: true,
},
EmployeeName: {
required: true,
type: String,
},
Email: {
required: true,
type: String,
},
Password: {
required: true,
type: String,
},
UserType: {
required: true,
type: String,
},
ProfilePic: {
type: String,
},
Status: {
type: String,
},
verifytoken: {
type: String,
},
token: {
type: String,
},
CreatedBy: {
type: String,
},
Team: [
{
type:String
}
],
Clients: [
{
type: mongoose.Schema.Types.ObjectId, // Use ObjectId if you are working with ObjectIds
ref: 'Client' // Replace 'Client' with the actual reference model name if needed
}
],
Requirements:[
{
type:mongoose.Schema.Types.ObjectId,
ref: 'Requirements'
}
],
claimedRequirements: [{ type: mongoose.Schema.Types.ObjectId, ref: "NewRequirement" }]
});
let NewUser = new mongoose.model("Users",userSchema);
app.get("/loggedinuserdata/:email",async(req,res)=>{
let loggedinuserdata = await NewUser.find({Email:req.params.email})
res.json(loggedinuserdata);
})
app.post("/newUser",upload.array("ProfilePic"),async(req,res)=>{
let userArr=await NewUser.find().and({Email:req.body.Email});
if (userArr.length>0) {
res.json({status:"failure",msg:"Email already Exist❌"});
}else{
try{
let newUser = new NewUser({
EmpCode:req.body.EmpCode,
EmployeeName:req.body.EmployeeName,
Email:req.body.Email,
Password:req.body.Password,
UserType:req.body.UserType,
ProfilePic:req.files[0].path,
Status:req.body.Status,
token:req.body.Token,
CreatedBy:req.body.CreatedBy,
Team:req.body.Team
});
await newUser.save();
res.json({status:"Success",msg:" User Created Successfully✅"});
}catch(error){
res.json({status:"Failed",error:error,msg:"Invalid Details ❌"});
console.log(error)
}
}
}
);
app.get("/userDetailsHome",async(req,res)=>{
// to get only usertype having only user
// let userDetailshome=await NewUser.find({UserType:"User"});
let userDetailshome=await NewUser.find();
res.json(userDetailshome);
})
// Assign Clients to Users
app.get('/userDetailstoAssignClient/:clientId', async (req, res) => {
const clientId = req.params.clientId;
try {
// Find users who do not have the specified client ID in their Clients array
const userDetails = await NewUser.find({
UserType: { $in: ["User", "TeamLead"] },
Clients: { $ne: clientId } // $ne operator excludes users with the clientId in Clients array
});
// Get the count of users
const count = userDetails.length;
// Now, to get the count of users for each clientId in the Clients array
const clientCounts = await NewUser.aggregate([
{ $unwind: "$Clients" }, // Deconstruct the Clients array
{ $group: {
_id: "$Clients", // Group by clientId
userCount: { $sum: 1 }, // Count the number of users for each clientId
users: { $push: "$$ROOT" } // Push the entire user document
}},
{ $lookup: {
from: 'clients', // The name of the collection for clients (adjust if necessary)
localField: '_id',
foreignField: '_id',
as: 'clientInfo' // Join client info based on clientId
}},
{ $unwind: "$clientInfo" }, // Optional: to flatten the client info
{ $project: {
_id: 0, // Exclude the default _id
clientId: "$_id", // Include the clientId
userCount: 1,
users: 1,
clientName: "$clientInfo.name" // Assuming the Client schema has a name field
}}
]);
res.json({ count, userDetails, clientCounts });
} catch (error) {
res.status(500).json({ message: "Server Error", error });
}
});
app.get('/userDetailsofAssignedClient/:clientId', async (req, res) => {
const clientId = req.params.clientId;
try {
// Find users who do not have the specified client ID in their Clients array
const userDetails = await NewUser.find({
UserType: { $in: ["User", "TeamLead"] },
Clients: { $in: clientId } // $ne operator excludes users with the clientId in Clients array
});
// Get the count of users
const count = userDetails.length;
res.json({ count, userDetails });
} catch (error) {
res.status(500).json({ message: "Server Error", error });
}
});
// Assign Requirement to Users
app.get('/userDetailstoAssignRequirement/:reqId/:userId', async (req, res) => {
const { reqId, userId } = req.params;
try {
// Find the user with the provided userId to get their team members
const user = await NewUser.findById(userId);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
// Get the user's Team array (assuming it's an array of user IDs)
const teamIds = user.Team; // This is an array of user IDs
// If the user has no team, return an empty array for team members
if (!teamIds || teamIds.length === 0) {
return res.json({ teamMembers: [], requirementDetails: null });
}
// Find the team members who do not have the specified reqId in their Requirements array
const teamMembers = await NewUser.find({
_id: { $in: teamIds }, // Filter users whose IDs are in the Team array
UserType: { $in: ["User"] }, // Ensure UserType is "User"
Requirements: { $ne: reqId } // Exclude users who already have this reqId in their Requirements array
});
// Find the requirement details using the reqId from the NewRequirement schema
const requirementDetails = await NewRequirment.findById(reqId);
if (!requirementDetails) {
return res.status(404).json({ message: "Requirement not found" });
}
// Return both team members and the requirement details
res.json({ teamMembers, requirementDetails });
} catch (error) {
res.status(500).json({ message: "Server Error", error });
}
});
app.get('/userDetailsofAssignedRequirement/:reqId/:userId', async (req, res) => {
const reqId = req.params.reqId;
const userId = req.params.userId;
try {
// Step 1: Find the user to get their Team array
const user = await NewUser.findById(userId);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
const teamIds = user.Team; // Get the Team array
// Step 2: Find users in the Team who have the specified reqId in their Requirements
const userDetails = await NewUser.find({
UserType: { $in: ["User"] },
Requirements: reqId, // Users with the specified reqId
_id: { $in: teamIds } // Users present in the Team
});
res.json(userDetails);
} catch (error) {
res.status(500).json({ message: "Server Error", error });
}
});
// Route to get users with UserType 'User'
app.get("/getUserDataToADDtoTeam", async (req, res) => {
try {
// Step 1: Get the list of all userIds that are in any Team array
const usersWithTeams = await NewUser.find({ "Team": { $exists: true, $ne: [] } }, "Team");
// Extract all the userIds from the Team arrays
let userIdsInTeams = usersWithTeams.flatMap(user =>
user.Team
.filter(id => id) // Ensure id is defined
.map(id => id.toString())
);
// Filter out any empty or invalid ObjectId strings
userIdsInTeams = userIdsInTeams.filter(id => id && mongoose.Types.ObjectId.isValid(id));
// Query to get users where UserType is 'User' and their _id is not in the Team array
const userDetails = await NewUser.find({
UserType: "User",
_id: { $nin: userIdsInTeams }
});
// Respond with the filtered user details as JSON
res.json(userDetails);
} catch (err) {
// Handle errors (e.g., database issues)
console.error("Error:", err);
res.status(500).json({ message: "Internal Server Error" });
}
});
app.post("/login", upload.none(), async (req, res) => {
console.log(req.body);
// Fetch user data based on the email provided
let fetchedData = await NewUser.find({ Email: req.body.Email });
console.log(fetchedData);
// Check if the user exists
if (fetchedData.length > 0) {
// Validate the password
if (fetchedData[0].Password === req.body.Password) {
// Prepare data to send back
let dataToSend = {
EmpCode: fetchedData[0].EmpCode,
EmployeeName: fetchedData[0].EmployeeName,
Email: fetchedData[0].Email,
UserType: fetchedData[0].UserType, // UserType retrieved from database
ProfilePic: fetchedData[0].ProfilePic,
Status: fetchedData[0].Status,
Id: fetchedData[0]._id,
ClaimedRequirements: fetchedData[0].claimedRequirements,
Token: fetchedData[0].tokenVersion
};
res.json({ status: "Success", msg: "Login Successfully ✅", data: dataToSend });
} else {
res.json({ status: "Failed", msg: "Invalid Password ❌" });
}
} else {
res.json({ status: "Failed", msg: "User Does Not Exist ❌" });
}
});
const secretKey = process.env.SECRET_KEY;
app.post("/sendpasswordlink", async (req, res) => {
console.log(req.body);
const { email } = req.body;
if (!email) {
return res.status(401).json({ status: 401, message: "Enter Your Email" });
}
try {
// Find user by email
const userfind = await NewUser.findOne({ Email: email });
if (!userfind) {
return res.status(401).json({ status: 401, message: "User not found with this email" });
}
// Generate a token for password reset
const token = jwt.sign({ _id: userfind._id }, secretKey, { expiresIn: "300s" });
// Update user with the generated token
const setusertoken = await NewUser.findByIdAndUpdate(
{ _id: userfind._id },
{ verifytoken: token },
{ new: true }
);
if (setusertoken) {
const mailOptions = {
from: process.env.EMAIL,
to: email,
subject: "Password Reset Link",
text: `This link is valid for 5 minutes : https://ornnova.com/HR/ResetPassword/${userfind._id}/${setusertoken.verifytoken}`
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log("Error", error);
return res.status(401).json({ status: 401, message: "Email Not Sent" });
} else {
console.log("Email Sent", info.response);
return res.status(201).json({ status: 201, message: "Email Sent Successfully" });
}
});
} else {
return res.status(500).json({ status: 500, message: "Error updating token" });
}
} catch (error) {
console.error(error);
return res.status(500).json({ status: 500, message: "Internal Server Error" });
}
});
// verify user for forgot password
// app.get("/ResetPasswordpage/:id/:token",async(req,res)=>{
// const {id,token} = req.params;
// try {
// const validuser = await NewUser.findOne({_id:id,verifytoken:token});
// const verifyToken = jwt.verify(token,secretKey);
// console.log(verifyToken)
// if (validuser && verifyToken._id){
// res.status(201).json({status:201,validuser})
// }else{
// res.status(401).json({status:401,message:"User Not Exist"})
// }
// } catch (error) {
// res.status(401).json({status:401,error })
// }
// })
app.get("/ResetPasswordpage/:id/:token", async (req, res) => {
const { id, token } = req.params;
try {
const validuser = await NewUser.findOne({ _id: id, verifytoken: token });
const verifyToken = jwt.verify(token, secretKey);
if (validuser && verifyToken._id) {
res.status(201).json({ status: 201, validuser });
} else {
res.status(401).json({ status: 401, message: "User Not Exist" });
}
} catch (error) {
res.status(401).json({ status: 401, error });
}
});
// Change Password
// app.post("/:id/:token",async(req,res)=>{
// const {id,token} = req.params;
// const{password} = req.body;
// try{
// const validuser = await NewUser.findOne({_id:id,verifytoken:token});
// const verifyToken = jwt.verify(token,secretKey);
// if (validuser && verifyToken._id) {
// // const newpassword = await bcrypt.hash(password,12);
// const newpassword = await (password);
// const setnewuserpass = await NewUser.findByIdAndUpdate({_id:id},{Password:newpassword})
// setnewuserpass.save();
// res.status(201).json({status:201,setnewuserpass})
// }else{
// res.status(401).json({status:401,message:"User Not Exist"})
// }
// }catch(error){
// res.status(401).json({status:401,error })
// }
// })
app.post("/Changepassword/:id/:token", async (req, res) => {
const { id, token } = req.params;
const { password } = req.body;
try {
const validuser = await NewUser.findOne({ _id: id, verifytoken: token });
const verifyToken = jwt.verify(token, secretKey);
if (validuser && verifyToken._id) {
const newpassword = password; // Make sure you're handling the password correctly
const setnewuserpass = await NewUser.findByIdAndUpdate({ _id: id }, { Password: newpassword });
// Save the updated password
await setnewuserpass.save();
// Return a successful response
res.status(201).json({ status: 201, message: "Password updated successfully" });
} else {
res.status(401).json({ status: 401, message: "User not found or token is invalid" });
}
} catch (error) {
res.status(500).json({ status: 500, message: "Server error", error });
}
});
app.delete("/deleteUser/:id",async(req,res)=>{
console.log(req.params.id);
try {
await NewUser.deleteMany({_id:req.params.id});
res.json({status:"success",msg:`User Deleted Successfully✅`});
} catch (error) {
res.json({status:"failure",msg:"Unable To Delete ❌",error:error});
}
});
app.get("/getUserData/:id", async (req, res) => {
try {
// Find the user by the given ID
const user = await NewUser.findById(req.params.id);
if (!user) {
return res.status(404).json({ msg: 'User not found' });
}
// Extract the Team array (which contains user IDs)
const teamUserIds = user.Team;
// Find the details of all users whose IDs are in the Team array
const teamUserDetails = await NewUser.find({ _id: { $in: teamUserIds } });
// Combine user data and team details into a single response object
const response = {
userDetails: user,
teamDetails: teamUserDetails
};
// Respond with the combined user and team details
res.json(response);
} catch (err) {
console.error("Error fetching user data:", err);
res.status(500).json({ msg: "Internal Server Error" });
}
});
app.get("/getUserdatatoUpdate/:id",async(req,res)=>{
let userdetails = await NewUser.findById({_id:req.params.id});
res.json(userdetails);
})
// Assuming you are using Express and Mongoose
app.put('/updateUser/:id', async (req, res) => {
const { id } = req.params;
const { name, Code, email, status, usertype, profile, Team } = req.body;
try {
// Fetch the current user
const currentUser = await NewUser.findById(id);
if (!currentUser) {
return res.status(404).json({ msg: 'User not found' });
}
// Merge new team members with existing ones if usertype is "TeamLead"
const teamObjectIds = usertype === "TeamLead"
? Array.from(new Set([
...currentUser.Team, // Existing team members
...Team.map(userId => new mongoose.Types.ObjectId(userId)) // New team members
]))
: currentUser.Team; // No change if usertype is not "TeamLead"
// Update user
const updatedUser = await NewUser.findByIdAndUpdate(
id,
{
EmployeeName: name,
EmpCode: Code,
Email: email,
Status: status,
UserType: usertype,
ProfilePic: profile,
Team: teamObjectIds // Correctly set Team
},
{ new: true } // Return the updated document
);
if (updatedUser) {
res.json({ msg: 'User updated successfully', updatedUser });
} else {
res.status(404).json({ msg: 'User not found' });
}
} catch (err) {
console.error(err);
res.status(500).json({ msg: 'Error updating user' });
}
});
let clientSchema= new mongoose.Schema({
ClientCode:{
required:true,
type:String,
unique:true,
},
ClientName:{
required:true,
type:String,
},
Services:{
required:true,
type:String,
},
Location:{
required:true,
type:String,
},
Name:{
// required:true,
type:String,
},
Spoc:{
// required:true,
type:String,
},
MobileNumber:{
// required:true,
type:Number,
},
Email:{
// required:true,
type:String,
},
Name1:{
type:String,
},
Spoc1:{
type:String,
},
MobileNumber1:{
type:Number,
},
Email1:{
type:String,
},
Name2:{
type:String,
},
Spoc2:{
type:String,
},
MobileNumber2:{
type:Number,
},
Email2:{
type:String,
},
Assign:[
{
type:String,
}
]
});
let NewClient = new mongoose.model("Clients",clientSchema);
app.post("/addClient",upload.none(),async(req,res)=>{
let ClientArr=await NewClient.find().and({ClientCode:req.body.ClientCode});
if (ClientArr.length>0) {
res.json({status:"failure",msg:"Client Code already Exist❌"});
}else{
try{
let newClient = new NewClient({
ClientCode:req.body.ClientCode,
ClientName:req.body.ClientName,
Services:req.body.Services,
Location:req.body.Location,
Name:req.body.Name,
Spoc:req.body.Spoc,
MobileNumber:req.body.MobileNumber,
Email:req.body.Email,
Name1:req.body.Name1,
Spoc1:req.body.Spoc1,
MobileNumber1:req.body.MobileNumber1,
Email1:req.body.Email1,
Name2:req.body.Name2,
Spoc2:req.body.Spoc2,
MobileNumber2:req.body.MobileNumber2,
Email2:req.body.Email2,
});
await newClient.save();
console.log(req.body);
res.json({status:"Success",msg:" Client Created Successfully✅"});
}catch(error){
res.json({status:"Failed",error:error,msg:"Invalid Details ❌"});
console.log(error);
}
}
}
);
app.get("/ClientsList", async (req, res) => {
try {
const clientsList = await NewClient.find();
const clientUserCounts = [];
for (const client of clientsList) {
// Find users for the current client and filter by userType
const users = await NewUser.find({
Clients: client._id,
});
const userCount = users.length;
// Count users of type 'user' and 'teamlead'
const allusers = await NewUser.find({
UserType: { $in: ['User', 'TeamLead'] }
} );
let allusersCount = allusers.length;
clientUserCounts.push({
clientId: client._id,
clientCode: client.ClientCode, // Ensure this field exists in your schema
clientName: client.ClientName, // Ensure this field exists in your schema
userCount: userCount, // Total user count
userTypeCounts:allusersCount, // Count of specific user types
clientDetails: {
location: client.Location,
typeOfService: client.Services,
}
});
}
res.json({ clientUserCounts }); // Ensure this is returned correctly
} catch (error) {
res.status(500).json({ message: "Server Error", error });
}
});
app.get("/allUsersCount",async(req,res)=>{
try{
// Count users of type 'user' and 'teamlead'
const allusers = await NewUser.find({
UserType: { $in: ['User', 'TeamLead'] }
} );
let allusersCount = allusers.length;
res.json(allusersCount);
} catch(err){
console.log(err);
}
})
app.get("/ClientsList/:id",async(req,res)=>{
let ClientsList = await NewClient.find({_id:req.params.id});
res.json(ClientsList);
})
app.get("/clientDetails",async(req,res)=>{
let clientdetails = await NewClient.find();
res.json(clientdetails);
})
app.delete("/deleteClient/:id",async(req,res)=>{
console.log(req.params.id);
try {
await NewClient.deleteMany({_id:req.params.id});
res.json({status:"success",msg:`Client Deleted Successfully✅`});
} catch (error) {
res.json({status:"failure",msg:"Unable To Delete ❌",error:error});
}
});
app.get("/getClientdatatoUpdate/:id",async(req,res)=>{
let clientdetails = await NewClient.findById({_id:req.params.id});
res.json(clientdetails);
})
app.put("/UpdateClient/:id", async(req,res)=>{
console.log(req.params.id);
try {
if(req.body.ClientCode.length>0){
await NewClient.updateOne({_id:req.body.id},
{ClientCode:req.body.ClientCode});
}
if(req.body.ClientName.length>0){
await NewClient.updateOne({_id:req.body.id},
{ClientName:req.body.ClientName});
}
if(req.body.Services.length>0){
await NewClient.updateOne({_id:req.body.id},
{Services:req.body.Services});
}
if(req.body.Location.length>0){
await NewClient.updateOne({_id:req.body.id},
{Location:req.body.Location});
}
if(req.body.Email.length>0){
await NewClient.updateOne({_id:req.body.id},
{Email:req.body.Email});
}
if(req.body.Email1.length>0){
await NewClient.updateOne({_id:req.body.id},
{Email1:req.body.Email1});
}
if(req.body.Email2.length>0){
await NewClient.updateOne({_id:req.body.id},
{Email2:req.body.Email2});
}
if(req.body.MobileNumber.length>0){
await NewClient.updateOne({_id:req.body.id},
{MobileNumber:req.body.MobileNumber});
}
if(req.body.MobileNumber1.length>0){
await NewClient.updateOne({_id:req.body.id},
{MobileNumber1:req.body.MobileNumber1});
}
if(req.body.MobileNumber2.length>0){
await NewClient.updateOne({_id:req.body.id},
{MobileNumber2:req.body.MobileNumber2});
}
if(req.body.Name.length>0){
await NewClient.updateOne({_id:req.body.id},
{Name:req.body.Name});
}
if(req.body.Name1.length>0){
await NewClient.updateOne({_id:req.body.id},
{Name1:req.body.Name1});
}
if(req.body.Name2.length>0){
await NewClient.updateOne({_id:req.body.id},
{Name2:req.body.Name2});
}
if(req.body.Spoc.length>0){
await NewClient.updateOne({_id:req.body.id},
{ Spoc:req.body. Spoc});
}
if(req.body.Spoc1.length>0){
await NewClient.updateOne({_id:req.body.id},
{ Spoc1:req.body. Spoc1});
}
if(req.body.Spoc2.length>0){
await NewClient.updateOne({_id:req.body.id},
{ Spoc2:req.body. Spoc2});
}
res.json({status:"success",msg:" Details Updated Successfully✅"});
} catch (error) {
res.json({status:"failure",msg:"Didn't Updated all ☹️"});
console.log(error);
}
})
const RequirementSchema = new mongoose.Schema({
regId: {
type: String,
required: true
},
client: {
type: String,
required: true
},
typeOfContract: {
type: String,
required: true
},
startDate: {
type: Date,
required: true
},
duration: {
type: String,
required: true
},
location: {
type: String,
required: true
},
sourceCtc: {
type: String,
required: true
},
qualification: {
type: String,
required: true
},
yearsExperience: {
type: String,
required: true
},
relevantExperience: {
type: String,
required: true
},
skill: {
type: String,
required: true
},
role:{
type:String,
},
requirementtype:{
type:String,
required:true
},
// assessments: [AssessmentSchema]
assessments: [
{
assessment: {
type: String,
required: true
},
yoe: {
type: String,
required: true
}
}
],
uploadedBy:{
type:String,
},
clientId:{
type:String,
},
update:{
type:String,
default:"New"
},
uploadedDate: {
type: Date,
default: Date.now
},
claimedBy: [{ userId: String, claimedDate: Date }]
});
let NewRequirment = new mongoose.model("Requirements",RequirementSchema);
app.post("/newRequirment",upload.none(),async(req,res)=>{
// let RegID=await NewRequirment.find().and({reqId:req.body.reqId});
// if (RegID.length>0) {
// res.json({status:"failure",msg:"Reg ID already Exist❌"});
// }else{
try{
const{
assessments
} = req.body;
// Ensure assessments is an array of objects
const formattedAssessments = Array.isArray(assessments) ? assessments.map(item => ({
assessment: item.assessment || "",
yoe: item.yoe || ""
})) : [];