Esempio n. 1
0
        public async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = "GetStop/{Id}")] HttpRequest req, string Id, ILogger log)
        {
            log.LogInformation("GET - Get Stop requested");

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

            if (!string.IsNullOrEmpty(Id))
            {
                var response = await _stopCosmosDbService.GetStopAsync(Id);

                if (response != null)
                {
                    return(new OkObjectResult(response));
                }
            }

            return(new BadRequestObjectResult("Not found"));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "delete", Route = "DeleteStatute/{Id}")] HttpRequest req, int Id,
            [Table("Statutes", Connection = "RipaStorage")] CloudTable statutes, ILogger log)
        {
            try
            {
                if (!RIPAAuthorization.ValidateAdministratorRole(req, log).ConfigureAwait(false).GetAwaiter().GetResult())
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new UnauthorizedResult());
            }

            try
            {
                Statute statute = new Statute {
                    PartitionKey = "CA", RowKey = Id.ToString(), OffenseCode = Id, ETag = "*"
                };
                TableOperation deleteOperation = TableOperation.Delete(statute);
                TableResult    result          = await statutes.ExecuteAsync(deleteOperation);

                return(new OkObjectResult(result));
            }
            catch
            {
                return(new BadRequestObjectResult("Statute Offense Code not found"));
            }
        }
        public async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "delete", Route = "DeleteUser/{Id}")] HttpRequest req, string Id, ILogger log)
        {
            log.LogInformation("Delete - Delete User requested");

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

            if (!string.IsNullOrEmpty(Id))
            {
                await _userProfileCosmosDbService.DeleteUserProfileAsync(Id);

                return(new OkObjectResult($"Deleted {Id}"));
            }

            return(new BadRequestObjectResult("Not found"));
        }
Esempio n. 4
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "Put", Route = "PutCity/{Id}")] City city, HttpRequest req, string Id,
            [Table("Cities", Connection = "RipaStorage")] CloudTable cities, ILogger log)
        {
            try
            {
                if (!RIPAAuthorization.ValidateAdministratorRole(req, log).ConfigureAwait(false).GetAwaiter().GetResult())
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new UnauthorizedResult());
            }

            try
            {
                city.PartitionKey = "CA";
                city.RowKey       = Id;
                city.Name         = Id;
                city.ETag         = "*";
                city.State        = "CA";
                TableOperation createOperation = TableOperation.InsertOrReplace(city);
                TableResult    result          = await cities.ExecuteAsync(createOperation);

                return(new OkObjectResult(result));
            }
            catch
            {
                return(new BadRequestObjectResult("City failed on insert or replace"));
            }
        }
Esempio n. 5
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "put", Route = "PutBeat/{Id}")] Beat beat, HttpRequest req, int Id,
            [Table("Beats", Connection = "RipaStorage")] CloudTable beats, ILogger log)

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

            try
            {
                beat.PartitionKey = "CA";
                beat.RowKey       = Id.ToString();
                beat.Id           = Id;
                beat.ETag         = "*";
                TableOperation createOperation = TableOperation.InsertOrReplace(beat);
                TableResult    result          = await beats.ExecuteAsync(createOperation);

                return(new OkObjectResult(result));
            }
            catch
            {
                return(new BadRequestObjectResult("beat failed on insert or replace"));
            }
        }
Esempio n. 6
0
        public async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log)
        {
            log.LogInformation("GET - Get Submissions requested");
            try
            {
                if (!RIPAAuthorization.ValidateAdministratorRole(req, log).ConfigureAwait(false).GetAwaiter().GetResult())
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new UnauthorizedResult());
            }

            SubmissionQuery submissionQuery = new SubmissionQuery()
            {
                StartDate = !string.IsNullOrWhiteSpace(req.Query["StartDate"]) ? DateTime.Parse(req.Query["StartDate"]) : DateTime.MinValue,
                EndDate   = !string.IsNullOrWhiteSpace(req.Query["EndDate"]) ? DateTime.Parse(req.Query["EndDate"]) : DateTime.MaxValue,
                Offset    = !string.IsNullOrWhiteSpace(req.Query["offset"]) ? Convert.ToInt32(req.Query["offset"]) : default,
Esempio n. 7
0
        public async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log)
        {
            log.LogInformation("GET - Get Users requested");

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

            var response = await _userProfileCosmosDbService.GetUserProfilesAsync("SELECT * FROM c ORDER BY c.name");

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

            var inputText    = req.Query["Search"];
            var submissionId = req.Query["SubmissionId"];
            var response     = await _stopCosmosDbService.GetErrorCodes(inputText, submissionId);

            return(new OkObjectResult(response));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "Put", Route = "PutSchool/{Id}")] School school, HttpRequest req, string Id,
            [Table("Schools", Connection = "RipaStorage")] CloudTable schools, ILogger log)
        {
            try
            {
                if (!RIPAAuthorization.ValidateAdministratorRole(req, log).ConfigureAwait(false).GetAwaiter().GetResult())
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new UnauthorizedResult());
            }

            try
            {
                if (string.IsNullOrWhiteSpace(school.CDSCode))
                {
                    throw new Exception("CDS CODE Must be provided");
                }
                school.PartitionKey = "CA";
                school.RowKey       = Id;
                school.Name         = Id;
                school.ETag         = "*";
                TableOperation createOperation = TableOperation.InsertOrReplace(school);
                TableResult    result          = await schools.ExecuteAsync(createOperation);

                return(new OkObjectResult(result));
            }
            catch
            {
                return(new BadRequestObjectResult("School failed on insert or replace"));
            }
        }
