Пример #1
0
        /// <summary>
        /// Hủy sản phẩm được chọn
        /// </summary>
        private void btncancel_Click(object sender, RoutedEventArgs e)
        {
            //Kiểm tra có nhập sản phẩm hay không?
            if (productViewModel == null)
            {
                var dialogError = new Messenge()
                {
                    Message = "Please select a product!"
                };
                dialogError.Sounds();
                dialogError.time  = 2000;
                dialogError.Owner = Window.GetWindow(this);
                dialogError.ShowDialog();
                btncancel.Visibility = Visibility.Hidden;
                return;
            }
            else
            {
                //xóa
                _listProduct.Remove(productViewModel);//Xóa đơn hàng được chọn trong listview

                //Cập nhật lại tổng sản phẩm
                double SumProducts = 0;
                foreach (var sumP in _listProduct)
                {
                    SumProducts += (double)sumP.Total;
                }

                //Cập nhật lại tổng tiền
                sumTotalOfProduct.Text = $"{SumProducts.ToString("N0")} đ";
                btncancel.Visibility   = Visibility.Hidden;
            }
        }
Пример #2
0
        private void NumberBuy_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (numberBuyTextBox.Text.Length > 0)
            {
                //Mở nút thêm
                btnAddToListProduct.Visibility = Visibility.Visible;

                // Kiểm tra còn đủ hàng hay không
                var db         = new MyShopEntities();
                var curProduct = db.Products.Find(product.Product_Id);
                int number     = 0;                // Số lượng mua
                int.TryParse(numberBuyTextBox.Text, out number);
                if (curProduct.Quantity < number)  // Nếu số lượng không đủ thì thông báo
                {
                    var dialogError = new Messenge()
                    {
                        Message = "Not enough quantity!"
                    };
                    dialogError.Sounds();
                    dialogError.time  = 2000;
                    dialogError.Owner = Window.GetWindow(this);
                    dialogError.ShowDialog();

                    numberBuyTextBox.Clear();

                    //Tắt nút thêm
                    btnAddToListProduct.Visibility = Visibility.Hidden;
                    return;
                }

                // Lấy số lượng người dùng muốn mua
                int NumberBuy = 0;
                int.TryParse(numberBuyTextBox.Text, out NumberBuy);

                // Phát sinh giá gốc
                double value = 0;
                value = (double)product.Price;
                originalPriceTextbox.Text = value.ToString("N0");

                //Sự kiện khuyến mãi (Chưa có)
                float eventPromotion = 0;
                sellPriceTextBox.Text = (value - value * eventPromotion / 100).ToString("N0");

                //tổng tiền
                totalTextBox.Text = (value * NumberBuy).ToString("N0");
            }
            else
            {
                btnAddToListProduct.Visibility = Visibility.Hidden;
                originalPriceTextbox.Clear();
                sellPriceTextBox.Clear();
                totalTextBox.Clear();
            }

            // Tính tiền trả lại + tiền sẽ thu nếu giao hàng
            CountExchange(null, null);
            CountMoneyWillGet(null, null);
        }
Пример #3
0
        public async Task Messenge(string message, string UserName)
        {
            User user = await _userManager.FindByNameAsync(UserName);

            Messenge messenge = new Messenge {
                Sender = UserName, Time = DateTime.Now, messenge = message, UrlImg = user.UrlImg
            };

            _context.Messenges.Add(messenge);
            await _context.SaveChangesAsync();

            var messenges = _context.Messenges.OrderBy(x => x.Time).ToList();
            await Clients.All.SendAsync("getMessenge", messenges);
        }
Пример #4
0
        private void toDayDatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            var db = new MyShopEntities();

            var orders       = db.OrderDetails;
            var products     = db.Products;
            var orderdetails = db.OrderDetails;

            if (fromDayDatePicker.SelectedDate != null)
            {
                var from = (DateTime)fromDayDatePicker.SelectedDate;
                var to   = (DateTime)toDayDatePicker.SelectedDate;

                if (DateTime.Compare(from, to) <= 0)
                {
                    var query = from orderdetail in orderdetails
                                join p in products on orderdetail.ProductId equals p.Product_Id
                                group p by p.CatId into pGroup
                                select new
                    {
                        Sum = orderdetails.Sum(o => o.Total)
                    };
                }
                else
                {
                    var dialogError = new Messenge()
                    {
                        Message = "The end date must be greater than the start date."
                    };
                    dialogError.Sounds();
                    dialogError.Owner = Window.GetWindow(this);
                    dialogError.ShowDialog();
                    return;
                }
            }
            else
            {
                var dialogError = new Messenge()
                {
                    Message = "Please select a start date."
                };
                dialogError.Sounds();
                dialogError.Owner = Window.GetWindow(this);
                dialogError.ShowDialog();
                return;
            }
        }
