private async void CheckInBook()
        {
            VisibilityCollapser();
            if (SelectedBookOfSelectedCustomer != null && SelectedCustomerHavingBook != null)
            {
                var obj = new CheckOutModel()
                {
                    BookId     = SelectedBookOfSelectedCustomer.BookId,
                    CustomerId = SelectedCustomerHavingBook.CustomerId,
                    Quantity   = SelectedBookOfSelectedCustomer.Quantity + 1
                };

                await _allCheckInoutOrderDataAccess.CheckOutBook(obj, Properties.Resources.CheckInBook);

                _log.Message("Checkin book ");
                RaiseCheckInOutEvent();
                GetAllOrders();
                GetBooks();
                GetAllCustomerHavingBook();
                BookCollectionBelongingToSelectedCustomer.Clear();
            }
            else
            {
                CheckInErrorMessage           = Properties.Resources.EmptyFieldErrorMsg;
                CheckInErrorMessageVisibility = Visibility.Visible;
            }
        }
Beispiel #2
0
        public IActionResult CheckOut(int id)
        {
            LibraryAsset  asset = _assets.GetById(id);
            CheckOutModel model = new CheckOutModel(id, asset, _checkOuts);

            return(View(model));
        }
        public async Task CheckOut()
        {
            CheckOutModel checkOut = new CheckOutModel
            {
                CheckInID = CheckedIn.Id,
                SubTotal  = CalculateSubTotal(),
                Tax       = CalculateTax(),
                Total     = CalculateSubTotal() + CalculateTax()
            };

            await _checkOutEndpoint.PostCheckOut(checkOut);

            RoomModel room = new RoomModel
            {
                RoomNumber = CheckedIn.RoomNumber
            };

            RoomModel checkedInRoom = await _roomEndpoint.GetRoom(room);

            checkedInRoom.IsAvailable = true;
            await _roomEndpoint.UpdateRoom(checkedInRoom);

            CheckedIn.IsCheckedOut = true;
            await _checkInEndpoint.UpdateCheckIn(CheckedIn);

            ClearCheckOut();
        }
        public ViewResult CheckOut(ShoppingCartModel cart)
        {
            var checkOut = new CheckOutModel();

            checkOut.Cart = cart;

            return(View(checkOut));
        }
 public Task CheckOut([FromBody] CheckOutModel model)
 {
     return(this.publishEndpoint.Publish(new CartCheckedOut
     {
         Username = model.Username,
         Timestamp = DateTime.Now
     }));
 }
        public IHttpActionResult CheckOut([FromBody] CheckOutModel model)
        {
            var cmd = new CheckOutBasket(model.BasketId, model.ShippingAddress);

            var basket = _commandDispatcher.ExecuteCommand <BasketAggregate>(cmd);

            return(Ok(BasketModel.FromAggregate(basket)));
        }
Beispiel #7
0
        public void Add(CheckOutModel model)
        {
            var errors = model.GetValidationErrors();

            if (!model.IsDelivery.HasValue)
            {
                errors.Add(new DbValidationError("IsDelivery", "Выберите способ получения товара"));
            }
            errors.ThrowIfHasErrors();

            var order = Db.CreateAndAdd <tblOrder>();

            order.IsDelivery = model.IsDelivery;
            order.Address    = model.Address;
            order.City       = model.City;
            order.Email      = model.Email;
            order.Phone      = model.Phone;
            order.Name       = model.Name;

            var productIds = UserInfo.Cart.Select(x => x.ProductId).ToList();

            var forSale   = ProductSingleStateEnum.ForSale.CastTo <int>();
            var soldState = ProductSingleStateEnum.Sold.CastTo <int>();

            lock (Locker)
            {
                var productItems = Db.Set <tblProduct>()
                                   .Where(x => productIds.Contains(x.Id))
                                   .Select(x =>
                                           new
                {
                    x.Id,
                    x.Name,
                    Items = x.tblProductSingles
                            .Where(s => s.State == forSale)
                            .Where(s => s.OrderId == null)
                            .ToList()
                });

                foreach (var cartItem in UserInfo.Cart)
                {
                    var count = cartItem.Count;
                    var prod  = productItems.Single(x => x.Id == cartItem.ProductId);
                    var items = prod.Items.Take(count).ToList();
                    if (items.Count != count)
                    {
                        throw new ValidationException($@"Выбранный вами товар: {prod.Name} уже куплен");
                    }

                    order.tblProductSingles.AddRangeUnique(items);
                    items.ForEach(x => x.State = soldState);
                }

                Db.SaveChanges();

                model.Id = order.Id;
            }
        }
