Example #1
0
        public async Task <IActionResult> CreatePolicy(PolicyDto policyForCreateDto)
        {
            var policyToCreate = new Policy();

            //Auto maping Dto to entity
            _mapper.Map(policyForCreateDto, policyToCreate);
            _repo.Add(policyToCreate);

            if (await _repo.SaveAll())
            {
                return(Ok());
            }

            throw new Exception($"Creating policy {policyForCreateDto.Name} failed on save");
        }
Example #2
0
        public async Task <bool> Execute(string subject, string id)
        {
            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentNullException(nameof(subject));
            }

            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentNullException(nameof(id));
            }

            var result = await _pendingRequestRepository.Get(id).ConfigureAwait(false);

            if (result == null)
            {
                throw new UmaPolicyNotFoundException();
            }

            if (result.Resource.Owner != subject)
            {
                throw new UmaNotAuthorizedException();
            }

            using (var transaction = new CommittableTransaction(new TransactionOptions {
                IsolationLevel = IsolationLevel.ReadCommitted
            }))
            {
                try
                {
                    result.IsConfirmed = true;
                    await _pendingRequestRepository.Delete(result.Id).ConfigureAwait(false);

                    await _policyRepository.Add(new Models.Policy
                    {
                        Id     = Guid.NewGuid().ToString(),
                        Claims = new List <Models.Claim>
                        {
                            new Models.Claim
                            {
                                Type  = SimpleIdServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject,
                                Value = result.RequesterSubject
                            }
                        },
                        ResourceSetIds = new List <string>
                        {
                            result.ResourceId
                        },
                        Scopes = result.Scopes == null ? new List <string>() : result.Scopes.ToList()
                    }).ConfigureAwait(false);
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }

            return(true);
        }
Example #3
0
        public IActionResult Add([FromBody] Policy policy)
        {
            try
            {
                if (policy.IsObjectNull())
                {
                    return(BadRequest("Policy object is null"));
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest("Invalid model object"));
                }

                var dbPolicy = _policyRepository.GetById(policy.PolicyNumber);
                if (dbPolicy.IsObjectNull() == false)
                {
                    return(BadRequest("Policy number already exists"));
                }

                _policyRepository.Add(policy);

                return(CreatedAtRoute("GetDetails", new { policyNumber = policy.PolicyNumber }, policy));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, "Internal server error"));
            }
        }
Example #4
0
        public bool AddPolicy(PolicyModel policy)
        {
            var entity = new Policie()
            {
                PolicyNumber     = policy.PolicyNumber,
                CarId            = policy.CarId,
                EffectiveDate    = (DateTime)policy.EffectiveDate,
                EndDate          = (DateTime)policy?.EndDate,
                IsGroupInsurance = policy.IsGroupInsurance,
                IsActive         = true,
                AddUser          = LoginUserDetails.GetWindowsLoginUserName(),
                AddDate          = DateUtil.GetCurrentDate(),
                CoverageId       = policy.CoverageId,
                ProductId        = policy.ProductId
            };

            _policyRepository.Add(entity);

            var latestPolicy = _policyRepository.GetAll().OrderByDescending(p => p.Id).FirstOrDefault();

            if (latestPolicy != null)
            {
                var clientPolocieModel = new ClientPolicie()
                {
                    ClientId  = policy.ClientId,
                    PolicieId = latestPolicy.Id,
                    IsActive  = true,
                    AddUser   = LoginUserDetails.GetWindowsLoginUserName(),
                    AddDate   = DateUtil.GetCurrentDate()
                };
                _commonService.AddClientPolocie(clientPolocieModel);
            }

            return(true);
        }
Example #5
0
        public async Task <Policy> Add(Policy policy)
        {
            if (string.IsNullOrEmpty(policy.PolicyHolder.Name))
            {
                return(null);
            }

            return(await _repository.Add(policy));
        }
        public IActionResult CreatePolicy([FromBody] Policy policy)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            //var policy = mapper.Map<EmployeeResource, Employee>(employeeResource);

            _policyRepository.Add(policy);

            return(Ok(policy));
        }
