Ejemplo n.º 1
0
        public CreateAllocationResponse CreateAllocation(CreateAllocationRequest request)
        {
            var(worker, team, person, allocatedBy) = GetCreateAllocationRequirements(request);

            var allocation = new AllocationSet
            {
                PersonId            = person.Id,
                WorkerId            = worker.Id,
                TeamId              = team.Id,
                AllocationStartDate = request.AllocationStartDate,
                CaseStatus          = "Open",
                CreatedBy           = allocatedBy.Email
            };

            _databaseContext.Allocations.Add(allocation);
            _databaseContext.SaveChanges();


            var response = new CreateAllocationResponse();

            //Add note
            try
            {
                var dt = DateTime.Now;

                var note = new AllocationCaseNote
                {
                    FirstName   = person.FirstName,
                    LastName    = person.LastName,
                    MosaicId    = person.Id.ToString(),
                    Timestamp   = dt.ToString("dd/MM/yyyy H:mm:ss"), //in line with imported form data
                    WorkerEmail = allocatedBy.Email,
                    Note        =
                        $"{dt.ToShortDateString()} | Allocation | {worker.FirstName} {worker.LastName} in {team.Name} was allocated to this person (by {allocatedBy.FirstName} {allocatedBy.LastName})",
                    FormNameOverall = "API_Allocation",
                    FormName        = "Worker allocated",
                    AllocationId    = allocation.Id.ToString(),
                    CreatedBy       = request.CreatedBy
                };

                var caseNotesDocument = new CaseNotesDocument()
                {
                    CaseFormData = JsonConvert.SerializeObject(note)
                };

                response.CaseNoteId   = _processDataGateway.InsertCaseNoteDocument(caseNotesDocument).Result;
                response.AllocationId = allocation.Id;
            }
            catch (Exception ex)
            {
                //roll back allocation record
                _databaseContext.Allocations.Remove(allocation);
                _databaseContext.SaveChanges();

                throw new UpdateAllocationException(
                          $"Unable to create a case note. Allocation not created: {ex.Message}");
            }

            return(response);
        }
        public async Task <string> InsertCaseNoteDocument(CaseNotesDocument caseNotesDoc)
        {
            var doc = BsonSerializer.Deserialize <BsonDocument>(caseNotesDoc.CaseFormData);
            await _sccvDbContext.getCollection().InsertOneAsync(doc)
            .ConfigureAwait(false);

            return(doc["_id"].AsObjectId.ToString());
        }
Ejemplo n.º 3
0
        public PostWarningNoteResponse PostWarningNote(PostWarningNoteRequest request)
        {
            var person = _databaseContext.Persons.FirstOrDefault(x => x.Id == request.PersonId);

            if (person == null)
            {
                throw new PersonNotFoundException($"Person with given id ({request.PersonId}) not found");
            }

            var warningNote = request.ToDatabaseEntity();

            _databaseContext.WarningNotes.Add(warningNote);
            _databaseContext.SaveChanges();

            var response = new PostWarningNoteResponse
            {
                WarningNoteId = warningNote.Id
            };

            // try
            // {
            var dt = DateTime.Now;

            var note = new WarningNoteCaseNote
            {
                FirstName       = person.FirstName,
                LastName        = person.LastName,
                MosaicId        = person.Id.ToString(),
                Timestamp       = dt.ToString("dd/MM/yyyy H:mm:ss"),
                Note            = $"{dt.ToShortDateString()} | Warning Note | Warning note created against this person",
                FormNameOverall = "API_WarningNote",
                FormName        = "Warning Note Created",
                WarningNoteId   = warningNote.Id.ToString(),
                WorkerEmail     = request.CreatedBy
            };

            var caseNotesDocument = new CaseNotesDocument
            {
                CaseFormData = JsonConvert.SerializeObject(note)
            };

            response.CaseNoteId = _processDataGateway.InsertCaseNoteDocument(caseNotesDocument).Result;
            // }
            // catch (Exception ex)
            // {
            //     _databaseContext.WarningNotes.Remove(warningNote);
            //     _databaseContext.SaveChanges();

            //     throw new PostWarningNoteException($"Unable to create a case note. Warning Note not created: {ex.Message}");
            // }

            return(response);
        }
        public void CanMapCreateCaseNoteRequestToCaseNotesDocument()
        {
            CreateCaseNoteRequest request = _fixture
                                            .Build <CreateCaseNoteRequest>()
                                            .With(x => x.ContextFlag, _faker.Random.String2(1))
                                            .With(x => x.CaseFormData, "{\"prop_one\": \"value one\",  \"prop_two\": \"value two\"}")
                                            .Create();

            GenericCaseNote note = new GenericCaseNote()
            {
                DateOfBirth     = request.DateOfBirth?.ToString("dd/MM/yyy"),
                DateOfEvent     = request.DateOfEvent?.ToString(),
                FirstName       = request.FirstName,
                LastName        = request.LastName,
                FormName        = request.FormName,
                FormNameOverall = request.FormNameOverall,
                WorkerEmail     = request.WorkerEmail,
                MosaicId        = request.PersonId.ToString()
            };

            var result = request.ToEntity();

            dynamic formData = JsonConvert.DeserializeObject(result.CaseFormData);

            //take the generated timestamp value and use it in the expected result
            note.Timestamp = formData["timestamp"];

            JObject coreProperties = JObject.Parse(JsonConvert.SerializeObject(note));

            coreProperties.Merge(JObject.Parse(request.CaseFormData));

            var expectedResult = new CaseNotesDocument()
            {
                CaseFormData = coreProperties.ToString()
            };

            result.Should().BeEquivalentTo(expectedResult);
        }
        public Task <string> Execute(CreateCaseNoteRequest request)
        {
            CaseNotesDocument doc = request.ToEntity();

            return(_processDataGateway.InsertCaseNoteDocument(doc));
        }
