示例#1
0
        public async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log)
        {
            log.LogInformation("GET - Get Stops requested");

            try
            {
                if (!RIPAAuthorization.ValidateUserOrAdministratorRole(req, log).ConfigureAwait(false).GetAwaiter().GetResult())
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new UnauthorizedResult());
            }

            string stopQueryString        = String.Empty;
            string stopSummaryQueryString = String.Empty;

            try
            {
                StopQueryUtility stopQueryUtility = new StopQueryUtility();
                StopQuery        stopQuery        = stopQueryUtility.GetStopQuery(req);
                stopQueryString        = stopQueryUtility.GetStopsQueryString(stopQuery, true);
                stopSummaryQueryString = stopQueryUtility.GetStopsSummaryQueryString(stopQuery);
            }
            catch (Exception ex)
            {
                log.LogError("An error occured while evaluating the stop query.", ex);
                return(new BadRequestObjectResult("An error occured while evaluating the stop query. Please try again."));
            }

            IEnumerable <Common.Models.Stop> stopResponse;
            IEnumerable <StopStatusCount>    stopStatusCounts;

            try
            {
                stopResponse = await _stopCosmosDbService.GetStopsAsync(stopQueryString);

                stopStatusCounts = await _stopCosmosDbService.GetStopStatusCounts(stopSummaryQueryString);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An error occurred getting stops requested.");
                return(new BadRequestObjectResult("An error occurred getting stops requested. Please try again."));
            }

            var response = new
            {
                stops   = stopResponse,
                summary = new SummaryResponse()
                {
                    Total       = stopStatusCounts.Sum(x => x.Count),
                    Submitted   = stopStatusCounts.Where(x => x.Status == "Submitted").Select(x => x.Count).FirstOrDefault(),
                    Resubmitted = stopStatusCounts.Where(x => x.Status == "Resubmitted").Select(x => x.Count).FirstOrDefault(),
                    Unsubmitted = stopStatusCounts.Where(x => x.Status == "Unsubmitted").Select(x => x.Count).FirstOrDefault(),
                    Pending     = stopStatusCounts.Where(x => x.Status == "Pending").Select(x => x.Count).FirstOrDefault(),
                    Failed      = stopStatusCounts.Where(x => x.Status == "Failed").Select(x => x.Count).FirstOrDefault(),
                }
            };

            return(new OkObjectResult(response));
        }
        public async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log)
        {
            log.LogInformation("Submit to DOJ requested - submit search");
            try
            {
                if (!RIPAAuthorization.ValidateUserOrAdministratorRole(req, log).ConfigureAwait(false).GetAwaiter().GetResult())
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new UnauthorizedResult());
            }

            UserProfile userProfile;

            try
            {
                var objectId = await RIPAAuthorization.GetUserId(req, log);

                userProfile = (await _userProfileCosmosDbService.GetUserProfileAsync(objectId));
                if (userProfile == null)
                {
                    throw new Exception($"User profile not found for {objectId}");
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);

                return(new BadRequestObjectResult("User profile was not found"));
            }

            string stopQueryString = String.Empty;

            try
            {
                StopQueryUtility stopQueryUtility = new StopQueryUtility();
                StopQuery        stopQuery        = stopQueryUtility.GetStopQuery(req);
                stopQueryString = stopQueryUtility.GetStopsQueryString(stopQuery, false);
            }
            catch (Exception ex)
            {
                log.LogError("An error occured while evaluating the stop query.", ex);
                return(new BadRequestObjectResult("An error occured while evaluating the stop query. Please try again."));
            }

            IEnumerable <Stop> stopResponse;

            try
            {
                stopResponse = await _stopCosmosDbService.GetStopsAsync(stopQueryString);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An error occurred getting stops requested.");
                return(new BadRequestObjectResult("An error occurred getting stops requested. Please try again."));
            }

            SubmissionUtilities submissionUtilities = new SubmissionUtilities(_stopCosmosDbService, _submissionCosmosDbService, _sftpService, log);
            Guid submissionId;

            if (!submissionUtilities.IsValidSFTPConnection())
            {
                return(new BadRequestObjectResult("An error occurred connecting to DOJ SFTP service."));
            }

            try
            {
                List <string> errorList = submissionUtilities.ValidateStops(stopResponse);
                if (errorList.Any())
                {
                    errorList.Add("Please adjust your filter criteria and try again.");
                    return(new BadRequestObjectResult(string.Join(Environment.NewLine, errorList)));
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An error occurred validating stops.");
                return(new BadRequestObjectResult("An error validating stops requested. Please try again."));
            }

            try
            {
                submissionId = await submissionUtilities.NewSubmission(stopResponse, userProfile);
            }
            catch (Exception ex)
            {
                log.LogError($"Failure Adding Submission to CosmosDb, No Records Submitted: {ex.Message}");
                return(new BadRequestObjectResult($"Failure Adding Submission to CosmosDb, No Records Submitted: {ex.Message}"));
            }

            await _submissionServiceBusService.SendServiceBusMessagesAsync(stopResponse.Select(x => new ServiceBusMessage(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new SubmissionMessage()
            {
                StopId = x.Id, SubmissionId = submissionId
            })))).ToList());

            return(new OkObjectResult(new { submissionId }));
        }
