public ActionResult Create([Bind(Include = "FilePathId,FileName,FileType,ProductId,ContentType,Content")] FilePath filePath)
        {
            if (ModelState.IsValid)
            {
                db.FilePaths.Add(filePath);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.ProductId = new SelectList(db.Products, "ProductId", "Name", filePath.ProductId);
            return(View(filePath));
        }
        public ActionResult Create([Bind(Include = "Id,OrderId,ProductId,Count,Total")] T_Shop_OFProduct t_Shop_OFProduct)
        {
            if (ModelState.IsValid)
            {
                db.T_Shop_OFProduct.Add(t_Shop_OFProduct);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.OrderId   = new SelectList(db.T_Shop_OrderForm, "Id", "FahuoId", t_Shop_OFProduct.OrderId);
            ViewBag.ProductId = new SelectList(db.T_Shop_Product, "Id", "Name", t_Shop_OFProduct.ProductId);
            return(View(t_Shop_OFProduct));
        }
        public ActionResult Create([Bind(Include = "BranchProductId,ProductId,BranchId,Quantity")] BranchProduct branchProduct)
        {
            if (ModelState.IsValid)
            {
                db.BranchProducts.Add(branchProduct);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.BranchId  = new SelectList(db.Branches, "BranchId", "BranchName", branchProduct.BranchId);
            ViewBag.ProductId = new SelectList(db.Products, "ProductId", "Name", branchProduct.ProductId);
            return(View(branchProduct));
        }
Example #4
0
        // GET: Orders
        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="textpiece_num"></param>
        /// <param name="texttotal_text"></param>
        /// <param name="Goodsid"></param>
        /// <param name="Number"></param>
        /// <returns></returns>
        public ActionResult Add(int?addressid, double textpiece_num, double texttotal_text, int?[] Goodsid, int?[] Number)
        {
            Userinfo user = Session["user"] as Userinfo;

            if (user != null)
            {
                //新增订单
                Orders orders = new Orders {
                    UserId     = user.Id,
                    OrderTime  = DateTime.Now,
                    Price      = (decimal)texttotal_text,
                    AddressId  = addressid,
                    OrderState = 0,
                    ordernum   = AddNumber.AddSeralNum(DateTime.Now)
                };
                db.Orders.Add(orders);
                //新增订单明细

                //循环添加商品到订单中
                for (int i = 0; i < Goodsid.Length; i++)
                {
                    OrderDetail odetail = new OrderDetail
                    {
                        Orders  = orders,
                        GoodsId = Goodsid[i],
                        Number  = Number[i],
                    };
                    db.OrderDetail.Add(odetail);

                    //同时对应得商品减去相应的库存
                    Goods gooods = db.Goods.Find(Goodsid[i]);
                    gooods.Amount = gooods.Amount - Number[i];
                }
                ;

                //向订单中添加完毕后,购物车的相关数据清空
                IQueryable <int?> cartdelete = Goodsid.AsQueryable();
                var cartlist = db.Cart.Where(c => c.UserId == user.Id && cartdelete.Contains(c.GoodsId));
                db.Cart.RemoveRange(cartlist);

                db.SaveChanges();

                //获取最新添加的订单编号
                // int Id = orders.Id;
                return(RedirectToAction("OrderDetail", new { Id = orders.Id }));
            }
            else
            {
                return(RedirectToAction("Login", "User"));
            }
        }
Example #5
0
        public ActionResult ChangeState(int Id)
        {
            T_Shop_Users item = db.T_Shop_Users.Find(Id);

            if (item.State == 1)
            {
                item.State = 2;
            }
            else
            {
                item.State = 1;
            }
            db.SaveChanges();

            return(RedirectToAction("index"));
        }
Example #6
0
        public Client insert(Client client)
        {
            var query = conn.Clients.Add(client);

            conn.SaveChanges();
            return(query);
        }
Example #7
0
        public JsonResult AddProduct(Product model)
        {
            string resultMSg = null;

            try
            {
                if (!model.Equals(null))
                {
                    db.Products.Add(model);
                    int resultId = db.SaveChanges();
                    resultMSg = resultId > 0 ? "Data Saved Successfully!" : "Data Saved Failed!";
                }
            }
            catch (Exception ex) { resultMSg = ex.Message; }
            return(Json(resultMSg, JsonRequestBehavior.AllowGet));
        }
Example #8
0
        /// <summary>
        /// xóa sản phẩm khỏi database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeleteProduct_Click(object sender, RoutedEventArgs e)
        {
            // Hiện thông báo xác nhận
            var dialog = new Dialog()
            {
                Message = "Delete this product, Are you sure?"
            };

            dialog.Owner = Window.GetWindow(this);
            if (dialog.ShowDialog() == false)
            {
                return;
            }

            //thao tác dưới cơ sở dữ liệu
            var db = new MyShopEntities();

            try
            {
                //xóa product sẽ xóa luôn ảnh của product

                //Tìm hình ảnh của product để xóa
                var imageProductFromDatabase = db.Photos.Find(_product.Product_Id);
                db.Photos.Remove(imageProductFromDatabase);
                db.SaveChanges();

                //tìm product theo id để xóa
                var productFromDatabase = db.Products.Find(_product.Product_Id);
                db.Products.Remove(productFromDatabase);
                db.SaveChanges();//cập nhật

                // cập nhật giao diện
                if (RefreshProductList != null)
                {
                    RefreshProductList.Invoke(true);
                    //tắt nút edit
                    btnEditProduct.IsEnabled = false;
                    //gán content = deleted và tắt nút false
                    btnDeleteProduct.Content = "Deleted";

                    btnDeleteProduct.IsEnabled = false;
                }
            }
            catch
            {
            }
        }
Example #9
0
        public ActionResult Register(FilaShop.User.User user)
        {
            Models.Userinfo u = new Models.Userinfo
            {
                Username = user.Username,
                Password = Comman.Md5.JiaMi(user.Password),
                Nickname = user.Nickname
            };
            db.Userinfo.Add(u);
            db.SaveChanges();
            if (user.returnurl != null && user.returnurl != "")
            {
                Session.Add("returnurl", user.returnurl);
            }

            return(RedirectToAction("Login"));
        }
Example #10
0
        public Category insert(Category category)
        {
            var query = conn.Categories.Add(category);

            conn.SaveChanges();
            return(query);
        }
Example #11
0
        public ActionResult Create([Bind(Include = "ProductId,Name,Description,Price,CategoryId")] Product product, HttpPostedFileBase upload)
        {
            Console.WriteLine("inside product create");
            try
            {
                if (ModelState.IsValid)
                {
                    Console.WriteLine("model valid");

                    if (upload != null && upload.ContentLength > 0)
                    {
                        var avatar = new FilePath
                        {
                            FileName    = System.IO.Path.GetFileName(upload.FileName),
                            FileType    = 1,
                            ContentType = upload.ContentType
                        };
                        using (var reader = new System.IO.BinaryReader(upload.InputStream))
                        {
                            avatar.Content = reader.ReadBytes(upload.ContentLength);
                        }
                        product.FilePaths = new List <FilePath> {
                            avatar
                        };
                    }

                    db.Products.Add(product);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }


            ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", product.CategoryId);
            return(View(product));
        }
Example #12
0
        /// <summary>
        /// xóa một orders
        /// </summary>
        private void deleteOrderMouseUp_MouseUp(object sender, MouseButtonEventArgs e)
        {
            //hiển thị thông báo muốn xóa hay không?
            var dialog = new Dialog()
            {
                Message = "Delete the selected order?"
            };

            dialog.Sounds();
            dialog.Owner = Window.GetWindow(this);
            if (dialog.ShowDialog() == false)
            {
                return;
            }

            //lấy item đã chọn trong listview
            dynamic itemOrderListView = listOrders.SelectedItem;

            try
            {
                //tìm order theo id
                var order = db.Purchases.Find(itemOrderListView.Purchase_Id);
                db.Purchases.Remove(order);
                db.SaveChanges();//lưu lại thay đổi

                //cập nhật lại danh sách
                CalculatePagingInfo();
                LoaddAllPurchase();

                //hiển thị thông báo thành công
                var dialogNotification = new Messenge()
                {
                    Message = "Order deleted successfully!"
                };
                dialogNotification.Sounds();
                dialogNotification.Owner = Window.GetWindow(this);
                dialogNotification.ShowDialog();
            }
            catch (Exception ex)
            {
            }
        }
Example #13
0
        /// <summary>
        /// Xóa một loại sản phẩm, nếu loại sản phẩm không có sản phẩm => Xóa
        /// nếu có sẽ hỏi người dùng xóa hay không
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeleteCategory_Click(object sender, RoutedEventArgs e)
        {
            if (btnDeleteCategory.Content.Equals("Cancel"))
            {
                // không cho phép chỉnh sửa các TextBox
                categoryIdTextBox.IsEnabled          = false;
                categoryNameTextBox.IsEnabled        = false;
                categoryDescriptionTextBox.IsEnabled = false;

                // Làm sạch các TextBox nếu vừa định Thêm mới
                if (btnUpdateCategory.Tag.Equals("Add"))
                {
                    categoryIdTextBox.Clear();
                    categoryNameTextBox.Clear();
                    categoryDescriptionTextBox.Clear();

                    // Tắt luôn hai button Sửa và Xóa (nếu vừa định Sửa thì thôi)
                    btnUpdateCategory.IsEnabled = false;
                    btnDeleteCategory.IsEnabled = false;
                }
                // Reset dữ liệu cũ nếu vừa định Sửa
                else
                {
                    // Lấy đối tượng ProductType tương ứng
                    var productType = listCategories.SelectedItem as Category;

                    categoryNameTextBox.Text = productType.Category_Name;
                    //editProductTypeId.Text = productType.Id;
                    categoryDescriptionTextBox.Text = productType.Description;
                }

                // Reset nội dung 2 button Sửa và Xóa
                btnUpdateCategory.Content = "Edit";
                btnDeleteCategory.Content = "Delete";
                btnAddCategory.IsEnabled  = true;

                // Bật lại List View
                listCategories.IsEnabled = true;
            }
            else
            {
                // Hiện thông báo xác nhận
                var dialog = new Dialog()
                {
                    Message = "Delete the selected category?"
                };
                dialog.Owner = Window.GetWindow(this);
                if (dialog.ShowDialog() == false)
                {
                    return;
                }

                // Lấy đối tượng từ List View
                var selectedItem = listCategories.SelectedItem as Category;

                // Tìm đối tượng tương ứng trong CSDL và xóa
                var db = new MyShopEntities();
                try
                {
                    var type = db.Categories.Where(x => x.Category_Id == selectedItem.Category_Id).FirstOrDefault();
                    db.Categories.Remove(type);
                    db.SaveChanges();


                    // Cập nhật
                    _categories.RemoveAt(listCategories.SelectedIndex);
                    listCategories.ItemsSource = null;
                    listCategories.ItemsSource = _categories;
                }
                catch (Exception ex)
                {
                    // Nếu bắt ngoại lệ (khóa ngoại) tức đang có sản phẩm thuộc loại muốn xóa
                    var showDialogError = new Dialog()
                    {
                        Message = "Product existence in Categories" +
                                  "\nDelete all?"
                    };
                    showDialogError.Sounds();
                    showDialogError.Owner = Window.GetWindow(this);

                    // Nếu user đồng ý, thì xóa hết sản phẩm tương ứng
                    if (showDialogError.ShowDialog() == true)
                    {
                        //Trước tiên phải xóa image của sản phẩm ở bảng Photo
                        db.Photos.RemoveRange(db.Photos.Where(x => x.Product.CatId == selectedItem.Category_Id).ToList());

                        // Tìm danh sách sản phẩm tương ứng sao đó RemoveRange
                        db.Products.RemoveRange(db.Products.Where(x => x.CatId == selectedItem.Category_Id).ToList());

                        // Sau cùng mới xóa loại sản phẩm
                        db.Categories.Remove(db.Categories.Where(x => x.Category_Id == selectedItem.Category_Id).FirstOrDefault());

                        // Cập nhật lên List View
                        _categories.Remove(selectedItem);
                        listCategories.ItemsSource = null;
                        listCategories.ItemsSource = _categories;
                        db.SaveChanges();
                    }
                    else
                    {
                        return;
                    }
                }

                // Xóa xong thì tắt 2 nút Sửa và Xóa + làm sạch TextBox
                btnUpdateCategory.IsEnabled = false;
                btnDeleteCategory.IsEnabled = false;

                categoryIdTextBox.Clear();
                categoryNameTextBox.Clear();
                categoryDescriptionTextBox.Clear();

                // Cập nhật combobox ở trang trước, nếu là chọn category
                if (RefreshCategoriesList != null)
                {
                    RefreshCategoriesList.Invoke(true);
                }
            }
        }
Example #14
0
        /// <summary>
        /// Thêm và Sửa category
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnUpdateCategory_Click(object sender, RoutedEventArgs e)
        {
            // content là sửa
            if (btnUpdateCategory.Content.Equals("Edit"))
            {
                // Thay nội dung các button
                btnUpdateCategory.Content = "Save"; // đổi content là lưu
                btnUpdateCategory.Tag     = "Edit"; // lưu đường dẫn btnUpdateCategory là sửa

                btnDeleteCategory.Content = "Cancel";
                btnAddCategory.IsEnabled  = false;// tắt nút add

                // Cho phép chỉnh sửa các TextBox, chỉ cho phép sửa tên là mô tả
                categoryIdTextBox.IsEnabled          = false;
                categoryNameTextBox.IsEnabled        = true;
                categoryDescriptionTextBox.IsEnabled = true;

                categoryNameTextBox.Focus();

                // Tạm thời vô hiệu hóa List View
                listCategories.IsEnabled = false;
            }

            // Content của button btnUpdateCategory là "lưu"
            else
            {
                // Kiểm tra dữ liệu có nhập đầy đủ không
                if (categoryIdTextBox.Text.Length == 0 ||
                    categoryNameTextBox.Text.Length == 0)
                {
                    var dialogError1 = new Dialog()
                    {
                        Message = "Please enter all the information!"
                    };
                    dialogError1.Owner = Window.GetWindow(this);
                    dialogError1.ShowDialog();
                    return;
                }

                // Tạo đối tượng từ các TextBox
                var category = new Category()
                {
                    //ID sẽ tự động tăng lên ở SQL
                    Category_Name = categoryNameTextBox.Text.Length == 0 ? null : categoryNameTextBox.Text,
                    //Id = editProductTypeId.Text.Length == 0 ? null : editProductTypeId.Text,
                    Description = categoryDescriptionTextBox.Text.Length == 0 ? null : categoryDescriptionTextBox.Text
                };

                #region THAO TÁC VỚI CSDL
                // Nếu xác nhận thêm mới (1 nút 2 chức năng, lưu khi thêm và lưu khi sửa)
                if (btnUpdateCategory.Tag.Equals("Add"))
                {
                    // Hiện thông báo xác nhận
                    var dialog = new Dialog()
                    {
                        Message = "Add category, Are you sure?"
                    };
                    dialog.Owner = Window.GetWindow(this);
                    if (dialog.ShowDialog() == false)
                    {
                        return;
                    }

                    var db = new MyShopEntities();
                    try
                    {
                        db.Categories.Add(category);
                        db.SaveChanges();

                        // Cập nhật lên List View
                        _categories.Add(category);
                        listCategories.SelectedIndex = _categories.Count - 1;
                    }
                    catch (Exception ex)
                    {
                    }
                }

                // Nếu xác nhận sửa
                if (btnUpdateCategory.Tag.Equals("Edit"))
                {
                    // Hiện thông báo xác nhận
                    var dialog = new Dialog()
                    {
                        Message = "Edit category, Are you sure?"
                    };
                    dialog.Owner = Window.GetWindow(this);
                    if (dialog.ShowDialog() == false)
                    {
                        return;
                    }

                    var db = new MyShopEntities();

                    // Kiểm tra xem user có sửa mã loại hay không (so sánh với List View)
                    if (category.Category_Id == ((Category)listCategories.SelectedItem).Category_Id)
                    {
                        // Tìm ID tương đương với category
                        var target = db.Categories.Find(category.Category_Id);
                        if (target != null)
                        {
                            // Sửa name và description
                            target.Category_Name = category.Category_Name;
                            target.Description   = category.Description;
                            db.SaveChanges();
                        }
                    }
                    else
                    {
                        // Nếu sửa ID thì sửa tất cả product thuộc category đó
                        var dialogNotification = new Dialog()
                        {
                            Message = "Edit id category,You need to fix all corresponding products?"
                        };
                        dialogNotification.Sounds();
                        dialogNotification.Owner = Window.GetWindow(this);

                        // Nếu đồng ý, thực hiện sửa lại tất cả sản phẩm tương ứng
                        if (dialogNotification.ShowDialog() == true)
                        {
                            //Kiểm tra mã mới đã tồn tại chưa
                            if (db.Categories.Find(category.Category_Id) != null)
                            {
                                var dialogError = new Dialog()
                                {
                                    Message = "ID category exist!"
                                };
                                dialogError.Owner = Window.GetWindow(this);
                                dialogError.ShowDialog();
                                return;
                            }

                            //Thêm đối tượng dữ liệu mới (mã loại mới)
                            db.Categories.Add(category);

                            //Tìm sản phẩm tương đương với category => sửa tất cả
                            var list = db.Products.Where(x => x.CatId == ((Category)listCategories.SelectedItem).Category_Id).ToList();
                            for (int i = 0; i < list.Count; i++)
                            {
                                list[i].CatId = category.Category_Id;
                            }

                            //Xóa dữ liệu cũ
                            var target = db.Categories.Find(((Category)listCategories.SelectedItem).Category_Id);
                            if (target != null)
                            {
                                db.Categories.Remove(target);
                            }
                            db.SaveChanges();
                        }
                    }

                    // Cập nhật lên List View
                    int curIndex = listCategories.SelectedIndex;
                    _categories.Insert(curIndex + 1, category);
                    _categories.RemoveAt(curIndex);
                    listCategories.SelectedIndex = curIndex;
                }
                #endregion

                // Reset nội dung 2 button Sửa và Xóa
                btnUpdateCategory.Content = "Edit";
                btnDeleteCategory.Content = "Delete";

                // Vô hiệu hóa các TextBox
                categoryIdTextBox.IsEnabled          = false;
                categoryNameTextBox.IsEnabled        = false;
                categoryDescriptionTextBox.IsEnabled = false;

                // Bật lại button Thêm và List View
                btnAddCategory.IsEnabled = true;
                listCategories.IsEnabled = true;

                // Cập nhật combobox ở trang trước
                if (RefreshCategoriesList != null)
                {
                    RefreshCategoriesList.Invoke(true);
                }
            }
        }
        private void BtnConfirm_Click(object sender, RoutedEventArgs e)
        {
            // Kiểm tra dữ liệu có thiếu không
            if ((rdoGoToShop.IsChecked == true && editMoneyTaken.Text.Length == 0) || // Nếu thanh toán trực tiếp mà chưa đưa tiền
                (rdoShip.IsChecked == true && editAddress.Text.Length == 0) ||        // Nếu thanh toán giao hàng mà không đưa địa chỉ
                (rdoShip.IsChecked == true && editMoneyWillGet.Text.Length == 0))     // Nếu thanh toán giao hàng mà không biết số tiền sẽ thu
            {
                var dialogError = new Dialog()
                {
                    Message = "Please enter the full information!"
                };
                dialogError.Sounds();
                dialogError.Owner = Window.GetWindow(this);
                dialogError.ShowDialog();
                return;
            }

            string customer_tel        = customerPhoneTextBox.Text.Length == 0 ? null : customerPhoneTextBox.Text;
            var    db                  = new MyShopEntities();
            var    itemOrderInDatabase = db.Purchases.Find(_purchaseID);

            //Khách hàng có trong cơ sở dữ liệu => thì nhập đúng số điện thoại thì tự động hiển thị tên
            //Khách hàng mới (có điền thông tin) => khách hàng mới => tạo khách hàng mới
            //Khách hàng vãng lai (có bộ chuyển đổi Converter để chuyển customerPhoneTextBox khi rỗng)

            //Xác nhận thêm hóa đơn
            var dialogNotification = new Dialog()
            {
                Message = "Confirm want to edit?"
            };

            dialogNotification.Sounds();
            dialogNotification.Owner = Window.GetWindow(this);
            dialogNotification.ShowDialog();
            if (true == dialogNotification.DialogResult)
            {
                //Thao tác để thêm vào CSDL
                try
                {
                    //Thêm mới khách hàng nếu không tìm thấy khách hàng trong cơ sở dữ liệu (khách hàng mới)
                    if (customer == null && customerPhoneTextBox.Text.Length != 0)
                    {
                        //Tạo thông tin khách hàng
                        var newCustomer = new Customer()
                        {
                            Tel      = customerPhoneTextBox.Text,
                            Fullname = CustomerNameTextBox.Text.Length < 0 ? null : CustomerNameTextBox.Text,
                            Address  = null,
                        };
                        db.Customers.Add(newCustomer);
                        db.SaveChanges();//lưu
                    }

                    // - Kiểm tra xem khách hàng thanh toán bằng hình thức nào
                    //    + Nếu thanh toán trực tiếp và thanh toán đủ tiền => hoàn thành đơn hàng
                    //    + Còn ngược lại thì sẽ lưu địa chỉ nơi nhận hàng và tiền ship

                    itemOrderInDatabase.Customer.Fullname = CustomerNameTextBox.Text.Length < 0 ? null : CustomerNameTextBox.Text;
                    itemOrderInDatabase.Customer.Tel      = customerPhoneTextBox.Text.Length < 0 ? null : customerPhoneTextBox.Text;
                    db.SaveChanges();

                    //Thêm hóa đơn mới
                    itemOrderInDatabase.CustomerTel = customer_tel;                                      //Gán lại số điện thoại
                    itemOrderInDatabase.UpdatedAt   = DateTime.Now;                                      //Cập nhật lại ngày update
                    itemOrderInDatabase.Total       = _listProduct.Sum((dynamic p) => (decimal)p.Total); //Cập nhật lại tổng tiền
                    itemOrderInDatabase.AtStore     = (bool)rdoGoToShop.IsChecked;                       //Kiểm tra thanh toàn thế nào

                    //Nếu thanh toán tại shop thì số tiền khách đưa là bao nhiêu
                    itemOrderInDatabase.MoneyTaken    = (bool)rdoGoToShop.IsChecked ? decimal.Parse(editMoneyTaken.Text) : 0;
                    itemOrderInDatabase.MoneyExchange = (bool)rdoGoToShop.IsChecked ? decimal.Parse(editMoneyExchange.Text) : 0;//Tiền trả lại

                    //Nếu thanh toán bằng online (giao hàng)
                    //Đỉa chỉ giao hàng
                    itemOrderInDatabase.DeliveryAdress = (bool)rdoShip.IsChecked ? editAddress.Text : null;

                    //Số tiền đã đặt trước (nếu có)
                    itemOrderInDatabase.Deposit = (bool)rdoShip.IsChecked ? decimal.Parse(editDeposit.Text) : 0;

                    //Phí ship
                    itemOrderInDatabase.Ship = (bool)rdoShip.IsChecked ? decimal.Parse(editShipCost.Text) : 0;

                    //Tổng tiền khi thanh toán
                    itemOrderInDatabase.MoneyWillGet = (bool)rdoShip.IsChecked ? decimal.Parse(editMoneyWillGet.Text) : 0;

                    //Trạng thái đơn hàng
                    var status = statusFilterComboBox.SelectedItem as OrderState;
                    itemOrderInDatabase.Status = status.OrderState_Key;
                    db.SaveChanges();

                    //Lấy tất cả chi tiết đơn hàng theo id
                    var detailOrderList = db.Purchases.Find(itemOrderInDatabase.Purchase_Id).OrderDetails;

                    //cập nhật lại số lượng của sản phẩm trước khi xóa sản phẩm
                    foreach (var product in detailOrderList)
                    {
                        var p = db.Products.Find(product.ProductId);
                        p.Quantity += product.Quantity;
                    }
                    db.SaveChanges();

                    //Xóa danh sách đơn hàng cũ
                    db.OrderDetails.RemoveRange(db.OrderDetails.Where(x => x.OrderId == itemOrderInDatabase.Purchase_Id)).ToList();

                    db.SaveChanges();//Lưu lại

                    //Cập nhật lại danh sách chi tiết đơn hàng order
                    for (int i = 0; i < _listProduct.Count; i++)
                    {
                        //Tạo order với chi tiết đơn đặt hàng
                        var orderDetail = new OrderDetail()
                        {
                            OrderId   = itemOrderInDatabase.Purchase_Id,
                            ProductId = _listProduct[i].ProductID,
                            Price     = _listProduct[i].Price,
                            Quantity  = _listProduct[i].Quantity,
                            Total     = _listProduct[i].Total,
                            CreatedAt = itemOrderInDatabase.CreatedAt,
                            UpdatedAt = DateTime.Now
                        };
                        db.OrderDetails.Add(orderDetail);
                        db.SaveChanges();//lưu

                        //nếu tạo đơn hàng với sản phâm đó thì mặc nhiên là sẽ trừ số lượng của sản phẩm đó đi
                        var updateQuantity = db.Products.Find(_listProduct[i].ProductID);
                        if (updateQuantity != null)
                        {
                            //lấy số lượng hiện tại trong CSDL và trừ đi số lượng sản phẩm đã thanh toán
                            updateQuantity.Quantity -= _listProduct[i].Quantity;
                            db.SaveChanges();
                        }
                        //Nếu mà khách trả lại hàng thì cập nhật lại số lượng lại cho product, sẽ tính sau
                    }
                    db.SaveChanges();

                    if (RefreshOrdersList != null)
                    {
                        RefreshOrdersList.Invoke(true);
                    }

                    //Thông báo khi sửa thành công
                    var dialogSuccessfully = new Messenge()
                    {
                        Message = "Edited an order successfully."
                    };
                    dialogSuccessfully.Sounds();
                    dialogSuccessfully.Owner = Window.GetWindow(this);
                    dialogSuccessfully.time  = 2000;
                    dialogSuccessfully.ShowDialog();
                }
                catch (Exception ex)
                {
                    var dialogerorr = new Dialog()
                    {
                        Message = "Error!"
                    };
                    dialogerorr.Owner = Window.GetWindow(this);
                    dialogerorr.ShowDialog();
                }
            }

            //Làm mới
            editProductId.Clear();
        }
        private void BtnAddProductSave_Click(object sender, RoutedEventArgs e)
        {
            // Kiểm tra thông tin có đầy đủ
            if (producIDTextBox.Text.Length == 0 ||
                productNameTextBox.Text.Length == 0 ||
                productPriceTextbox.Text.Length == 0 ||
                productQuantityTextbox.Text.Length == 0 ||
                productDescriptionTextBox.Text.Length == 0 ||
                ProductTypeComboxBox.SelectedIndex == -1)
            {
                var dialogError1 = new Dialog()
                {
                    Message = "Please enter all the information!"
                };
                dialogError1.Owner = Window.GetWindow(this);
                dialogError1.ShowDialog();
                return;
            }

            var dialogError = new Dialog()
            {
                Message = isEditProduct ? "Confirm product repair, Are you sure?" : "Add new product, Are you sure?"
            };

            dialogError.Owner = Window.GetWindow(this);

            if (true == dialogError.ShowDialog())
            {
                try
                {
                    var db = new MyShopEntities();

                    // Tạo đối tượng Product tương ứng
                    var product = new Product()
                    {
                        //Product_Id = int.Parse(producIDTextBox.Text),
                        Product_Name = productNameTextBox.Text,
                        SKU          = storeCodeTextBox.Text,
                        Price        = decimal.Parse(productPriceTextbox.Text),
                        Quantity     = int.Parse(productQuantityTextbox.Text),
                        Description  = productDescriptionTextBox.Text.Length == 0 ? null : productDescriptionTextBox.Text,

                        // Còn thiếu trường CatId và photo
                    };
                    // Tìm Id của loại sản phẩm đã chọn
                    var category = ProductTypeComboxBox.SelectedValue as Category;

                    if (category != null)
                    {
                        product.CatId = category.Category_Id;

                        // Nếu sửa
                        if (isEditProduct)
                        {
                            try
                            {
                                var oldProduct = db.Products.Find(int.Parse(producIDTextBox.Text));

                                oldProduct.Product_Name = product.Product_Name;
                                oldProduct.SKU          = product.SKU;
                                oldProduct.Price        = product.Price;
                                oldProduct.Description  = product.Description;
                                oldProduct.Quantity     = product.Quantity; // số lượng mới

                                //thiếu catID và photo

                                if (oldProduct.CatId != category.Category_Id) // Nếu có thay đổi mã sản phẩm
                                {
                                    oldProduct.CatId = product.CatId;
                                }


                                //trường image
                                if (imgProduct.Tag.ToString() != null)
                                {
                                    var imageFull = imgProduct.Tag.ToString();
                                    var image     = new BitmapImage(new Uri(imageFull, UriKind.Absolute));
                                    var encoder   = new JpegBitmapEncoder();
                                    encoder.Frames.Add(BitmapFrame.Create(image));

                                    using (var stream = new MemoryStream())
                                    {
                                        encoder.Save(stream);
                                        oldProduct.Photos.First().Data = stream.ToArray();
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        }

                        // Nếu thêm
                        else
                        {
                            db.Products.Add(product);
                            db.SaveChanges();

                            //trường image
                            var imageFull = imgProduct.Tag.ToString();
                            var image     = new BitmapImage(new Uri(imageFull, UriKind.Absolute));
                            var encoder   = new JpegBitmapEncoder();
                            encoder.Frames.Add(BitmapFrame.Create(image));

                            using (var stream = new MemoryStream())
                            {
                                encoder.Save(stream);
                                var photo = new Photo()
                                {
                                    ProductId = product.Product_Id,
                                    Data      = stream.ToArray()
                                };
                                db.Photos.Add(photo);
                                db.SaveChanges();
                            }

                            // refresh lại textbox
                            Refresh();
                        }
                    }
                    db.SaveChanges();

                    // Nếu trang vừa rồi là danh sách sản phẩm thì cập nhật nó
                    if (RefreshProductList != null)
                    {
                        RefreshProductList.Invoke(true);
                    }

                    var dialog = new Messenge()
                    {
                        Message = "Added product Successful!"
                    };
                    dialog.Owner = Window.GetWindow(this);
                    dialog.Sounds();
                    dialog.ShowDialog();
                }
                catch (Exception ex)
                {
                    //var dialogError1 = new Dialog() { Message = "Product id not exist!" };
                    //dialogError1.Owner = Window.GetWindow(this);
                    //dialogError1.ShowDialog();
                }
            }
        }
Example #17
0
 public ActionResult AddSave(T_Shop_Product product)
 {
     db.T_Shop_Product.Add(product);
     db.SaveChanges();
     return(RedirectToAction("index"));
 }
Example #18
0
        private void BtnConfirm_Click(object sender, RoutedEventArgs e)
        {
            // Kiểm tra dữ liệu có thiếu không
            if ((rdoGoToShop.IsChecked == true && editMoneyTaken.Text.Length == 0) || // Nếu thanh toán trực tiếp mà chưa đưa tiền
                (rdoShip.IsChecked == true && editAddress.Text.Length == 0) ||        // Nếu thanh toán giao hàng mà không đưa địa chỉ
                (rdoShip.IsChecked == true && editMoneyWillGet.Text.Length == 0))     // Nếu thanh toán giao hàng mà không biết số tiền sẽ thu
            {
                var dialogError = new Dialog()
                {
                    Message = "Please enter the full information!"
                };
                dialogError.Sounds();
                dialogError.Owner = Window.GetWindow(this);
                dialogError.ShowDialog();
                return;
            }

            string customer_tel = customerPhoneTextBox.Text.Length == 0 ? null : customerPhoneTextBox.Text;
            var    db           = new MyShopEntities();

            //Khách hàng có trong cơ sở dữ liệu => thì nhập đúng số điện thoại thì tự động hiển thị tên
            //Khách hàng mới (có điền thông tin) => khách hàng mới => tạo khách hàng mới
            //Khách hàng vãng lai (có bộ chuyển đổi Converter để chuyển customerPhoneTextBox khi rỗng)

            //Xác nhận thêm hóa đơn
            var dialogNotification = new Dialog()
            {
                Message = "Confirm want to add?"
            };

            dialogNotification.Sounds();
            dialogNotification.Owner = Window.GetWindow(this);
            dialogNotification.ShowDialog();
            if (true == dialogNotification.DialogResult)
            {
                //Thao tác để thêm vào CSDL
                try
                {
                    //Thêm mới khách hàng nếu không tìm thấy khách hàng trong cơ sở dữ liệu (khách hàng mới)
                    if (customer == null && customerPhoneTextBox.Text.Length != 0)
                    {
                        //Tạo thông tin khách hàng
                        var newCustomer = new Customer()
                        {
                            Tel      = customerPhoneTextBox.Text,
                            Fullname = CustomerNameTextBox.Text.Length < 0 ? null : CustomerNameTextBox.Text,
                            Address  = null,
                        };
                        db.Customers.Add(newCustomer);
                        db.SaveChanges();//lưu
                    }

                    // - Kiểm tra xem khách hàng thanh toán bằng hình thức nào
                    //    + Nếu thanh toán trực tiếp và thanh toán đủ tiền => hoàn thành đơn hàng
                    //    + Còn ngược lại thì sẽ lưu địa chỉ nơi nhận hàng và tiền ship

                    //Thêm hóa đơn mới
                    var bill = new Purchase()
                    {
                        CustomerTel    = customer_tel,
                        CreatedAt      = DateTime.Now,
                        UpdatedAt      = null,
                        Total          = _listProduct.Sum((dynamic p) => (decimal)p.Total),
                        AtStore        = (bool)rdoGoToShop.IsChecked,
                        MoneyTaken     = (bool)rdoGoToShop.IsChecked ? decimal.Parse(editMoneyTaken.Text) : 0,
                        MoneyExchange  = (bool)rdoGoToShop.IsChecked ? decimal.Parse(editMoneyExchange.Text) : 0,
                        DeliveryAdress = (bool)rdoShip.IsChecked ? editAddress.Text : null,
                        Deposit        = (bool)rdoShip.IsChecked ? decimal.Parse(editDeposit.Text) : 0,
                        Ship           = (bool)rdoShip.IsChecked ? decimal.Parse(editShipCost.Text) : 0,
                        MoneyWillGet   = (bool)rdoShip.IsChecked ? decimal.Parse(editMoneyWillGet.Text) : 0,
                        Status         = (bool)rdoGoToShop.IsChecked ? 2 : 1
                    };
                    db.Purchases.Add(bill);
                    db.SaveChanges();

                    //Thêm danh sách sản phẩm được order
                    for (int i = 0; i < _listProduct.Count; i++)
                    {
                        //Tạo order với chi tiết đơn đặt hàng
                        var orderDetail = new OrderDetail()
                        {
                            OrderId   = bill.Purchase_Id,
                            ProductId = _listProduct[i].ProductID,
                            Price     = _listProduct[i].Price,
                            Quantity  = _listProduct[i].Quantity,
                            Total     = _listProduct[i].Total,
                            CreatedAt = DateTime.Now,
                            UpdatedAt = null
                        };
                        db.OrderDetails.Add(orderDetail);
                        db.SaveChanges();//lưu

                        //nếu tạo đơn hàng với sản phâm đó thì mặc nhiên là sẽ trừ số lượng của sản phẩm đó đi
                        var updateQuantity = db.Products.Find(_listProduct[i].ProductID);
                        if (updateQuantity != null)
                        {
                            //lấy số lượng hiện tại trong CSDL và trừ đi số lượng sản phẩm đã thanh toán
                            updateQuantity.Quantity -= _listProduct[i].Quantity;
                            db.SaveChanges();
                        }
                        //Nếu mà khách trả lại hàng thì cập nhật lại số lượng lại cho product, sẽ tính sau
                    }
                    db.SaveChanges();

                    //Thông báo khi thêm order thành công
                    var dialogSuccessfully = new Messenge()
                    {
                        Message = "Added an order successfully"
                    };
                    dialogSuccessfully.Sounds();
                    dialogSuccessfully.Owner = Window.GetWindow(this);
                    dialogSuccessfully.time  = 2000;
                    dialogSuccessfully.ShowDialog();
                }
                catch (Exception ex)
                {
                }
            }

            //Làm mới
            editProductId.Clear();
            for (int i = 0; i < _listProduct.Count; i++)
            {
                _listProduct.RemoveAt(i);
            }
            sumTotalOfProduct.Text = "0 đ";
            rdoGoToShop.IsChecked  = true;
        }