Ejemplo n.º 6
0
        public void PatchWarningNote(PatchWarningNoteRequest request)
        {
            WarningNote warningNote = _databaseContext.WarningNotes.FirstOrDefault(x => x.Id == request.WarningNoteId);

            if (warningNote == null)
            {
                throw new PatchWarningNoteException($"Warning Note with given id ({request.WarningNoteId}) not found");
            }

            if (warningNote.Status == "closed")
            {
                throw new PatchWarningNoteException(
                          $"Warning Note with given id ({request.WarningNoteId}) has already been closed");
            }

            Person person = _databaseContext.Persons.FirstOrDefault(x => x.Id == warningNote.PersonId);

            if (person == null)
            {
                throw new PatchWarningNoteException("Person not found");
            }

            Worker worker = _databaseContext.Workers.FirstOrDefault(x => x.Email == request.ReviewedBy);

            if (worker == null)
            {
                throw new PatchWarningNoteException($"Worker ({request.ReviewedBy}) not found");
            }


            warningNote.LastReviewDate = request.ReviewDate;
            warningNote.NextReviewDate = request.NextReviewDate;
            if (request.Status?.ToLower() == "closed")
            {
                warningNote.Status         = "closed";
                warningNote.EndDate        = _systemTime.Now;
                warningNote.NextReviewDate = null;
            }

            warningNote.LastModifiedBy = request.ReviewedBy;

            var review = PostWarningNoteReview(request);

            _databaseContext.WarningNoteReview.Add(review);
            _databaseContext.SaveChanges();

            var dt = DateTime.Now;

            var note = new WarningNoteCaseNote
            {
                FirstName       = person.FirstName,
                LastName        = person.LastName,
                MosaicId        = person.Id.ToString(),
                Timestamp       = dt.ToString("dd/MM/yyyy H:mm:ss"),
                Note            = $"{dt.ToShortDateString()} | Warning Note | {((request.Status == "closed") ? "Warning note against this person ended" : "Warning note against this person reviewed")}",
                FormNameOverall = "API_WarningNote",
                FormName        = (request.Status == "closed") ? "Warning Note Ended" : "Warning Note Reviewed",
                WarningNoteId   = warningNote.Id.ToString(),
                WorkerEmail     = request.ReviewedBy
            };

            var caseNotesDocument = new CaseNotesDocument
            {
                CaseFormData = JsonConvert.SerializeObject(note)
            };

            _ = _processDataGateway.InsertCaseNoteDocument(caseNotesDocument).Result;
        }
