public DependentModel GETeditMethod(int?id)
        {
            DependentModel cv = new DependentModel();

            using (var deprepo = new DependentRepository())
            {
                if (id.HasValue && id != 0)
                {
                    Dependent _dependent = deprepo.GetById(id.Value);

                    cv.DependentId      = _dependent.DependentId;
                    cv.IdentityNo       = _dependent.IdentityNo;
                    cv.DependentFname   = _dependent.DependentFname;
                    cv.DependentSname   = _dependent.DependentSname;
                    cv.DependentRole    = _dependent.DependentRole;
                    cv.DOB_Dependent    = _dependent.DOB_Dependent;
                    cv.Sex              = _dependent.Sex;
                    cv.Title            = _dependent.Title;
                    cv.Age              = _dependent.Age;
                    cv.DependentAllergy = _dependent.DependentAllergy;
                }

                return(cv);
            }
        }
        public void NoDiscountApplied(string dependentName)
        {
            //Arrange
            int     dependentCost = 500;
            decimal discount      = .1m;

            var rule = new DependentRule(
                dependentCost: dependentCost,
                discount: discount
                );

            DependentModel dependentModel = new DependentModel()
            {
                Name = dependentName
            };

            CalculatorResult result = new CalculatorResult();


            //Act
            rule.Calculate(dependentModel, result);


            //Assert
            decimal expectedTotalCost = dependentCost;

            Assert.AreEqual(dependentCost, result.Total);

            Assert.AreEqual(1, result.Results.Count);

            Assert.AreEqual(CostCodeEnum.DependentBaseCost, result.Results[0].CostCode);
            Assert.AreEqual(dependentCost, result.Results[0].Value);

            Assert.AreEqual(0, result.SubResults.Count);
        }
        public void ShouldDeleteDependent()
        {
            string         delegateId     = hdid;
            string         dependentId    = "123";
            DependentModel dependentModel = new DependentModel()
            {
                DelegateId = delegateId, OwnerId = dependentId
            };

            RequestResult <DependentModel> expectedResult = new RequestResult <DependentModel>()
            {
                ResourcePayload = dependentModel,
                ResultStatus    = Common.Constants.ResultType.Success,
            };

            Mock <IDependentService> dependentServiceMock = new Mock <IDependentService>();

            dependentServiceMock.Setup(s => s.Remove(dependentModel)).Returns(expectedResult);

            Mock <IHttpContextAccessor> httpContextAccessorMock = CreateValidHttpContext(token, userId, hdid);

            DependentController dependentController = new DependentController(
                new Mock <ILogger <UserProfileController> >().Object,
                dependentServiceMock.Object,
                httpContextAccessorMock.Object
                );
            var actualResult = dependentController.Delete(delegateId, dependentId, dependentModel);

            Assert.IsType <JsonResult>(actualResult);
            Assert.True(((JsonResult)actualResult).Value.IsDeepEqual(expectedResult));
        }
        public void CreateMethod(DependentModel cv, int patientid, string Gender, string Role, string Title)
        {
            using (var deprepo = new DependentRepository())
            {
                //if (cv.DependentId == 0)
                //{
                //string date = cv.DOB_Dependent.ToString("d");
                string result      = cv.DOB_Dependent.Substring(6);
                int    currentyear = DateTime.Now.Year;

                int       age        = currentyear - Convert.ToInt32(result);
                Dependent _dependent = new Dependent
                {
                    DependentId      = cv.DependentId,
                    IdentityNo       = cv.IdentityNo,
                    DependentFname   = cv.DependentFname,
                    DependentSname   = cv.DependentSname,
                    DependentRole    = Role,
                    DOB_Dependent    = cv.DOB_Dependent,  //date,
                    Sex              = Gender,
                    Title            = Title,
                    Age              = Convert.ToString(age),
                    DependentAllergy = cv.DependentAllergy,
                    PatientId        = patientid
                };

                deprepo.Insert(_dependent);
                //}
            }
        }
        public DependentModel DetailsMethod(int?id)
        {
            DependentModel cv = new DependentModel();

            using (var deprepo = new DependentRepository())
            {
                if (id.HasValue && id != 0)
                {
                    Dependent _dep = deprepo.GetById(id.Value);

                    cv.DependentId      = _dep.DependentId;
                    cv.IdentityNo       = _dep.IdentityNo;
                    cv.DependentFname   = _dep.DependentFname;
                    cv.DependentSname   = _dep.DependentSname;
                    cv.Title            = _dep.Title;
                    cv.Age              = _dep.Age;
                    cv.DependentRole    = _dep.DependentRole;
                    cv.DOB_Dependent    = _dep.DOB_Dependent;
                    cv.Sex              = _dep.Sex;
                    cv.DependentAllergy = _dep.DependentAllergy;
                    cv.patientName      = _dep.PatientId.ToString();
                }

                return(cv);
            }
        }
        public void AdditionalCreateMethod(DependentModel cv, int patientid, string Gender, string Role, string Title)
        {
            using (var deprepo = new DependentRepository())
            {
                if (cv.DependentId == 0)
                {
                    //int paid = Convert.ToInt32(patientid);
                    //var patientemailKey = da.Patients.ToList().Find(x => x.PatientId == paid);

                    //string date = cv.DOB_Dependent.ToString("d");
                    string result      = cv.DOB_Dependent.Substring(6);
                    int    currentyear = DateTime.Now.Year;

                    int age = currentyear - Convert.ToInt32(result);

                    Dependent _dependent = new Dependent
                    {
                        DependentId      = cv.DependentId,
                        IdentityNo       = cv.IdentityNo,
                        DependentFname   = cv.DependentFname,
                        DependentSname   = cv.DependentSname,
                        DependentRole    = Role,
                        Title            = cv.Title,
                        DOB_Dependent    = cv.DOB_Dependent, //date,
                        Sex              = Gender,
                        Age              = Convert.ToString(age),
                        DependentAllergy = cv.DependentAllergy,
                        PatientId        = patientid
                    };

                    deprepo.Insert(_dependent);
                }
            }
        }
        public DependentModel GETdeleteMethod(int id)
        {
            DependentModel cv = new DependentModel();

            using (var deprepo = new DependentRepository())
            {
                if (id != 0)
                {
                    Dependent _dependent = deprepo.GetById(id);

                    cv.DependentId      = _dependent.DependentId;
                    cv.IdentityNo       = _dependent.IdentityNo;
                    cv.DependentFname   = _dependent.DependentFname;
                    cv.DependentSname   = _dependent.DependentSname;
                    cv.DependentRole    = _dependent.DependentRole;
                    cv.DOB_Dependent    = _dependent.DOB_Dependent;
                    cv.Sex              = _dependent.Sex;
                    cv.Title            = _dependent.Title;
                    cv.Age              = _dependent.Age;
                    cv.DependentAllergy = _dependent.DependentAllergy;
                    cv.patientName      = _dependent.PatientId.ToString();
                }

                return(cv);
            }
        }
        public void ShouldAddDependent()
        {
            Mock <IHttpContextAccessor> httpContextAccessorMock = CreateValidHttpContext(token, userId, hdid);
            Mock <IDependentService>    dependentServiceMock    = new Mock <IDependentService>();
            DependentModel expectedDependend = new DependentModel()
            {
                OwnerId              = $"OWNER",
                DelegateId           = $"DELEGATER",
                Version              = (uint)1,
                DependentInformation = new DependentInformation()
                {
                    DateOfBirth = new DateTime(1980, 1, 1),
                    Gender      = "Female",
                    FirstName   = firstName,
                    LastName    = lastname,
                }
            };
            RequestResult <DependentModel> expectedResult = new RequestResult <DependentModel>()
            {
                ResourcePayload = expectedDependend,
                ResultStatus    = Common.Constants.ResultType.Success,
            };

            dependentServiceMock.Setup(s => s.AddDependent(hdid, It.IsAny <AddDependentRequest>())).Returns(expectedResult);

            DependentController dependentController = new DependentController(
                new Mock <ILogger <UserProfileController> >().Object,
                dependentServiceMock.Object,
                httpContextAccessorMock.Object
                );
            var actualResult = dependentController.AddDependent(new AddDependentRequest());

            Assert.True(((JsonResult)actualResult).Value.IsDeepEqual(expectedResult));
        }
        public void ValidateRemove()
        {
            DependentModel delegateModel = new DependentModel()
            {
                OwnerId = mockHdId, DelegateId = mockParentHdId
            };
            Mock <IUserDelegateDelegate> mockDependentDelegate = new Mock <IUserDelegateDelegate>();

            mockDependentDelegate.Setup(s => s.Delete(It.Is <UserDelegate>(d => d.OwnerId == mockHdId && d.DelegateId == mockParentHdId), true)).Returns(new DBResult <UserDelegate>()
            {
                Status = DBStatusCode.Deleted,
            });

            Mock <IUserProfileDelegate> mockUserProfileDelegate = new Mock <IUserProfileDelegate>();

            mockUserProfileDelegate.Setup(s => s.GetUserProfile(mockParentHdId)).Returns(new DBResult <UserProfile>()
            {
                Payload = new UserProfile()
            });
            Mock <INotificationSettingsService> mockNotificationSettingsService = new Mock <INotificationSettingsService>();

            mockNotificationSettingsService.Setup(s => s.QueueNotificationSettings(It.IsAny <NotificationSettingsRequest>()));
            IDependentService service = new DependentService(
                new Mock <ILogger <DependentService> >().Object,
                mockUserProfileDelegate.Object,
                new Mock <IPatientService>().Object,
                mockNotificationSettingsService.Object,
                mockDependentDelegate.Object
                );
            RequestResult <DependentModel> actualResult = service.Remove(delegateModel);

            Assert.Equal(Common.Constants.ResultType.Success, actualResult.ResultStatus);
        }