Beispiel #8
0
        public IActionResult Hold(int id)
        {
            LibraryAsset  asset = _assets.GetById(id);
            CheckOutModel model = new CheckOutModel(id, asset, _checkOuts)
            {
                HoldCount = _checkOuts.GetCurrentHolds(id).Count(),
            };

            return(View(model));
        }
 public async Task PostCheckOut(CheckOutModel checkOut)
 {
     using (HttpResponseMessage response = await _apiHelper.ApiClient.PostAsJsonAsync("/api/CheckOut", checkOut))
     {
         if (response.IsSuccessStatusCode == false)
         {
             throw new Exception(response.ReasonPhrase);
         }
     }
 }
        public HttpResponseMessage CheckOutTitle(CheckOutModel checkOutModel)
        {
            Guid outputTitleId;
            var  isValid = Guid.TryParse(checkOutModel.TitleId, out outputTitleId);

            if (!isValid)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              "Invalid Title Id."));
            }

            Guid outputPaymentId;

            isValid = Guid.TryParse(checkOutModel.PaymentMethodId, out outputPaymentId);
            if (!isValid)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              "Invalid Payment Id."));
            }
            var title = _titleService.GetById(outputTitleId);

            if (title == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound,
                                              "Invalid Title Id."));
            }
            if (title.AvailableStock == 0)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, "No Available Stock to Rent"));
            }

            var userId = RequestContext.Principal.Identity.GetUserId();

            if (!_settingsValueService.ValidateUserPaymentId(outputPaymentId, userId))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Payment Method!"));
            }

            if (!ProcessPayment(_settingsValueService.GetById(outputPaymentId)))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, "An Error Occurred while processing your payment. Please update your payment method."));
            }

            _rentalHistoryService.Create(new RentalHistory
            {
                UserId        = userId,
                Returned      = false,
                CurrentStatus = CurrentStatus.Processing,
                TitleId       = title.Id
            });

            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Beispiel #11
0
        public IActionResult Index(CheckOutModel model)
        {
            var cart = SessionHelper.GetObjectFromJson <List <ProductToCart> >(HttpContext.Session, "cart");

            ViewBag.cart = cart;
            if (cart != null)
            {
                ViewBag.total = cart.Sum(item => item.ProductModel.ProductPrice * item.Quantity);
            }
            return(View(model));
        }
        public ActionResult CheckOut()
        {
            var shoppingCartList = (List <ShoppingCartModel>)Session["shoppingCart"];

            if (shoppingCartList.Count() == 0)
            {
                return(Redirect("/shoppingcart/index"));
            }
            //kollar först om man är inloggad
            if (!(bool)Session["userLoggedIn"])
            {
                return(Redirect("/login/index"));
            }
            //hämtar hela shoppingcart-listan
            //hämtar vilken användare det är, jämför Email med session-objektet = ["userName"]
            // för att få användar-info och lägger allting i en array, så man kan använda user[0] för att lätt komma åt infon
            var user = (from x in (List <UserModel>)Session["userList"]
                        where x.Email == (string)Session["userName"]
                        select x).ToArray();

            //skapar en ny lista med vad som skall checkas ut!


            //för varje produkt i shoppingcarten så kopieras användarens information och informationen om vilka produkter som ska med
            foreach (var item in shoppingCartList)
            {
                var newCheckOut = new CheckOutModel()
                {
                    //personinfon blir samma varje gång efterseom det är user[0], user[0] skapas längre upp
                    Firstname    = user[0].Firstname,
                    Lastname     = user[0].Lastname,
                    Email        = user[0].Email,
                    Personnumber = user[0].Personnumber,
                    PhoneNumber  = user[0].PhoneNumber,
                    Address      = user[0].Address,

                    //lägger in infon om vilka produkter som skall köpas i produktlistan
                    //går igenom hela listan och lägger till det som finns

                    PricePerProduct  = item.Price,
                    ProductName      = item.ProductName,
                    imgUrl           = item.imgUrl,
                    totalPrice       = shoppingCartList[0].totalPrice,
                    ProductID        = item.ProductID,
                    TotalAmountPerID = item.TotalAmountPerID,
                };
                //lägger in grejer checkout-listan
                checkOutList.Add(newCheckOut);
            }


            return(View(checkOutList));
        }