Example #7
0
 public async Task Handle(PolicyCreated notification, CancellationToken cancellationToken)
 {
     await policis.Add(new Policy
     {
         PolicyNumber    = notification.PolicyNumber,
         PolicyStartDate = notification.PolicyFrom,
         PolicyEndDate   = notification.PolicyTo,
         ProductCode     = notification.ProductCode,
         PolicyHolder    = $"{notification.PolicyHolder.FirstName} {notification.PolicyHolder.LastName}",
         PremiumAmount   = notification.TotalPremium,
     });
 }
        public List <PolicyDTO> Add(List <PolicyDTO> model)
        {
            try
            {
                List <PolicyEntity> policiesEntity = mapper.Map <List <PolicyDTO>, List <PolicyEntity> >(model);
                policyRepository.Add(policiesEntity);
            }
            catch (VuelingException ex)
            {
                throw ex;
            }

            return(model);
        }
Example #9
0
        public static void CreatePolicy(IPolicyRepository policyRepository, string name, string dictionaryName)
        {
            var policy = new RuleEngineBasedPolicy(policyRepository.GetNextId(), name, dictionaryName);

            policyRepository.Add(policy);
            foreach (var rule in rules)
            {
                policy.AssignRule(rule);
            }
            foreach (var function in ruleFunctions)
            {
                policy.AssignRuleFunction(function);
            }
            Policy = policy;
        }
Example #10
0
        public Policy DrawPolicy(int gameId)
        {
            var game = _gameDataService.GetGame(gameId);

            var    policiesLeft        = Settings.PolicyDeckAmount - game.Policies.Count();
            var    liberalPoliciesLeft = Settings.LiberalPolicyAmount - game.Policies.Where(x => x.PolicyType == PolicyType.Liberal).Count();
            Random rnd        = new Random();
            var    policyType = rnd.NextDouble() < (liberalPoliciesLeft / policiesLeft) ? PolicyType.Liberal : PolicyType.Facist;

            var policy = new Policy(policyType);

            policy.GameId = gameId;
            policy        = _policyRepository.Add(policy);
            return(policy);
        }
Example #11
0
 public ActionResult Add(Policy model)
 {
     try
     {
         if (string.IsNullOrEmpty(model.Contents))
         {
             return(Json(new { IsSuccess = false, Message = "Vui lòng thêm nội dung" }, JsonRequestBehavior.AllowGet));
         }
         model.Createddate = DateTime.Now;
         model.LinkSeo     = HelperString.RenderLinkSeo(model.MetaTitle);
         policyRepository.Add(model);
         return(Json(new { IsSuccess = true, Message = "Thêm mới thành công" }, JsonRequestBehavior.AllowGet));
     }
     catch (Exception)
     {
         return(Json(new { IsSuccess = false, Message = "Thêm mới thất bại" }, JsonRequestBehavior.AllowGet));
     }
 }
Example #12
0
        public async Task <IActionResult> PostPolicy([FromBody] Policy policy)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            RiskValidator oValidator = new RiskValidator(policy.RiskType, policy.Coverage);
            var           result     = oValidator.ValidateRisk();

            if (result == "OK")
            {
                _policyRepository.Add(policy);
                return(CreatedAtAction("GetPolicy", new { id = policy.Id }, policy));
            }
            else
            {
                return(BadRequest(result));
            }
        }