Пример #10
0
        public async Task ReadsOnlyPermittedEntries()
        {
            var users = new[] {
                ManagedAuthenticationHandler.AuthorizedJson1,
                ManagedAuthenticationHandler.AuthorizedJson2
            };
            var totalEntitiesPerUser = 6;
            var model = new DependentModel
            {
                Value  = "some-value",
                Public = false
            };

            foreach (var usr in users)
            {
                HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(usr);
                for (var i = 0; i < totalEntitiesPerUser; i++)
                {
                    var r = await HttpClient.PostAsJsonAsync("dependentmodel", model);

                    r.EnsureSuccessStatusCode();
                }
            }
            var c = await HttpClient.GetStringAsync($"dependentmodel?query=value ==\"" + model.Value + "\"");

            var jObj = JObject.Parse(c);
            var jArr = jObj["data"] as JArray;

            jArr.Count.ShouldBe(totalEntitiesPerUser);
        }
Пример #11
0
        public void Create_CanHandleNull(bool isNull, int timesRepoCalled)
        {
            DependentModel dependentModel = isNull ? null : new DependentModel();

            var result = sut.Create(dependentModel);

            dependentsRepository.Verify(x => x.Create(It.IsAny <DependentDataModel>()), Times.Exactly(timesRepoCalled));
            loggerRepository.Verify(x => x.Log(It.IsAny <Exception>()), Times.Never);
        }