示例#3
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] string officerName, HttpRequest req,
            ILogger log)
        {
            log.LogInformation("CPRA Report Generation Requested");
            try
            {
                if (!RIPAAuthorization.ValidateUserOrAdministratorRole(req, log).ConfigureAwait(false).GetAwaiter().GetResult())
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new UnauthorizedResult());
            }

            await _blobContainerClient.CreateIfNotExistsAsync();

            byte[] fileBytes;
            string tempPath  = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.csv");
            var    startDate = req.Query["StartDate"];
            var    endDate   = req.Query["EndDate"];
            var    fileName  = $"{startDate}-{endDate}-CPRAReport.csv";
            string stopQueryString;
            string stopSummaryQueryString;

            try
            {
                StopQueryUtility stopQueryUtility = new StopQueryUtility();
                StopQuery        stopQuery        = stopQueryUtility.GetStopQuery(req);
                stopQueryString        = stopQueryUtility.GetStopsQueryString(stopQuery, true, true);
                stopSummaryQueryString = stopQueryUtility.GetStopsSummaryQueryString(stopQuery);
            }
            catch (Exception ex)
            {
                log.LogError("An error occurred while evaluating the stop query.", ex);
                return(new BadRequestObjectResult("An error occurred while evaluating the stop query. Please try again."));
            }

            List <Stop> stopResponse;
            IEnumerable <StopStatusCount> stopStatuses;
            int totalStopCount = 0;

            try
            {
                stopResponse = await _stopCosmosDbService.GetStopsAsync(stopQueryString) as List <Stop>;

                stopStatuses = await _stopCosmosDbService.GetStopStatusCounts(stopSummaryQueryString);

                foreach (var stopStatus in stopStatuses)
                {
                    totalStopCount += stopStatus.Count;
                }
            }
            catch (Exception ex)
            {
                log.LogError("An error occurred getting stops requested.", ex);
                return(new BadRequestObjectResult("An error occurred getting stops requested. Please try again."));
            }

            if (totalStopCount == 0)
            {
                return(new OkObjectResult("No valid stops were found during that date range."));
            }

            var builder = new StringBuilder();

            try
            {
                foreach (var stop in stopResponse)
                {
                    var dojStop = _stopService.CastToDojStop(stop);
                    dojStop.Officer = null;
                    var jsonStop = JsonConvert.SerializeObject(dojStop);
                    if (stop.Location.Beat != null)
                    {
                        jsonStop += $"|{stop.Location.Beat.Codes.Text}";
                    }
                    jsonStop = jsonStop.Replace("\"", "\"\"");
                    builder.AppendLine($"\"{jsonStop}\"");
                }
            }
            catch (Exception ex)
            {
                log.LogError("An error occurred while parsing stops.", ex.Message);
            }

            await File.WriteAllTextAsync(tempPath, builder.ToString(), Encoding.UTF8);

            using (StreamReader sr = new StreamReader(tempPath))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    sr.BaseStream.CopyTo(ms);
                    fileBytes = ms.ToArray();
                }
            }

            File.Delete(tempPath);

            try
            {
                await blobUtilities.UploadBlobCpraReport(fileBytes, fileName, officerName, _blobContainerClient);
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(ex.Message));
            }

            var result = new CpraResult
            {
                FileName  = $"{officerName}/{fileName}",
                CpraItems = new List <CpraListItem>
                {
                    new CpraListItem()
                    {
                        Level  = 1,
                        Header = "Total stops in date range",
                        Detail = totalStopCount.ToString(),
                    },
                    new CpraListItem()
                    {
                        Level  = 1,
                        Header = "Submitted stops included on report",
                        Detail = stopResponse.Count.ToString(),
                    },
                    new CpraListItem()
                    {
                        Level  = 1,
                        Header = "From Date",
                        Detail = startDate,
                    },
                    new CpraListItem()
                    {
                        Level  = 1,
                        Header = "To Date",
                        Detail = endDate,
                    }
                }
            };

            return(new OkObjectResult(result));
        }