コード例 #1
0
        public OrderProductModel Convert(OrderProduct orderProduct)
        {
            if (orderProduct == null)
            {
                return(null);
            }

            return(new OrderProductModel()
            {
                OrderProductId = orderProduct.OrderProductId,
                OrderId = orderProduct.OrderId,
                ProductId = orderProduct.ProductId
            });
        }
コード例 #2
0
ファイル: CartServices.cs プロジェクト: blossomvn1/ecommerce
        public async Task <int> TaoDonHang(CartRequest gh, int userId)
        {
            Order dh = new Order
            {
                CreatedDate   = DateTime.UtcNow,
                PaymentStatus = gh.isPaid,
                Customer      = await _context.Customers.FirstOrDefaultAsync(o => o.CustomerId == userId),
                Amount        = 1,
                Address       = gh.shippingAddress.address,
                City          = gh.shippingAddress.city,
                TotalPrice    = gh.totalPrice,
                PaymentType   = await _context.PaymentTypes.FirstOrDefaultAsync(o => o.PaymentName == gh.paymentMethod)
            };

            dh.OrderProduct = new List <OrderProduct>();

            foreach (var item in gh.cartItems)
            {
                OrderProduct dhsp = new OrderProduct
                {
                    Order   = dh,
                    Product = await _context.Products.FirstOrDefaultAsync(o => o.ProductId == item.product),
                    Amount  = item.qty
                };
                dh.OrderProduct.Add(dhsp);
                var x = await _context.Products.FirstOrDefaultAsync(o => o.ProductId == item.product);

                x.InventoryNumber = x.InventoryNumber - item.qty;
                await _context.SaveChangesAsync();
            }

            dh.OrderStatus = new List <OrderStatus>();
            OrderStatus ttdh = new OrderStatus
            {
                OrderStatusName = "Chờ xác nhận",
                OrderId         = dh.OrderId,
                CreatedDate     = DateTime.UtcNow,
                Order           = dh
            };

            dh.OrderStatus.Add(ttdh);
            await _context.SaveChangesAsync();

            var createResult = await _context.Orders.AddAsync(dh);

            await _context.SaveChangesAsync();

            // return createResult is not null;
            return(dh.OrderId);
        }
コード例 #3
0
 public void UpdateOrderProduct(OrderProduct orderProduct)
 {
     using (var context = new InstantStoreDataContext())
     {
         var orderProductUpdated = context.OrderProducts.FirstOrDefault(x => x.Id == orderProduct.Id);
         if (orderProductUpdated != null)
         {
             orderProductUpdated.Count           = orderProduct.Count;
             orderProductUpdated.Price           = orderProduct.Price;
             orderProductUpdated.PriceCurrencyId = orderProduct.PriceCurrencyId;
             context.SubmitChanges();
         }
     }
 }
コード例 #4
0
 public IEnumerable<OrderProduct> AddorUpdateOrderProducts(OrderProduct orderproduct)
 {
     if (orderproduct.OrderProductID > 0)
     {
         OrderProduct oid = this.GetOrderProdById(orderproduct.OrderProductID);
         dbcontext.Entry(oid).CurrentValues.SetValues(orderproduct);
     }
     else
     {
         dbcontext.OrderProducts.Add(orderproduct);
     }
     dbcontext.SaveChanges();
     return dbcontext.OrderProducts.ToList();
 }
コード例 #5
0
        // GET: OrderProducts/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            OrderProduct orderProduct = db.OrderProducts.Find(id);

            if (orderProduct == null)
            {
                return(HttpNotFound());
            }
            return(View(orderProduct));
        }
コード例 #6
0
        public OrderOption AddProductToOrder(int orderId, int productId)
        {
            Order        order        = dbContext.Orders.Find(orderId);
            Product      product      = dbContext.Products.Find(productId);
            OrderProduct orderProduct = new OrderProduct
            {
                Order   = order,
                Product = product
            };

            dbContext.OrderProducts.Add(orderProduct);
            dbContext.SaveChanges();
            return(GetOrder(orderId));
        }