Пример #12
0
        public async Task <DependentModel> SaveDependent(DependentModel Dependent)
        {
            using (var unitOfWork = _unitOfWorkFactory.CreateUnitOfWork())
            {
                var retval = await _dependentDal.SaveDependent(unitOfWork, Dependent);

                await unitOfWork.Complete();

                return(retval);
            }
        }
Пример #13
0
        public ActionResult AddDependent(int?PatientId)
        {
            var user = pb.GetPatients().Find(x => x.PatientId == PatientId.Value);

            var model = new DependentModel
            {
                patientName = user.Title + " " + user.FullName.ToUpper() + " " + user.Surname.ToUpper()
            };

            return(View(model));
        }
Пример #14
0
        /// <inheritdoc />
        public RequestResult <IEnumerable <DependentModel> > GetDependents(string hdId, int page, int pageSize)
        {
            // Get Dependents from database
            int offset = page * pageSize;
            DBResult <IEnumerable <ResourceDelegate> > dbResourceDelegates = this.resourceDelegateDelegate.Get(hdId, offset, pageSize);

            // Get Dependents Details from Patient service
            List <DependentModel> dependentModels = new List <DependentModel>();
            RequestResult <IEnumerable <DependentModel> > result = new RequestResult <IEnumerable <DependentModel> >()
            {
                ResultStatus = ResultType.Success,
            };
            StringBuilder resultErrorMessage = new StringBuilder();

            foreach (ResourceDelegate resourceDelegate in dbResourceDelegates.Payload)
            {
                this.logger.LogDebug($"Getting dependent details for Dependent hdid: {resourceDelegate.ResourceOwnerHdid} ...");
                RequestResult <PatientModel> patientResult = Task.Run(async() => await this.patientService.GetPatient(resourceDelegate.ResourceOwnerHdid, PatientIdentifierType.HDID).ConfigureAwait(true)).Result;

                if (patientResult.ResourcePayload != null)
                {
                    dependentModels.Add(DependentModel.CreateFromModels(resourceDelegate, patientResult.ResourcePayload));
                }
                else
                {
                    if (result.ResultStatus != ResultType.Error)
                    {
                        result.ResultStatus = ResultType.Error;
                        resultErrorMessage.Append($"Communication Exception when trying to retrieve Dependent(s) - HdId: {resourceDelegate.ResourceOwnerHdid};");
                    }
                    else
                    {
                        resultErrorMessage.Append($" HdId: {resourceDelegate.ResourceOwnerHdid};");
                    }
                }
            }

            result.ResourcePayload = dependentModels;
            if (result.ResultStatus != ResultType.Error)
            {
                result.ResultStatus     = ResultType.Success;
                result.ResultError      = null;
                result.TotalResultCount = dependentModels.Count;
            }
            else
            {
                result.ResultError = new RequestResultError()
                {
                    ResultMessage = resultErrorMessage.ToString(), ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationExternal, ServiceType.Patient)
                };
            }

            return(result);
        }
