Ejemplo n.º 1
0
        public Task <bool> Handle(RegisterCovidPatientCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                NotifyValidationErrors(request);
                return(Task.FromResult(false));
            }

            var patient = new Patient(Guid.NewGuid(), request.Name, request.Email, request.RegistrationDate, PatientType.COVID19);

            if (_patientRepository.GetByEmail(patient.Email) != null)
            {
                _mediator.RaiseEvent(new DomainNotification(request.MessageType, "E-mail is already registered."));
                return(Task.FromResult(false));
            }

            _patientRepository.Add(patient);

            if (Commit())
            {
                _mediator.RaiseEvent(new PatientCovidRegisteredEvent(patient.Id, patient.Name, patient.Email, patient.RegistrationDate));
            }

            return(Task.FromResult(true));
        }
Ejemplo n.º 2
0
        public ContractResponse <PatientGetResponse> Add(ContractRequest <AddUpdatePatientRequest> request)
        {
            try
            {
                var model       = request.Data.Patient.ToPatient();
                var brokenRules = model.GetBrokenRules().ToList();

                if (!brokenRules.Any())
                {
                    _patientRepository.Add(model);
                    _uow.Commit();


                    var responseModel = new PatientGetResponse {
                        Id = model.Id
                    };
                    return(ContractUtil.CreateResponse(request, responseModel));
                }

                return(ContractUtil.CreateInvalidResponse <PatientGetResponse>(brokenRules));
            }
            catch (Exception ex)
            {
                _logger.LogError(20, ex, ex.Message);
                return(ContractUtil.CreateInvalidResponse <PatientGetResponse>(ex));
            }
        }
Ejemplo n.º 3
0
        public BaseResponse <int> Add(BaseRequest <Patient> dto)
        {
            BaseResponse <int> response = new BaseResponse <int>();

            try
            {
                Patient patient = dto.Value;

                if (patient.Validate())
                {
                    response.Value   = _patientRepository.Add(patient);
                    response.Success = true;
                }
                else
                {
                    response.Success     = false;
                    response.BrokenRules = patient.BrokenRules;
                }
            }
            catch (Exception ex)
            {
                SetErrorResponse(response, ex);
            }

            return(response);
        }
Ejemplo n.º 4
0
        public IActionResult Add(PatientViewModel model)
        {
            if (_patientRepository.GetAll().ToList().Any(x => x.FirstName.Equals(model.FirstName) && x.LastName.Equals(model.LastName)))
            {
                ModelState.AddModelError("", "Patient with same first name and last name already exist");
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                Patient patient = model;
                patient.Gender = Enum.GetName(typeof(Gender), model.Gender);
                _patientRepository.Add(patient);

                _patientRepository.SaveChanges();

                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception)
            {
                return(View(model));
            }
        }
Ejemplo n.º 5
0
        public Task <bool> Handle(RegisterNewPatientCommand message, CancellationToken cancellationToken)
        {
            if (!message.IsValid())
            {
                NotifyValidationErrors(message);
                return(Task.FromResult(false));
            }

            var patient = new Patient.Builder(Guid.NewGuid()).Named(message.FullName).BornIn(message.BirthDate)
                          .WithCpf(message.Cpf)
                          .WithGender(message.Gender).WithPhone(message.Phone).WhichIsActive().Build();

            if (_patientRepository.GetByCpf(patient.Cpf) != null)
            {
                _bus.RaiseEvent(new DomainNotification(message.MessageType,
                                                       $"There is already a patient registered with this CPF ({patient.Cpf})"));
                return(Task.FromResult(false));
            }

            if (!patient.IsValid())
            {
                NotifyValidationErrors(patient.ValidationResult);
                return(Task.FromResult(false));
            }

            _patientRepository.Add(patient);

            if (Commit())
            {
                _bus.RaiseEvent(new PatientRegisteredEvent(patient));
            }

            return(Task.FromResult(true));
        }
Ejemplo n.º 6
0
        public IActionResult Create(PatientViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;

                if (model.Photo != null)
                {
                    string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
                }

                Patient newPatient = new Patient
                {
                    PersonId           = model.PersonId,
                    ProblemCategoryId  = model.ProblemCategoryId,
                    ProblemDescription = model.ProblemDescription,
                    EmployeId          = model.EmployeId,
                    Date  = model.Date,
                    IUser = 1,
                    IDate = DateTime.Now,
                    EUser = 0,
                    EDate = null,

                    PhotoPath = uniqueFileName
                };

                _patientRepository.Add(newPatient);
                return(RedirectToAction("details", new { id = newPatient.Id }));
            }

            return(View());
        }
