private IEnumerable <BusinessTrip> FilterAndSortBusinessTrips(BusinessTripFilter filter, Func <BusinessTrip, bool> predicate) { IEnumerable <BusinessTrip> filteredSortedCollection; // Параметры сортировки string sortField = filter.SortField ?? "Default"; string order = filter.SortOrder ?? "Asc"; // Компараторы сортировки по возрастанию или по убыванию IComparer <string> stringComparer = Comparer <string> .Create((x, y) => order.Equals("Asc")?(x ?? "").CompareTo(y ?? "") : (y ?? "").CompareTo(x ?? "")); IComparer <DateTime> dateTimeComparer = Comparer <DateTime> .Create((x, y) => order.Equals("Asc")?x.CompareTo(y) : y.CompareTo(x)); switch (sortField) { case "Code": filteredSortedCollection = Database.BusinessTrips.Get(predicate).OrderBy(bt => bt.Name, stringComparer); break; case "DateStart": filteredSortedCollection = Database.BusinessTrips.Get(predicate).OrderBy(bt => bt.DateStart, dateTimeComparer); break; case "DateEnd": filteredSortedCollection = Database.BusinessTrips.Get(predicate).OrderBy(bt => bt.DateEnd, dateTimeComparer); break; case "Destination": filteredSortedCollection = Database.BusinessTrips.Get(predicate).OrderBy(bt => bt.Destination, stringComparer); break; default: filteredSortedCollection = Database.BusinessTrips.Get(predicate).OrderBy(bt => bt.Name); break; } return(filteredSortedCollection); }
public IEnumerable <BusinessTripEntity> GetBusinessTripsBy(BusinessTripFilter filter, string[] userRole) { IQueryable <BusinessTripEntity> businessTrips = storage.GetStorageFor <BusinessTripEntity>(); if (!string.IsNullOrEmpty(filter.UserId)) { Guid filterGuid = GetGuidBy(filter.UserId); return(businessTrips.Where(m => m.Id == filterGuid)); } if (userRole.Contains(Role.Hr.ToString())) { if (filter.Status.HasValue) { businessTrips = businessTrips.Where(m => m.Status == filter.Status); } else { businessTrips = businessTrips.Where(AllStatusFilter()); } } else { businessTrips = businessTrips.Where(RegularUserStatusFilter()); } if (filter.StartingDate.HasValue) { businessTrips = businessTrips.Where(m => m.StartingDate >= filter.StartingDate); } if (filter.EndingDate.HasValue) { businessTrips = businessTrips.Where(m => m.EndingDate <= filter.EndingDate); } if (!string.IsNullOrEmpty(filter.Location)) { businessTrips = businessTrips.Where(m => m.ClientLocation.Contains(filter.Location)); } if (!string.IsNullOrEmpty(filter.Person)) { businessTrips = businessTrips.Where(m => m.User.Name.Contains(filter.Person)); } if (!string.IsNullOrEmpty(filter.MeansOfTransportation)) { businessTrips = businessTrips.Where(m => m.MeansOfTransportation.Contains(filter.MeansOfTransportation)); } if (!string.IsNullOrEmpty(filter.Accommodation)) { businessTrips = businessTrips.Where(m => m.Accomodation.Contains(filter.Accommodation)); } return(businessTrips); }
public void Get_DescSortIsSet_ReturnsSortedArray(string field) { BusinessTripFilter filter = new BusinessTripFilter { SortField = field, SortOrder = "Desc" }; BusinessTrip[] businessTrips = new BusinessTrip[] { new BusinessTrip() { Id = 1, Name = "bt_47", DateStart = new DateTime(2018, 09, 12), DateEnd = new DateTime(2018, 09, 25), Destination = "Kazan" }, new BusinessTrip() { Id = 2, Name = "bt_48", DateStart = new DateTime(2018, 10, 08), DateEnd = new DateTime(2018, 10, 15), Destination = "Moscow" }, new BusinessTrip() { Id = 3, Name = "bt_50", DateStart = new DateTime(2018, 11, 03), DateEnd = new DateTime(2018, 11, 07), Destination = "Rostov" }, new BusinessTrip() { Id = 4, Name = "bt_53", DateStart = new DateTime(2018, 12, 01), DateEnd = new DateTime(2018, 12, 05), Destination = "Sochi" } }; Mock <IUnitOfWork> mock = new Mock <IUnitOfWork>(); mock.Setup(m => m.BusinessTrips.Get(It.IsAny <Func <BusinessTrip, bool> >())) .Returns((Func <BusinessTrip, bool> predicate) => businessTrips.Where(predicate)); BusinessTripService businessTripService = GetNewService(mock.Object); BusinessTripDTO[] result = businessTripService.Get(filter).ToArray(); Assert.AreEqual(4, result.Length); Assert.AreEqual(4, result[0].Id); Assert.AreEqual(3, result[1].Id); Assert.AreEqual(2, result[2].Id); Assert.AreEqual(1, result[3].Id); Assert.AreEqual("bt_53", result[0].Name); Assert.AreEqual("bt_50", result[1].Name); Assert.AreEqual("bt_48", result[2].Name); Assert.AreEqual("bt_47", result[3].Name); }
[TestCase(null, null, null, "Moscow")] // Destination public void Get_OneFilterParameterAndIsAntiFilterIsSet_ReturnsFilteredArray(string code, string dateStart, string dateEnd, string destination) { BusinessTripFilter filter = new BusinessTripFilter { Code = new string[] { code, null, "" }, DateStart = dateStart, DateEnd = dateEnd, Destination = new string[] { destination, null, "" }, IsAntiFilter = true }; BusinessTrip[] businessTrips = new BusinessTrip[] { new BusinessTrip() { Id = 1, Name = "bt_33", DateStart = new DateTime(2018, 09, 01), DateEnd = new DateTime(2018, 09, 05), Destination = "Moscow" }, new BusinessTrip() { Id = 2, Name = "bt_34", DateStart = new DateTime(2018, 09, 01), DateEnd = new DateTime(2018, 09, 05), Destination = "Moscow" }, new BusinessTrip() { Id = 3, Name = "bt_45", DateStart = new DateTime(2018, 09, 02), DateEnd = new DateTime(2018, 09, 07), Destination = "Spb" }, new BusinessTrip() { Id = 4, Name = "bt_47", DateStart = new DateTime(2018, 09, 03), DateEnd = new DateTime(2018, 09, 08), Destination = "Spb" } }; Mock <IUnitOfWork> mock = new Mock <IUnitOfWork>(); mock.Setup(m => m.BusinessTrips.Get(It.IsAny <Func <BusinessTrip, bool> >())) .Returns((Func <BusinessTrip, bool> predicate) => businessTrips.Where(predicate)); BusinessTripService businessTripService = GetNewService(mock.Object); BusinessTripDTO[] result = businessTripService.Get(filter).ToArray(); Assert.AreEqual(2, result.Length); Assert.AreEqual(3, result[0].Id); Assert.AreEqual(4, result[1].Id); Assert.AreEqual("bt_45", result[0].Name); Assert.AreEqual("bt_47", result[1].Name); }
[TestCase(null, null, null, null, "Moscow", "Spb")] // Destination1, Destination2 public void Get_TwoFilterParametersAreSet_ReturnsFilteredArray(string code1, string code2, string dateStart, string dateEnd, string destination1, string destination2) { BusinessTripFilter filter = new BusinessTripFilter { Code = new string[] { code1, code2, null, "" }, DateStart = dateStart, DateEnd = dateEnd, Destination = new string[] { destination1, destination2, null, "" } }; BusinessTrip[] businessTrips = new BusinessTrip[] { new BusinessTrip() { Id = 1, Name = "bt_53", DateStart = new DateTime(2018, 09, 02), DateEnd = new DateTime(2018, 09, 05), Destination = "Rostov" }, new BusinessTrip() { Id = 2, Name = "bt_54", DateStart = new DateTime(2018, 09, 02), DateEnd = new DateTime(2018, 09, 05), Destination = "Kazan" }, new BusinessTrip() { Id = 3, Name = "bt_55", DateStart = new DateTime(2018, 09, 01), DateEnd = new DateTime(2018, 09, 07), Destination = "Sochi" }, new BusinessTrip() { Id = 4, Name = "bt_47", DateStart = new DateTime(2018, 09, 01), DateEnd = new DateTime(2018, 09, 05), Destination = "Moscow" } }; Mock <IUnitOfWork> mock = new Mock <IUnitOfWork>(); mock.Setup(m => m.BusinessTrips.Get(It.IsAny <Func <BusinessTrip, bool> >())) .Returns((Func <BusinessTrip, bool> predicate) => businessTrips.Where(predicate)); BusinessTripService businessTripService = GetNewService(mock.Object); BusinessTripDTO[] result = businessTripService.Get(filter).ToArray(); Assert.AreEqual(1, result.Length); Assert.AreEqual(4, result[0].Id); Assert.AreEqual("bt_47", result[0].Name); }
// Получение списка командировок по фильтру public virtual IEnumerable <BusinessTripDTO> Get(BusinessTripFilter filter) { Func <BusinessTrip, bool> predicate = CreatePredicate(filter); IEnumerable <BusinessTrip> filteredSortedCollection = FilterAndSortBusinessTrips(filter, predicate); InitializeMapper(); IEnumerable <BusinessTripDTO> collection = Mapper.Map <IEnumerable <BusinessTrip>, IEnumerable <BusinessTripDTO> >(filteredSortedCollection); return(collection); }
public ActionResult Index(BusinessTripFilter filter, string filterAsJsonString, int page = 1) { if (filterAsJsonString != null) { filter = System.Web.Helpers.Json.Decode <BusinessTripFilter>(filterAsJsonString); } IEnumerable <BusinessTripDTO> btDto = (_businessTripService as BusinessTripService).Get(filter); // Filter btDto = _businessTripService.GetPage(btDto, page); // Paging Mapper.Initialize(cfg => cfg.CreateMap <BusinessTripDTO, BusinessTripViewModel>() .ForMember(bt => bt.Employees, opt => opt.Ignore())); IEnumerable <BusinessTripViewModel> businessTrips = Mapper.Map <IEnumerable <BusinessTripDTO>, IEnumerable <BusinessTripViewModel> >(btDto); BusinessTripListViewModel model = new BusinessTripListViewModel { BusinessTrips = businessTrips, Filter = filter, PageInfo = _businessTripService.PageInfo }; if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") { _logger.Info("Executed async request"); var transformModel = new { BusinessTrips = model.BusinessTrips.Select(bt => new { bt.Id, Code = bt.Name, DateStart = bt.DateStart.ToString("dd MMMM yyyy"), DateEnd = bt.DateEnd.ToString("dd MMMM yyyy"), bt.Destination }).ToArray(), model.Filter, model.PageInfo }; return(Json(transformModel, JsonRequestBehavior.AllowGet)); } _logger.Info("Executed sync request"); return(View("Index", model)); }
private Func <BusinessTrip, bool> CreatePredicate(BusinessTripFilter filter) { bool predicate(BusinessTrip businessTrip) { bool returnValue = false; if (filter.IsAntiFilter) // Если флаг установлен, то выбираются записи несоответствующие фильтру { returnValue = true; } // Фильтр по коду командировки if (filter.Code != null) { string[] сodeArray = filter.Code.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); // Удаляем пустые элементы из массива if (сodeArray.Length > 0) { bool flag = true; foreach (string code in сodeArray) { if (Regex.IsMatch(businessTrip.Name, code, RegexOptions.IgnoreCase)) { flag = false; break; } } if (flag) { return(returnValue); // Проверяемая запись не соответствует фильтру по коду командировки } } } // Фильтр по дате начала командировки if (!string.IsNullOrWhiteSpace(filter.DateStart) && DateTime.TryParse(filter.DateStart, out DateTime date_start) && businessTrip.DateStart != date_start) { return(returnValue); // Проверяемая запись не соответствует фильтру по дате начала командировки } // Фильтр по дате окончания командировки if (!string.IsNullOrWhiteSpace(filter.DateEnd) && DateTime.TryParse(filter.DateEnd, out DateTime date_end) && businessTrip.DateEnd != date_end) { return(returnValue); // Проверяемая запись не соответствует фильтру по дате окончания командировки } // Фильтр по месту назначения if (filter.Destination != null) { string[] destinationArray = filter.Destination.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); // Удаляем пустые элементы из массива if (destinationArray.Length > 0) { bool flag = true; foreach (string destination in destinationArray) { if (Regex.IsMatch(businessTrip.Destination, destination, RegexOptions.IgnoreCase)) { flag = false; break; } } if (flag) { return(returnValue); // Проверяемая запись не соответствует фильтру по месту назначения } } } return(!returnValue); // Если дошли до сюда, значит проверяемая запись соответствует фильтру } return(predicate); }