public Customer_PoliciesDto SaveCustomerPolicy(Customer_PoliciesDto custPolicy) { using (var db = new GapInsuranceDBModel()) { Customer_Policies dbCustPolicy = null; //TODO. change throw exceptions since this is not very testable. if (custPolicy.CoverPercentage > 100) { throw new InvalidOperationException("Cover percentage can't be higher than 100%"); } if (!db.Customers.Any(x => x.Id == custPolicy.CustomerId)) { throw new KeyNotFoundException("Customer not found"); } if (!db.Policies.Any(x => x.Id == custPolicy.PolicyId)) { throw new KeyNotFoundException("Policy not found"); } if (custPolicy.RiskType == RiskType.High && custPolicy.CoverPercentage > 50) { throw new InvalidOperationException("Cover percentage can't be higher than 50% when risk is high"); } if (custPolicy.Id > 0) { dbCustPolicy = db.Customer_Policies.FirstOrDefault(o => o.Id == custPolicy.Id); } if (dbCustPolicy == null) { dbCustPolicy = new Customer_Policies(); db.Customer_Policies.Add(dbCustPolicy); } dbCustPolicy.PolicyId = db.Policies.FirstOrDefault(x => x.Id == custPolicy.PolicyId).Id; dbCustPolicy.StartDate = custPolicy.StartDate; dbCustPolicy.EndDate = custPolicy.EndDate; dbCustPolicy.Price = custPolicy.Price; dbCustPolicy.RiskType = (int)custPolicy.RiskType; dbCustPolicy.CustomerId = db.Customers.FirstOrDefault(x => x.Id == custPolicy.CustomerId).Id; dbCustPolicy.Active = custPolicy.Active; dbCustPolicy.CoverPercentage = custPolicy.CoverPercentage; db.SaveChanges(); return(Mapper.Map <Customer_Policies, Customer_PoliciesDto>(dbCustPolicy)); } }
public void createCustomerPolicy() { var pman = new PolicyManager(); var custPolicy = new Customer_PoliciesDto(); custPolicy.Id = 100000; custPolicy.PolicyId = 1004; custPolicy.StartDate = DateTime.Now; custPolicy.EndDate = DateTime.Now.AddYears(1); custPolicy.Price = 1000; custPolicy.RiskType = RiskType.Medium; custPolicy.CustomerId = 1000; custPolicy.CoverPercentage = 98; custPolicy.Active = false; pman.SaveCustomerPolicy(custPolicy); // custPolicy. }
public IHttpActionResult Post([FromBody] Customer_PoliciesDto policy) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { var updatedPolicy = policyManager.SaveCustomerPolicy(policy); return(Ok(updatedPolicy)); } catch (InvalidOperationException ex) { return(BadRequest(ex.Message)); } catch (KeyNotFoundException ex) { return(BadRequest(ex.Message)); } }