Пример #5
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)
            {
            }
        }
Пример #6
0
        static void Main(string[] args)
        {
            //var builder = new ConfigurationBuilder()
            //                .SetBasePath(Directory.GetCurrentDirectory())
            //                .AddJsonFile("appsetings.json", false, true);

            //IConfigurationRoot configurationRoot = builder.Build();
            //var connectionString = configurationRoot.GetConnectionString("DebugConnectionString");

            // RegisterUser();
            using (var context = new Context())
            {
                var users = context.Users
                            .ToList();
                var messeges = context.Messenges.ToList();
                Console.WriteLine("Логин:");
                var user = new User();
                user.Login = Console.ReadLine();
                Console.WriteLine("Сообщение:");
                var messege = new Messenge();
                messege.Text = Console.ReadLine();
                user.Messenges.Add(messege);
                context.SaveChanges();

                foreach (var userInDb in users)
                {
                    if (!user.Login.Equals(userInDb.Login))
                    {
                        context.Add(user);
                    }
                }

                //var result = context.Messenges.ToList();
                foreach (var messegeInDb in messeges.OrderBy(x => x.CreationDate))
                {
                    Console.WriteLine($"{messegeInDb.User.Login}: {messegeInDb.Text}");
                }
                context.SaveChanges();
            }
        }
Пример #7
0
        private void toDayDatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (fromDayDatePicker.SelectedDate != null)
            {
                var from = (DateTime)fromDayDatePicker.SelectedDate;
                var to   = (DateTime)toDayDatePicker.SelectedDate;

                if (DateTime.Compare(from, to) < 0)
                {
                    CalculatePagingInfo();
                    LoaddAllPurchase();
                }
                else
                {
                    var dialogError = new Messenge()
                    {
                        Message = "The end date must be greater than the start date."
                    };
                    dialogError.Sounds();
                    dialogError.Owner = Window.GetWindow(this);
                    dialogError.ShowDialog();
                    return;
                }
            }
            else
            {
                var dialogError = new Messenge()
                {
                    Message = "Please select a start date."
                };
                dialogError.Sounds();
                dialogError.Owner = Window.GetWindow(this);
                dialogError.ShowDialog();
                return;
            }
        }
Пример #8
0
        public static void DownloadBD(string PatchSave = null, Messenge messenge = null)
        {
            PatchSave += PatchSave != null?Path.Combine(PatchSave, Setting.NameFolderData) : Setting.NameFolderData;

            Directory.CreateDirectory(PatchSave);
            List <Month> months = new List <Month>(0);

            // Получение списка месяцев
            restart : try
            {
                var Mon = GetMonths.Get();
                if (messenge != null)
                {
                    messenge.Invoke("Будет загруженно " + Mon.Count + " вариантов");
                }
                // Проход по месяцам
                foreach (var elem in Mon)
                {
                    Month month = new Month {
                        Name = elem.Mesac, vars = new List <Var>(0)
                    };
                    // Проход по вариантам
                    string PatchVar = Path.Combine(PatchSave, elem.Mesac.Replace(":", null).Replace(" ", null));
                    PatchVar = Path.GetFullPath(PatchVar);
                    Directory.CreateDirectory(PatchVar);
                    foreach (var ElemTwo in elem.varXimIndices)
                    {
                        if (messenge != null)
                        {
                            messenge.Invoke("Начинаю загрузку: " + ElemTwo.Num);
                        }
res:
                        try
                        {
                            month.vars.Add(new Var {
                                Num = ElemTwo.Num, varOtvet = GetVar.Get(ElemTwo.Id, PatchVar, true, messenge)
                            });
                        }
                        catch { if (messenge != null)
                                {
                                    messenge.Invoke("Произошла ошибка осуществляю перезапуск: " + ElemTwo.Num);
                                }
                                goto res; }
                        if (messenge != null)
                        {
                            messenge.Invoke("Скачал вариант: " + ElemTwo.Num);
                        }
                    }
                    if (messenge != null)
                    {
                        messenge.Invoke("Скачал месяц: " + elem.Mesac);
                    }
                    months.Add(month);
                }
            }
            catch (Exception e) { Console.WriteLine(e.Message); goto restart; }
            Bd = new DataSave {
                months = months, Patch = Path.GetFullPath(PatchSave)
            };
            File.WriteAllText((PatchSave != null) ? Path.Combine(PatchSave, Setting.NameJsonBd) : Setting.NameJsonBd, JsonConvert.SerializeObject(Bd));
            if (messenge != null)
            {
                messenge.Invoke("Готово");
            }
        }