コード例 #7
0
ファイル: OrderProduct.cs プロジェクト: dakhabirov/ToolsWorld
        /// <summary>
        /// Добавить.
        /// </summary>
        /// <param name="orderId">Идентификатор заказа.</param>
        /// <param name="productId">Идентификатор товара.</param>
        /// <param name="amount">Количество.</param>
        /// <param name="price">Цена.</param>
        public static void Insert(int orderId, int productId, int amount, double price)
        {
            OrderProduct orderProduct = new OrderProduct
            {
                OrderId   = orderId,
                ProductId = productId,
                Amount    = amount,
                Price     = price,
                Sum       = amount * price
            };

            myDbContext.OrderProducts.Add(orderProduct);
            myDbContext.SaveChanges();
        }
コード例 #8
0
        public IHttpActionResult Post(int id)
        {
            TempOrderProduct temporderProduct = temporderProductRepository.Get(id);
            var       pid    = temporderProduct.ProductID;
            TempOrder torder = temporderrepo.Get(Convert.ToInt32(temporderProductRepository.Get(id).TempOrderId));

            temporderProductRepository.Delete(temporderProductRepository.Get(id).TempOrderProductID);
            temporderrepo.Delete(Convert.ToInt32(torder.TempOrderId));


            Order order = new Order();

            order.date          = DateTime.Now;
            order.PayMentMethod = torder.PayMentMethod;
            order.Quantity      = torder.Quantity;
            order.Size          = torder.Size;
            order.totalAmount   = torder.totalAmount;
            orderrepo.Insert(order);


            OrderProduct orderProduct = new OrderProduct();

            orderProduct.ProductHistoryId = producthis.GetByProductNameCategory(productrepo.Get(Convert.ToInt32(pid)).Product_name, productrepo.Get(Convert.ToInt32(pid)).MainCategoryId).ProductHistoryId;
            orderProduct.CustomerID       = temporderProduct.CustomerID;
            orderProduct.OrderID          = order.OrderID;
            productorderrepo.Insert(orderProduct);

            Profit profit = new Profit();

            ProductHistory phis = producthis.Get(orderProduct.ProductHistoryId);

            profit.OrderProductId = orderProduct.OrderProductId;
            if (phis.Sale != null)
            {
                var p  = (double)phis.UnitPrice;
                var v  = Convert.ToDouble(phis.Sale.Amount) / 100;
                var c1 = (p - (p * v));
                profit.ProfitAmount = ((decimal)c1 - phis.Cost) * order.Quantity;
            }
            else
            {
                profit.ProfitAmount = (phis.UnitPrice - phis.Cost) * order.Quantity;
            }


            profitrepo.Insert(profit);

            return(Ok("success"));
        }
コード例 #9
0
        //A brand new function for adding a product to the currently open order
        public async Task <IActionResult> AddToCart(int id)
        {
            //gets the user that's currently logged in
            ApplicationUser currentUser = await GetCurrentUserAsync();

            //will only add a product to the order IF the user is logged int
            if (currentUser != null)
            {
                if (ModelState.IsValid)
                {
                    //Finds the first order that matches the user's Id AND has no payment type (this signifies the order is open, and there should only be one)
                    Order orderToAddTo = await _context.Order
                                         .Where(o => o.UserId == currentUser.Id)
                                         .Where(o => o.PaymentTypeId == null)
                                         .FirstOrDefaultAsync();

                    //If there is no current open order, we'll create one!
                    if (orderToAddTo == null)
                    {
                        //Creates a new order...
                        orderToAddTo = new Order
                        {
                            DateCreated = DateTime.Now,
                            UserId      = currentUser.Id,
                            User        = currentUser
                        };
                        //...then adds it to the database! This object's id is also now its database id
                        _context.Add(orderToAddTo);
                        await _context.SaveChangesAsync();
                    }

                    //Adds a new OrderProduct resource to link the desired product to the open order
                    OrderProduct newProductOnOrder = new OrderProduct
                    {
                        ProductId = id,
                        OrderId   = orderToAddTo.OrderId
                    };

                    //Adds the product to the order and returns us to the Index view
                    _context.Add(newProductOnOrder);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Details", "Orders"));
                }
            }

            //If the user is not logged in, or the model state is invalid, go to the index page
            return(RedirectToAction(nameof(Index)));
        }
        public async Task <IActionResult> AddToOrder(int ProductId, int Quantity)
        {
            //Get the current user
            var user = await _userManager.GetUserAsync(HttpContext.User);

            //Check if Order exists for the current user
            var currentOrder = GetCurrentOrder(user.Id);

            //If yes, add the product to OrderProducts for the Quantity amount of times
            if (currentOrder != null)
            {
                for (int i = 0; i < Quantity; i++)
                {
                    OrderProduct orderProduct = new OrderProduct()
                    {
                        OrderId   = currentOrder.OrderId,
                        ProductId = ProductId
                    };
                    _context.Update(orderProduct);
                }
                await _context.SaveChangesAsync();
            }
            //Otherwise, create a new order and add the products to OrderProducts for the Quantity amount of times
            else
            {
                Order newOrder = new Order()
                {
                    DateCreated = DateTime.Now,
                    UserId      = user.Id,
                    User        = user
                };
                _context.Update(newOrder);
                await _context.SaveChangesAsync();

                var newOrderFromDB = GetCurrentOrder(user.Id);
                for (int i = 0; i < Quantity; i++)
                {
                    OrderProduct orderProduct = new OrderProduct()
                    {
                        OrderId   = newOrderFromDB.OrderId,
                        ProductId = ProductId
                    };
                    _context.Update(orderProduct);
                }
                await _context.SaveChangesAsync();
            }

            return(RedirectToAction("Details"));
        }