Ejemplo n.º 7
0
        public async Task <int> FirstVisit_Post(FirstVisitVM firstVisit)
        {
            firstVisit.Visit.VisitDate = firstVisit.Visit.VisitDate + firstVisit.Visit.TimeOfVisit;
            var visits = _visitRepository.GetForDateTime(firstVisit.Visit.VisitDate);

            if (firstVisit.Visit.DentistId == 0)
            {
                if (visits.Any())
                {
                    if (visits.Select(v => v.PatientId).Contains(firstVisit.Visit.PatientId))
                    {
                        // return 1;
                    }
                    var dentists = _dentistRepository.GetAll().Select(d => d.Id).ToList();
                    foreach (var v in visits)
                    {
                        if (dentists.Contains(v.DentistId))
                        {
                            dentists.Remove(v.DentistId);
                        }
                    }
                    if (dentists.Any())
                    {
                        firstVisit.Visit.DentistId = dentists.First();
                    }
                }
                else
                {
                    firstVisit.Visit.DentistId = _dentistRepository.GetAll().Select(d => d.Id).First();
                }
            }
            var patient = _mapper.Map <Patient>(firstVisit.Patient);
            await _patientRepository.Add(patient);

            var address = _mapper.Map <Address>(firstVisit.Patient.Address);

            address.PatientId = patient.Id;
            await _addressRepository.Add(address);

            var visit = _mapper.Map <Visit>(firstVisit.Visit);

            visit.PatientId = patient.Id;
            await _visitRepository.Add(visit);

            return(0);
        }
Ejemplo n.º 8
0
        public void given_new_patient_when_adding_should_return_new_id()
        {
            _repository.Add(Arg.Any <Patient>()).Returns(1, 3, 5);

            Assert.That(_service.AddPatient(new Patient()), Is.EqualTo(1));
            Assert.That(_service.AddPatient(new Patient()), Is.EqualTo(3));
            Assert.That(_service.AddPatient(new Patient()), Is.EqualTo(5));
        }
Ejemplo n.º 9
0
 public IActionResult AddPatient([FromBody] Patient model)
 {
     model.FullName = (string)(model.FirstName + " " + model.LastName);
     model.Date     = DateTime.Now;
     model.MRN      = GenMRN();
     model.Display  = model.FirstName + " " + model.LastName + "-" + model.MRN;
     _repo.Add(model);
     return(new OkObjectResult(new { patientId = model.PatientId }));
 }
        public ActionResult CreatePatient(PatientViewModel patientViewModel)
        {
            if (ModelState.IsValid)
            {
                patientRepository.Add(patientViewModel.ToDomainModel());
                return(RedirectToAction("Index"));
            }

            return(View(patientViewModel));
        }
Ejemplo n.º 11
0
        public void Register(PatientRegistrationDTO registrationDTO)
        {
            PatientAccountMemento memento = registrationDTO.ToPatientAccountMemento();

            memento.IsActivated = false;
            memento.IsBlocked   = false;
            memento.City        = _cityRepository.Get(registrationDTO.CityId).GetMemento();
            PatientAccount patientAccount = new PatientAccount(memento);

            _patientRepository.Add(patientAccount);
        }
Ejemplo n.º 12
0
        public async Task <Patient> Add(Patient entity)
        {
            try
            {
                var bOpDoneSuccessfully = await _PatientRepository.Add(entity);

                return(bOpDoneSuccessfully);
            }
            catch (Exception ex)
            {
                throw new Exception("BusinessLogic:PatientBusiness::InsertPatient::Error occured.", ex);
            }
        }
Ejemplo n.º 13
0
        public void Add(GuestPatientDTO guestPatient)
        {
            var patient = new Patient(new PatientMemento()
            {
                Name      = guestPatient.Name,
                Surname   = guestPatient.Surname,
                Jmbg      = guestPatient.Jmbg,
                BloodType = BloodType.Unknown,
                RhFactor  = RhFactor.Unknown
            });

            _repository.Add(patient);
        }