Пример #15
0
 public DependentDataModel(DependentModel dependentModel, decimal discountAmount)
 {
     EmployeeId = dependentModel?.EmployeeId ?? 0;
     DependentId = dependentModel?.DependentId ?? 0;
     DependentName = dependentModel?.DependentName ?? string.Empty;
     BenefitCost = new BenefitCostDataModel()
     {
         IsDependent = true,
         DiscountAmount = discountAmount,
         BaseDeductionCost = 500,
     };
 }
Пример #16
0
        public IActionResult Delete(string hdid, string dependentHdid, [FromBody] DependentModel dependent)
        {
            if (dependent.OwnerId != dependentHdid || dependent.DelegateId != hdid)
            {
                this.logger.LogError($"Parameters do not match body of delete.");
                return(new BadRequestResult());
            }

            RequestResult <DependentModel> result = this.dependentService.Remove(dependent);

            return(new JsonResult(result));
        }
        //#region GetAllDependents...
        //public List<DependentModel> GetAllStaffDependents(int Id)
        //{
        //    RegisterRepository rp = new RegisterRepository();
        //    using (var deprepo = new DependentRepository())
        //    {
        //        var name = rp.GetAll().ToList().Find(x => x.Id == Id);

        //        var user = deprepo.GetAll().FindAll(x => x.PatientId == Id).ToList();

        //        return user.Select(x => new DependentModel()
        //        {
        //            DependentId = x.DependentId,
        //            IdentityNo = x.IdentityNo,
        //            DependentFname = x.DependentFname,
        //            DependentSname = x.DependentSname,
        //            DependentRole = x.DependentRole,
        //            DOB_Dependent = x.DOB_Dependent,
        //            Sex = x.Sex,
        //            Title = x.Title,
        //            Age = x.Age,
        //            DependentAllergy = x.DependentAllergy,
        //            patientName = name.FullName
        //        }).ToList();
        //    }
        //}
        //#endregion

        #region GetDependentId...
        public DependentModel GetDependentId(int?id)
        {
            DependentModel cv = new DependentModel();

            using (var deprepo = new DependentRepository())
            {
                Dependent _dep = deprepo.GetById(id.Value);

                cv.DependentId = _dep.DependentId;

                return(cv);
            }
        }
