浏览代码

enhancement

zinab_elgendy 2 月之前
父节点
当前提交
9b5c5e5641
共有 1 个文件被更改,包括 97 次插入97 次删除
  1. 97 97
      MTWorkHR.Application/Services/User/AttendanceService.cs

+ 97 - 97
MTWorkHR.Application/Services/User/AttendanceService.cs

@@ -31,141 +31,141 @@ namespace MTWorkHR.Application.Services
             _globalInfo = globalInfo;
             _userService = userService;
         }
-        public async Task<PagingResultDto<AttendanceDto>> GetAll(AttendancePagingInputDto PagingInputDto)
+        public async Task<PagingResultDto<AttendanceDto>> GetAll(AttendancePagingInputDto pagingInputDto)
         {
-            var res = await _unitOfWork.Attendance.GetAllWithChildrenAsync();
-            var query = res.Item1;
+            // Fetch all attendances with related data
+            var attendanceResult = await _unitOfWork.Attendance.GetAllWithChildrenAsync();
+            var query = attendanceResult.Item1.AsQueryable();
 
+            // Apply filters based on user type and input
             if (_globalInfo.UserType != UserTypeEnum.Business)
             {
                 query = query.Where(m => m.UserId == _globalInfo.UserId);
-
             }
-            if (PagingInputDto.Filter != null)
+
+            if (!string.IsNullOrEmpty(pagingInputDto.Filter))
             {
-                var filter = PagingInputDto.Filter;
-                query = query.Where(u => u.LeaveReason!.Contains(filter) || u.UserName!.Contains(filter));
+                query = query.Where(u => u.LeaveReason!.Contains(pagingInputDto.Filter) || u.UserName!.Contains(pagingInputDto.Filter));
             }
-                  
-            if (PagingInputDto.SearchDate != null)
+
+            if (pagingInputDto.SearchDate != null)
             {
-                query = query.Where(u => u.AttendanceDate.Date == PagingInputDto.SearchDate.Value.Date);
+                query = query.Where(u => u.AttendanceDate.Date == pagingInputDto.SearchDate.Value.Date);
             }
 
-            if (PagingInputDto.UserId != null)
+            if (!string.IsNullOrEmpty(pagingInputDto.UserId))
             {
-                query = query.Where(u => u.UserId == PagingInputDto.UserId);
+                query = query.Where(u => u.UserId == pagingInputDto.UserId);
             }
 
-            var order = query.OrderBy(PagingInputDto.OrderByField + " " + PagingInputDto.OrderType);
+            // Apply sorting
+            var orderedQuery = query.OrderBy($"{pagingInputDto.OrderByField} {pagingInputDto.OrderType}");
+
+            // Apply paging
+            var pagedQuery = orderedQuery
+                .Skip((pagingInputDto.PageNumber - 1) * pagingInputDto.PageSize)
+                .Take(pagingInputDto.PageSize);
 
-            var page = order.Skip((PagingInputDto.PageNumber * PagingInputDto.PageSize) - PagingInputDto.PageSize).Take(PagingInputDto.PageSize);
+            // Fetch total count for pagination
+            var totalCount = await query.CountAsync();
 
-            var total = await query.CountAsync();
+            // Map attendance data to DTOs
+            var attendanceDtos = MapperObject.Mapper.Map<IList<AttendanceDto>>(await pagedQuery.ToListAsync());
 
-            var list = MapperObject.Mapper
-                .Map<IList<AttendanceDto>>(await page.ToListAsync());
 
-           // var employeesListx = list.Select(a => a.UserId).Distinct();
+            // Fetch all company employees
             var employeesList = await _userService.GetAllCompanyEmployees();
-            Dictionary<string, UserBasicInfoDto> employeeDictList = new Dictionary<string, UserBasicInfoDto>();
-            List<AttendanceDto> attendanceResult = new List<AttendanceDto>();
 
-            if (string.IsNullOrEmpty(PagingInputDto.UserId))
+            // Filter employees by name if provided
+            if (!string.IsNullOrEmpty(pagingInputDto.UserName))
+            {
+                var filter = pagingInputDto.UserName;
+                var filters = filter.Split(" ");
+                var firstNameFilter = filters[0];
+                var lastNameFilter = filters.Length > 1 ? filters[1] : "";
+
+                employeesList = employeesList.Where(u =>
+                    u.UserName.Contains(filter) || u.Email.Contains(filter) || u.FavoriteName.Contains(filter) ||
+                    u.FirstName.Contains(filter) || u.LastName.Contains(filter) ||
+                    (u.FirstName.Contains(firstNameFilter) && (string.IsNullOrEmpty(lastNameFilter) || u.LastName.Contains(lastNameFilter))) ||
+                    (u.LastName.Contains(lastNameFilter) && (string.IsNullOrEmpty(firstNameFilter) || u.FirstName.Contains(firstNameFilter)))
+                ).ToList();
+            }
+
+            // Create a dictionary to store user data
+            var userDataDictionary = new Dictionary<string, UserBasicInfoDto>();
+
+            // Fetch user data for all employees
+            foreach (var employee in employeesList)
             {
-                if (PagingInputDto.UserName != null)
+                var user = await _userService.GetUserWithAttachmentById(employee.Id);
+                if (user != null)
                 {
-                    //employeesList = employeesList.Where(u => u.FirstName.Contains(PagingInputDto.UserName) || u.LastName.Contains(PagingInputDto.UserName) ||
-                    //u.UserName.Contains(PagingInputDto.UserName) || u.Email.Contains(PagingInputDto.UserName)
-                    //).ToList();
-                    var filter = PagingInputDto.UserName;
-                    var filters = filter.Split(" ");
-                    var firstNameFilter = filters[0];
-                    var lastNameFilter = filters.Length > 1 ? filters[1] : "";
-
-                    employeesList = employeesList.Where(u =>
-                        u.UserName.Contains(filter) || u.Email.Contains(filter) || u.FavoriteName.Contains(filter) || u.FirstName.Contains(filter) || u.LastName.Contains(filter) ||
-                        u.FirstName.Contains(firstNameFilter) && (string.IsNullOrEmpty(lastNameFilter) || u.LastName.Contains(lastNameFilter)) ||
-                        u.LastName.Contains(lastNameFilter) && (string.IsNullOrEmpty(firstNameFilter) || u.FirstName.Contains(firstNameFilter))
-                    ).ToList();
+                    var userDto = MapperObject.Mapper.Map<UserBasicInfoDto>(user);
+                    userDto.ProfileImage = await GetProfileImageAsync(user.UserAttachments);
+                    userDataDictionary[employee.Id] = userDto;
                 }
+            }
+
+            // Combine attendance data with user data
+            var result = new List<AttendanceDto>();
+            if (string.IsNullOrEmpty(pagingInputDto.UserId))
+            {
                 foreach (var employee in employeesList)
                 {
-                    var latestAttendance = list.LastOrDefault(a => a.UserId == employee.Id);
-
-                    var user = await _userService.GetUserWithAttachmentById(employee.Id);
-                    if (user != null)
+                    var latestAttendance = attendanceDtos.LastOrDefault(a => a.UserId == employee.Id);
+                    if (latestAttendance != null)
                     {
-                        var entitiy = MapperObject.Mapper.Map<UserBasicInfoDto>(user);
-                        //item.Employee = entitiy;
-                        var attach = user.UserAttachments?.FirstOrDefault(a => a.AttachmentTypeId == 9);
-                        if (attach != null)
-                            using (var stream = new MemoryStream(attach.Content))
-                            {
-                                var file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FilePath)
-                                {
-                                    Headers = new HeaderDictionary(),
-                                    ContentType = attach.ContentType,
-                                };
-
-                                System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
-                                {
-                                    FileName = file.FileName
-                                };
-                                file.ContentDisposition = cd.ToString();
-                                entitiy.ProfileImage = file;
-
-                            }
-                        employeeDictList.Add(employee.Id, entitiy);
-                        if (latestAttendance != null)
-                            latestAttendance.Employee = entitiy;
-                        else
+                        latestAttendance.Employee = userDataDictionary[employee.Id];
+                    }
+                    else
+                    {
+                        latestAttendance = new AttendanceDto
                         {
-                            latestAttendance = new AttendanceDto { UserId = employee.Id, UserName = employee.UserName, Employee = entitiy };
-                        }
-                        attendanceResult.Add(latestAttendance);
+                            UserId = employee.Id,
+                            UserName = employee.UserName,
+                            Employee = userDataDictionary[employee.Id]
+                        };
                     }
+                    result.Add(latestAttendance);
                 }
             }
             else
             {
-                var user = await _userService.GetUserWithAttachmentById(PagingInputDto.UserId);
-                if (user != null)
+                foreach (var attendance in attendanceDtos)
                 {
-                    var entitiy = MapperObject.Mapper.Map<UserBasicInfoDto>(user);
-                    foreach (var item in list)
-                    {
-                        var attach = user.UserAttachments?.FirstOrDefault(a => a.AttachmentTypeId == 9);
-                        if (attach != null)
-                            using (var stream = new MemoryStream(attach.Content))
-                            {
-                                var file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FilePath)
-                                {
-                                    Headers = new HeaderDictionary(),
-                                    ContentType = attach.ContentType,
-                                };
-
-                                System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
-                                {
-                                    FileName = file.FileName
-                                };
-                                file.ContentDisposition = cd.ToString();
-                                entitiy.ProfileImage = file;
-
-                            }
-                        item.Employee = entitiy;
-                    }
+                    attendance.Employee = userDataDictionary[pagingInputDto.UserId];
                 }