コード例 #11
0
        public async Task CurrentCountOrderProductsByUserId(string userId)
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;

            var dbContext = new ApplicationDbContext(options);

            var repository = new EfDeletableEntityRepository <OrderProduct>(dbContext);
            var service    = new OrderProductService(repository);

            var orderProduct1 = new OrderProduct
            {
                ProductId = 1,
                CreatorId = userId,
                Quantity  = 1,
                Price     = 10,
                Status    = OrderProductStatus.Active,
            };

            var orderProduct2 = new OrderProduct
            {
                ProductId = 2,
                CreatorId = userId,
                Quantity  = 1,
                Price     = 5,
                Status    = OrderProductStatus.Active,
            };

            var orderProduct3 = new OrderProduct
            {
                ProductId = 3,
                CreatorId = userId,
                Quantity  = 1,
                Price     = 5,
                Status    = OrderProductStatus.Completed,
            };
            await repository.AddAsync(orderProduct1);

            await repository.AddAsync(orderProduct2);

            await repository.AddAsync(orderProduct3);

            await repository.SaveChangesAsync();

            var count = service.CurrentCountOrderProductsByUserId(userId);

            Assert.Equal(2, count);
        }
コード例 #12
0
        public Order Get(int orderId)
        {
            var order = new Order();

            try
            {
                _sqlConnection.Open();

                SqlCommand cmd = new SqlCommand("Select * from [Order] where id=@id", _sqlConnection);
                cmd.Parameters.Add("@id", SqlDbType.Int).Value = orderId;

                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        order.Id         = (int)rdr["id"];
                        order.CustomerId = (int)rdr["CustomerId"];
                        order.OrderDate  = DateTime.Parse(rdr["OrderDate"].ToString());
                    }
                }

                cmd = new SqlCommand("Select * from OrderProduct where orderId=@orderId", _sqlConnection);
                cmd.Parameters.Add("@orderId", SqlDbType.Int).Value = orderId;

                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        var orderProduct = new OrderProduct();

                        orderProduct.Id        = (int)rdr["id"];
                        orderProduct.OrderId   = (int)rdr["OrderId"];
                        orderProduct.ProductId = (int)rdr["ProductId"];
                        orderProduct.Qty       = int.Parse(rdr["Qty"].ToString());

                        order.OrderProducts.Add(orderProduct);
                    }
                }
            }
            finally
            {
                if (_sqlConnection != null)
                {
                    _sqlConnection.Close();
                }
            }

            return(order);
        }