Beispiel #13
0
        public async Task CheckOut(int reservaId, CheckOutModel model)
        {
            var reserva = await _context
                          .Reserva
                          .Where(r => r.ReservaId == reservaId)
                          .Include(q => q.Quarto.TipoQuarto)
                          .FirstOrDefaultAsync();

            if (reserva == null)
            {
                throw new Exception("Reserva não cadastrada.");
            }

            if (reserva.CheckIn == null)
            {
                throw new Exception("Check-In não foi realizado.");
            }

            if (reserva.CheckOut != null)
            {
                throw new Exception("Check-Out já cadastrado.");
            }

            reserva.TaxasConsumo = model.TaxasConsumo;
            reserva.ValorDiarias = reserva.Quarto.TipoQuarto.Valor;
            reserva.CheckOut     = DateTime.Now;

            var tempoHospedagem = (reserva.CheckOut.Value - reserva.CheckIn.Value);

            if (reserva.DataSaida < DateTime.Now.Date)
            {
                reserva.Multa = reserva.Quarto.TipoQuarto.Valor;
            }
            else
            {
                reserva.Multa = 0;
            }

            if (tempoHospedagem.TotalDays <= 1)
            {
                reserva.ValorTotal = reserva.ValorDiarias + reserva.TaxasConsumo + reserva.Multa;
            }
            else
            {
                reserva.ValorTotal = ((int)Math.Ceiling(tempoHospedagem.TotalDays) * reserva.ValorDiarias) + reserva.TaxasConsumo + reserva.Multa;
            }

            reserva.StatusId = Status.Finalizada;

            reserva.Quarto.SituacaoId = Situacao.Disponivel;

            await _context.SaveChangesAsync();
        }
Beispiel #14
0
        public IActionResult CheckOut(CheckOutModel model)
        {
            // Kiểm tra nếu chưa đăng nhập, trả về trang login
            if (HttpContext.Session.GetInt32("UserID") == null)
            {
                return(RedirectToAction("Login", "Accounts"));
            }


            // Nếu chưa nhập đủ sđt và địa chỉ thì quay lại
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Index", model));
            }

            // Tính % còn lại sau khi sale
            double sale = 1;

            if (CheckDiscount(model.DiscountCode) != -1)
            {
                sale = (100 - CheckDiscount(model.DiscountCode)) / 100;
            }

            var cart = SessionHelper.GetObjectFromJson <List <ProductToCart> >(HttpContext.Session, "cart");

            HttpContext.Session.Remove("cart");

            var order = new Order()
            {
                DateTime   = DateTime.UtcNow,
                UserId     = HttpContext.Session.GetInt32("UserID").GetValueOrDefault(),
                TotalPrice = cart.Sum(item => item.ProductModel.ProductPrice * item.Quantity) * sale,
                Address    = model.Address,
                Phone      = model.PhoneNumber
            };

            foreach (var item in cart)
            {
                var orderDetail = new OrderDetail()
                {
                    Quantity  = item.Quantity,
                    Amount    = item.Quantity * item.ProductModel.ProductPrice,
                    ProductId = item.ProductModel.ProductId
                };
                order.OrderDetails.Add(orderDetail);
            }

            dataContext.Orders.Add(order);
            dataContext.SaveChanges();

            return(RedirectToAction("Index", "Home"));
        }
Beispiel #15
0
        public IHttpActionResult CheckOut([FromBody] CheckOutModel model)
        {
            var basketId  = model.BasketId;
            var address   = model.ShippingAddress;
            var cmd       = Command.NewCheckOut(ShippingAddress.NewShippingAddress(address));
            var processId = FSharpOption <ProcessId> .Some(ProcessId.NewProcessId(Guid.NewGuid()));

            var envelope = createCommand(AggregateId.NewAggregateId(basketId), AggregateVersion.Irrelevant, null, null, processId, cmd);

            var basket = CommitCommand(envelope);

            return(Ok(basket));
        }
        public IActionResult OrderPayment()
        {
            var cart = PageMaster.GetShoppingCart();

            ViewBag.CountCartItems = cart.CartProducts.Count();

            var model = new CheckOutModel
            {
                State = CheckOutState.Payment
            };

            return(View(model));
        }
        public IActionResult CheckOut(int id)
        {
            var asset = _asset.getByID(id);
            var model = new CheckOutModel
            {
                assetId       = id,
                imageUrl      = asset.imageUrl,
                title         = asset.title,
                libraryCardId = "",
                isCheckout    = _checkout.isCheckOut(id),
            };

            return(View(model));
        }
        public IActionResult Checkout(CheckOutModel model)
        {
            Response <string> res = new Response <string>();


            res.IsSuccess = true;
            res.Code      = "200";
            res.Message   = null;
            res.Data      = Url.Action("PartialCart", "Product");



            return(new JsonResult(res));
        }