Пример #18
0
 public ActionResult Create(DependentModel _depmodel, int PatientId, string Gender, string Role, string Title)
 {
     try
     {
         PatientId = Convert.ToInt32(System.Web.HttpContext.Current.Session["_Patient"]);
         db.AdditionalCreateMethod(_depmodel, PatientId, Gender, Role, Title);
         TempData["Msg"] = "Data has been saved succeessfully";
         return(RedirectToAction("Index", "Dependent", new { patId = PatientId }));
     }
     catch
     {
         return(View());
     }
 }
Пример #19
0
 public ActionResult Edit(int id, DependentModel _depmodel)
 {
     try
     {
         // TODO: Add update logic here
         db.PostEditMethod(_depmodel);
         TempData["Msg"] = "Data has been updated succeessfully";
         return(RedirectToAction("Index", "Dependent", new { patId = db.GetDependentId(id).PatientId }));
     }
     catch
     {
         return(PartialView());
     }
 }
        public DependentModel PostEditMethod(DependentModel cv)
        {
            //string date = cv.DOB_Dependent.ToString("d");
            string result      = cv.DOB_Dependent.Substring(6);
            int    currentyear = DateTime.Now.Year;

            int age = currentyear - Convert.ToInt32(result);

            using (var deprepo = new DependentRepository())
            {
                if (cv.DependentId == 0)
                {
                    Dependent _dependent = new Dependent
                    {
                        DependentId      = cv.DependentId,
                        IdentityNo       = cv.IdentityNo,
                        DependentFname   = cv.DependentFname,
                        DependentSname   = cv.DependentSname,
                        DependentRole    = cv.DependentRole,
                        DOB_Dependent    = cv.DOB_Dependent, //date,
                        Sex              = cv.Sex,
                        Title            = cv.Title,
                        Age              = Convert.ToString(age),
                        DependentAllergy = cv.DependentAllergy,
                    };

                    deprepo.Insert(_dependent);
                }

                else
                {
                    Dependent _dependent = deprepo.GetById(cv.DependentId);

                    _dependent.DependentId      = cv.DependentId;
                    _dependent.IdentityNo       = cv.IdentityNo;
                    _dependent.DependentFname   = cv.DependentFname;
                    _dependent.DependentSname   = cv.DependentSname;
                    _dependent.DependentRole    = cv.DependentRole;
                    _dependent.DOB_Dependent    = cv.DOB_Dependent;// date;
                    _dependent.Sex              = cv.Sex;
                    _dependent.Age              = Convert.ToString(age);
                    _dependent.Title            = cv.Title;
                    _dependent.DependentAllergy = cv.DependentAllergy;

                    deprepo.Update(_dependent);
                }

                return(cv);
            }
        }
