Exemplo n.º 1
0
        public async Task <ActionResult <IEnumerable <Models.Task> > > Get(int recordID, int studentID, int unitID, int typeID, int assignmentID, int cohortID, DateTime startDate, DateTime endDate)
        {
            object BLLResponse = new TimesheetBLL(_context).GetTimesheetRecordBLL(recordID: recordID, studentID: studentID, unitID: unitID, typeID: typeID, assignmentID: assignmentID, cohortID: cohortID, startDate: startDate, endDate: endDate, userClaims: User);

            if (BLLResponse.GetType().BaseType == typeof(Exception))
            {
                // Create log entries for Debug log
                ((APIException)BLLResponse).Exceptions.ForEach(ex => Logger.Msg <AttendancesController>((Exception)ex, Serilog.Events.LogEventLevel.Debug));

                // Return response from API
                return(BadRequest(new { errors = ((APIException)BLLResponse).Exceptions.Select(x => x.Message).ToArray() }));
            }
            else
            {
                try
                {
                    TimesheetGetDTO BLLResponseDTO = (TimesheetGetDTO)(BLLResponse);

                    // Apply all the criteria with supplied or default values from BLL
                    IQueryable <Timesheet> dbRequest = _context.Timesheets
                                                       .Where(x => x.Date >= BLLResponseDTO.StartDate && x.Date <= BLLResponseDTO.EndDate);

                    if (BLLResponseDTO.StudentID != 0)
                    {
                        dbRequest = dbRequest.Where(x => x.StudentID == BLLResponseDTO.StudentID);
                    }
                    if (BLLResponseDTO.CohortID != 0)
                    {
                        dbRequest = dbRequest.Include(timesheet => timesheet.ForStudent).Where(x => x.ForStudent.CohortID == BLLResponseDTO.CohortID);
                    }
                    if (BLLResponseDTO.TypeID != 0)
                    {
                        dbRequest = dbRequest.Include(timesheet => timesheet.AssignmentAlloc).Where(x => x.AssignmentAlloc.TypeID == BLLResponseDTO.TypeID);
                    }
                    if (BLLResponseDTO.UnitID != 0)
                    {
                        dbRequest = dbRequest.Include(timesheet => timesheet.AssignmentAlloc).Where(x => x.AssignmentAlloc.UnitID == BLLResponseDTO.UnitID);
                    }
                    if (BLLResponseDTO.AssignmentID != 0)
                    {
                        dbRequest = dbRequest.Include(timesheet => timesheet.AssignmentAlloc).Where(x => x.AssignmentAlloc.TaskID == BLLResponseDTO.AssignmentID);
                    }

                    List <Timesheet> dbResponse = await dbRequest.ToListAsync();

                    // Convert result to TimesheetGetDTO
                    List <TimesheetGetDTO> response = new List <TimesheetGetDTO>();
                    dbResponse.ForEach(x => response.Add(new TimesheetGetDTO(x)));

                    Logger.Msg <TimesheetsController>($"[{User.FindFirstValue("email")}] [GET] ", Serilog.Events.LogEventLevel.Debug);
                    return(Ok(response));
                }
                catch (Exception ex)
                {
                    // Local log entry. Database reconciliation issues are more serious so reported as Error
                    Logger.Msg <TimesheetsController>($"[GET] Database sync error {ex.Message}", Serilog.Events.LogEventLevel.Error);

                    // Return response to client
                    return(StatusCode(500, new { errors = "Database update failed. Contact the administrator to resolve this issue." }));
                }
            }
        }// End of Get
        /// <summary>
        /// Business logic for retrieving Timesheet records
        /// </summary>
        /// <param name="recordID"></param>
        /// <param name="studentID"></param>
        /// <param name="assignmentID"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="userClaims"></param>
        /// <returns></returns>
        internal object GetTimesheetRecordBLL(int recordID, int studentID, int unitID, int typeID, int assignmentID, int cohortID, DateTime startDate, DateTime endDate, ClaimsPrincipal userClaims)
        {
            // Check if the current user is a staff member (or Super Admin)
            bool isUserStaff = userClaims.IsInRole("Staff") || userClaims.IsInRole("SuperAdmin");

            // Get the StudentID of the currrent user (or null)
            int currentStudentID = isUserStaff ? 0 : _context.Users.Where(x => x.Email == userClaims.FindFirstValue("email")).Include(users => users.StudentData).FirstOrDefault()?.StudentData.StudentID ?? 0;

            // Apply defaults
            if (startDate == DateTime.MinValue)
            {
                startDate = DateTime.Today;
            }
            if (endDate == DateTime.MinValue)
            {
                endDate = DateTime.Today;
            }
            if (!isUserStaff)
            {
                studentID = currentStudentID;
            }

            // Create a new APIException object to store possible exceptions as checks are performed.
            APIException exceptionList = new APIException();

            Dictionary <string, bool> exceptionTests = new Dictionary <string, bool>()
            {
                { "recordID must be valid", recordID != 0 && !_context.Timesheets.Any(x => x.RecordID == recordID) },
                { "cohortID must be valid", cohortID != 0 && !_context.Cohorts.Any(x => x.CohortID == cohortID) },
                { "unitID must be valid", unitID != 0 && !_context.Units.Any(x => x.UnitID == unitID) },
                { "typeID must be valid", typeID != 0 && !_context.TaskTypes.Any(x => x.TypeID == typeID) },
                { "assignmentID must be valid", assignmentID != 0 && !_context.Tasks.Any(x => x.TaskID == assignmentID) },
                { "studentID must be valid", studentID != 0 && !_context.Students.Any(x => x.StudentID == studentID) },
                { "startDate cannot be after the endDate", !(startDate <= endDate) }
            };

            foreach (KeyValuePair <string, bool> kvp in exceptionTests)
            {
                if (kvp.Value)
                {
                    exceptionList.AddExMessage(kvp.Key);
                }
            }

            if (!exceptionList.HasExceptions)
            {
                TimesheetGetDTO getParams = new TimesheetGetDTO
                {
                    RecordID     = recordID,
                    StudentID    = studentID,
                    CohortID     = cohortID,
                    AssignmentID = assignmentID,
                    TypeID       = typeID,
                    UnitID       = unitID,
                    StartDate    = startDate,
                    EndDate      = endDate
                };

                return(getParams);
            }
            else
            {
                return(exceptionList);
            }
        } // End of GetTimesheetRecordBLL