Esempio n. 10
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "Put", Route = "PutStatute/{Id}")] Statute statute, HttpRequest req, int Id,
            [Table("Statutes", Connection = "RipaStorage")] CloudTable statutes, ILogger log)
        {
            try
            {
                if (!RIPAAuthorization.ValidateAdministratorRole(req, log).ConfigureAwait(false).GetAwaiter().GetResult())
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new UnauthorizedResult());
            }

            try
            {
                if (statute.OffenseCode == 0)
                {
                    throw new Exception("Offense Code Must be type Integer and is required");
                }
                statute.PartitionKey = "CA";
                statute.RowKey       = Id.ToString();
                statute.OffenseCode  = Id;
                statute.ETag         = "*";
                TableOperation createOperation = TableOperation.InsertOrReplace(statute);
                TableResult    result          = await statutes.ExecuteAsync(createOperation);

                return(new OkObjectResult(result));
            }
            catch
            {
                return(new BadRequestObjectResult("Statute failed on insert or replace"));
            }
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "Put", Route = "PutTemplate/{Id}")] Template template, HttpRequest req, string Id,
            [Table("Templates", Connection = "RipaStorage")] CloudTable templates, ILogger log)
        {
            try
            {
                if (!RIPAAuthorization.ValidateAdministratorRole(req, log).ConfigureAwait(false).GetAwaiter().GetResult())
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new UnauthorizedResult());
            }

            try
            {
                if (String.IsNullOrEmpty(Id))
                {
                    throw new Exception("template id is required");
                }
                template.PartitionKey = "CA";
                template.RowKey       = Id;
                template.ETag         = "*";
                TableOperation createOperation = TableOperation.InsertOrReplace(template);
                TableResult    result          = await templates.ExecuteAsync(createOperation);

                return(new OkObjectResult(result));
            }
            catch
            {
                return(new BadRequestObjectResult("Template failed on insert or replace"));
            }
        }