Пример #21
0
        public ActionResult Create()
        {
            int patientid = Convert.ToInt32(System.Web.HttpContext.Current.Session["PatientId"]);

            System.Web.HttpContext.Current.Session["Cancel"] = patientid;
            var user = pb.GetPatients().Find(x => x.PatientId == patientid);

            var model = new DependentModel
            {
                patientName = user.Title + " " + user.FullName.ToUpper() + " " + user.Surname.ToUpper()
            };

            return(View(model));
        }
Пример #22
0
 public ActionResult Delete(int id, DependentModel _depmodel)
 {
     try
     {
         // TODO: Add delete logic here
         int thisId = id;
         db.PostDeleteMethod(id);
         TempData["Msg"] = "Data has been deleted succeessfully";
         return(RedirectToAction("Index", "PatientDependent", new { patId = db.GetDependentId(id).PatientId }));
     }
     catch
     {
         return(PartialView());
     }
 }
Пример #23
0
        public ActionResult Editfromprofile(int id, DependentModel _depmodel)
        {
            try
            {
                int PatientId = Convert.ToInt32(System.Web.HttpContext.Current.Session["DpId"]);

                // TODO: Add update logic here
                db.PostEditMethod(_depmodel);
                TempData["Msg"] = "Data has been updated succeessfully";
                return(RedirectToAction("ViewPatient", "Patient", new { PatientId = PatientId }));
            }
            catch
            {
                return(PartialView());
            }
        }
Пример #24
0
        public async Task <int> Create(DependentModel dependent)
        {
            try
            {
                if (dependent != null)
                {
                    decimal discount = dependent.DependentName?.StartsWith("a", StringComparison.OrdinalIgnoreCase) == true ? .10m : 0;
                    return(await dependentsRepository.Create(new DependentDataModel(dependent, discount)));
                }

                return(0);
            }
            catch (Exception ex)
            {
                await loggerRepository.Log(ex).ConfigureAwait(false);

                throw;
            }
        }
Пример #25
0
        /// <inheritdoc />
        public RequestResult <DependentModel> Remove(DependentModel dependent)
        {
            DBResult <ResourceDelegate> dbDependent = this.resourceDelegateDelegate.Delete(dependent.ToDBModel(), true);

            if (dbDependent.Status == DBStatusCode.Deleted)
            {
                this.UpdateNotificationSettings(dependent.OwnerId, dependent.DelegateId, isDelete: true);
            }

            RequestResult <DependentModel> result = new RequestResult <DependentModel>()
            {
                ResourcePayload = new DependentModel(),
                ResultStatus    = dbDependent.Status == DBStatusCode.Deleted ? ResultType.Success : ResultType.Error,
                ResultError     = dbDependent.Status == DBStatusCode.Deleted ? null : new RequestResultError()
                {
                    ResultMessage = dbDependent.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database)
                },
            };

            return(result);
        }
Пример #26
0
        public async Task <DependentModel> SaveDependent(UnitOfWork unitOfWork, DependentModel model)
        {
            try
            {
                var entity = new Dependent {
                    Id = model.Id, EmployeeId = model.EmployeeId, FirstName = model.FirstName, LastName = model.LastName
                };

                var trackedEntity =
                    await unitOfWork.PayrollContext.Dependents.FirstOrDefaultAsync(x => x.Id == model.Id);

                if (trackedEntity != null)
                {
                    entity.Id = trackedEntity.Id;
                }
                else
                {
                    trackedEntity = unitOfWork.PayrollContext.Dependents.Create();
                    unitOfWork.PayrollContext.Dependents.Add(trackedEntity);
                }

                unitOfWork.PayrollContext.Entry(trackedEntity).CurrentValues.SetValues(entity);

                await unitOfWork.PayrollContext.SaveChangesAsync();

                return(new DependentModel()
                {
                    Id = trackedEntity.Id,
                    EmployeeId = trackedEntity.EmployeeId,
                    FirstName = trackedEntity.FirstName,
                    LastName = trackedEntity.LastName
                });
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                throw;
            }
        }