コード例 #13
0
        public async void CreateOrderMethod()
        {
            if (CreateVisibility == Visibility.Visible)
            {
                Order order = new Order("hahahaha");
                await Catalog <Order> .Instance.Create(order);

                Order latestOrder =
                    Catalog <Order> .Instance.GetList.Find(x => x.OrderDate >= DateTime.Now.Subtract(TimeSpan.FromSeconds(5)));

                OrderHistory orderHistory = new OrderHistory(latestOrder, Controller.StoreId);
                await Catalog <OrderHistory> .Instance.Create(orderHistory);

                bool gotData = false;

                foreach (var i in _listOfOrders)
                {
                    if (i.ActualAmount > 0)
                    {
                        OrderProduct op = new OrderProduct(latestOrder.Id, i.Product.Id, i.ActualAmount);
                        await Catalog <OrderProduct> .Instance.Create(op);

                        OrderHistoryData ohd = new OrderHistoryData(orderHistory.Id, i.Product.Name, i.SupplierName, i.SupplierEmail,
                                                                    i.Missing, i.Product.AmountPerBox, i.SuggestedAmount, i.ActualAmount);
                        await Catalog <OrderHistoryData> .Instance.Create(ohd);

                        gotData = true;
                    }
                }

                if (gotData == false)
                {
                    await Catalog <Order> .Instance.Delete(order.Id);

                    await Catalog <OrderHistory> .Instance.Delete(orderHistory.Id);
                }
                OnPropertyChanged(nameof(OrderHistoryCatalog));
            }
            else
            {
                OnPropertyChanged(nameof(OrderHistoryCatalog));

                DataVisibility   = Visibility.Collapsed;
                CreateVisibility = Visibility.Visible;

                OnPropertyChanged(nameof(DataVisibility));
                OnPropertyChanged(nameof(CreateVisibility));
            }
        }
コード例 #14
0
        public bool CancelOrders(int OrderId)
        {
            try
            {
                OrderProduct cancelOrders    = _unitOfWork.OrderRepository.Find(x => x.Id == OrderId, y => y.OrderProductItem).FirstOrDefault <OrderProduct>();
                var          shippingAddress = _shoppingCartRepository.GetAddress(cancelOrders.ShippingAddressId);


                UserService userService = new UserService();
                var         user        = userService.GetUser(cancelOrders.CustomerId);

                if (cancelOrders.CustomerId == CurrentUserId())
                {
                    var orderStatusId = (int)((Enums.OrderStatus)Enum.Parse(typeof(Enums.OrderStatus), "Cancelled"));


                    if (cancelOrders.OrderStatusId < 10)
                    {
                        foreach (var orderItem in cancelOrders.OrderProductItem)
                        {
                            if (orderItem.OrderItemStatus < 10)
                            {
                                orderItem.OrderItemStatus = orderStatusId;
                                orderItem.OrderCancel     = true;
                            }
                        }
                        cancelOrders.OrderStatusId = orderStatusId;
                        cancelOrders.OrderCancel   = true;
                        _unitOfWork.UpdateAndSave(cancelOrders);

                        try
                        {
                            VSOnline.VSECommerce.Domain.Helper.MailHelper.SendOrderCancellationMail(user.Email, OrderId.ToString());
                            VSOnline.VSECommerce.Domain.Helper.MessageHelper.SendOrderCancellationSMS(OrderId, shippingAddress.PhoneNumber);
                        }
                        catch
                        {
                        }

                        return(true);
                    }
                }
            }
            catch
            {
                return(false);
            }
            return(false);
        }
コード例 #15
0
        public void CreateOrder()
        {
            Order order = new Order();

            foreach (CartItem item in Items)
            {
                OrderProduct orderProduct = new OrderProduct();
                orderProduct.VariantId = item.VariantId;
                orderProduct.Quantity  = item.Quantity;
                order.LineItems.Add(orderProduct);
            }

            order.BranchId = laGranLuchaManager.CurrentBranch.Id;
            apiManager.SendFakeRequestSucceded(order, null);
        }
コード例 #16
0
ファイル: Model1.cs プロジェクト: ilanitif/finally
        internal static void PayOrde(string card, string cardNumber, string cvc, string firstName, string lastName, string Id, string street, string city, string post_code, OrderProduct or)
        {
            if (card == string.Empty || firstName == string.Empty || lastName == string.Empty || street == string.Empty || city == string.Empty)
            {
                throw new ApplicationException("One or more of the deatails is missing please try again");
            }
            if (cardNumber.Length < 9) throw new ApplicationException("Card number not valid please try again");
            if (cvc.Length != 3) throw new ApplicationException("Card securty code (cvc) not valid please try again");
            if (Id.Length < 9) throw new ApplicationException("Id number not valid please try again");
            if (post_code.Length < 4) throw new ApplicationException("Post code not valid please try again");

            Order ordery = client.GetOrder(or.Order.Id);
            //closing order by date time feled
            ordery.DateOfPayment = DateTime.Now;
        }