Ejemplo n.º 14
0
 public void Add(Patient patient)
 {
     try
     {
         _patientRepository.Add(patient);
         _logger.LogInformation("New patient was added!");
     }
     catch (Exception exception)
     {
         _logger.LogError("An error occurred while adding the patient" + " | " + exception);
         throw;
     }
 }
 public IActionResult Post(Patient patient)
 {
     try
     {
         _patientRepository.Add(patient);
         var cacheKey = "Patient" + patient.Id;
         _cache.Set(cacheKey, patient);
         return(CreatedAtAction("Get", new { id = patient.Id }, patient));
     }
     catch (Exception e)
     {
         return(StatusCode(500, $"Cannot save this patient -- Internal error: {e}"));
     }
 }
Ejemplo n.º 16
0
        public async Task <IActionResult> AddPatient([FromBody] PatientRequestDto patientRequestDto)
        {
            if (String.IsNullOrEmpty(patientRequestDto.StudyRequests[0].EstimatedEndTime))
            {
                patientRequestDto.StudyRequests[0].EstimatedEndTime = null;
            }
            var resultModel = new ServiceResultModel <Patient> {
                IsSuccess = false, Errors = new List <string>()
            };
            var patientExsists = _patientRepository.Any(p => p.PatientName == patientRequestDto.PatientName);

            if (patientExsists)
            {
                return(BadRequest("Patient already exsits"));
            }


            var newPatient = _patientRepository.Add(new Patient
            {
                PatientName  = patientRequestDto.PatientName,
                DOB          = patientRequestDto.DOB,
                PatientSexId = patientRequestDto.PatientSex,
                RoomId       = (int)patientRequestDto.RoomNameId,
            });


            var saved = (newPatient != null) ? await _unitOfWork.CommitAsync() : 0;

            var newDoctorPatient = _doctorPatientRepository.Add(new DoctorPatient {
                DoctorId = patientRequestDto.DoctorRequests[0].DoctorId, PatientId = newPatient.PatientId
            });
            var doctorPatientSaved = (newDoctorPatient != null) ? await _unitOfWork.CommitAsync() : 0;

            var newStudy = _studyRepository.Add(new Study {
                PatientId = newPatient.PatientId, StudyStatusId = patientRequestDto.StudyRequests[0].StudyStatusId, DoctorId = patientRequestDto.DoctorRequests[0].DoctorId, PlannedStartTime = DateTime.Now.ToShortDateString(), EstimatedEndTime = patientRequestDto.StudyRequests[0].EstimatedEndTime, Descriptions = patientRequestDto.StudyRequests[0].Descriptions
            });
            var savedStudy = (newStudy != null) ? await _unitOfWork.CommitAsync() : 0;

            var resultPatient = _patientRepository.GetById(newPatient.PatientId);

            if (saved > 0 && doctorPatientSaved > 0 && savedStudy > 0)
            {
                resultModel.IsSuccess = true;
                resultModel.Data      = resultPatient;
                return(Ok(resultModel));
            }

            return(Ok("No Patient Details found"));
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> Upload()
        {
            FileInfo file = new FileInfo(@"D:\1.xlsx");

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            using ExcelPackage package  = new ExcelPackage(file);
            ExcelWorksheet workSheet = package.Workbook.Worksheets[0];

            int totalRows = workSheet.Dimension.Rows;

            for (int i = 2; i <= totalRows; i++)
            {
                Patient patient = new Patient
                {
                    Name      = workSheet.ConvertToString(i, 1),
                    Telephone = workSheet.ConvertToString(i, 2),
                    Gender    = workSheet.ConvertToString(i, 3) == "ذكر" ? GenderEnum.Male : GenderEnum.Female
                };
                await patientRepository.Add(patient).ConfigureAwait(true);

                await unitOfWork.CompleteAsync().ConfigureAwait(true);
            }
            return(Ok());
        }
Ejemplo n.º 18
0
        public async Task <PatientDto> Add(PatientDto model)
        {
            model.Code = string.Empty;
            var entity = _patientRepository.Add(_mapper.Map <TPatient>(model));
            await _patientRepository.SaveChangeAsync();

            var maxId = await _patientRepository.Repo.MaxAsync(c => c.Id);

            entity.Code = $"BN-{(maxId + 1):D8}";
            await _patientRepository.SaveChangeAsync();

            model.Id = entity.Id;

            return(model);
        }
Ejemplo n.º 19
0
        public async Task Adicionar(Patient patient)
        {
            if (!ExecutarValidacao(new PatientValidation(), patient))
            {
                return;
            }

            if (await _patientRepository.CpfExists(patient.Cpf))
            {
                Notificar("This document has been already regitered in our system!");
                return;
            }

            await _patientRepository.Add(patient);
        }
        public ActionResult create(PatientDataModel student)
        {
            if (!ModelState.IsValid)
            {
                return(View(student));
            }

            var data = repository.Add(student);

            if (data == null)
            {
                ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");
                return(View(student));
            }
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 21
0
        public PatientDto CreatePatient(string phoneNo, string firstName, string lastName, string createdBy, string email)
        {
            var patientID = Guid.NewGuid().ToString();

            if (string.IsNullOrEmpty(phoneNo))
            {
                throw new Exception("The PhoneNo cannot be null!");
            }

            if (string.IsNullOrEmpty(firstName))
            {
                throw new Exception("The Firstname cannot be null!");
            }

            if (string.IsNullOrEmpty(lastName))
            {
                throw new Exception("The Lastname cannot be null!");
            }

            if (string.IsNullOrEmpty(createdBy))
            {
                throw new Exception("The CreatedBy cannot be null!");
            }

            if (string.IsNullOrEmpty(email))
            {
                throw new Exception("The Email cannot be null!");
            }

            try {
                _patientRepository.Add(patientID, phoneNo, firstName, lastName, createdBy, email);

                var patientDto = _patientRepository.FindByPhoneNo(phoneNo);

                if (patientDto == null)
                {
                    throw new InvalidPatientIDException("The PhoneNo is not correct!");
                }

                return(patientDto);
            }
            catch (SqlException ex) {
                throw new DuplicatePhoneNoException("The PhoneNo exists in the database! " + ex.Message);
            }
        }
Ejemplo n.º 22
0
        public bool Register(Patient patient)
        {
            if (!IsUsernameUnique(patient.Username))
            {
                MessageBox.Show("Uneto korisničko ime već postoji u sistemu", "Podaci nisu unikatni",
                                MessageBoxButton.OK);
                return(false);
            }

            if (!IsJMBGUnique(patient.JMBG))
            {
                MessageBox.Show("Uneti JMBG već postoji u sistemu", "Podaci nisu unikatni", MessageBoxButton.OK);
                return(false);
            }

            _patientRepository.Add(patient);
            return(true);
        }
Ejemplo n.º 23
0
        public async Task <Response> Handle(AddPatientRequest request, CancellationToken cancellationToken)
        {
            //Verifica se a requisição é válida
            if (request == null)
            {
                AddNotification("Request", "A requisição é inválida!");
                return(new Response(this));
            }

            //Verifica se o CPF inserido é válido
            if (!request.CPF.IsValidCpf())
            {
                AddNotification("CPF", "CPF Inválido, por favor insira um válido!");
                return(new Response(this));
            }

            //Verifica se o paciente já está cadastrado
            if (_patientRepository.Exists(request.Email, request.CPF, request.RG))
            {
                AddNotification("Paciente", "Paciente já cadastrado");
                return(new Response(this));
            }

            //Instancia o paciente e verifica se existe algum dado inválido
            Entities.Patient patient = new(request.FirstName, request.LastName,
                                           request.Email, request.Password, request.Phone, request.BirthDate, request.CPF, request.RG,
                                           request.CEP, request.Address, request.District, request.Complement, request.City, request.State);
            AddNotifications(patient);

            if (IsInvalid())
            {
                return(new Response(this));
            }

            //Insere os dados no banco
            _patientRepository.Add(patient);

            //Cria o objeto da resposta
            var response = new Response(this, patient);

            //Retorna a resposta
            return(await Task.FromResult(response));
        }
Ejemplo n.º 24
0
        public IHttpActionResult Post([FromBody] PatientEntryModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var entity = new Patient
                    {
                        Account = new Account
                        {
                            Username     = model.Username,
                            Password     = model.Password,
                            Email        = model.Email,
                            CreationDate = DateTime.Now
                        },
                        FirstName      = model.FirstName,
                        LastName       = model.LastName,
                        BirthDate      = model.BirthDate.Value,
                        Status         = model.Status,
                        Gender         = model.Gender,
                        Telephone      = model.Telephone,
                        Address        = model.Address,
                        MedicareNumber = model.MedicareNumber
                    };

                    _repository.Add(entity);
                    _repository.Commit();

                    model.AccountId = entity.AccountId;

                    return(base.Ok(model));
                }
                else
                {
                    return(base.BadRequest(ModelState));
                }
            }
            catch (Exception ex)
            {
                return(base.BadRequest(ex.Message));
            }
        }