Пример #27
0
        public ActionResult Create(int?PatientId)
        {
            if (PatientId.HasValue)
            {
                var name = pb.GetPatients().Find(x => x.PatientId == PatientId.Value);

                var model = new DependentModel
                {
                    patientName = name.FullName.ToUpper() + " " + name.Surname.ToUpper(),
                    DDLName     = db.DDPatient()
                };

                System.Web.HttpContext.Current.Session["_Patient"] = PatientId;
                return(View(model));
            }

            //var model = new DependentModel
            //{
            //    patientName = name.
            //    DDLName = db.DDPatient()
            //};

            return(View());
        }
Пример #28
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public EmployeeModel()
 {
     Dependents = new DependentModel[] { };
 }
 public async Task <DependentModel> SaveDependent(DependentModel dependent)
 {
     return(await _dependentService.SaveDependent(dependent));
 }
Пример #30
0
        /// <inheritdoc />
        public RequestResult <DependentModel> AddDependent(string delegateHdId, AddDependentRequest addDependentRequest)
        {
            this.logger.LogTrace($"Dependent hdid: {delegateHdId}");
            this.logger.LogDebug("Getting dependent details...");
            RequestResult <PatientModel> patientResult = Task.Run(async() => await this.patientService.GetPatient(addDependentRequest.PHN, PatientIdentifierType.PHN).ConfigureAwait(true)).Result;

            if (patientResult.ResourcePayload == null)
            {
                return(new RequestResult <DependentModel>()
                {
                    ResultStatus = ResultType.Error,
                    ResultError = new RequestResultError()
                    {
                        ResultMessage = "Communication Exception when trying to retrieve the Dependent", ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationExternal, ServiceType.Patient)
                    },
                });
            }

            // Verify dependent's details entered by user
            if (!addDependentRequest.Equals(patientResult.ResourcePayload))
            {
                return(new RequestResult <DependentModel>()
                {
                    ResultStatus = ResultType.Error,
                    ResultError = new RequestResultError()
                    {
                        ResultMessage = "The information you entered did not match. Please try again.", ErrorCode = ErrorTranslator.ServiceError(ErrorType.InvalidState, ServiceType.Patient)
                    },
                });
            }
            else
            {
                // Insert Dependent to database
                var dependent = new UserDelegate()
                {
                    OwnerId = patientResult.ResourcePayload.HdId, DelegateId = delegateHdId
                };

                DBResult <UserDelegate> dbDependent = this.userDelegateDelegate.Insert(dependent, true);
                if (dbDependent.Status == DBStatusCode.Created)
                {
                    this.logger.LogDebug("Finished adding dependent");
                    this.UpdateNotificationSettings(dependent.OwnerId, delegateHdId);
                    return(new RequestResult <DependentModel>()
                    {
                        ResourcePayload = DependentModel.CreateFromModels(dbDependent.Payload, patientResult.ResourcePayload),
                        ResultStatus = ResultType.Success,
                    });
                }
                else
                {
                    this.logger.LogError("Error adding dependent");
                    return(new RequestResult <DependentModel>()
                    {
                        ResourcePayload = new DependentModel(),
                        ResultStatus = ResultType.Error,
                        ResultError = new RequestResultError()
                        {
                            ResultMessage = dbDependent.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database)
                        },
                    });
                }
            }
        }