コード例 #17
0
 /// <summary>
 /// 获取套系产品
 /// </summary>
 /// <param name="suiteNo">套系编号</param>
 /// <param name="boxes">包装数据集</param>
 /// <param name="frames">框条数据集</param>
 /// <returns>套系产品</returns>
 public IEnumerable <OrderProduct> GetSuiteProducts(string suiteNo, IEnumerable <Box> boxes, IEnumerable <Frame> frames)
 {
     using (DataSet ds = ExecuteQuery(string.Format(@"SELECT *, Size = ProductSizeA + '*' + ProductSizeB FROM dbo.V_SearchSuiteProduct WHERE SuiteNO='{0}'", suiteNo)))
     {
         try
         {
             return(from DataRow row in ds.Tables[0].Rows select OrderProduct.FromSuiteProduct(row, boxes, frames));
         }
         catch
         {
             MessageBoxEx.Error(string.Format(@"在数据库中查询套系产品列表时遇到了问题导致失败!{0}方法名称:'OrderProducts.GetSuiteProducts'", Environment.NewLine));
         }
         return(new OrderProduct[] {});
     }
 }
コード例 #18
0
 public bool UpdateAndSaveTransactionId(int orderId, OrderDTO orderDTO)
 {
     try
     {
         OrderProduct orderProduct = context.OrderProducts.Where(x => x.Id == orderId).FirstOrDefault();
         orderProduct.TransactionId             = orderDTO.TransactionId;
         this.context.Entry(orderProduct).State = EntityState.Modified;
         this.context.SaveChanges();
         return(true);
     }
     catch
     {
     }
     return(false);
 }
コード例 #19
0
        public void addOrderProduct(Order order, ViewCartDTO vcdto)
        {
            foreach (var cartItem in vcdto.CartProduct)
            {
                OrderProduct op = new OrderProduct();
                op.VariantID    = cartItem.Variant_ID;
                op.SellingPrice = cartItem.SellingPrice;
                op.OrderID      = order.ID;
                op.ID           = Guid.NewGuid();

                op.Qty = 1;
                dbContext.OrderProduct.Add(op);
                dbContext.SaveChanges();
            }
        }
コード例 #20
0
        public async Task CreateOrderProductAsync(int productId, string creatorId, decimal productPrice, int quantity)
        {
            var orderProduct = new OrderProduct
            {
                ProductId = productId,
                CreatorId = creatorId,
                Quantity  = quantity,
                Price     = quantity * productPrice,
                Status    = OrderProductStatus.Active,
            };

            await this.orderProductRepository.AddAsync(orderProduct);

            await this.orderProductRepository.SaveChangesAsync();
        }
コード例 #21
0
        public productObject TranslateOrderProduct(OrderProduct orderProduct)
        {
            var prod = new productObject();

            prod.sku               = orderProduct.Sku;
            prod.name              = orderProduct.Name;
            prod.description       = orderProduct.Description;
            prod.category          = orderProduct.Category;
            prod.quantity          = orderProduct.Quantity;
            prod.quantitySpecified = true;
            prod.price             = orderProduct.UnitPrice;
            prod.priceSpecified    = true;

            return(prod);
        }
コード例 #22
0
        public static OrderProductDTO MapToOrderProductDto(this OrderProduct source)
        {
            if (source == null)
            {
                return(null);
            }

            return(new OrderProductDTO
            {
                Id = source.Id.ToString(),
                OrderId = source.OrderId.ToString(),
                ProductId = source.ProductId.ToString(),
                Quantity = source.Quantity.ToString()
            });
        }
コード例 #23
0
        public async Task <IActionResult> DeleteOrder(OrderProduct item)
        {
            var order = await _context.Order.FindAsync(item.Order.OrderId);

            var itemToDelete = _context.OrderProduct.Where(op => op.OrderId == item.Order.OrderId);

            foreach (OrderProduct p in itemToDelete)
            {
                _context.OrderProduct.Remove(p);
            }
            _context.Order.Remove(order);
            await _context.SaveChangesAsync();

            return(RedirectToAction("Index", "Home"));
        }