Ejemplo n.º 25
0
        public async Task <IActionResult> CreatePatient(PatientWriteDtoModel model)
        {
            // we can use auto mapper to map internal model to dto
            PatientModel entity = new PatientModel
            {
                DateOfBirth  = model.DateOfBirth,
                EmailAddress = model.EmailAddress,
                MetaData     = model.MetaData.Select(x => new MetaDataModel {
                    Key = x.Key, Value = x.Value
                }).ToList(),
                PatientName = model.PatientName,
                OfficialID  = model.OfficialID
            };

            _patientRepository.Add(entity);
            if (_patientRepository.SaveChanges())
            {
                return(Ok(new { message = "Patient added successfully." }));
            }

            return(BadRequest());
        }
Ejemplo n.º 26
0
        public IActionResult Create(Patient patient)
        {
            if (ModelState.IsValid)
            {
                var logged_usr_id        = signInManager.UserManager.GetUserId(User);
                var logged_user_hospital = userManager.Users
                                           .Where(usr => usr.Id == logged_usr_id)
                                           .FirstOrDefault();
                patient.Hospital = logged_user_hospital;

                var already_patient = patientRepository.GetPatientByCitizenId(patient.CitizenId);
                if (already_patient != null)
                {
                    //already citizen is patient
                    TempData["ErrorMessage"] = "You are already a Patient and already Hospitalized!";
                    return(RedirectToAction("Index"));
                }

                Patient newPatient = patientRepository.Add(patient);
                TempData["SuccessMessage"] = "Patient Hospitalized Successfully!";
            }
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 27
0
        public async Task <Patient> AddPatientAsync(int hospitalId, int illnessId, int levelOfPain)
        {
            // add patient to hospital
            var hospital = await _hospitalRepository.GetAsync(hospitalId);

            if (hospital == null)
            {
                return(null);
            }

            var waiting = hospital.WaitingList.FirstOrDefault(x => x.LevelOfPain == levelOfPain);

            if (waiting == null)
            {
                return(null);
            }

            waiting.PatientCount += 1;

            await _hospitalRepository.SaveAsync(hospital);

            // calculate the waiting time
            var waitingTime = await GetHospitalsWatingTimeAsync();

            waitingTime[hospitalId] = hospital.WaitingTotal;

            // save patient
            var patient = _patientRepository.Add(new Patient
            {
                Id          = Guid.NewGuid(),
                HospitalId  = hospitalId,
                IllnessId   = illnessId,
                LevelOfPain = levelOfPain
            });

            return(patient);
        }
Ejemplo n.º 28
0
        public ActionResult Create(PatientEditViewModel creatingPatient) //[Bind(Include = "Id,Name,DayOfBirth,Status,TaxCode, ")]
        {
            List <Doctor> docs = new List <Doctor>();

            if (creatingPatient.SelectedDoctorsId != null)
            {
                docs.AddRange(repo.GetDoctorsById(creatingPatient.SelectedDoctorsId.ToArray <int>()));
            }
            if (ModelState.IsValid)
            {
                Patient newPatient = new Patient
                {
                    Doctors    = docs,
                    DayOfBirth = creatingPatient.DayOfBirth,
                    Name       = creatingPatient.Name,
                    Status     = creatingPatient.Status,
                    TaxCode    = creatingPatient.TaxCode
                };
                repo.Add(newPatient);
                return(RedirectToAction("Index"));
            }
            creatingPatient.DoctorSelectList = GetDoctorsSelectList(creatingPatient.SelectedDoctorsId.ToArray <int>());
            return(View(creatingPatient));
        }
Ejemplo n.º 29
0
        public async Task <PatientResponse> AddPatientAsync(AddPatientRequest request)
        {
            var patient = _patientMapper.Map(request);

            Patient result = _patientRepository.Add(patient);

            await _patientRepository.UnitOfWork.SaveChangesAsync();


            // Create new records in joining table:
            if (request.RiskFactors != null && result != null)
            {
                foreach (GetRiskFactorRequest riskFactor in request.RiskFactors)
                {
                    AddPatientRiskFactorRequest addPRFRequest = new AddPatientRiskFactorRequest
                    {
                        PatientId    = result.Id,
                        RiskFactorId = riskFactor.Id
                    };
                    await _patientRiskFactorService.AddPatientRiskFactor(addPRFRequest);
                }
            }
            return(_patientMapper.Map(result));
        }
Ejemplo n.º 30
0
 public void Put(int id, [FromBody] Location location)
 {
     PatientRepository.Add(id, location);
 }