Beispiel #19
0
        public IActionResult Checkout(int id)
        {
            var asset = _asset.GetBYId(id);
            var model = new CheckOutModel
            {
                AssetId       = id,
                ImageUrl      = asset.ImageUrl,
                Title         = asset.Title,
                LibraryCardId = "",
                IsCheckOut    = _checkOut.IsCheckeOut(id)
            };

            return(View(model));
        }
Beispiel #20
0
        public IActionResult CheckOut(int assetid)   // assetID
        {
            var asset = _interface.GetById(assetid);

            var model = new CheckOutModel
            {
                AssetID       = asset.ID,
                Title         = asset.Title,
                ImageUrl      = asset.ImageUrl,
                LibraryCardID = "",
                IsCheckedOut  = _checkOutInterface.IsCheckedOut(assetid)
            };

            return(View(model));
        }
Beispiel #21
0
        public IActionResult Hold(int id)
        {
            var asset = _libraryAsset.GetById(id);
            var model = new CheckOutModel
            {
                AssetId       = id,
                ImageUrl      = asset.ImageUrl,
                Title         = asset.Title,
                LibraryCardId = "",
                IsCheckedOut  = _checkOut.IsCheckedOut(id),
                HoldCount     = _checkOut.GetCurrentHolds(id).Count()
            };

            return(View(model));
        }
Beispiel #22
0
        public ActionResult CheckOut(CheckOutModel checkout)
        {
            try
            {
                checkout.userdata.UserId = @User.Identity.Name;

                ViewBag.checkOutMessage = LetsShopImplementation.PlaceOrder(checkout);
                ShoppingCartImplementation.EmptyCart(@User.Identity.Name);
                return(View());
            }
            catch (Exception ex)
            {
                return(View());
            }
        }
Beispiel #23
0
 public ActionResult Cart(CheckOutModel model)
 {
     try
     {
         Service.Order.Add(model);
         return(RedirectToRouteNotify("Ordered", new { id = model.Id }));
     }
     catch (ValidationException ex)
     {
         AddModelErrors(ex);
         var cart = Service.Cart.GetCart();
         cart.CheckOutModel = model;
         return(View("~/Views/Public/Cart/Index.cshtml", cart));
     }
 }
        //______________________________________________________________________________________

        /// <summary>
        /// This method is used to populate the user and the cart details during the checkout of an order.
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>

        public static CheckOutModel GetCheckOutDetails(string UserId)
        {
            CheckOutModel CheckOut = new CheckOutModel();
            UserData      userdata = DataProvider.GetUserDetailsByUserName(UserId);

            CheckOut.userdata = userdata;
            CheckOut.CartList = ShoppingCartImplementation.GetFromCart(UserId);
            double total = 0;

            foreach (var item in CheckOut.CartList)
            {
                total          = total + item.Cart.Quantity * item.Product.Price;
                CheckOut.Total = total;
            }
            return(CheckOut);
        }
Beispiel #25
0
        public async Task <IActionResult> CheckOut([FromBody] CheckOutModel model)
        {
            var useCase = new CheckOutBasket(
                model.BasketId,
                new AddressDto(
                    model.ShippingAddress.StreetAndNumber,
                    model.ShippingAddress.ZipAndCity,
                    model.ShippingAddress.StateOrProvince,
                    model.ShippingAddress.Country
                    )
                );
            var cmd = new Command <CheckOutBasket>(useCase);

            var basket = await _commandHandler.Execute <CheckedOutBasket>(cmd);

            return(Ok(BasketModel.FromAggregateRoot(basket)));
        }
        public IActionResult OrderDetail()
        {
            var cart = PageMaster.GetShoppingCart();

            cart.CartProducts      = Repository.GetCartItems(cart);
            ViewBag.CountCartItems = cart.CartProducts.Count();

            var model = new CheckOutModel
            {
                State         = CheckOutState.OrderDetail,
                Cart          = cart,
                TotalPrice    = Repository.GetCartTotalPrice(cart),
                TotalQuantity = cart.CartProducts.Sum(p => p.Quantity)
            };

            return(View(model));
        }
        private async void CheckOutBook()
        {
            VisibilityCollapser();
            if (SelectedBook != null && SelectedCustomer != null)
            {
                if (SelectedBook.Quantity <= 0)
                {
                    CheckOutErrorMessage           = Properties.Resources.BookOutOfStockMsg;
                    CheckOutErrorMessageVisibility = Visibility.Visible;
                    return;
                }
                ///Check if the user has already taken the same book previously
                var tx = AllOrderData.Where(t => t.BookId == SelectedBook.BookId && t.CustomerId == SelectedCustomer.CustomerId && t.HasBook == 1).ToList();
                if (tx.Count != 0)
                {
                    //MessageBox.Show("This User has this book");
                    CheckOutErrorMessage           = Properties.Resources.UserAlreadyHasBookMsg;
                    CheckOutErrorMessageVisibility = Visibility.Visible;
                    return;
                }


                CheckOutModel _checkOutModel = new CheckOutModel()
                {
                    OrderId    = DateTime.Now.ToString().GetHashCode().ToString("x"),
                    BookId     = SelectedBook.BookId,
                    CustomerId = SelectedCustomer.CustomerId,
                    DateTime   = DateTime.Now,
                    HasBook    = 1,
                    Quantity   = SelectedBook.Quantity - 1
                };

                await _allCheckInoutOrderDataAccess.CheckOutBook(_checkOutModel, Properties.Resources.CheckOutBook);

                _log.Message("CheckOut book ");
                GetAllOrders();
                GetBooks();
                GetAllCustomerHavingBook();
                RaiseCheckInOutEvent();
            }
            else
            {
                CheckOutErrorMessage           = Properties.Resources.EmptyFieldErrorMsg;
                CheckOutErrorMessageVisibility = Visibility.Visible;
            }
        }