コード例 #24
0
        public void Update(OrderProduct orderproduct)
        {
            if (orderproduct == null)
            {
                return;
            }
            var ordprd = DB.OrderProducts.FirstOrDefault(u => u.ID == orderproduct.ID);

            if (ordprd == null)
            {
                return;
            }
            DB.Entry(ordprd).CurrentValues.SetValues(orderproduct);
            DB.SaveChanges();
        }
コード例 #25
0
        public async Task <ActionResult> Delete(int id, OrderProduct orderProduct)
        {
            try
            {
                orderProduct.OrderProductId = id;
                _context.OrderProduct.Remove(orderProduct);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                return(View());
            }
        }
コード例 #26
0
        public bool Delete(int?Id)
        {
            var          result          = 0;
            OrderProduct getOrderProduct = Get(Id);

            getOrderProduct.IsDelete   = true;
            getOrderProduct.DeleteDate = DateTimeOffset.Now.LocalDateTime;
            result = myContext.SaveChanges();

            if (result > 0)
            {
                status = true;
            }
            return(status);
        }
コード例 #27
0
        // GET: OrderProducts/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            OrderProduct orderProduct = orderProductRepo.GetItem((int)id);

            if (orderProduct == null)
            {
                return(HttpNotFound());
            }
            return(View(orderProduct));
        }
コード例 #28
0
        // GET: OrderProducts/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            OrderProduct orderProduct = db.OrderProducts.Find(id);

            if (orderProduct == null)
            {
                return(HttpNotFound());
            }
            ViewBag.ProductID = new SelectList(db.Products, "ProductID", "Name", orderProduct.ProductID);
            return(View(orderProduct));
        }
コード例 #29
0
        public static List <OrderProduct> CreateOrderProducts(List <ShoppingCart> shoppingCart, Customer customer, CustomerAddress customerAddress)
        {
            List <OrderProduct> orderProducts = new List <OrderProduct>();

            foreach (var sh in shoppingCart)
            {
                OrderProduct orderProduct = new OrderProduct();
                orderProduct.ProductId       = sh.ProductId;
                orderProduct.StoreId         = sh.StoreId;
                orderProduct.CustomerId      = customer.CustomerId;
                orderProduct.CustomerAddress = customerAddress;
                orderProducts.Add(orderProduct);
            }
            return(orderProducts);
        }
コード例 #30
0
ファイル: OrderLogic.cs プロジェクト: NeaEnot/GUIDT
        private OrderProductView MapOrderProductView(OrderProduct orderProduct)
        {
            Product product = context.Products.FirstOrDefault(rec => rec.Id == orderProduct.ProductId);

            return
                (new OrderProductView
            {
                Id = orderProduct.Id,
                OrderId = orderProduct.OrderId,
                ProductId = orderProduct.ProductId,
                Count = orderProduct.Count,
                Price = orderProduct.Price,
                ProductName = product != null ? product.Name : "Undefined"
            });
        }
コード例 #31
0
        public async Task <IActionResult> PutOrderProduct([FromRoute] int id, [FromBody] OrderProduct orderProduct)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != orderProduct.Id)
            {
                return(BadRequest());
            }

            string       userId           = User.Claims.First(c => c.Type == "UserId").Value;
            OrderProduct tempOrderProduct = await _context.OrderProducts.AsNoTracking().FirstOrDefaultAsync(i => i.Id == id);

            orderProduct.OrderId   = tempOrderProduct.OrderId;
            orderProduct.ProductId = tempOrderProduct.ProductId;
            var tempOrder = await _context.Orders.FirstOrDefaultAsync(i => i.Id == tempOrderProduct.OrderId);

            if (User.IsInRole("Admin") || tempOrder.UserId.Equals(userId))//jei admin, gali visus
            {
                //order.Date = DateTime.Now.ToLocalTime();
                //order.UserId = tempOrder.UserId;
                _context.Entry(orderProduct).State = EntityState.Modified;

                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!OrderProductExists(id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                        //return BadRequest("Bandykite dar kartą, arba trūksta duomenų");
                    }
                }

                return(NoContent());
                //return Ok(order);
            }

            return(Unauthorized());
        }