Пример #9
0
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            string _username = "";
            string _password = "";

            _username = tbUser.Text;
            _password = MD5Hash(Base64Encode(tbPass.Password));

            var accCount = DataProvider.Ins.db.Users.Where(x => x.UserName.ToString() == _username && x.Password.ToString() == _password).ToList().Count();

            // Kiểm tra nếu chưa nhập username hay password
            if (tbUser.Text.Length == 0 && tbPass.Password.Length == 0)
            {
                // Hiện thông báo lỗi
                var dialog = new Messenge()
                {
                    Message = "Please enter your account and password"
                };
                dialog.Sounds();
                dialog.time  = 2000;
                dialog.Owner = Window.GetWindow(this);
                dialog.ShowDialog();
                return;
            }
            else if (tbUser.Text.Length == 0)
            {
                // Hiện thông báo lỗi
                var dialog = new Messenge()
                {
                    Message = "Please enter your account"
                };
                dialog.Sounds();
                dialog.time  = 2000;
                dialog.Owner = Window.GetWindow(this);
                dialog.ShowDialog();
                return;
            }
            else if (tbPass.Password.Length == 0)
            {
                // Hiện thông báo lỗi
                var dialog = new Messenge()
                {
                    Message = "Please enter a password"
                };
                dialog.Sounds();
                dialog.time  = 2000;
                dialog.Owner = Window.GetWindow(this);
                dialog.ShowDialog();
                return;
            }


            //Nếu đăng nhập thành công, ẩn màn hình login
            if (accCount > 0)
            {
                Dashboard dashboard = new Dashboard();
                dashboard.Show();
                this.Close();
            }
            // Nếu thông tin tài khoản nhập vào sai
            else
            {
                // Hiện thông báo lỗi
                var dialog = new Messenge()
                {
                    Message = "Account or password is incorrect"
                };
                dialog.Sounds();
                dialog.time     = 2000;
                tbUser.Text     = "";
                tbPass.Password = "";
                dialog.Owner    = Window.GetWindow(this);
                dialog.ShowDialog();
                return;
            }
        }
Пример #10
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();
            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();
        }
Пример #11
0
        /// <summary>
        /// Thêm sản phẩm vào danh sách sản phẩm
        /// </summary>
        private void btnAddToListProduct_Click(object sender, RoutedEventArgs e)
        {
            ProgressBar.IsIndeterminate = true;

            double SumProducts = 0;

            //Không nhập số lượng
            if (numberBuyTextBox.Text == "")
            {
                var dialogError = new Messenge()
                {
                    Message = "Please enter the quantity!"
                };
                dialogError.Sounds();
                dialogError.Owner = Window.GetWindow(this);
                dialogError.ShowDialog();
                return;
            }

            //Tìm sản phẩm trong list xem có cùng với sản phẩm mới thêm vào không, nếu có thì gộp lại
            foreach (var p in _listProduct.ToList())
            {
                if (editProductId.Text == p.ProductName)
                {
                    //Thêm sản phẩm mới, thay cho sản phẩm cũ
                    var newProductInListView = new ProductViewModel()
                    {
                        ProductID   = product.Product_Id,
                        ProductName = product.Product_Name,
                        Price       = decimal.Parse(product.Price.ToString()),
                        Quantity    = int.Parse(numberBuyTextBox.Text) + p.Quantity,
                        Total       = decimal.Parse(totalTextBox.Text) + p.Total,
                    };
                    _listProduct.Remove(p);
                    _listProduct.Add(newProductInListView);

                    foreach (var sumP in _listProduct)
                    {
                        SumProducts += (double)sumP.Total;
                    }

                    listProducts.ItemsSource = _listProduct;
                    sumTotalOfProduct.Text   = $"{SumProducts.ToString("N0")} đ";
                    numberBuyTextBox.Clear();
                    return;
                }
            }

            var productInListView = new ProductViewModel()
            {
                ProductID   = product.Product_Id,
                ProductName = product.Product_Name,
                Price       = decimal.Parse(product.Price.ToString()),
                Quantity    = int.Parse(numberBuyTextBox.Text),
                Total       = decimal.Parse(totalTextBox.Text),
            };

            _listProduct.Add(productInListView);

            foreach (var p in _listProduct)
            {
                SumProducts += (double)p.Total;
            }

            listProducts.ItemsSource = _listProduct;
            sumTotalOfProduct.Text   = $"{SumProducts.ToString("N0")} đ";

            ProgressBar.IsIndeterminate = false;
            ProgressBar.Visibility      = Visibility.Hidden;
            numberBuyTextBox.Clear();
        }
Пример #12
0
        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();
                }
            }
        }
Пример #13
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;
        }