+                result = attendanceDtos.ToList();
             }
-                
-            var response = new PagingResultDto<AttendanceDto>
+
+            // Return the paged result
+            return new PagingResultDto<AttendanceDto>
             {
-                Result = !string.IsNullOrEmpty(PagingInputDto.UserId) ? list : attendanceResult,
-                //Result = ! string.IsNullOrEmpty( PagingInputDto.UserId ) ? list : dayGroupByUser,
-                Total = !string.IsNullOrEmpty(PagingInputDto.UserId) ? total : attendanceResult.Count //total
+                Result = result,
+                Total = string.IsNullOrEmpty(pagingInputDto.UserId) ? result.Count : totalCount
             };
+        }
 
-            return response;
+        // Helper method to get profile image
+        private async Task<FormFile> GetProfileImageAsync(ICollection<AttachmentDto> attachments)
+        {
+            var profileImage = attachments?.FirstOrDefault(a => a.AttachmentTypeId == 9);
+            if (profileImage == null) return null;
+
+            using (var stream = new MemoryStream(profileImage.Content))
+            {
+                var file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(profileImage.FileName), profileImage.FilePath)
+                {
+                    Headers = new HeaderDictionary(),
+                    ContentType = profileImage.ContentType,
+                    ContentDisposition = new System.Net.Mime.ContentDisposition
+                    {
+                        FileName = profileImage.FileName
+                    }.ToString()
+                };
+                return file;
+            }
         }
 
         public override async Task<AttendanceDto> Create(AttendanceDto input)