コード例 #32
0
        public void EF6SourceTest()
        {
            using (var dataSource = _source.BeginTransaction())
            {
                // arrange
                var customer = new Customer {
                    Name = "dummy"
                };
                var product1 = new Product("dummy product1", 35)
                {
                    AmountValue = 29.30M,
                    Description = "A dummy product 1 description"
                };
                var product2 = new Product("dummy product2", 13)
                {
                    AmountValue = 109.90M,
                    Description = "A dummy product 2 description"
                };
                var orderProduct1 = new OrderProduct(product1, 15);
                var orderProduct2 = new OrderProduct(product2, 5);
                var order         = new Order(customer, new OrderProduct[] { orderProduct1, orderProduct2 });

                // act
                _source.Set <Customer>().Add(customer);
                _source.Set <Product>().Add(product1);
                _source.Set <Product>().Add(product2);
                _source.Set <OrderProduct>().Add(orderProduct1);
                _source.Set <OrderProduct>().Add(orderProduct2);
                _source.Set <Order>().Add(order);

                _source.CommitState();

                var returnOrder = _source.Set <Order>()
                                  .Where(o => o.CustomerId == customer.Id)
                                  .Include(o => o.Customer)
                                  .Include(o => o.OrderProducts)
                                  .AsNoTracking()
                                  .Single();

                // assert
                Assert.AreEqual(order.Id, returnOrder.Id);
                Assert.AreEqual(order.TotalAmount, returnOrder.TotalAmount);
                Assert.AreEqual(order.Customer.Name, returnOrder.Customer.Name);
                Assert.AreEqual(order.OrderProducts.Count, returnOrder.OrderProducts.Count);

                dataSource.CommitTransaction();
            }
        }
コード例 #33
0
ファイル: ShoppingCart.cs プロジェクト: cj8397/2hourVer2
        public void AddItem(int productID, int? qty, string sessionID)
        {
                var item = new OrderProduct();
                item.sessionID = sessionID;
                item.quantity = qty;
                item.productID = productID;
                item.updatedSession = DateTime.Now;

                if (db.Visits.Any(v => v.sessionID == sessionID))
                {
                    isValidItem(sessionID, productID);
                }

                db.OrderProducts.Add(item);
                db.SaveChanges();

        }
コード例 #34
0
        //public void CreateDict([Bind(Include = "prod,quantity")] ClientOrderViewModel cc)
        //{
        //    if (prodDict.ContainsKey(cc.prod))
        //    {
        //        prodDict[cc.prod] = prodDict[cc.prod] + cc.Quantity;
        //    }
        //    else
        //    {
        //        prodDict.Add(cc.prod, cc.Quantity);
        //    }
        //}
        //    //cc.OrderedProducts = GetOrderList(orderID);
        //    //AllProducts = cd.ListProducts();
        //    //cc.AllProducts = AllProducts;
        //    //// cc.OrderedProducts = AllProductsOrder;
        //    //return View("Create", cc);
        //}
        // public ActionResult CreateOrder()
        public void CreateOrder(int RetailerID, int StoreID, string datepicker)
        {
            Order order = new Order();
            order.RetailerID = RetailerID;
            order.StoreID = StoreID;
            order.Status = "PE";
            order.DeliveryDate = Convert.ToDateTime(datepicker);
            //order.RetailerID = 4;
            //order.StoreID = 4;
            //order.Status = "PE";
            //order.DeliveryDate = null;

            ClientOrderDAL clientorder = new ClientOrderDAL();
            clientorder.AddorUpdate(order);

            foreach (KeyValuePair<int, int> entry in prodDict)
            {
                OrderProduct orderproduct = new OrderProduct();
                orderproduct.OrderID = order.OrderID;
                orderproduct.ProductID = entry.Key;
                orderproduct.Quantity = entry.Value;
                clientorder.AddorUpdateOrderProducts(orderproduct);
            }

            //ClientOrderViewModel orderprod = new ClientOrderViewModel();
            //orderprod.AllProducts = AllProducts;
            //orderprod.OrderedProducts = cd.AllOrderedProduct(order.OrderID);
            //ViewBag.StoreID = new SelectList(db.Stores, "StoreID", "Name");
            //ViewBag.RetailerID = new SelectList(db.Retailers, "RetailerID", "Name");
            //return View("Create", orderprod);

            orderID = order.OrderID;
            ViewBag.StoreID = new SelectList(db.Stores, "StoreID", "Name");
            ViewBag.RetailerID = new SelectList(db.Retailers, "RetailerID", "Name");
            //return orderID;
            CreateFinal(orderID);
            //return RedirectToAction("CreateFinal");
        }