Ejemplo n.º 7
0
        public UpdateAllocationResponse UpdateAllocation(UpdateAllocationRequest request)
        {
            var response = new UpdateAllocationResponse();

            try
            {
                var allocation = _databaseContext.Allocations.FirstOrDefault(x => x.Id == request.Id);

                if (allocation == null)
                {
                    throw new EntityUpdateException($"Allocation {request.Id} not found");
                }

                if (allocation.CaseStatus?.ToUpper() == "CLOSED")
                {
                    throw new UpdateAllocationException("Allocation already closed");
                }

                var(person, createdBy) = GetUpdateAllocationRequirements(allocation, request);


                //copy existing values in case adding note fails
                var tmpAllocation = (AllocationSet)allocation.Clone();
                SetDeallocationValues(allocation, request.DeallocationDate, request.CreatedBy);
                _databaseContext.SaveChanges();

                try
                {
                    var note = new DeallocationCaseNote
                    {
                        FirstName          = person.FirstName,
                        LastName           = person.LastName,
                        MosaicId           = person.Id.ToString(),
                        Timestamp          = DateTime.Now.ToString("dd/MM/yyyy H:mm:ss"),
                        WorkerEmail        = createdBy.Email,    //required for my cases search
                        DeallocationReason = request.DeallocationReason,
                        FormNameOverall    = "API_Deallocation", //prefix API notes so they are easy to identify
                        FormName           = "Worker deallocated",
                        AllocationId       = request.Id.ToString(),
                        CreatedBy          = request.CreatedBy
                    };

                    var caseNotesDocument = new CaseNotesDocument()
                    {
                        CaseFormData = JsonConvert.SerializeObject(note)
                    };

                    response.CaseNoteId = _processDataGateway.InsertCaseNoteDocument(caseNotesDocument).Result;
                }
                catch (Exception ex)
                {
                    var allocationToRestore = _databaseContext.Allocations.FirstOrDefault(x => x.Id == request.Id);
                    RestoreAllocationValues(tmpAllocation, allocationToRestore);

                    _databaseContext.SaveChanges();

                    throw new UpdateAllocationException(
                              $"Unable to create a case note. Allocation not updated: {ex.Message}");
                }
            }
            catch (Exception ex)
            {
                throw new EntityUpdateException($"Unable to update allocation {request.Id}: {ex.Message}");
            }

            return(response);
        }
Ejemplo n.º 8
0
        public void UpdatePerson(UpdatePersonRequest request)
        {
            Person person = _databaseContext
                            .Persons
                            .Include(x => x.Addresses)
                            .Include(x => x.PhoneNumbers)
                            .Include(x => x.OtherNames)
                            .FirstOrDefault(x => x.Id == request.Id);

            if (person == null)
            {
                throw new UpdatePersonException("Person not found");
            }

            person.AgeContext               = request.ContextFlag;
            person.DateOfBirth              = request.DateOfBirth;
            person.DateOfDeath              = request.DateOfDeath;
            person.EmailAddress             = request.EmailAddress;
            person.Ethnicity                = request.Ethnicity;
            person.FirstLanguage            = request.FirstLanguage;
            person.FirstName                = request.FirstName;
            person.FullName                 = $"{request.FirstName} {request.LastName}";
            person.Gender                   = request.Gender;
            person.LastModifiedBy           = request.CreatedBy;
            person.LastName                 = request.LastName;
            person.NhsNumber                = request.NhsNumber;
            person.PreferredMethodOfContact = request.PreferredMethodOfContact;
            person.Religion                 = request.Religion;
            person.Restricted               = request.Restricted;
            person.SexualOrientation        = request.SexualOrientation;
            person.Title = request.Title;

            //replace phone numbers
            _databaseContext.PhoneNumbers.RemoveRange(person.PhoneNumbers);

            if (request.PhoneNumbers != null)
            {
                foreach (var number in request.PhoneNumbers)
                {
                    person.PhoneNumbers.Add(number.ToEntity(person.Id, request.CreatedBy));
                }
            }

            //replace other names
            _databaseContext.PersonOtherNames.RemoveRange(person.OtherNames);

            if (request.OtherNames != null)
            {
                foreach (var otherName in request.OtherNames)
                {
                    person.OtherNames.Add(otherName.ToEntity(person.Id, request.CreatedBy));
                }
            }

            //check for changed address
            if (request.Address != null)
            {
                Address displayAddress = person.Addresses.FirstOrDefault(x => x.IsDisplayAddress == "Y");

                if (displayAddress == null)
                {
                    person.Addresses.Add(GetNewDisplayAddress(request.Address.Address, request.Address.Postcode,
                                                              request.Address.Uprn, request.CreatedBy));
                }
                else
                {
                    //has address changed?
                    if (!(request.Address.Address == displayAddress.AddressLines &&
                          request.Address.Postcode == displayAddress.PostCode &&
                          displayAddress.Uprn == request.Address.Uprn))
                    {
                        displayAddress.IsDisplayAddress = "N";
                        displayAddress.EndDate          = DateTime.Now;
                        displayAddress.LastModifiedBy   = request.CreatedBy;

                        person.Addresses.Add(GetNewDisplayAddress(request.Address.Address, request.Address.Postcode,
                                                                  request.Address.Uprn, request.CreatedBy));
                    }
                }
            }
            else //address not provided, remove current display address if it exists
            {
                Address displayAddress = person.Addresses.FirstOrDefault(x => x.IsDisplayAddress == "Y");

                if (displayAddress != null)
                {
                    displayAddress.IsDisplayAddress = "N";
                    displayAddress.EndDate          = DateTime.Now;
                    displayAddress.LastModifiedBy   = request.CreatedBy;
                }
            }

            DateTime dt = DateTime.Now;

            UpdatePersonCaseNote note = new UpdatePersonCaseNote()
            {
                FirstName       = person.FirstName,
                LastName        = person.LastName,
                MosaicId        = person.Id.ToString(),
                Timestamp       = dt.ToString("dd/MM/yyyy H:mm:ss"), //in line with imported form data
                WorkerEmail     = request.CreatedBy,
                Note            = $"{dt.ToShortDateString()} Person details updated - by {request.CreatedBy}.",
                FormNameOverall = "API_Update_Person",
                FormName        = "Person updated",
                CreatedBy       = request.CreatedBy
            };

            CaseNotesDocument caseNotesDocument = new CaseNotesDocument()
            {
                CaseFormData = JsonConvert.SerializeObject(note)
            };

            //TODO: refactor so gateways don't call each other
            _ = _processDataGateway.InsertCaseNoteDocument(caseNotesDocument).Result;

            _databaseContext.SaveChanges();
        }