Beispiel #28
0
        public HttpResponseMessage CheckOutDirectly([FromBody] CheckOutModel checkOutModel)
        {
            if (ValidationService.AuthorizeToken(GetToken(), "post:/api/organizer/checkoutdirectly") == false)
            {
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("无访问权限", System.Text.Encoding.GetEncoding("UTF-8"), "application/text")
                });
            }
            User     organizer = ValidationService.FindUserWithToken(GetToken());
            Activity activity  = myService.FindActivity(new Guid(checkOutModel.activityId));

            //判断权限
            if (myService.CheckIfOrganizerCanManageActivity(activity, organizer) == false)
            {
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.Forbidden, Content = new StringContent("登陆用户无直接check out权限", System.Text.Encoding.GetEncoding("UTF-8"), "application/text")
                });
            }
            List <string> errorName = new List <string>();

            foreach (string volunteerid in checkOutModel.volunteerIds)
            {
                User volunteer = myService.FindUser(new Guid(volunteerid));
                if (activity.CheckOutDirectly(volunteer, checkOutModel.isComplete))
                {
                    continue;
                }
                else
                {
                    errorName.Add(volunteer.Name);
                    continue;
                }
            }
            if (errorName.Any())
            {
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.NotAcceptable, Content = new StringContent("以下用户状态错误,无法直接check out:" + errorName.ToString(), System.Text.Encoding.GetEncoding("UTF-8"), "application/text")
                });
            }
            else
            {
                return(new HttpResponseMessage(HttpStatusCode.Accepted));
            }
        }
Beispiel #29
0
        public async Task <IActionResult> PayPalPayment(CheckOutModel model)
        {
            var order = _DataContext.Orders.FirstOrDefault(x => x.OrderId == model.OrderId);

            if (order == null)
            {
                return(NotFound());
            }

            var cart = SessionHelper.GetObjectFromJson <List <ProductToCart> >(HttpContext.Session, "cart");

            HttpContext.Session.Remove("cart");

            double sale = 1;

            if (CheckDiscount(model.DiscountCode) != -1)
            {
                sale = (100 - CheckDiscount(model.DiscountCode)) / 100;
            }

            var hostname = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";

            try
            {
                var paypalPayment = await _PaymentService.GetURLPaymentWithPaypal(cart, sale, hostname);

                order.PaypalId = paypalPayment.PaypalId;

                _DataContext.Orders.Update(order);

                _DataContext.SaveChanges();

                return(Redirect(paypalPayment.RedirectURL));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();

                //Process when Checkout with Paypal fails
                return(Redirect("/Cart/PaymentFail"));
            }
        }
Beispiel #30
0
        public ActionResult CheckOut(CheckOutModel checkout)
        {
            try
            {
                checkout.userdata.UserId = @User.Identity.Name;

                ViewBag.checkOutMessage = LetsShopImplementation.PlaceOrder(checkout);
                ShoppingCartImplementation.EmptyCart(@User.Identity.Name);
                return(View());
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, "UI Policy");
                if (rethrow)
                {
                    throw;
                }
                return(View());
            }
        }