Beispiel #1
0
        public ActionResult editProductOrder(int ID)
        {
            ViewBag.Warehouse = virames <Warehouse> .Initialize(new List <Warehouse>()).Where(x => x.Center == false && x.Quality == false).GetList().Select(x => new SelectListItem
            {
                Value = x.ID.ToString(),
                Text  = x.Code + " | " + x.WarehouseName
            });

            ViewBag.Project = virames <Project> .Initialize(new List <Project>()).GetList().Select(x => new SelectListItem
            {
                Value = x.ID.ToString(),
                Text  = x.Code + " | " + x.Definition + " | " + x.StartDate + " | " + x.EndDate
            });

            ViewBag.Material = virames <Material> .Initialize(new List <Material>()).Where(x => x.MaterialType.Producible).GetList().Select(x => new SelectListItem
            {
                Value = x.ID.ToString(),
                Text  = x.MaterialType + " | " + x.Code + " | " + x.Definition + " | " + x.OnHand + " | " + x.TraceType + " | " + x.Status
            });

            ViewBag.SpeCode = virames <SpeCode> .Initialize(new List <SpeCode>()).Where(x => x.SpeCodeType == SpeCodeType.ProductOrder).GetList().Select(x => new SelectListItem
            {
                Value = x.ID.ToString(),
                Text  = x.SpecialCode + " | "
            });

            ViewBag.Status = new SelectList(Enum.GetValues(typeof(Status)));

            ProductOrder productOrder = virames <ProductOrder>
                                        .Initialize(new ProductOrder()).Where(x => x.ID.ToString() == ID.ToString())
                                        .Take();

            ViewBag.ProductOrder = productOrder;
            return(View(productOrder));
        }
        public async Task <ProductOrder> AddProductOrderAsync(ProductOrder productOrder)
        {
            var lineItem = await _context.Set <ProductOrder> ()
                           .AddAsync(productOrder);

            return(lineItem.Entity);
        }