Esempio n. 12
0
        public async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "put", Route = "PutStop/{Id}")] Common.Models.Stop stop, HttpRequest req, string Id, ILogger log)
        {
            log.LogInformation($"PUT - Put Stop requested, ID: {Id}, OID: {stop.OfficerId}, DATE: {stop.Date}, TIME: {stop.Time}");

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

                return(new UnauthorizedResult());
            }

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

                stop.EditStopOfficerId = (await _userProfileCosmosDbService.GetUserProfileAsync(objectId)).OfficerId;
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);

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

            if (string.IsNullOrEmpty(Id))
            {
                return(new BadRequestObjectResult("Stop Id cannot be empty or null"));
            }

            if (stop.OfficerId.Length != 9)
            {
                return(new BadRequestObjectResult("Officer ID must be 9 char"));
            }

            if (stop.Location.City == null)
            {
                return(new BadRequestObjectResult("City is required"));
            }

            if (stop.Status == null)
            {
                stop.Status = SubmissionStatus.Unsubmitted.ToString();
            }

            stop.Ori = Environment.GetEnvironmentVariable("ORI"); //What is an Originating Agency Identification (ORI) Number? A nine-character identifier assigned to an agency. Agencies must identify their ORI Number...

            bool isDuplicate = await _stopCosmosDbService.CheckForDuplicateStop(stop.Id, stop.Ori, stop.OfficerId, stop.Date, stop.Time);

            if (isDuplicate)
            {
                log.LogError($"This appears to be a duplicate Stop: ID: {Id}, SID: {stop.Id}, OID: {stop.OfficerId}, DATE: {stop.Date}, TIME: {stop.Time}");

                return(new BadRequestObjectResult("This appears to be a duplicate Stop"));
            }

            stop.IsEdited = Id == "0" ? false : true;

            try
            {
                if (Id != "0")
                {
                    //Protect the submission history
                    Common.Models.Stop editingStop = await _stopCosmosDbService.GetStopAsync(Id);

                    editingStop.Id = $"{stop.Id}-{DateTime.UtcNow:yyyyMMddHHmmss}";
                    await _stopAuditCosmosDbService.UpdateStopAuditAsync(editingStop.Id, editingStop);

                    log.LogInformation($"Saving stop audit ID: {editingStop.Id}");
                    stop.ListSubmission = editingStop.ListSubmission;
                }
            }
            catch (Exception ex)
            {
                log.LogError($"Failed getting stop to protect submission history, ID: {Id}, SID: {stop.Id}, OID: {stop.OfficerId}, DATE: {stop.Date}, TIME: {stop.Time}");

                return(new BadRequestObjectResult("Failed getting stop submission history"));
            }

            int retryAttemps = GetRetrySetting("RetryAttemps", 3);
            int retrywait    = GetRetrySetting("RetryWait", 1000);

            while (retryAttemps > 0)
            {
                try
                {
                    stop.Id = Id;
                    if (stop.Id == "0")
                    {
                        await _stopCosmosDbService.AddStopAsync(stop);
                    }
                    else
                    {
                        if (!RIPAAuthorization.ValidateAdministratorRole(req, log).ConfigureAwait(false).GetAwaiter().GetResult())
                        {
                            return(new UnauthorizedResult());
                        }

                        await _stopCosmosDbService.UpdateStopAsync(stop);
                    }

                    log.LogInformation($"PUT - saved stop, ID: {Id}, SID: {stop.Id}, OID: {stop.OfficerId}, DATE: {stop.Date}, TIME: {stop.Time}");

                    return(new OkObjectResult(stop));
                }
                catch (Exception exception)
                {
                    log.LogError($"Failed to insert/update stop, attempt counter: {retryAttemps}, ID: {Id}, SID: {stop.Id}, OID: {stop.OfficerId}, DATE: {stop.Date}, TIME: {stop.Time}", exception.GetBaseException());
                }

                await Task.Delay(retrywait);

                retryAttemps--;
            }

            return(new BadRequestObjectResult("The maximum number of attemps to save the STOP was exceeded"));
        }
Esempio n. 13
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log)
        {
            try
            {
                if (!RIPAAuthorization.ValidateAdministratorRole(req, log).ConfigureAwait(false).GetAwaiter().GetResult())
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new UnauthorizedResult());
            }

            try
            {
                int recordCount = 0;
                _log = log;
                var formData = await req.ReadFormAsync();

                var file = req.Form.Files["file"];

                var account = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("RipaStorage"));
                var client  = account.CreateCloudTableClient();

                DataSet dataSet = RunExcelDataReader(file);

                if (dataSet.Tables["Beat_Table"] != null)
                {
                    recordCount += await ProcessEntities(dataSet.Tables["Beat_Table"], client.GetTableReference("Beats"));
                }

                recordCount += await ProcessEntities(dataSet.Tables["City_Table"], client.GetTableReference("Cities"));

                recordCount += await ProcessEntities(dataSet.Tables["School_Table"], client.GetTableReference("Schools"));

                // CA DOJ currently has the table name as "Offense Table" which does not follow the conventions of the other tables
                if (dataSet.Tables["Offense_Table"] != null)
                {
                    recordCount += await ProcessEntities(dataSet.Tables["Offense_Table"], client.GetTableReference("Statutes"));
                }
                else if (dataSet.Tables["Offense Table"] != null)
                {
                    recordCount += await ProcessEntities(dataSet.Tables["Offense Table"], client.GetTableReference("Statutes"));
                }

                string responseMessage;
                if (recordCount >= 1)
                {
                    responseMessage = $"Upload complete: {recordCount} {(recordCount > 1 ? "records" : "record")} updated.";
                }
                else
                {
                    responseMessage = "No records found";
                }

                return(new OkObjectResult(responseMessage));
            }
            catch (Exception ex)
            {
                _log.LogError(ex.Message);
                return(new BadRequestObjectResult("File Format Error.  Sheets should be included: City_Table, School_Table, and Offense_Table"));
            }
        }