コード例 #35
0
ファイル: HomeController.cs プロジェクト: ilanitif/finally
        public ActionResult YourDeatails(string notes, int quantity, string deliveryAdress, string country, string city, string card, string street, string streetNumber, int productId, int shippingId)
        {
            Session["url"] = "YourDeatails";
            BuyNet.User u = (BuyNet.User)Session["User"];
            if(u==null)
            {
                return RedirectToAction("Login");
            }
            if (country == string.Empty || country == null) { country = u.Country; }
            if (city == string.Empty || city == null) { city = u.City; }
            if (streetNumber == string.Empty || streetNumber == null) { streetNumber = u.Street_number; }
            Shipping_Company ship = client.GetShipping_Company(shippingId);
            ship.city = city;
            ship.country = country;
            ship.streetNumber = street+" "+streetNumber;
            Product product = client.GetProduct(productId);
            try
            {
                Order or = new Order();
                or.Shipping_Company = ship;
                or.User = u;
                or.DateOfPayment = null;
                or.Single = true;
                client.AddOrder(or);

                foreach (var item in client.GetOrders())
                {
                    if (item.BuyerId == or.User.Id && item.DateOfPayment == null && item.Single==true)
                    {
                        OrderProduct op = new OrderProduct()
                        {
                            Quantity = quantity,
                            Product = product,
                            Order = item,
                            OrderId = item.Id,
                            PriceAtPayment = int.Parse(product.Price.ToString()) * int.Parse(quantity.ToString())
                        };
                        op.OrderId = item.Id;
                        item.DateOfPayment = DateTime.Now;
                        client.Edit_Order(item.Id, item);
                        client.AddOrderProduct(op);
                        break;
                    }

                }

            }
            catch (Exception ex)
            {

                throw ex;
            }

            ViewBag.user = User;

            return RedirectToAction("uSERP");
        }
コード例 #36
0
ファイル: HomeController.cs プロジェクト: ilanitif/finally
        public ActionResult AddToCart(int product)
        {
            /*, int qantity*/

            Session["url"] = "userP";
            BuyNet.User u = (BuyNet.User)Session["User"];
            if (u == null)
            {
                return RedirectToAction("login");
            }
            List<Order> userOrders = client.GetOrders().Where(o => o.User.UserName.Trim().ToLower() == u.UserName.Trim().ToLower()).ToList();
            Order order = userOrders.Where(o => o.DateOfPayment == null).FirstOrDefault();
            if (order == null)
            {
                order = new Order()
                {
                    User = u,
                    Shipping_Company = client.GetShipping_Company(2),
                    DateOfPayment = null,
                };
                client.AddOrder(order);
            }

            OrderProduct op = new OrderProduct();
            op.Order = order;
            op.Product = client.GetProduct(product);
            op.Quantity = 1;
            op.PriceAtPayment = int.Parse(op.Product.Price.ToString()) * int.Parse(op.Quantity.ToString());
            client.AddOrderProduct(op);

            return RedirectToAction("Userp");//or return view
        }
コード例 #37
0
 public static OrderProduct CreateOrderProduct(long productID, decimal expectedQuantity, decimal customerTargetPrice, decimal orderValue, short currencyID, long orderID, long productNameID, short uOMID)
 {
     OrderProduct orderProduct = new OrderProduct();
     orderProduct.ProductID = productID;
     orderProduct.ExpectedQuantity = expectedQuantity;
     orderProduct.CustomerTargetPrice = customerTargetPrice;
     orderProduct.OrderValue = orderValue;
     orderProduct.CurrencyID = currencyID;
     orderProduct.OrderID = orderID;
     orderProduct.ProductNameID = productNameID;
     orderProduct.UOMID = uOMID;
     return orderProduct;
 }
コード例 #38
0
 public void AddToOrderProducts(OrderProduct orderProduct)
 {
     base.AddObject("OrderProducts", orderProduct);
 }