Пример #31
0
        /// <inheritdoc />
        public RequestResult <DependentModel> AddDependent(string delegateHdId, AddDependentRequest addDependentRequest)
        {
            this.logger.LogTrace($"Dependent hdid: {delegateHdId}");

            int?maxDependentAge = this.configurationService.GetConfiguration().WebClient.MaxDependentAge;

            if (maxDependentAge.HasValue)
            {
                DateTime minimumBirthDate = DateTime.UtcNow.AddYears(maxDependentAge.Value * -1);
                if (addDependentRequest.DateOfBirth < minimumBirthDate)
                {
                    return(new RequestResult <DependentModel>()
                    {
                        ResultStatus = ResultType.Error,
                        ResultError = new RequestResultError()
                        {
                            ResultMessage = "Dependent age exceeds the maximum limit", ErrorCode = ErrorTranslator.ServiceError(ErrorType.InvalidState, ServiceType.Patient)
                        },
                    });
                }
            }

            this.logger.LogTrace("Getting dependent details...");
            RequestResult <PatientModel> patientResult = Task.Run(async() => await this.patientService.GetPatient(addDependentRequest.PHN, PatientIdentifierType.PHN).ConfigureAwait(true)).Result;

            if (patientResult.ResultStatus == ResultType.Error)
            {
                return(new RequestResult <DependentModel>()
                {
                    ResultStatus = ResultType.Error,
                    ResultError = new RequestResultError()
                    {
                        ResultMessage = "Communication Exception when trying to retrieve the Dependent", ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationExternal, ServiceType.Patient)
                    },
                });
            }

            if (patientResult.ResultStatus == ResultType.ActionRequired)
            {
                return(new RequestResult <DependentModel>()
                {
                    ResultStatus = ResultType.ActionRequired,
                    ResultError = ErrorTranslator.ActionRequired(ErrorMessages.DataMismatch, ActionType.DataMismatch),
                });
            }

            this.logger.LogDebug($"Finished getting dependent details...{JsonSerializer.Serialize(patientResult)}");

            // Verify dependent's details entered by user
            if (patientResult.ResourcePayload == null || !this.ValidateDependent(addDependentRequest, patientResult.ResourcePayload))
            {
                this.logger.LogDebug($"Dependent information does not match request: {JsonSerializer.Serialize(addDependentRequest)} response: {JsonSerializer.Serialize(patientResult.ResourcePayload)}");
                return(new RequestResult <DependentModel>()
                {
                    ResultStatus = ResultType.ActionRequired,
                    ResultError = ErrorTranslator.ActionRequired(ErrorMessages.DataMismatch, ActionType.DataMismatch),
                });
            }

            // Verify dependent has HDID
            if (string.IsNullOrEmpty(patientResult.ResourcePayload.HdId))
            {
                return(new RequestResult <DependentModel>()
                {
                    ResultStatus = ResultType.ActionRequired,
                    ResultError = ErrorTranslator.ActionRequired(ErrorMessages.InvalidServicesCard, ActionType.NoHdId),
                });
            }

            string       json    = JsonSerializer.Serialize(addDependentRequest.TestDate, addDependentRequest.TestDate.GetType());
            JsonDocument jsonDoc = JsonDocument.Parse(json);

            // Insert Dependent to database
            var dependent = new ResourceDelegate()
            {
                ResourceOwnerHdid = patientResult.ResourcePayload.HdId,
                ProfileHdid       = delegateHdId,
                ReasonCode        = ResourceDelegateReason.COVIDLab,
                ReasonObjectType  = addDependentRequest.TestDate.GetType().AssemblyQualifiedName,
                ReasonObject      = jsonDoc,
            };
            DBResult <ResourceDelegate> dbDependent = this.resourceDelegateDelegate.Insert(dependent, true);

            if (dbDependent.Status == DBStatusCode.Created)
            {
                this.logger.LogTrace("Finished adding dependent");
                this.UpdateNotificationSettings(dependent.ResourceOwnerHdid, delegateHdId);

                return(new RequestResult <DependentModel>()
                {
                    ResourcePayload = DependentModel.CreateFromModels(dbDependent.Payload, patientResult.ResourcePayload),
                    ResultStatus = ResultType.Success,
                });
            }
            else
            {
                this.logger.LogError("Error adding dependent");
                return(new RequestResult <DependentModel>()
                {
                    ResourcePayload = new DependentModel(),
                    ResultStatus = ResultType.Error,
                    ResultError = new RequestResultError()
                    {
                        ResultMessage = dbDependent.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database)
                    },
                });
            }
        }