public HttpResponseMessage PostSale([FromBody]SetCartDTO cart) { if (IsAuthorized(Request, new List<Roles>() { Roles.Admin, Roles.Employee })) { if (ModelState.IsValid) { using (var transaction = db.Database.BeginTransaction()) { try { var employId = Convert.ToInt32(Request.Headers.Where(m => m.Key == "xcmps383authenticationid").First().Value.First()); var checkout = db.Carts.FirstOrDefault(m => m.User_Id == cart.User_Id && m.CheckoutReady == true); if (checkout == null) { return Request.CreateResponse(HttpStatusCode.NotFound, "Could not find cart"); } SalesModel newSale = new SalesModel() { SalesDate = DateTime.Now, Cart = checkout, User = db.Users.FirstOrDefault(m => m.Id == checkout.User_Id), EmployeeId = employId }; foreach (var item in checkout.Games) { for (int i = 0; i < item.Quantity; i++) { newSale.Total += item.Game.Price; item.Game.InventoryStock--; db.Entry(item.Game).CurrentValues.SetValues(item.Game); db.SaveChanges(); } } try { checkout.CheckoutReady = false; db.Entry(checkout).CurrentValues.SetValues(checkout); db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateResponse(HttpStatusCode.InternalServerError, ex); } try { db.Sales.Add(newSale); db.SaveChanges(); transaction.Commit(); return Request.CreateResponse(HttpStatusCode.Created, cart); } catch (DbUpdateConcurrencyException ex) { return Request.CreateResponse(HttpStatusCode.InternalServerError, ex); } } catch (Exception e) { transaction.Rollback(); return Request.CreateResponse(HttpStatusCode.BadRequest, e); } } } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } } return Request.CreateResponse(HttpStatusCode.Unauthorized); }
public GetSalesDTO Create(SalesModel sale) { return new GetSalesDTO() { URL = urlHelper.Link("SaleRoute", new { id = sale.Id }), SalesDate = sale.SalesDate, Total = sale.Total, Cart = Create(sale.Cart) }; }