예제 #1
0
 public ActionResult TakeOrder()
 {
     if (Session["cart"] != null)
     {
         Employee loginEmployee = Session["myLogin"] as Employee;
         MyCart   myCart        = Session["cart"] as MyCart;
         Order    order         = new Order()
         {
             OrderDate       = DateTime.Now,
             EmployeeID      = loginEmployee.EmployeeID,
             OrderTotalPrice = myCart.TotalPrice
         };
         _orderManager.AddOrder(order);
         foreach (CartItem cartItem in myCart.ListCart)
         {
             OrderDetail orderDetail = new OrderDetail
             {
                 OrderID           = order.OrderID,
                 ProductID         = cartItem.ID,
                 ProductAmount     = cartItem.Amount,
                 UnitPrice         = cartItem.Price,
                 ProductTotalPrice = cartItem.Price * cartItem.Amount
             };
             _orderDetailManager.AddOrderDetail(orderDetail);
             Product product = _productManager.GetProduct(cartItem.ID);
             product.UnitsInStock -= cartItem.Amount;
             _productManager.UpdateProduct(product);
         }
         TempData["message"] = "Yeni sipariş oluştu ve stoklar güncellendi.";
     }
     Session["cart"] = null;
     return(RedirectToAction("ListOrder"));
 }
        private void buttonTakeOrder_Click(object sender, EventArgs e)
        {
            FormAdminPanel myUserControl = (FormAdminPanel)ParentForm;
            Employee       LoginEmployee = _employeeManager.GetEmployee(myUserControl.Text);
            Order          order         = new Order()
            {
                OrderDate       = DateTime.Now,
                EmployeeID      = LoginEmployee.EmployeeID,
                OrderTotalPrice = decimal.Parse(labelTotalPrice.Text)
            };

            _orderManager.AddOrder(order);

            foreach (CartItem cartItem in _myCart.ListCart)
            {
                OrderDetail orderDetail = new OrderDetail
                {
                    OrderID           = order.OrderID,
                    ProductID         = cartItem.ID,
                    ProductAmount     = cartItem.Amount,
                    UnitPrice         = cartItem.Price,
                    ProductTotalPrice = cartItem.Price * cartItem.Amount
                };
                _orderDetailManager.AddOrderDetail(orderDetail);
            }

            MessageBox.Show("Yeni Sipariş Oluştu ");
        }
        public async Task <ActionResult> PlaceOrder()
        {
            Payment       createdPayment = null;
            List <CartVM> lstcartVM      = Session["cart"] as List <CartVM>;

            DomainModels.Order order = new DomainModels.Order();

            var     userManager = HttpContext.GetOwinContext().GetUserManager <AppUserManager>();
            AppUser user        = await userManager.FindByNameAsync(User.Identity.Name);

            if (user != null)
            {
                order.UserId    = user.Id;
                order.CreatedAt = DateTime.Now;
                _orderservice.Add(order);

                OrderDetail orderDetail = new OrderDetail();
                foreach (var item in lstcartVM)
                {
                    orderDetail.OrderId   = order.OrderID;
                    orderDetail.UserId    = order.UserId;
                    orderDetail.ProductId = item.ProductId;
                    orderDetail.Quantity  = item.Quantity;
                    _orderdetailservice.AddOrderDetail(orderDetail);
                }
            }

            #region Paypal
            var apiContext = GetApiContext();

            decimal totalCost = lstcartVM.Sum(p => p.Price * p.Quantity) * 100m;

            var payment = new Payment
            {
                experience_profile_id = AppConstants.experienceprofile,
                intent = "sale",
                payer  = new Payer
                {
                    payment_method = "paypal"
                },
                transactions = new List <Transaction>
                {
                    new Transaction
                    {
                        description = "Single Payment WebShop",
                        amount      = new Amount
                        {
                            currency = "EUR",
                            total    = (totalCost / 100.00m).ToString(),
                        },
                        item_list = CreatePaypalItemListOrders(lstcartVM)
                    }
                },
                redirect_urls = new RedirectUrls
                {
                    return_url = Url.Action("Return", "Cart", null, Request.Url.Scheme),
                    cancel_url = Url.Action("Cancel", "Cart", null, Request.Url.Scheme)
                }
            };

            try
            {
                createdPayment        = payment.Create(apiContext);
                order.PayPalReference = createdPayment.id;
                _orderservice.Edit(order);
            }
            catch (PayPal.PaymentsException Ex)
            {
                Debug.WriteLine(Ex.ToString());
            }

            var approvalUrl = createdPayment.links.FirstOrDefault(x => x.rel.Equals("approval_url", StringComparison.OrdinalIgnoreCase));
            #endregion Paypal

            Session["cart"] = null;
            return(Redirect(approvalUrl.href));
        }
        public ActionResult AddOrder(Customer customer, int NumberDiscountPass = 0, string CodePass = "")
        {
            //Check null session cart
            if (Session["Cart"] == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            Customer customercheck = new Customer();
            bool     status        = false;
            //Is Customer
            Customer customerNew = new Customer();

            if (Session["Member"] == null)
            {
                //Insert customer into DB
                customerNew          = customer;
                customerNew.isMember = false;
                _customerService.AddCustomer(customerNew);
            }
            else
            {
                //Is member
                Member member = Session["Member"] as Member;
                customercheck = _customerService.GetAll().FirstOrDefault(x => x.fullName.Contains(member.fullName));
                if (customercheck != null)
                {
                    status = true;
                }
                else
                {
                    customerNew.fullName    = member.fullName;
                    customerNew.addresss    = member.addresss;
                    customerNew.email       = member.email;
                    customerNew.phoneNumber = member.phoneNumber;
                    customerNew.isMember    = true;
                    _customerService.AddCustomer(customerNew);
                }
            }
            //Add order
            OrderShip order = new OrderShip();

            if (status)
            {
                order.customerID = customercheck.id;
            }
            else
            {
                order.customerID = customerNew.id;
            }
            order.dateOrder  = DateTime.Now;
            order.dateShip   = DateTime.Now.AddDays(3);
            order.isPaid     = false;
            order.isDelete   = false;
            order.isDelivere = false;
            order.isApproved = false;
            order.isReceived = false;
            order.isCancel   = false;
            order.offer      = NumberDiscountPass;
            _orderService.AddOrder(order);
            //Add order detail
            List <Cart> listCart = GetCart();
            decimal     sumtotal = 0;

            foreach (Cart item in listCart)
            {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.orderID   = order.id;
                orderDetail.productID = item.productID;
                orderDetail.quantity  = item.quantity;
                orderDetail.price     = item.price;
                _orderDetailService.AddOrderDetail(orderDetail);
                sumtotal += orderDetail.quantity.Value * orderDetail.price.Value;
                if (Session["Member"] != null)
                {
                    //Remove Cart
                    _cartService.RemoveCart(item.productID.Value, item.memberID.Value);
                }
            }
            if (NumberDiscountPass != 0)
            {
                _orderService.UpdateTotal(order.id, sumtotal - (sumtotal / 100 * NumberDiscountPass));
            }
            else
            {
                _orderService.UpdateTotal(order.id, sumtotal);
            }
            if (CodePass != "")
            {
                //Set discountcode used
                _discountCodeDetailService.Used(CodePass);
            }
            Session["Code"] = null;
            Session["num"]  = null;
            Session["Cart"] = null;
            if (status)
            {
                SentMail("Đặt hàng thành công", customercheck.email, "*****@*****.**", "id0ntkn0w", "<p style=\"font-size:20px\">Cảm ơn bạn đã đặt hàng<br/>Mã đơn hàng của bạn là: " + order.id + "</p>");
            }
            else
            {
                SentMail("Đặt hàng thành công", customerNew.email, "*****@*****.**", "id0ntkn0w", "<p style=\"font-size:20px\">Cảm ơn bạn đã đặt hàng<br/>Mã đơn hàng của bạn là: " + order.id + "</p>");
            }
            return(RedirectToAction("Message"));
        }
예제 #5
0
        public async Task <IActionResult> Payment(PaymentViewModel paymentViewModel)
        {
            if (ModelState.IsValid)
            {
                Dictionary <int, string> result = new Dictionary <int, string>();
                int                  isReturn   = 0;                                      // Success or fail
                string               message    = string.Empty;                           // Message
                ProductDetail        productDetailUpdate;                                 // Update product detail
                List <ProductDetail> lstProductDetailUpdate = new List <ProductDetail>(); // Update product detail list
                CartDetail           cartDetailUpdate;                                    // Update cart detail
                List <CartDetail>    lstCartDetailUpdate = new List <CartDetail>();       // Update cart detail list

                foreach (var item in paymentViewModel.Products.Cart)
                {
                    productDetailUpdate = productDetailService.GetOne(item.ProductDetail.ID);
                    if (productDetailUpdate != null)
                    {
                        if (productDetailUpdate.Quantity <= 0)
                        {
                            isReturn = 0;
                            message  = "outofstock";
                            goto Finish;
                        }
                        lstProductDetailUpdate.Add(productDetailUpdate);
                    }
                }

                Order order = null; // Order Entity
                try
                {
                    DataTranfer(out order, paymentViewModel);
                }
                catch (Exception e)
                {
                    message = e.Message;
                    goto Finish;
                }

                // Call Service => Execute
                #region --- Main Execute ---

                // Create new order
                result = orderService.Create(order);

                // Check create new order success or fail
                paymentViewModel.OrderId = result.Keys.FirstOrDefault();
                if (paymentViewModel.OrderId <= 0)             // Create fail
                {
                    result.TryGetValue(isReturn, out message); // Get error message
                    goto Finish;
                }
                else // Add new order successful
                {
                    try
                    {
                        DataTranferOrderDetail(ref order, paymentViewModel);
                    }
                    catch (Exception e)
                    {
                        message = e.Message;
                        goto Finish;
                    }
                }

                result.Clear();
                // Create new order detail
                result = orderDetailService.AddOrderDetail(order);

                // Check create new order detail success or fail
                isReturn = result.Keys.FirstOrDefault();
                if (isReturn <= 0)                             // Create fail
                {
                    result.TryGetValue(isReturn, out message); // Get error message
                    goto Finish;
                }
                else // Create order detail successful, then update quantity of product
                {
                    // Update quantity of product
                    for (int i = 0; i < lstProductDetailUpdate.Count; i++)
                    {
                        lstProductDetailUpdate[i].Quantity -= paymentViewModel.Products.Cart[i].BuyedQuantity;
                    }
                    isReturn = productDetailService.Update(lstProductDetailUpdate); // Update

                    if (isReturn <= 0)
                    {
                        message = "Cập nhật số lượng sản phẩm không thành công";
                        goto Finish;
                    }

                    // Update cart detail
                    foreach (var item in paymentViewModel.Products.Cart)
                    {
                        cartDetailUpdate = cartDetailService.Get(item.CartDetailId);
                        if (cartDetailUpdate != null)
                        {
                            cartDetailUpdate.State = 2;
                            lstCartDetailUpdate.Add(cartDetailUpdate);
                        }
                    }
                    isReturn = cartDetailService.Updates(lstCartDetailUpdate); // Update

                    if (isReturn <= 0)
                    {
                        message = "Cập nhật trạng thái của sản phẩm trong giỏ hàng không thành công";
                        goto Finish;
                    }
                }

Finish:
                // isReturn = 0: Error || 1: Success
                // Giải thích: isReturn = dbContext.Commit = số dòng được thay đổi trong sql
                paymentViewModel.IsError = (isReturn == 0);
                paymentViewModel.Message = message;

                #endregion --- Main Execute ---

                if (paymentViewModel.IsError) // Error
                {
                    return(View(paymentViewModel));
                }

                List <ProductDetail> temp = new List <ProductDetail>();
                foreach (var item in lstProductDetailUpdate)
                {
                    productDetailUpdate = new ProductDetail()
                    {
                        Id       = item.Id,
                        Quantity = item.Quantity
                    };
                    temp.Add(productDetailUpdate);
                }

                // Call SignalR update quantity
                await _hubContext.Clients.All.SendAsync("ReloadQuantity", temp);

                // Call SignalR update statistical
                await _hubContext.Clients.All.SendAsync("ReloadStatistical");

                // Send email
                User user = await userManager.GetUserAsync(User);

                SendEmail(paymentViewModel, user.Email);

                // Call SignalR notification
                await _hubContext.Clients.All.SendAsync("OrderSuccess");

                paymentViewModel.Email            = user.Email;
                paymentViewModel.IsPaymentSuccess = true;
                return(View(paymentViewModel));
            }

            //    //string userIDProc = order.UserId;
            //    //DataTable dataTable = new DataTable();
            //    //dataTable.Columns.Add(new DataColumn("ID", typeof(int)));
            //    //dataTable.Columns.Add(new DataColumn("Quantity", typeof(int)));
            //    //dataTable.Columns.Add(new DataColumn("Processed", typeof(int)));
            //    //dataTable.Columns.Add(new DataColumn("UserIDProc", typeof(string)));
            //    //foreach(var item in order.OrderDetail)
            //    //{
            //    //    dataTable.Rows.Add(item.ProductDetailId, item.Quantity, 0, userIDProc);
            //    //}
            //    //string query = "UpdateProductDetail @ListID";
            //    //orderDetailService.ExecStoreUpdate(query, new SqlParameter("@ListID", dataTable));

            return(View(paymentViewModel));
        }