-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDB.cs
More file actions
1026 lines (872 loc) · 35.7 KB
/
Copy pathDB.cs
File metadata and controls
1026 lines (872 loc) · 35.7 KB
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
using Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text;
namespace Queries;
public class DB
{
private readonly ModelContext _db; // Declare _db field
private readonly IHttpContextAccessor _httpContextAccessor;
public DB(ModelContext db, IHttpContextAccessor httpContextAccessor)
{
_db = db; // Initialize _db in the constructor
_httpContextAccessor = httpContextAccessor;
}
//Employees attending on day
public async Task<int> EmployeesOnSite(DateTime day)
{
var employees = await _db.Employees
.Include(e => e.Availabilities)
.Where(e => e.Availabilities.Any(a => a.Date == DateOnly.FromDateTime(day)))
.ToArrayAsync();
int amount = employees.Length;
return amount;
}
public async Task<ActionResult<Object[]>> GetEmployeesOnSite(DateTime day)
{
try
{
//Get all employees for the day of the year in Availability
var employees = await _db.Employees
.Include(e => e.Availabilities)
.Where(e => e.Availabilities.Any(a => a.Date == DateOnly.FromDateTime(day)))
.ToArrayAsync();
return new ObjectResult(new
{
success = true,
employees
});
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in GetEmployeesOnSite: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult<Object[]>> GetEmpsOnEvent(int id)
{
try
{
//Get all employees for the day of the year in Availability
var employees = await _db.Events
.Where(e => e.Id == id)
.SelectMany(e => e.Attendees).Select(e => e.Employee)
.ToArrayAsync();
// Now, 'employees' is of type EmployeeEvent[]
return new ObjectResult(new
{
success = true,
employees
});
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in GetEmployeesOnSite: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<List<Employee>> GetEmployees()
{
var employees = await _db.Employees
.Include(e => e.Room)
.Include(e => e.Availabilities)
.Include(e => e.Reviews)
.Include(e => e.AttendedEvents)
.AsSplitQuery()
.ToListAsync();
return employees;
}
public async Task<ActionResult<Employee>> AddEmp(Employee emp, IEmailSender emailSender)
{
try
{
if (_db.Employees.Count() == 0) emp.Id = 1;
else
emp.Id = _db.Employees.Max(e => e.Id) + 1;
var employee = _db.Employees.Add(emp);
await _db.SaveChangesAsync();
// send an email to the new employee saying that their account has been created successfully
await emailSender.SendEmailAsync(new Message(new List<string> { emp.Email }, "Account Created", $"Your account has been created successfully {emp.FirstName} {emp.LastName}!"));
return emp;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
public async Task<ActionResult<List<Availability>>> GetAllDates()
{
var Dates = await _db.Availabilities
.Include(w => w.Employee)
.AsSplitQuery()
.ToListAsync();
return Dates;
}
public async Task<ActionResult<List<String>>> GetAllMails()
{
// Return a list of all employee emails
var mails = await _db.Employees
.Select(e => e.Email)
.ToListAsync();
return mails;
}
public async Task<ActionResult> Login(string email, string password)
{
try
{
var employee = await _db.Employees
.Where(e => e.Email.ToLower() == email.ToLower())
.FirstOrDefaultAsync();
if (employee == null)
{
return new ObjectResult(new { success = false, message = "Employee not found!" });
}
// Check if the password is correct
if (!BCrypt.Net.BCrypt.Verify(password, employee.Password))
{
return new ObjectResult(new { success = false, message = "Incorrect password!" });
}
return new ObjectResult(new { success = true, employee });
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return new ObjectResult(new { success = false, message = "Something went wrong!" });
}
}
public async Task<ActionResult> JoinDay(string email, DateTime day)
{
var employee = await _db.Employees.AsNoTracking()
.Include(e => e.Availabilities)
.FirstOrDefaultAsync(e => e.Email.ToLower() == email.ToLower());
if (employee == null)
{
return new ObjectResult(new { success = false, message = "Employee not found." });
}
var date = DateOnly.FromDateTime(day);
if (employee.Availabilities.Any(a => a.Date == date))
{
// delete the availability
var availability = employee.Availabilities.Where(a => a.Date == date).FirstOrDefault();
_db.Availabilities.Remove(availability);
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, message = false });
}
// Rest of your code...
var newAvailability = new Availability
{
EmployeeId = employee.Id,
Date = date
};
_db.Availabilities.Add(newAvailability);
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, message = true });
}
public async Task<ActionResult> InOffice(string email, DateTime day)
{
var emp = await _db.Employees
.Include(e => e.Availabilities)
.Where(e => e.Email == email)
.FirstOrDefaultAsync();
if (emp == null)
{
return new ObjectResult(new { success = false, message = "Employee not found!" });
}
var avail = emp.Availabilities.Where(a => a.Date == DateOnly.FromDateTime(day)).FirstOrDefault();
if (avail != null)
{
return new ObjectResult(new { success = true, message = true });
}
return new ObjectResult(new { success = true, message = false });
}
public async Task<ActionResult> AddPfp(string email, string pfp)
{
try
{
var emp = await _db.Employees
.Where(e => e.Email == email)
.FirstOrDefaultAsync();
if (emp == null)
{
return new ObjectResult(new { success = false, message = "Employee not found!" });
}
else
{
// Attempt to convert the string to a byte array
try
{
byte[] imageBytes = Convert.FromBase64String(pfp);
emp.ProfilePicture = imageBytes;
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, message = "Profile picture updated!" });
}
catch (Exception ex)
{
// Handle the exception and return an appropriate response
return new ObjectResult(new { success = false, message = "Error decoding base64 string: " + ex.Message });
}
}
}
catch (Exception ex)
{
// Handle any other exceptions that might occur
return new ObjectResult(new { success = false, message = "An error occurred: " + ex.Message });
}
}
public async Task<int> EventAtt(int id) =>
(from e in _db.Events where e.Id == id select e.Attendees).First().Count;
public async Task<ActionResult<List<Room>>> GetAvailableSpaces()
{
try
{
List<Room> rooms = await _db.Rooms.Include(r => r.Employee).ToListAsync();
return new ObjectResult(new { success = true, rooms });
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in GetAvailableSpaces: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult<Room>> ClaimSpace(int RoomNumber, string email)
{
try
{
// Get the room with the specified id
var room = await _db.Rooms
.Where(r => r.RoomNumber == RoomNumber)
.FirstOrDefaultAsync();
if (room == null)
{
return new ObjectResult(new { success = false, message = "Room not found!" });
}
// Get the employee with the specified id
var employee = await _db.Employees
.Where(e => e.Email == email)
.Include(e => e.Room)
.FirstOrDefaultAsync();
if (employee == null)
{
return new ObjectResult(new { success = false, message = "Employee not found!" });
}
if (employee.Room != null)
{
return new ObjectResult(new { success = false, message = "Employee already claimed a room!\n There is a limit of one per person." });
}
// Check if the room is already claimed
if (room.Employee != null && room.Employee != employee)
{
return new ObjectResult(new { success = false, message = "Room already claimed!" });
}
// Claim the room
room.Employee = employee;
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, room });
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in ClaimSpace: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult<Room>> ReleaseSpace(int RoomNumber, string email)
{
try
{
// Get the room with the specified id
var room = await _db.Rooms
.Where(r => r.RoomNumber == RoomNumber)
.FirstOrDefaultAsync();
if (room == null)
{
return new ObjectResult(new { success = false, message = "Room not found!" });
}
// Get the employee with the specified id
var employee = await _db.Employees
.Where(e => e.Email == email)
.FirstOrDefaultAsync();
if (employee == null)
{
return new ObjectResult(new { success = false, message = "Employee not found!" });
}
// Check if the room is already claimed
if (room.Employee == null || room.Employee != employee)
{
return new ObjectResult(new { success = false, message = "Room not claimed!" });
}
// Release the room
room.Employee = null;
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, room });
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in ReleaseSpace: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult<Room>> ReleaseSpaceAdmin(int RoomNumber)
{
try
{
// Get the room with the specified id
var room = await _db.Rooms
.Where(r => r.RoomNumber == RoomNumber)
.Include(r => r.Employee).FirstOrDefaultAsync();
if (room == null)
{
return new ObjectResult(new { success = false, message = "Room not found!" });
}
// Check if the room is already claimed
if (room.Employee == null)
{
return new ObjectResult(new { success = false, message = "Room not claimed!" });
}
// Release the room
room.Employee = null;
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, room });
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in ReleaseSpaceAdmin: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult<Event>> GetEvent(int eventId)
{
try
{
var events = await _db.Events
.Include(e => e.Reviews)
.Include(e => e.Attendees)
.Where(e => e.Id == eventId)
.FirstOrDefaultAsync();
return events;
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in GetEvent: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult<List<Event>>> GetEvents()
{
try
{
List<Event> events = await _db.Events
.Include(e => e.Reviews)
.Include(e => e.Attendees)
.OrderBy(e => e.Date)
.ThenBy(e => e.StartTime)
.ThenBy(e => e.Location)
.ThenBy(e => e.Name)
.ToListAsync();
return events;
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in GetEvents: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult<List<Event>>> GetPublicEvents()
{
try
{
List<Event> events = await _db.Events
.Include(e => e.Reviews)
.Include(e => e.Attendees)
.OrderBy(e => e.Date)
.ThenBy(e => e.StartTime)
.ThenBy(e => e.Location)
.ThenBy(e => e.Name)
.Where(e => e.isPublic == true)
.ToListAsync();
return events;
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in GetEvents: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult<List<Event>>> GetPrivateEvents()
{
try
{
List<Event> events = await _db.Events
.Include(e => e.Reviews)
.Include(e => e.Attendees)
.OrderBy(e => e.Date)
.ThenBy(e => e.StartTime)
.ThenBy(e => e.Location)
.ThenBy(e => e.Name)
.Where(e => e.isPublic == false)
.ToListAsync();
return events;
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in GetEvents: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult<List<Event>>> GetEventsByEmployee(int employeeId)
{
try
{
var events = await _db.Events
.Include(e => e.Reviews)
.Include(e => e.Attendees)
.OrderBy(e => e.Date)
.ThenBy(e => e.StartTime)
.ThenBy(e => e.Location)
.ThenBy(e => e.Name)
.ToListAsync();
var userEvents = events
.Where(e => e.Attendees.Any(attendee => attendee.EmployeeId == employeeId))
.ToList();
return userEvents;
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in GetEventsByEmployee: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult<Event>> AddEvent(Event newEvent)
{
try
{
// Add the new event to the database
await _db.Events.AddAsync(newEvent);
await _db.SaveChangesAsync();
return newEvent;
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in AddEvent: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<IActionResult> DeleteEvent(int eventId)
{
try
{
// Get the event with the specified id
var eventToDelete = await _db.Events
.Where(e => e.Id == eventId)
.FirstOrDefaultAsync();
if (eventToDelete == null)
{
return new ObjectResult(new { success = false, message = "Event not found!" });
}
// Delete the event
_db.Events.Remove(eventToDelete);
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, message = "Event deleted!" });
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in DeleteEvent: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<bool> CheckJoin(int eventId, int userId)
{
var query = (from e in _db.Events where e.Id == eventId select e);
var Events = query.Any(x => x.Attendees.Any(e => e.EmployeeId == userId));
return Events;
}
public async Task<IActionResult> ApproveEvent(int eventId)
{
try
{
// Get the event with the specified id
var eventToApprove = await _db.Events
.Where(e => e.Id == eventId)
.FirstOrDefaultAsync();
if (eventToApprove == null)
{
return new ObjectResult(new { success = false, message = "Event not found!" });
}
// Approve the event
eventToApprove.isPublic = true;
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, message = "Event approved!" });
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in ApproveEvent: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult<Event>> EditEvent(int eventId, Event updatedEvent, IEmailSender emailSender)
{
try
{
// var eventToEdit = await _db.Events.FindAsync(id);
// if (eventToEdit == null)
// {
// return NotFound();
// }
// // Get all EmployeeEvent records for this event
// var employeeEvents = _db.EmployeeEvents.Where(ee => ee.EventId == eventToEdit.Id);
// // Get all attendees (Employees) for this event
// var attendees = employeeEvents.Select(ee => ee.Employee).ToList();
// // Check if there are any attendees
// if (attendees.Any())
// {
// // Get the email addresses of the attendees
// var attendeeEmails = attendees.Select(a => a.Email).ToList();
// var changes = new StringBuilder();
// // Compare and update properties
// CompareAndUpdateProperty("Location", eventToEdit.Location, input.Location, changes);
// CompareAndUpdateProperty("Date", eventToEdit.Date, input.Date, changes);
// CompareAndUpdateProperty("StartTime", eventToEdit.StartTime, input.StartTime, changes);
// CompareAndUpdateProperty("EndTime", eventToEdit.EndTime, input.EndTime, changes);
// CompareAndUpdateProperty("Description", eventToEdit.Description, input.Description, changes);
// // Update or add the new event
// eventToEdit.Location = input.Location;
// eventToEdit.Date = input.Date;
// eventToEdit.StartTime = input.StartTime;
// eventToEdit.EndTime = input.EndTime;
// eventToEdit.Description = input.Description;
// await _db.SaveChangesAsync();
// // Create a message
// var message = new StringBuilder();
// message.AppendLine("Event:");
// message.AppendLine($"Location: {eventToEdit.Location}");
// message.AppendLine($"Date: {eventToEdit.Date}");
// message.AppendLine($"Start Time: {eventToEdit.StartTime}");
// message.AppendLine($"End Time: {eventToEdit.EndTime}");
// message.AppendLine($"Description: {eventToEdit.Description}");
// // Append changes
// if (changes.Length > 0)
// {
// message.AppendLine("\nChanges:");
// message.Append(changes.ToString());
// }
// // Send email
// _emailSender.SendEmailAsync(new Message(attendeeEmails, "Event Changed", message.ToString()));
// }
// return eventToEdit;
// Get the event with the specified id
var eventToEdit = await _db.Events
.Where(e => e.Id == eventId)
.FirstOrDefaultAsync();
if (eventToEdit == null)
{
return new ObjectResult(new { success = false, message = "Event not found!" });
}
// Get all EmployeeEvent records for this event
var employeeEvents = _db.EmployeeEvents.Where(ee => ee.EventId == eventToEdit.Id);
// Get all attendees (Employees) for this event
var attendees = employeeEvents.Select(ee => ee.Employee).ToList();
var changes = new StringBuilder();
// Compare properties
CompareProperty("Name", eventToEdit.Name, updatedEvent.Name, changes);
CompareProperty("Location", eventToEdit.Location, updatedEvent.Location, changes);
CompareProperty("Date", eventToEdit.Date, updatedEvent.Date, changes);
CompareProperty("StartTime", eventToEdit.StartTime, updatedEvent.StartTime, changes);
CompareProperty("EndTime", eventToEdit.EndTime, updatedEvent.EndTime, changes);
CompareProperty("Description", eventToEdit.Description, updatedEvent.Description, changes);
// Update
eventToEdit.Name = updatedEvent.Name;
eventToEdit.Location = updatedEvent.Location;
eventToEdit.Date = updatedEvent.Date;
eventToEdit.StartTime = updatedEvent.StartTime;
eventToEdit.EndTime = updatedEvent.EndTime;
eventToEdit.Description = updatedEvent.Description;
// Save changes
await _db.SaveChangesAsync();
// Check if there are any attendees
if (attendees.Any())
{
// Get the email addresses of the attendees
var attendeeEmails = attendees.Select(a => a.Email).ToList();
// Create a message
var message = new StringBuilder();
message.AppendLine("Event:");
message.AppendLine($"Location: {eventToEdit.Location}");
message.AppendLine($"Date: {eventToEdit.Date}");
message.AppendLine($"Start Time: {eventToEdit.StartTime}");
message.AppendLine($"End Time: {eventToEdit.EndTime}");
message.AppendLine($"Description: {eventToEdit.Description}");
// Append changes
if (changes.Length > 0)
{
message.AppendLine("\nChanges:");
message.Append(changes.ToString());
}
// Send email
emailSender.SendEmailAsync(new Message(attendeeEmails, "Event Changed", message.ToString()));
}
return eventToEdit;
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in EditEvent: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult<Employee>> EditUser(int id, Employee updatedEmployee, IEmailSender emailSender)
{
try
{
// Get the event with the specified id
var userToEdit = await _db.Employees
.Where(e => e.Id == id)
.FirstOrDefaultAsync();
if (userToEdit == null)
{
return new ObjectResult(new { success = false, message = "User not found!" });
}
// Update
userToEdit.FirstName = (updatedEmployee.FirstName == null ? userToEdit.FirstName : updatedEmployee.FirstName);
userToEdit.LastName = (updatedEmployee.LastName == null ? userToEdit.LastName : updatedEmployee.LastName);
userToEdit.Email = (updatedEmployee.Email == null ? userToEdit.Email : updatedEmployee.Email);
// Save changes
await _db.SaveChangesAsync();
var attendeeEmails = _db.Employees
.Where(e => e.Id == id).Select(e => e.Email).ToList();
// Create a message
var message = new StringBuilder();
message.AppendLine($"Your new Employee info is :\n FirstName: {userToEdit.FirstName} \n " +
$"LastName: {userToEdit.LastName} \n Email: {userToEdit.Email}");
// Send email
emailSender.SendEmailAsync(new Message(attendeeEmails, "Employee info Changed", message.ToString()));
return userToEdit;
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in EditEvent: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult> IsAdmin(string email)
{
try
{
var employee = await _db.Employees
.Where(e => e.Email == email)
.FirstOrDefaultAsync();
if (employee == null)
{
return new ObjectResult(new { success = false, message = "Employee not found!" });
}
return new ObjectResult(new { success = true, isAdmin = employee.IsAdmin });
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in IsAdmin: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<IActionResult> RemoveEmployee(int id)
{
try
{
// Get the event with the specified id
var userToDelete = await _db.Employees.Where(e => e.Id == id).FirstOrDefaultAsync();
if (userToDelete == null)
{
return new ObjectResult(new { success = false, message = "User not found!" });
}
// Delete the event
_db.Employees.Remove(userToDelete);
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, message = "User deleted!" });
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in RemoveEmployee: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
private void CompareProperty(string propertyName, object oldValue, object newValue, StringBuilder changes)
{
if (!object.Equals(oldValue, newValue))
{
changes.AppendLine($"{propertyName}:");
changes.AppendLine($"Old value: {oldValue}");
changes.AppendLine($"New value: {newValue}");
changes.AppendLine();
}
}
public async Task<ActionResult> AddRoom(int Rnum, string Rname)
{
try
{
if (_db.Rooms.Any(x => x.RoomNumber == Rnum))
{
return new ObjectResult(new { success = false, message = $"Room already exists with room number {Rnum}!" });
}
Room room = new(Rnum, Rname, true);
_db.Rooms.Add(room);
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, message = "Room added!" });
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error in AddRoom: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult> DeleteRoom(int Rnum)
{
try
{
var room = await _db.Rooms
.Where(r => r.RoomNumber == Rnum)
.FirstOrDefaultAsync();
if (room == null)
{
return new ObjectResult(new { success = false, message = "Room not found!" });
}
_db.Rooms.Remove(room);
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, message = "Room deleted!" });
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error in DeleteRoom: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult> UpdateRoom(int Rnum, string Rname)
{
try
{
var room = await _db.Rooms
.Where(r => r.RoomNumber == Rnum)
.FirstOrDefaultAsync();
if (room == null)
{
return new ObjectResult(new { success = false, message = "Room not found!" });
}
room.RoomName = Rname;
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, message = "Room updated!" });
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error in UpdateRoom: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult> ForgotPassword(string email, IEmailSender emailSender)
{
try
{
var employee = await _db.Employees
.Where(e => e.Email.ToLower() == email.ToLower())
.FirstOrDefaultAsync();
if (employee == null)
{
return new ObjectResult(new { success = false, message = "Email not found!" });
}
// Generate a password reset token
var token = Guid.NewGuid().ToString();
var host = _httpContextAccessor.HttpContext.Request.Host;
bool isLocal = host.Host.Contains("localhost");
string http = isLocal ? "https://" : "";
// Save the token to the database
employee.Token = token;
employee.TokenExpirationDate = DateTime.Now.AddMinutes(30);
await _db.SaveChangesAsync();
emailSender.SendEmailAsync(new Message(new List<string> { email }, "Password Reset", $"Click here to reset your password: {http}{host}/resetpassword/{token}, it will expire in 30 minutes"));
return new ObjectResult(new { success = true, message = "Password change link sent!" });
}
catch (Exception ex)
{
// Log or handle the exception appropriately
Console.Error.WriteLine($"Error in ForgotPassword: {ex.Message}");
return new ObjectResult(new { success = false, message = "An error occurred." });
}
}
public async Task<ActionResult> EmployeeEventAttendance(int userId)
{
try
{
var emp = from e in _db.Employees where userId == e.Id select e;
var query = from e in emp
let eventsAttend = e.AttendedEvents
.Where(v => userId == v.EmployeeId && v.Event.Date < DateOnly.FromDateTime(DateTime.Now))
.ToList()
select new
{
EmpEvent = e,
CountAttend = eventsAttend.Count
};
foreach (var c in query)
{
Console.WriteLine(c.CountAttend);
c.EmpEvent.AmountOfTimesAttended = c.CountAttend;
}
await _db.SaveChangesAsync();
return new ObjectResult(new { success = true, message = "Token not found or either used up!" });
}
catch (Exception)
{
return new ObjectResult(new { success = false, message = "Token not found or either used up!" });
}
}
public async Task<ActionResult> ForgotPasswordConfirmation(string token, string password, string ConfirmPassword, IEmailSender emailSender)
{
try
{
var employee = await _db.Employees
.Where(e => e.Token == token)
.FirstOrDefaultAsync();
if (employee == null)
{
return new ObjectResult(new { success = false, message = "Token not found or either used up!" });
}
if (employee.TokenExpirationDate < DateTime.Now)
{
Console.WriteLine(employee.TokenExpirationDate);