Esempio n. 14
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Importing user profiles from uploaded csv");
            var count = 0;

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

            try
            {
                using (var reader = new StreamReader(req.Form.Files[0].OpenReadStream()))
                    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                    {
                        var agency = req.Query["agency"];
                        csv.Context.RegisterClassMap <UserProfileMap>();
                        var records = csv.GetRecords <Common.Models.UserProfile>().ToList();
                        count = records.Count();

                        foreach (var record in records)
                        {
                            record.StartDate = DateTime.Now.AddYears(-record.YearsExperience);
                            if (string.IsNullOrEmpty(record.Agency))
                            {
                                record.Agency = agency;
                            }
                            record.FirstName ??= "";
                            record.LastName ??= "";
                            await _userProfileCosmosDbService.UpdateUserProfileAsync(record.Id, record);
                        }
                    }

                string responseMessage;

                if (count >= 0)
                {
                    responseMessage = $"Upload Complete: {count} {(count > 1 ? "records" : "record")} uploaded";
                }
                else
                {
                    responseMessage = "No records found";
                }

                return(new OkObjectResult(responseMessage));
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new BadRequestObjectResult("There was an error with the file format.  Please verify data and try again."));
            }
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "GetSubmission/{Id}")] HttpRequest req, string Id, ILogger log)
        {
            log.LogInformation("GET - Get Submission requested");
            try
            {
                if (!RIPAAuthorization.ValidateAdministratorRole(req, log).ConfigureAwait(false).GetAwaiter().GetResult())
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new UnauthorizedResult());
            }

            //limit
            var queryLimit  = !string.IsNullOrWhiteSpace(req.Query["limit"]) ? Convert.ToInt32(req.Query["limit"]) : default;
            var queryOffset = !string.IsNullOrWhiteSpace(req.Query["offset"]) ? Convert.ToInt32(req.Query["offset"]) : default;
            var limit       = string.Empty;

            if (queryLimit != 0)
            {
                limit = Environment.NewLine + $"OFFSET {queryOffset} LIMIT {queryLimit}";
            }

            var queryOrderBy = !string.IsNullOrWhiteSpace(req.Query["OrderBy"]) ? req.Query["OrderBy"] : default;
            var queryOrder   = !string.IsNullOrWhiteSpace(req.Query["Order"]) ? req.Query["Order"] : default;

            var order = Environment.NewLine + "ORDER BY c.StopDateTime DESC";

            if (!string.IsNullOrWhiteSpace(queryOrderBy))
            {
                order = Environment.NewLine + $"ORDER BY c.{queryOrderBy} ";
                if (!string.IsNullOrWhiteSpace(queryOrder))
                {
                    if (queryOrder.ToString().ToUpperInvariant() == "DESC" || queryOrder.ToString().ToUpperInvariant() == "ASC")
                    {
                        order += queryOrder;
                    }
                }
            }

            List <string> whereStatements = new List <string>();
            string        join            = string.Empty;

            join += Environment.NewLine + "JOIN ListSubmission IN c.ListSubmission";
            whereStatements.Add(Environment.NewLine + $"ListSubmission.Id = '{Id}'");

            if (!string.IsNullOrWhiteSpace(req.Query["ErrorCode"]))
            {
                join += Environment.NewLine + "JOIN ListSubmissionError IN ListSubmission.ListSubmissionError";
                whereStatements.Add(Environment.NewLine + $"ListSubmissionError.Code = '{req.Query["ErrorCode"]}'");
            }

            string where = string.Empty;
            if (whereStatements.Count > 0)
            {
                where = " WHERE ";
                foreach (var whereStatement in whereStatements)
                {
                    where += Environment.NewLine + whereStatement;
                    where += Environment.NewLine + "AND";
                }
                where = where.Remove(where.Length - 3);
            }

            if (!string.IsNullOrEmpty(Id))
            {
                var submissionResponse = await _submissionCosmosDbService.GetSubmissionAsync(Id);

                if (submissionResponse != null)
                {
                    string query = $"SELECT VALUE c FROM c {join} {where} {order} {limit}";

                    var stopResponse = await _stopCosmosDbService.GetStopsAsync(query);

                    var getSubmissionErrorSummariesResponse = await _stopCosmosDbService.GetSubmissionErrorSummaries(Id);

                    var response = new
                    {
                        submission = new {
                            submissionResponse.Id,
                            submissionResponse.DateSubmitted,
                            submissionResponse.RecordCount,
                            submissionResponse.OfficerId,
                            submissionResponse.OfficerName,
                            submissionResponse.MaxStopDate,
                            submissionResponse.MinStopDate,
                            ErrorCount = getSubmissionErrorSummariesResponse.Sum(x => x.Count)
                        },
                        stops   = stopResponse,
                        summary = getSubmissionErrorSummariesResponse
                    };

                    return(new OkObjectResult(response));
                }
            }
            return(new BadRequestObjectResult("Submission Id not found"));
        }