Example #13
0
 public ActionResult <Policy> Add([FromBody] Policy policy)
 {
     try
     {
         //ensure we have a valid policy and it doesn't already exist
         if (policy != null && !Get().Any(p => p.PolicyNumber == policy.PolicyNumber))
         {
             _policyRepository.Add(policy);
         }
         else
         {
             return(BadRequest());
         }
     }
     catch (Exception ex)
     {
         // log exception
         throw;
     }
     return(policy);
 }
        public IPolicy SellPolicy(string nameOfInsuredObject, DateTime validFrom, short validMonths, IList <Risk> selectedRisks)
        {
            var insurancePeriod   = new NewInsurancePeriod(validFrom, validMonths);
            var effectivePolicies = GetEffectivePolicies(nameOfInsuredObject, insurancePeriod);

            if (effectivePolicies.Any())
            {
                throw new ExistingEffectivePolicyException("Effective policy found that conflicts with requested validity period");
            }
            if (selectedRisks.Except(AvailableRisks).Any())
            {
                throw new InitialSelectedRiskUnavailableException("Some of the selected risks are not avaiable for selling");
            }

            var policy          = new Policy();
            var policyAggregate = new PolicyAggregate(policy);

            policyAggregate.Create(nameOfInsuredObject, insurancePeriod, selectedRisks);
            policyRepository.Add(policy);
            return(policy);
        }
Example #15
0
        public IPolicy SellPolicy(IPolicy policy)
        {
            var policyId = IdGenerator.ConstructPolicyId(policy.NameOfInsuredObject, policy.ValidFrom);

            if (_policyRepository.Get(policyId) != null)
            {
                throw new DuplicatePolicyException(policy.NameOfInsuredObject, policy.ValidFrom);
            }

            var policyModel = new PolicyModel {
                Id = policyId,
                NameOfInsuredObject = policy.NameOfInsuredObject,
                ValidFrom           = policy.ValidFrom,
                ValidTill           = policy.ValidTill,
                InsuredRisks        = policy.InsuredRisks,
                Premium             = policy.Premium
            };

            foreach (var risk in policy.InsuredRisks)
            {
                var riskId = IdGenerator.ConstructRiskId(risk.Name, policy.NameOfInsuredObject, policy.ValidFrom);

                var riskModel = new RiskModel
                {
                    Name                = risk.Name,
                    ValidFrom           = policy.ValidFrom,
                    ValidTill           = policy.ValidTill,
                    PolicyEffectiveDate = policy.ValidFrom,
                    PolicyId            = policyId,
                    Id          = riskId,
                    YearlyPrice = risk.YearlyPrice
                };

                _riskRepository.Add(riskModel);
            }

            _policyRepository.Add(policyModel);

            return(policy);
        }