Beispiel #3
0
        public void Scan(IProduct product)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product object is null");
            }

            var order = orders.FirstOrDefault(x => x.Product.SKU == product.SKU);

            if (order == null)
            {
                order = new ProductOrder()
                {
                    Product = product, Quantity = 1
                };
                orders.Add(order);
            }
            else
            {
                order.Quantity++;
            }

            // assumption -- offers can be validated different ways but not much concerned at this point
            if (offers != null)
            {
                foreach (Offer offer in offers)
                {
                    if (offer.IsValid(order))
                    {
                        offer.ApplyOffer(order, orders);
                    }
                }
            }
        }
        /// <summary>
        /// Place Order and verify registred user
        /// </summary>
        /// <param name="ProductId"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public async Task <bool> PlaceOrder(string ProductId, string UserId)
        {
            try
            {
                var res      = false;
                var objectId = new ObjectId(ProductId);
                FilterDefinition <Product> filter = Builders <Product> .Filter.Eq("ProductId", objectId);

                _dbproductCollection = _mongoContext.GetCollection <Product>(typeof(Product).Name);
                var product = await _dbproductCollection.FindAsync(filter).Result.FirstOrDefaultAsync();

                if (product != null)
                {
                    var order = new ProductOrder()
                    {
                        ProductId = product.ProductId,
                        UserId    = UserId
                    };
                    _dbproductorderCollection = _mongoContext.GetCollection <ProductOrder>(typeof(ProductOrder).Name);
                    await _dbproductorderCollection.InsertOneAsync(order);
                }
                res = true;
                return(res);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
Beispiel #5
0
        public ActionResult Details(int id, bool recentOrder)
        {
            List <int>     productIDs = (from r in _entities.ProductOrderDetails where r.ProductOrderID == id select r.ProductID).ToList();
            List <Product> products   = new List <Product> ();

            foreach (int iID in productIDs)
            {
                products.Add(_entities.Products.Single(a => a.ID == iID));
            }

            MembershipUser muc           = Membership.GetUser();
            int            memberOrderID = (from r in _entities.MemberOrders where r.ProductOrderID == id && r.MemberInfo.MemberID == (Guid)muc.ProviderUserKey select r.ID).FirstOrDefault();

            ProductOrder productOrder = _entities.ProductOrders.Single(a => a.ID == id);
            DateTime     today        = DateTime.Today;
            bool         uPO          = true;

            if (productOrder.OrderCloseDate < today)
            {
                uPO = false;
            }

            ProductOrderViewModel viewModel = new ProductOrderViewModel
            {
                ProductOrder    = productOrder,
                ProductOrderIDs = (from r in _entities.ProductOrders.Where(a => a.OrderCloseDate >= today && uPO || !uPO && a.OrderCloseDate < today) orderby r.OrderCloseDate, r.ID select r.ID).ToList(),
                Products        = products,
                MemberOrderID   = memberOrderID,
            };

            ViewData["RecentOrder"] = recentOrder;

            return(View(viewModel));
        }
Beispiel #6
0
        public async Task <IActionResult> Create([Bind("Id,Data,Kwota,Zrealizowane,ClientId")] Order order)
        {
            if (ModelState.IsValid)
            {
                var lista = HttpContext.Request.Form["selectedProducts"];
                _context.Add(order);
                await _context.SaveChangesAsync();

                var money = 0.0;
                foreach (var l in lista)
                {
                    var pg  = new ProductOrder();
                    var szt = HttpContext.Request.Form[l];
                    pg.ProductId   = int.Parse(l);
                    pg.ilosc_sztuk = int.Parse(szt);
                    var p    = _context.Products.Where(p => p.Id == pg.ProductId).First();
                    var cena = p.Cena;
                    money     += cena * Int32.Parse(szt);
                    pg.OrderId = order.Id;
                    if (pg.ilosc_sztuk != 0)
                    {
                        _context.Add(pg);
                    }
                    await _context.SaveChangesAsync();
                }
                order.Kwota = money;
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ClientId"] = new SelectList(_context.Clients, "Id", "Nazwa_firmy", order.ClientId);
            return(View(order));
        }
Beispiel #7
0
 public void Post([FromBody] ProductOrder productOrder)
 {
     productOrder.Name        = productOrder.Name;
     productOrder.TotalAmount = productOrder.Price * productOrder.Amount;
     productOrder.Discount    = CalculateDiscount(productOrder.Amount, productOrder.Price);
     productOrders.Add(productOrder);
 }
        public IActionResult ProcessOrder()
        {
            Order neworder = new Order();

            neworder.UserId = Int32.Parse(Request.Cookies["UserID"]);
            string cart = Request.Cookies["cart"];

            if (!string.IsNullOrEmpty(cart))
            {
                List <int> productids = parseCart(cart);
                var        products   = from p in _context.Products
                                        select p;
                var selectedproducts = products.Where(p => productids.Contains(p.ProductId));
                foreach (var item in selectedproducts)
                {
                    ProductOrder po = new ProductOrder();
                    po.Product = item;
                    po.Order   = neworder;
                    _context.ProductOrders.Add(po);
                    neworder.Total += item.Price;
                }
                _context.Orders.Add(neworder);
                _context.SaveChanges();

                return(RedirectToAction("Order", neworder));
            }

            return(RedirectToAction("Checkout"));
        }
        public async Task <IActionResult> AddToCart(string id)
        {
            var order = new Order();

            order.OrderId          = Guid.NewGuid().ToString();
            order.HasBeenPlaced    = 0;
            order.HasBeenConfirmed = "0";
            order.ClientId         = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            _context.Order.Add(order);
            var stocks = _context.StockEntry.Include(s => s.Product).OrderBy(x => x.RemainingStock);

            foreach (var stock in stocks)
            {
                if (stock.ProductId == id)
                {
                    stock.RemainingStock--;
                    _context.Update(stock);
                    break;
                }
            }
            await _context.SaveChangesAsync();

            var productorder = new ProductOrder();

            productorder.IdProductOrder = Guid.NewGuid().ToString();
            productorder.OrderIdFk      = order.OrderId;
            productorder.ProductIdFk    = id;
            _context.ProductOrder.Add(productorder);
            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Beispiel #10
0
        public async Task <List <CartItemWithDetailsDto> > PlaceOrder(List <CartItemWithDetailsDto> dtoList, string userId)
        {
            var     date          = DateTime.Now;
            decimal totalPrice    = dtoList.Sum(dto => dto.Quantity * dto.ProductPrice);
            string  invoiceNumber = GenerateInvoiceNumber();
            Order   order         = new Order()
            {
                Date          = date,
                TotalPrice    = totalPrice,
                InvoiceNumber = invoiceNumber,
                UserId        = userId
            };

            await _cartRepository.CreateNewOrder(order);

            foreach (var dto in dtoList)
            {
                ProductOrder productOrder = new ProductOrder()
                {
                    OrderId   = order.Id,
                    ProductId = dto.ProductId,
                    Quantity  = dto.Quantity
                };

                await _cartRepository.CreateProductOrder(productOrder);

                var cartItem = await _cartRepository.GetCartItem(dto.Id);

                await _cartRepository.DeleteCartItem(cartItem);
            }

            return(dtoList);
        }
Beispiel #11
0
        private void btnDiagnoseSubmit_Click(object sender, EventArgs e)
        {
            string       status;
            bool         prodOrderMade = false;
            ProductOrder po            = new ProductOrder();

            foreach (OrderLine ol in selectedServiceOrder.serviceParts)
            {
                if (ol.ColOrderQuantity > ol.ColStockQuantity)
                {
                    if (!prodOrderMade)
                    {
                        po.PordStatus        = "Requested";
                        po.RequestingEmpID   = currentUser.ID;
                        po.PordRequestSource = "SO-" + selectedServiceOrder.ID.ToString();
                        po            = GlobalConfig.Connection.CreateProductOrder(po, out status);
                        prodOrderMade = true;
                    }
                    ol.ProdOrderID = po.ID;
                }
                GlobalConfig.Connection.CreateOrderLine(ol, out status);
            }
            selectedServiceOrder.SerOrdDiagnosis = txtDiagnoseDescription.Text;
            selectedServiceOrder.TechnicianID    = currentUser.ID;
            selectedServiceOrder.SerOrdStatus    = "Diagnosed";
            GlobalConfig.Connection.EditServiceOrder(selectedServiceOrder, out status);
            MessageBox.Show(status);
        }
Beispiel #12
0
        // GET: ProductOrderController/Create
        public ActionResult Create()
        {
            ProductOrder productOrder = new ProductOrder();

            if (ProductOrders.Count == 0)
            {
                productOrder.orderId = 1;
                ProductOrders.Add(productOrder);
            }
            else
            {
                if (productOrder.orderId == 0)
                {
                    ProductOrder lastProductOrder = ProductOrders.Last();
                    productOrder.orderId = lastProductOrder.orderId + 1;
                    ProductOrders.Add(productOrder);
                }
            }
            ViewBag.clientId = new SelectList
                               (
                ClientController.Clients,
                "id",
                "name"
                               );
            return(View(productOrder));
        }
Beispiel #13
0
        public async Task <string> Checkout(string StreetAddress, string?Complex, string Suburb, string City, string Province, string PostCode)
        {
            ACMEDbContext context   = new ACMEDbContext();
            string        email     = HttpContext.Session.GetString("Email");
            var           user      = context.Users.Where(u => u.Email == email).Include(u => u.ShoppingCart).First();
            ShoppingCart  cart      = user.ShoppingCart;
            var           cartItems = context.ProductShoppingCarts.Where(psc => psc.ShoppingCart.ShoppingCartID == cart.ShoppingCartID).Include(psc => psc.Product).ToList();

            string shippingAddress = StreetAddress + ", " + ((Complex != null) ? (Complex + ", ") : "") + Suburb + ", " + City + ", " + Province + ", " + PostCode;
            Order  order           = new Order();

            order.OrderDate       = DateTime.Now.Date;
            order.ETA             = DateTime.Now.AddDays(2).Date;
            order.ShippingAddress = shippingAddress;
            order.User            = user;
            context.Orders.Add(order);

            await context.SaveChangesAsync();

            foreach (var item in cartItems)
            {
                ProductOrder po = new ProductOrder();
                po.Order    = order;
                po.Product  = item.Product;
                po.Quantity = item.Quantity;

                context.Stock.First(s => s.Product == item.Product).Quantity -= item.Quantity;
                context.ProductOrders.Add(po);
                context.ProductShoppingCarts.Remove(item);
            }

            await context.SaveChangesAsync();

            return("Ok");
        }
        public async Task RemoveProductFromOrderAsync(int productId, ClaimsPrincipal user)
        {
            var product = await this.DbContext.Products.FindAsync(productId);


            if (product == null || this.userManager.GetUserId(user) == null)
            {
                throw new NotFoundException();
            }

            var order = this.DbContext.Orders.Include(o => o.Product).FirstOrDefault(o => o.UserId == this.userManager.GetUserId(user));

            if (order == null)
            {
                throw new NotFoundException();
            }
            var productToRemove = new ProductOrder();

            foreach (var productToCheck in order.Product)
            {
                if (productToCheck.ProductId == productId)
                {
                    productToRemove = productToCheck;
                }
            }
            order.Product.Remove(productToRemove);
            this.DbContext.Orders.Update(order);
            await this.DbContext.SaveChangesAsync();
        }
Beispiel #15
0
        /// <summary>
        /// Better approach to save things into database(than db.SaveChanges()) for this controller.
        /// </summary>
        /// <param name="view">Say the view state, where it is calling from.</param>
        /// <param name="productOrder">Your model information to send in email to developer when failed to save.</param>
        /// <returns>If successfully saved returns true or else false.</returns>
        bool SaveDatabase(ViewStates view, ProductOrder productOrder = null)
        {
            // working those at HttpPost time.
            switch (view)
            {
            case ViewStates.Create:
                break;

            case ViewStates.Edit:
                break;

            case ViewStates.Delete:
                break;
            }

            try     {
                var changes = db.SaveChanges(productOrder);
                if (changes > 0)
                {
                    RemoveOutputCacheOnIndex();
                    RemoveOutputCache(CurrentControllerRemoveOutputCacheUrl);
                    return(true);
                }
            } catch (Exception ex) {
                throw new Exception("Message : " + ex.Message.ToString() + " Inner Message : " + ex.InnerException.Message.ToString());
            }
            return(false);
        }
Beispiel #16
0
        public IActionResult AddNewOrder(AddOrderViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var availableItems = _unitOfWork.ProductRepository.GetQuantityInStock(model.ProductId);

            if (model.Quantity > availableItems)
            {
                ModelState.AddModelError("", _localizer["MaxQuantityExceeded"]);
                return(View(model));
            }

            var product = _unitOfWork.ProductRepository.FindBy(a => a.ProductId == model.ProductId).FirstOrDefault();

            product.QuantityInStock -= model.Quantity;

            var newOrder = new ProductOrder
            {
                Product         = product,
                QuantityOrdered = model.Quantity,
                Client          = _userManager.FindByNameAsync(User.Identity.Name).Result
            };

            _unitOfWork.ProductOrderRepository.Add(newOrder);
            _unitOfWork.SaveChanges();
            return(RedirectToAction("Index", "Home"));
        }
Beispiel #17
0
        public ActionResult Create(ProductOrder productOrder)
        {
            bool viewOf = ViewTapping(ViewStates.CreatePostBefore, productOrder);

            if (DropDownDynamic == false)
            {
                GetDropDowns(productOrder);
            }
            if (ModelState.IsValid)
            {
                db.ProductOrders.Add(productOrder);
                bool state = SaveDatabase(ViewStates.Create, productOrder);
                if (state)
                {
                    AppVar.SetSavedStatus(ViewBag, CreatedSaved);                     // Saved Successfully.
                }
                else
                {
                    AppVar.SetErrorStatus(ViewBag, CreatedError);                     // Failed to save
                }

                viewOf = ViewTapping(ViewStates.CreatePostAfter, productOrder, state);
                return(View(productOrder));
            }
            viewOf = ViewTapping(ViewStates.CreatePostAfter, productOrder, false);
            AppVar.SetErrorStatus(ViewBag, CreatedError);             // record is not valid for creation
            return(View(productOrder));
        }
        public IHttpActionResult PutProductOrder(int id, ProductOrder productOrder)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != productOrder.OrderId)
            {
                return(BadRequest());
            }

            db.Entry(productOrder).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductOrderExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Beispiel #19
0
        public ActionResult Edit(ProductOrder productOrder)
        {
            bool viewOf = ViewTapping(ViewStates.EditPostBefore, productOrder);

            if (ModelState.IsValid)
            {
                db.Entry(productOrder).State = EntityState.Modified;
                bool state = SaveDatabase(ViewStates.Edit, productOrder);
                if (state)
                {
                    AppVar.SetSavedStatus(ViewBag, EditedSaved); // Saved Successfully.
                }
                else
                {
                    AppVar.SetErrorStatus(ViewBag, EditedError);                     // Failed to Save
                }

                viewOf = ViewTapping(ViewStates.EditPostAfter, productOrder, state);
                return(RedirectToAction("Index"));
            }
            viewOf = ViewTapping(ViewStates.EditPostAfter, productOrder, false);
            if (DropDownDynamic == false)
            {
                GetDropDowns(productOrder);              // Generating drop downs
            }
            AppVar.SetErrorStatus(ViewBag, EditedError); // record not valid for save
            return(View(productOrder));
        }
        public ProductOrder Update(int id, ProductOrder lineItem)
        {
            var sqlUpdate = @"UPDATE [dbo].[ProductOrders]
                                    SET [ProductId] = @productId
                                        ,[OrderId] = @orderId
                                        ,[Qty] = @qty
                                        ,[IsActive] = @isActive
                                    OUTPUT INSERTED.*
                                    WHERE Id = @id";

            using var db = new SqlConnection(_connectionString);

            var parameters = new
            {
                lineItem.ProductId,
                lineItem.OrderId,
                lineItem.Qty,
                lineItem.IsActive,
                id
            };

            var updatedLineItem = db.QueryFirstOrDefault <ProductOrder>(sqlUpdate, parameters);

            return(updatedLineItem);
        }
Beispiel #21
0
        /// <summary>
        /// Always tap once before going into the view.
        /// </summary>
        /// <param name="view">Say the view state, where it is calling from.</param>
        /// <param name="productOrder">Gives the model if it is a editing state or creating posting state or when deleting.</param>
        /// <returns>If successfully saved returns true or else false.</returns>
        bool ViewTapping(ViewStates view, ProductOrder productOrder = null, bool entityValidState = true)
        {
            switch (view)
            {
            case ViewStates.Index:
                break;

            case ViewStates.Create:
                break;

            case ViewStates.CreatePostBefore:                     // before saving it
                break;

            case ViewStates.CreatePostAfter:     // after saving
                break;

            case ViewStates.Edit:
                break;

            case ViewStates.Details:
                break;

            case ViewStates.EditPostBefore:                     // before saving it
                break;

            case ViewStates.EditPostAfter:     // after saving
                break;

            case ViewStates.Delete:
                break;
            }
            return(true);
        }
Beispiel #22
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Quantity,ProductId,ClientOrderId")] ProductOrder productOrder)
        {
            if (id != productOrder.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(productOrder);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ProductOrderExists(productOrder.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ClientOrderId"] = new SelectList(_context.ClientOrder, "Id", "Id", productOrder.ClientOrderId);
            ViewData["ProductId"]     = new SelectList(_context.Set <Product>(), "Id", "Id", productOrder.ProductId);
            return(View(productOrder));
        }
        public ProductOrdersRowViewModel(ProductOrder order, string culture)
        {
            ProductName       = (culture == "ar-EG") ? order.Product.NameAr : order.Product.NameEn;
            ClientName        = order.Client.FullName;
            ClientPhone       = order.Client.PhoneNumber;
            QuantityRequested = order.QuantityOrdered;

            var priceWithDiscount = order.Product.OriginalPrice - (order.Product.OriginalPrice * order.Product.Discount) / 100;
            var discountOf2       = order.Product.DiscountOfTwo;

            if (order.Product.DiscountOfTwo > 0)
            {
                if (QuantityRequested % 2 == 0)
                {
                    PricePaid = (priceWithDiscount - priceWithDiscount * (discountOf2 / 100)) * QuantityRequested;
                }
                else
                {
                    PricePaid = ((priceWithDiscount - priceWithDiscount * (discountOf2 / 100)) * (QuantityRequested - 1)) + priceWithDiscount;
                }
            }
            else
            {
                PricePaid = priceWithDiscount * QuantityRequested;
            }
        }
Beispiel #24
0
        public ActionResult ChooseLocation(int id)
        {
            int          ordID = Convert.ToInt32(Session["OrderID"]);
            ProductOrder por   = db.ProductOrders.Where(po => po.ProductOrderID == ordID).Include(po => po.Location.Client.User).FirstOrDefault();

            por.LocationID           = id;
            por.ProductOrderStatusID = 2;
            por.DateOfOrder          = DateTime.Now;
            db.SaveChanges();
            SendEmailController se = new SendEmailController();

            se.OrderConfrimed(por);
            if (Convert.ToInt32(Session["UserRoleID"]) == 1)
            {
                return(RedirectToAction("MakePayment"));
            }
            else
            {
                TempData["SuccessMessage"] = "Order placed!";
                return(RedirectToAction("Index", "Client"));
            }


            //Come the f**k on and merge already f*****g hell
        }
Beispiel #25
0
        public async Task <IActionResult> Edit(int id, [Bind("ProductOrderID,ProductID,OrderID")] ProductOrder productOrder)
        {
            if (id != productOrder.ProductOrderID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(productOrder);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ProductOrderExists(productOrder.ProductOrderID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["OrderID"]   = new SelectList(_context.Orders, "OrderID", "OrderID", productOrder.OrderID);
            ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "ProductID", productOrder.ProductID);
            return(View(productOrder));
        }
Beispiel #26
0
        public JsonResult ThucHienThanhToan(string pFullName, string pEmail, string pMobile, string pAddress, string pAddressDelivery, string pCity, string pDistrict, string pTimeDelivery, string pDayDelivery)
        {
            V308CMSEntities   mEntities         = new V308CMSEntities();
            AccountRepository accountRepository = new AccountRepository(mEntities);
            ShopCart          mShopCart;
            List <Product>    mList;
            ProductOrder      mProductOrder = new ProductOrder();

            try
            {
                if (HttpContext.User.Identity.IsAuthenticated == true && Session["UserId"] != null)
                {
                    if (Session["ShopCart"] != null)
                    {
                        mShopCart = (ShopCart)Session["ShopCart"];
                        mList     = mShopCart.List;
                        mProductOrder.AccountID = (int)Session["UserId"];
                        mProductOrder.Address   = pAddress + "____" + pAddressDelivery;
                        mProductOrder.Date      = DateTime.Now;
                        mProductOrder.Detail    = "Đơn mua hàng - Giao ngày:" + pDayDelivery + " - Giờ giao: " + pTimeDelivery;
                        mProductOrder.Email     = pEmail;
                        mProductOrder.FullName  = pFullName;
                        mProductOrder.Phone     = pMobile;
                        mProductOrder.Status    = 0;
                        //mProductOrder.ProductDetail = V308HTMLHELPER.TaoDanhSachSanPhamGioHang(mList);
                        mProductOrder.ProductDetail = JsonSerializer.SerializeToString <ShopCart>(mShopCart);
                        mProductOrder.Price         = mShopCart.getTotalPrice();
                        mEntities.AddToProductOrder(mProductOrder);
                        mEntities.SaveChanges();
                        Session["ShopCart"] = new ShopCart();
                        //Gửi email báo cho người mua và quản trị về việc mua hàng
                        //gửi email cho khách
                        string EmailContent = "Thông tin đơn hàng của " + pFullName + " từ C-FOOD: <br/> " + V308HTMLHELPER.TaoDanhSachSanPhamGioHang(mList) + " <br/> Email: " + pEmail + "<br/> Mobile: " + pMobile + " <br/> Ngày : " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + "";
                        //V308Mail.SendMail(pEmail, "Thông tin đơn hàng của " + pFullName + " từ C-FOOD: " + " - " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + "", EmailContent);
                        //gửi email tới admin
                        string EmailContent2 = "Thông tin đơn hàng của " + pFullName + " từ C-FOOD: <br/> " + V308HTMLHELPER.TaoDanhSachSanPhamGioHang(mList) + " <br/> Email: " + pEmail + "<br/> Mobile: " + pMobile + " <br/> Ngày : " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + "";
                        //V308Mail.SendMail("*****@*****.**", "Thông tin đơn hàng của " + pFullName + " từ C-FOOD: " + " - " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + "", EmailContent2);

                        return(Json(new { code = 1, message = "Hoàn thành mua bán. Chúng tôi sẽ liên lạc ngay với bạn qua số điện thoại bạn đã cung cấp." }));
                    }
                    else
                    {
                        return(Json(new { code = 3, message = "Giỏ hàng chưa có sản phẩm nào." }));
                    }
                }
                else
                {
                    return(Json(new { code = 2, message = "Vui lòng đăng nhập." }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { code = 0, message = "Có lỗi xảy ra. Vui lòng thử lại." }));
            }
            finally
            {
                mEntities.Dispose();
                accountRepository.Dispose();
            }
        }
        public ActionResult AddProduct(ProductOrder productOrder)
        {
            var orderView = Session["OrderView"] as OrderView;
            var ProductID = int.Parse(Request["ProductID"]);
            //buscar el producto
            var product = db.Products.Find(ProductID);

            productOrder = new ProductOrder();
            {
                productOrder.ProductID          = product.ProductID;
                productOrder.ProductDescription = product.ProductDescription;
                productOrder.UnitPrice          = product.UnitPrice;
                productOrder.OrderQty           = int.Parse(Request["OrderQty"]);
            };

            orderView.Products.Add(productOrder);

            var listC = db.Customers.ToList();

            ViewBag.CustomerID = new SelectList(listC, "CustomerID", "CustomerName");
            var listP = db.Products.ToList();

            ViewBag.ProductID      = new SelectList(listP, "ProductID", "ProductDescription");
            ViewBag.BranchOfficeID = new SelectList(db.BranchOffices, "BranchOfficeID", "BranchOfficeAddress");
            return(View("NewOrder", orderView));
        }
        public async Task <int> Add(Order order, string username)
        {
            var customer = await db.Customers.SingleOrDefaultAsync(c => c.UserName == username);

            var CustomerCart = await _crtRepo.GetUserCart(username);

            order.CustomerID = customer.CustomerID;
            db.Orders.Add(order);
            IList <ProductOrder> productOrderList = new List <ProductOrder>();

            foreach (var item in CustomerCart)
            {
                var ProductOrder = new ProductOrder
                {
                    OrderId   = order.OrderId,
                    ProductID = item.ProductID,
                    Quatity   = item.amount
                };
                productOrderList.Add(ProductOrder);
            }
            db.ProductOrders.AddRange(productOrderList);
            await _crtRepo.RemoveAllCart(username);

            return(await db.SaveChangesAsync());
        }
 public ProductOrderContract(ProductOrder data)
 {
     Id        = data.Id;
     Quantity  = data.Quantity;
     ProductId = data.ProductId;
     OrderId   = data.OrderId;
 }
Beispiel #30
0
        public void AddProductOrder(ProductOrderDTO productOrderDTO)
        {
            ProductOrder productOrder = new ProductOrder();

            productOrder.OrderId     = unitOfWork.DashboardRepository.NextNumberGenerator("ProductOrder");
            productOrder.OrderNumber = "OD" + productOrder.OrderId.ToString();

            List <ProductOrderDetail> productOrderDetails = new List <ProductOrderDetail>();

            ProductOrderConvertor.ConvertToProductOrderEntity(ref productOrder, productOrderDTO, false);
            ProductOrderDetail productOrderDetail = new ProductOrderDetail();

            productOrderDetail.ProductOrderDetailId = unitOfWork.DashboardRepository.NextNumberGenerator("ProductOrderDetail");
            productOrderDetail.OrderId          = productOrder.OrderId;
            productOrderDetail.ProductMappingId = productOrderDTO.ProductMappingId;
            productOrderDetail.Quantity         = productOrderDTO.Quantity;
            productOrderDetail.OrderAddress     = productOrderDTO.OrderAddress;
            if (productOrderDTO.ExpectedDeliveryDate == DateTime.MinValue)
            {
                productOrderDetail.DeliveryExpectedDate = DateTime.Now.AddDays(10);
            }
            else
            {
                productOrderDetail.DeliveryExpectedDate = productOrderDTO.ExpectedDeliveryDate;
            }
            productOrderDetails.Add(productOrderDetail);
            productOrder.ProductOrderDetails = productOrderDetails;
            unitOfWork.ProductOrderRepository.Add(productOrder);
            unitOfWork.SaveChanges();
        }
        private LicensePackage CreateLicenseForOrder(ProductOrder productOrder, string orderNumber)
        {
            //TODO: Might have performance hit.
            var licenseToCreate = new License
                {
                    LicenseKey = new Guid().ToString(),
                    OrderNumber = orderNumber,
                    Product = _productRepository.GetProductByName(productOrder.ProductName)
                    //Create rest of license object here
                };
                var package = licenseToCreate.GetLicensePackageFromLicense();
                _licenseRepository.CreateLicense(licenseToCreate);

            return package;
        }