Ejemplo n.º 9
0
        //Handle case note creation exception like below for now
        public AddNewResidentResponse AddNewResident(AddNewResidentRequest request)
        {
            Address address = null;
            List <PersonOtherName> names = null;
            Person resident;
            List <dbPhoneNumber> phoneNumbers = null;

            try
            {
                resident = AddNewPerson(request);

                if (request.Address != null)
                {
                    address            = AddResidentAddress(request.Address, resident.Id, request.CreatedBy);
                    resident.Addresses = new List <Address> {
                        address
                    };
                }

                if (request.OtherNames?.Count > 0)
                {
                    names = AddOtherNames(request.OtherNames, resident.Id, request.CreatedBy);
                    resident.OtherNames = new List <PersonOtherName>();
                    resident.OtherNames.AddRange(names);
                }

                if (request.PhoneNumbers?.Count > 0)
                {
                    phoneNumbers          = AddPhoneNumbers(request.PhoneNumbers, resident.Id, request.CreatedBy);
                    resident.PhoneNumbers = new List <dbPhoneNumber>();
                    resident.PhoneNumbers.AddRange(phoneNumbers);
                }

                _databaseContext.Persons.Add(resident);
                _databaseContext.SaveChanges();
            }
            catch (DbUpdateException ex)
            {
                throw new ResidentCouldNotBeinsertedException(
                          $"Error with inserting resident record has occurred - {ex.Message}");
            }

            string caseNoteId           = null;
            string caseNoteErrorMessage = null;

            //Add note
            try
            {
                DateTime dt = DateTime.Now;

                CreatePersonCaseNote note = new CreatePersonCaseNote()
                {
                    FirstName       = resident.FirstName,
                    LastName        = resident.LastName,
                    MosaicId        = resident.Id.ToString(),
                    Timestamp       = dt.ToString("dd/MM/yyyy H:mm:ss"), //in line with imported form data
                    WorkerEmail     = request.CreatedBy,
                    Note            = $"{dt.ToShortDateString()} Person added - by {request.CreatedBy}.",
                    FormNameOverall = "API_Create_Person",
                    FormName        = "Person added",
                    CreatedBy       = request.CreatedBy
                };

                CaseNotesDocument caseNotesDocument = new CaseNotesDocument()
                {
                    CaseFormData = JsonConvert.SerializeObject(note)
                };

                //TODO: refactor to appropriate pattern when using base API

                caseNoteId = _processDataGateway.InsertCaseNoteDocument(caseNotesDocument).Result;
            }
            catch (Exception ex)
            {
                caseNoteErrorMessage =
                    $"Unable to create a case note for creating a person {resident.Id}: {ex.Message}";
            }

            return(resident.ToResponse(address, names, phoneNumbers, caseNoteId, caseNoteErrorMessage));
        }