Example #16
0
 public Policy AddPolicy(string name, string dictionaryName)
 {
     try
     {
         using (var scope = new TransactionScope())
         {
             var id     = policyRep.GetNextId();
             var policy = new RuleEngineBasedPolicy(id, name, dictionaryName);
             policyRep.Add(policy);
             scope.Complete();
             return(policy);
         }
     }
     catch (Exception exp)
     {
         var res = policyRep.TryConvertException(exp);
         if (res == null)
         {
             throw;
         }
         throw res;
     }
 }
        public async Task <bool> Execute(ConfirmSharedLinkParameter confirmSharedLinkParameter)
        {
            if (confirmSharedLinkParameter == null)
            {
                throw new ArgumentNullException(nameof(confirmSharedLinkParameter));
            }

            if (string.IsNullOrWhiteSpace(confirmSharedLinkParameter.ConfirmationCode))
            {
                throw new BaseUmaException(Errors.ErrorCodes.InvalidRequestCode, Errors.ErrorDescriptions.TheConfirmationCodeMustBeSpecified);
            }

            var sharedLink = await _sharedLinkRepository.Get(confirmSharedLinkParameter.ConfirmationCode).ConfigureAwait(false);

            if (sharedLink == null)
            {
                throw new BaseUmaException(Errors.ErrorCodes.InvalidRequestCode, Errors.ErrorDescriptions.TheConfirmationCodeIsInvalid);
            }

            var resourceId = sharedLink.ResourceId;
            var resource   = await _resourceSetRepository.Get(resourceId).ConfigureAwait(false);

            if (resource == null)
            {
                throw new BaseUmaException(Errors.ErrorCodes.InternalError, string.Format(Errors.ErrorDescriptions.TheResourceSetDoesntExist, resourceId));
            }

            if (resource.Owner == confirmSharedLinkParameter.Subject)
            {
                throw new BaseUmaException(Errors.ErrorCodes.InternalError, Errors.ErrorDescriptions.TheSharedLinkCannotBeUsedByTheOwner);
            }

            var policy = new Policy
            {
                Id             = Guid.NewGuid().ToString(),
                ResourceSetIds = new List <string> {
                    resourceId
                },
                Claims = new List <Claim>
                {
                    new Claim
                    {
                        Type  = "sub",
                        Value = confirmSharedLinkParameter.Subject
                    }
                },
                Scopes = sharedLink.Scopes.ToList()
            };

            using (var transaction = new CommittableTransaction(new TransactionOptions {
                IsolationLevel = IsolationLevel.ReadCommitted
            }))
            {
                try
                {
                    await _sharedLinkRepository.Delete(sharedLink.ConfirmationCode).ConfigureAwait(false);

                    await _policyRepository.Add(policy).ConfigureAwait(false);

                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }

            return(true);
        }
Example #18
0
 public async Task Add(Policy policy)
 {
     await _policyRepositor.Add(policy);
 }
Example #19
0
 public ActionResult <Policy> Create([FromBody] Policy policy)
 {
     _policyRepository.Add(policy);
     return(Ok());
 }
Example #20
0
        public async Task <string> Execute(AddPolicyParameter addPolicyParameter)
        {
            var json = addPolicyParameter == null ? string.Empty : JsonConvert.SerializeObject(addPolicyParameter);

            _umaServerEventSource.StartAddingAuthorizationPolicy(json);
            if (addPolicyParameter == null)
            {
                throw new ArgumentNullException(nameof(addPolicyParameter));
            }

            if (addPolicyParameter.ResourceSetIds == null || !addPolicyParameter.ResourceSetIds.Any())
            {
                throw new BaseUmaException(ErrorCodes.InvalidRequestCode,
                                           string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, Constants.AddPolicyParameterNames.ResourceSetIds));
            }

            foreach (var resourceSetId in addPolicyParameter.ResourceSetIds)
            {
                var resourceSet = await _repositoryExceptionHelper.HandleException(
                    string.Format(ErrorDescriptions.TheResourceSetCannotBeRetrieved, resourceSetId),
                    () => _resourceSetRepository.Get(resourceSetId));

                if (resourceSet == null)
                {
                    throw new BaseUmaException(ErrorCodes.InvalidResourceSetId, string.Format(ErrorDescriptions.TheResourceSetDoesntExist, resourceSetId));
                }

                if (addPolicyParameter.Scopes.Any(r => !resourceSet.Scopes.Contains(r)))
                {
                    throw new BaseUmaException(ErrorCodes.InvalidScope, ErrorDescriptions.OneOrMoreScopesDontBelongToAResourceSet);
                }
            }

            // Insert policy
            var policy = new Policy
            {
                Id             = Guid.NewGuid().ToString(),
                ClientIds      = addPolicyParameter.ClientIdsAllowed,
                ResourceSetIds = addPolicyParameter.ResourceSetIds,
                IsResourceOwnerConsentNeeded = addPolicyParameter.IsResourceOwnerConsentNeeded,
                Script = addPolicyParameter.Script,
                Scopes = addPolicyParameter.Scopes,
                Claims = addPolicyParameter.Claims == null ? new List <Claim>() : addPolicyParameter.Claims.Select(c => new Claim
                {
                    Type  = c.Type,
                    Value = c.Value
                }).ToList()
            };

            await _repositoryExceptionHelper.HandleException(ErrorDescriptions.ThePolicyCannotBeInserted, () => _policyRepository.Add(policy));

            _umaServerEventSource.FinishToAddAuthorizationPolicy(JsonConvert.SerializeObject(policy));
            return(policy.Id);
        }
Example #21
0
 public void Create([FromBody] Policy policy)
 {
     _policyRepository.Add(policy);
 }