[HttpGet, Route("searchReport"), AllowAnonymous]//AmigoTenantClaimsAuthorize(ActionCode = ConstantsSecurity.ActionCode.WeeklyReportSearch)
        public HttpResponseMessage SearchReport([FromUri] DriverPayReportSearchRequest search)
        {
            var response = Request.CreateResponse();

            response.Content = new PushStreamContent((outputStream, httpContent, transportContext)
                                                     => _serviceApplicationService.GenerateDataCsvToReportExcel(outputStream, httpContent, transportContext, search), new MediaTypeHeaderValue("text/csv"));
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName        = "DriverPayReport.csv",
                DispositionType = "inline"
            };
            return(response);
        }
        public async Task DriverPayReportSearch_Call_PagedList_in_repository()
        {

            var request = new DriverPayReportSearchRequest()
            {
                ReportDateFrom  = new DateTime(2017,1,25),
                ReportDateTo = new DateTime(2017, 2, 2),
                DriverId = 3015,
                PageSize = 10, Page = 1
            };

            var userList = new List<string>() {"Root"};

           
            var json1 =@"[Data"":""[{""Id"":3015,""UserName"":""Root"",""FirstName"":""Root"",""LastName"":""AmigoTenant"", ""ProfilePictureUrl"":null,""Email"":"""",""PhoneNumber"":null,""Claims"":[]}],""IsValid"":true,""Messages"":null}]"" )";

            var response = new HttpResponseMessage
            {
                /*Content = new StringContent("[\"Root\"]"), */
                StatusCode = HttpStatusCode.OK,
                Content = new StringContent(json1, Encoding.UTF8, "application/json")

        };

            A.CallTo(() => _repo.ListPagedAsync(null, 0, 0, null, null))
                .WithAnyArguments().Returns(Task.FromResult(new Query.Common.PagedList<DriverPayReportDTO>() { PageSize = 1, Page = 1, Total = 1, Items = new List<DriverPayReportDTO>()
            {
                new DriverPayReportDTO() { DayPayDriverTotal = 95000, Driver = "root", DriverUserId = 3015,ReportDate = new DateTime(2017,1,27)}
            } }));

            A.CallTo(() => _repoIdentitySeverAgent.AmigoTenantTUser_Details_IdentityServer(userList)).WithAnyArguments().Returns(Task.FromResult(response));

            // ACT

           // var resp = await appService.SearchDriverPayReportAsync(request);

            //Assert
            //Assert.NotNull(resp);
            A.CallTo(() => _repo.ListPagedAsync(null, 0, 0, null, null)).WithAnyArguments().MustHaveHappened(Repeated.NoMoreThan.Once);


        }
 public async Task <ResponseDTO <PagedList <DriverPayReportDTO> > > Search([FromUri] DriverPayReportSearchRequest search)
 {
     return(await _serviceApplicationService.SearchDriverPayReportAsync(search));
 }
        public async Task <ResponseDTO <PagedList <DriverPayReportDTO> > > SearchDriverPayReportAsync(DriverPayReportSearchRequest search)
        {
            Expression <Func <DriverPayReportDTO, bool> > queryFilter = p => true;

            if (search.ReportDateFrom.HasValue && search.ReportDateTo.HasValue)
            {
                var toPlusADay = search.ReportDateTo.Value.AddDays(1);
                queryFilter = queryFilter.And(p => p.ReportDate.Value >= search.ReportDateFrom);
                queryFilter = queryFilter.And(p => p.ReportDate.Value < toPlusADay);
            }
            else if (search.ReportDateFrom.HasValue && !search.ReportDateTo.HasValue)
            {
                queryFilter = queryFilter.And(p => p.ReportDate.Value >= search.ReportDateFrom);
            }
            else if (!search.ReportDateFrom.HasValue && search.ReportDateTo.HasValue)
            {
                var toPlusADay = search.ReportDateTo.Value.AddDays(1);
                queryFilter = queryFilter.And(p => p.ReportDate.Value < toPlusADay);
            }

            if (search.DriverId > 0)
            {
                queryFilter = queryFilter.And(p => p.DriverUserId == search.DriverId);
            }

            if (search.DedicatedLocationId > 0)
            {
                queryFilter = queryFilter.And(p => p.DedicatedLocationId == search.DedicatedLocationId);
            }

            var report = await _serviceDriverReportDataAccess.ListPagedAsync(queryFilter, search.Page, search.PageSize);

            ResponseDTO <List <UserResponse> > users = new ResponseDTO <List <UserResponse> >();

            if (report.Items.Any())
            {
                List <string> userList = report.Items.Select(q => q.Driver).ToList();
                users = await SetUsersAdditionalInformation(userList);
            }

            var result = report.Items
                         .GroupBy(u => new
            {
                u.Driver,
                u.DriverUserId,
                u.DedicatedLocationCode
            })
                         .Select(g =>
                                 new DriverPayReportDTO
            {
                Driver                = g.Key.Driver,
                DriverUserId          = g.Key.DriverUserId,
                DedicatedLocationCode = g.Key.DedicatedLocationCode,
                DayPayDriverTotal     = g.Sum(x => x.DayPayDriverTotal),
            }
                                 ).ToList();

            foreach (var item in result)
            {
                Expression <Func <AmigoTenanttServiceLatestDTO, bool> > expressionLatestService = p => p.AmigoTenantTUserId == item.DriverUserId;
                var latestAmigoTenantTService = (await _serviceAmigoTenantTServiceLatestDataAccess.ListAsync(expressionLatestService)).FirstOrDefault();

                if (latestAmigoTenantTService != null)
                {
                    item.ChargeNo   = latestAmigoTenantTService.ChargeNo;
                    item.ChargeType = latestAmigoTenantTService.ChargeType;
                    if (latestAmigoTenantTService.ServiceFinishDate != null)
                    {
                        item.ServiceStatusOffOnDesc = Constants.ServiceStatus.Dispatched;
                    }
                    else
                    {
                        item.ServiceStatusOffOnDesc = Constants.ServiceStatus.Offline;
                    }
                }
                else
                {
                    item.ServiceStatusOffOnDesc = Constants.ServiceStatus.Offline;
                }

                item.ServiceLatestInformation = string.Format("Current Location: {0}, Status: {1}, Dispatcher: {2}", item.CurrentLocationCode, item.ServiceStatusOffOnDesc, item.DispatcherCode);

                var user = users.Data.FirstOrDefault(q => q.UserName.ToLower() == item.Driver.ToLower());
                if (user != null)
                {
                    item.FirstName = user.FirstName;
                    item.LastName  = user.LastName;
                }
            }

            var pagedResult = new PagedList <DriverPayReportDTO>()
            {
                Items    = result,
                PageSize = report.PageSize,
                Page     = report.Page,
                Total    = result.Count
            };

            return(ResponseBuilder.Correct(pagedResult));
        }
        public async void GenerateDataCsvToReportExcel(Stream outputStream, HttpContent httpContent, TransportContext transportContext, DriverPayReportSearchRequest search)
        {
            var list = await SearchDriverPayReportAsync(search);

            try
            {
                if (list.Data.Items.Count > 0)
                {
                    using (var writer = new StreamWriter(outputStream))
                    {
                        var headers = new List <string> {
                            "Driver ID", "First Name", "Last Name", "Total Pay", "Dedicated Location", "Current Activity", "Charge No"
                        };
                        await writer.WriteLineAsync(ExcelHelper.GetHeaderDetail(headers));

                        foreach (var item in list.Data.Items)
                        {
                            await writer.WriteLineAsync(ProcessCellDataToReport(item));
                        }
                    }
                }
            }
            catch (HttpException ex)
            {
                return;
            }
            finally
            {
                outputStream.Close();
            }
        }