public ActionResult Edit(Xe x)
 {
     if (ModelState.IsValid)
     {
         x.TrangThai             = true;
         _context.Entry(x).State = EntityState.Modified;
         _context.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(x));
 }
Example #2
0
 public ActionResult Create(WarehouseModel model)
 {
     if (ModelState.IsValid)
     {
         db.WarehouseModel.Add(model);
         db.Entry(model).State = System.Data.Entity.EntityState.Added;
         db.SaveChanges();
         CreateViewBag();
         return(RedirectToAction("Index"));
     }
     ;
     return(View(model));
 }
Example #3
0
        public async Task <IActionResult> Edit(int?id, [FromBody] PostType postType)
        {
            try
            {
                if (id == null)
                {
                    return(BadRequest());
                }
                else
                {
                    var postTypeToUpdate = _context.PostTypes.FirstOrDefault(p => p.PostTypeId == id);
                    if (postTypeToUpdate == null)
                    {
                        return(NotFound());
                    }
                    else
                    {
                        postTypeToUpdate.CreatedDate           = postType.CreatedDate;
                        postTypeToUpdate.PostTypeName          = postType.PostTypeName;
                        postTypeToUpdate.SortOrder             = postType.SortOrder;
                        postTypeToUpdate.ModifiedDate          = DateTime.Now;
                        _context.Entry(postTypeToUpdate).State = EntityState.Modified;
                        await _context.SaveChangesAsync();

                        return(new ObjectResult(postTypeToUpdate));
                    }
                }
            }
            catch
            {
                return(BadRequest());
            }
        }
        public ActionResult Delete(int id)
        {
            HoaDon hd = _context.HoaDon.Find(id);

            hd.TrangThai             = false;
            _context.Entry(hd).State = System.Data.Entity.EntityState.Modified;
            _context.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public ActionResult Edit(PaymentMethodModel paymentmethodmodel)
 {
     if (ModelState.IsValid)
     {
         db.Entry(paymentmethodmodel).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(paymentmethodmodel));
 }
Example #6
0
 public ActionResult Edit(TrainerModel trainermodel)
 {
     if (ModelState.IsValid)
     {
         db.Entry(trainermodel).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(trainermodel));
 }
Example #7
0
 public ActionResult Edit(RegistryModel rolesmodel)
 {
     if (ModelState.IsValid)
     {
         _context.Entry(rolesmodel).State = System.Data.Entity.EntityState.Modified;
         _context.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(rolesmodel));
 }
Example #8
0
 public ActionResult Edit(LocationOfProductModel model)
 {
     if (ModelState.IsValid)
     {
         db.Entry(model).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(model));
 }
Example #9
0
 public ActionResult Edit(SteelFIModel steelfimodel)
 {
     if (ModelState.IsValid)
     {
         db.Entry(steelfimodel).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(steelfimodel));
 }
Example #10
0
 public ActionResult Edit(CurrencyModel Currency)
 {
     if (ModelState.IsValid)
     {
         db.Entry(Currency).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(Currency));
 }
Example #11
0
 public ActionResult Edit(CourseModel coursemodel)
 {
     if (ModelState.IsValid)
     {
         db.Entry(coursemodel).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     CreateViewBag(coursemodel.CategoryId);
     return(View(coursemodel));
 }
Example #12
0
        public ActionResult Edit(RolesModel rolesmodel)
        {
            if (ModelState.IsValid)
            {
                if (rolesmodel.OrderBy <= 0)
                {
                    ModelState.AddModelError("LonHon0", new Exception("Vui lòng nhập thứ tự lớn hơn 0"));
                    return(View(rolesmodel));
                }

                db.Entry(rolesmodel).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(rolesmodel));
        }
Example #13
0
        public bool UpdateNormal(AccountModel model, out string errorMessage)
        {
            // làm ơn đừng code gì trong này nữa nha
            // update bình thường thôi
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    errorMessage = "";
                    _context.Entry(model).State = System.Data.Entity.EntityState.Modified;
                    _context.SaveChanges();

                    scope.Complete();
                    return(true);
                }
                catch
                {
                    errorMessage = Resources.LanguageResource.SystemError;
                    return(false);
                }
            }
        }
Example #14
0
        public ActionResult Edit(CalendarOfEventModel model, int[] trainers)
        {
            if (ModelState.IsValid)
            {
                //model.TrainerModel == 2 item
                //trainers => Update

                var modelUpdate = db.CalendarOfEventModel.Where(p => p.EventId == model.EventId).FirstOrDefault();
                modelUpdate.CourseId   = model.CourseId;
                modelUpdate.EventCode  = model.EventCode;
                modelUpdate.StartDate  = model.StartDate;
                modelUpdate.StartTime  = model.StartTime;
                modelUpdate.EndTime    = model.EndTime;
                modelUpdate.LocationId = model.LocationId;
                //modelUpdate.CreateDate = model.CreateDate;
                //modelUpdate.UserCreate = model.UserCreate;
                modelUpdate.Actived = model.Actived;

                modelUpdate.TrainerModel.Clear();
                if (trainers != null && trainers.Length > 0)
                {
                    var newTrainers = db.TrainerModel
                                      .Where(r => trainers.Contains(r.TrainerId))
                                      .ToList();

                    foreach (var newTrainer in newTrainers)
                    {
                        modelUpdate.TrainerModel.Add(newTrainer);
                    }
                }

                db.Entry(modelUpdate).State = EntityState.Modified;
                db.SaveChanges();

                return(RedirectToAction("Index"));
            }
            CreateViewBag(model.CourseId, model.LocationId);
            return(View(model));
        }
Example #15
0
        public void UpdateProduct(HttpPostedFileBase excelfile, int?AccountId)
        {
            #region    // Duyệt danh sách insert
            EntityDataContext _context      = new EntityDataContext();
            string            ErrorEmpty    = "";
            string            ErrorIsNumber = "";
            string            Error         = "";
            bool check           = true;
            int  QuantityProduct = 0;
            try
            {
                using (var package = new ExcelPackage(excelfile.InputStream))
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                        int            col       = 1;
                        for (int row = 7; worksheet.Cells[row, col].Value != null; row++)
                        {
                            #region    //Gán giá trị tạm
                            int     ProductId    = 0;
                            decimal ImportPrice  = 0;
                            decimal ShippingFee  = 0;
                            decimal ExchangeRate = 0;
                            decimal pprice1      = 0;
                            decimal pprice2      = 0;
                            decimal pprice3      = 0;
                            decimal pprice4      = 0;

                            #endregion

                            #region     // Kiểm tra giá trị cột
                            //Mã sản phẩm
                            if (worksheet.Cells[row, 2].Text == "")
                            {
                                check       = false;
                                ErrorEmpty += " Dòng " + row + " Cột 'Mã sản phẩm' ,";
                            }
                            else if (int.TryParse(worksheet.Cells[row, 2].Value.ToString(), out ProductId) == false)
                            {
                                check          = false;
                                ErrorIsNumber += " Dòng " + row + " Cột 'Mã sản phẩm' ,";
                            }

                            //Mã Sản Phẩm Cửa hàn
                            if (worksheet.Cells[row, 3].Text == "")
                            {
                                check       = false;
                                ErrorEmpty += " Dòng " + row + " Cột 'Mã Sản Phẩm Cửa hàng' ,";
                            }

                            //Tên Sản Phẩm
                            if (worksheet.Cells[row, 5].Text == "")
                            {
                                check       = false;
                                ErrorEmpty += " Dòng " + row + " Cột 'Tên Sản Phẩm' ,";
                            }

                            //Giá nhập
                            if (worksheet.Cells[row, 6].Text == "")
                            {
                                check       = false;
                                ErrorEmpty += " Dòng " + row + " Cột 'Giá nhập' ,";
                            }
                            else if (decimal.TryParse(worksheet.Cells[row, 6].Value.ToString(), out ImportPrice) == false)
                            {
                                check          = false;
                                ErrorIsNumber += " Dòng " + row + " Cột 'Giá nhập' ,";
                            }

                            //Tỷ giá
                            if (worksheet.Cells[row, 7].Text == "")
                            {
                                check       = false;
                                ErrorEmpty += " Dòng " + row + " Cột 'Tỷ giá' ,";
                            }
                            else if (decimal.TryParse(worksheet.Cells[row, 7].Value.ToString(), out ExchangeRate) == false)
                            {
                                check          = false;
                                ErrorIsNumber += " Dòng " + row + " Cột 'Tỷ giá' ,";
                            }

                            //Phí vận chuyển
                            if (worksheet.Cells[row, 8].Text == "")
                            {
                                check       = false;
                                ErrorEmpty += " Dòng " + row + " Cột 'Phí vận chuyển' ,";
                            }
                            else if (decimal.TryParse(worksheet.Cells[row, 8].Value.ToString(), out ShippingFee) == false)
                            {
                                check          = false;
                                ErrorIsNumber += " Dòng " + row + " Cột 'Phí vận chuyển' ,";
                            }

                            //Vip
                            if (worksheet.Cells[row, 9].Text == "")
                            {
                                check       = false;
                                ErrorEmpty += " Dòng " + row + " Cột 'Vip' ,";
                            }
                            else if (decimal.TryParse(worksheet.Cells[row, 9].Value.ToString(), out pprice1) == false)
                            {
                                check          = false;
                                ErrorIsNumber += " Dòng " + row + " Cột 'Vip' ,";
                            }

                            //Vip-Bạc
                            if (worksheet.Cells[row, 10].Text == "")
                            {
                                check       = false;
                                ErrorEmpty += " Dòng " + row + " Cột 'Vip-Bạc' ,";
                            }
                            else if (decimal.TryParse(worksheet.Cells[row, 10].Value.ToString(), out pprice2) == false)
                            {
                                check          = false;
                                ErrorIsNumber += " Dòng " + row + " Cột 'Vip-Bạc' ,";
                            }

                            //Vip-Vàng
                            if (worksheet.Cells[row, 11].Text == "")
                            {
                                check       = false;
                                ErrorEmpty += " Dòng " + row + " Cột 'Vip-Vàng' ,";
                            }
                            else if (decimal.TryParse(worksheet.Cells[row, 11].Value.ToString(), out pprice3) == false)
                            {
                                check          = false;
                                ErrorIsNumber += " Dòng " + row + " Cột 'Vip-Vàng' ,";
                            }

                            //Vip-Bạch kim
                            if (worksheet.Cells[row, 12].Text == "")
                            {
                                check       = false;
                                ErrorEmpty += " Dòng " + row + " Cột 'Vip-Bạch kim' ,";
                            }
                            else if (decimal.TryParse(worksheet.Cells[row, 12].Value.ToString(), out pprice4) == false)
                            {
                                check          = false;
                                ErrorIsNumber += " Dòng " + row + " Cột 'Vip-Bạch kim' ,";
                            }

                            #endregion

                            if (check)
                            {
                                #region     //Cập nhật Product

                                ProductModel p = _context.ProductModel.Where(m => m.ProductId == ProductId).FirstOrDefault();
                                p.ProductStoreCode = worksheet.Cells[row, 3].Value.ToString();
                                if (worksheet.Cells[row, 4].Text != "")
                                {
                                    p.ProductCode = worksheet.Cells[row, 4].Value.ToString();
                                }
                                p.ProductName = worksheet.Cells[row, 5].Value.ToString();
                                p.ImportPrice = ImportPrice;
                                p.ShippingFee = ShippingFee;
                                p.COGS        = p.ImportPrice * ExchangeRate + p.ShippingFee;

                                #endregion

                                #region     // Cập nhật giá VIP
                                //Product Price 1
                                ProductPriceModel price1 = _context.ProductPriceModel.Where(pp => pp.ProductId == ProductId && pp.CustomerLevelId == 1).FirstOrDefault();
                                price1.Price = pprice1;
                                //Product Price 2
                                ProductPriceModel price2 = _context.ProductPriceModel.Where(pp => pp.ProductId == ProductId && pp.CustomerLevelId == 2).FirstOrDefault();
                                price2.Price = pprice2;

                                //Product Price 3
                                ProductPriceModel price3 = _context.ProductPriceModel.Where(pp => pp.ProductId == ProductId && pp.CustomerLevelId == 3).FirstOrDefault();
                                price3.Price = pprice3;

                                //Product Price 3
                                ProductPriceModel price4 = _context.ProductPriceModel.Where(pp => pp.ProductId == ProductId && pp.CustomerLevelId == 4).FirstOrDefault();
                                price4.Price = pprice4;

                                #endregion

                                #region     // Update Database
                                _context.Entry(price1).State = System.Data.Entity.EntityState.Modified;
                                _context.Entry(price2).State = System.Data.Entity.EntityState.Modified;
                                _context.Entry(price3).State = System.Data.Entity.EntityState.Modified;
                                _context.Entry(price4).State = System.Data.Entity.EntityState.Modified;
                                _context.Entry(p).State      = System.Data.Entity.EntityState.Modified;
                                _context.SaveChanges();
                                #endregion
                            }
                            QuantityProduct++;
                        }
                        ts.Complete();
                    }
                }
            }
            catch (EntityException ex)
            {
                Error = "Xảy ra lỗi trong quá trình cập nhật !" + ex;
            }

            #region Note
            NotificationModel n = new NotificationModel();
            if (check == true && Error == "")
            {
                n.Note = "Đã cập nhật thành công giá của " + QuantityProduct + " sản phẩm !";
            }
            else
            {
                n.Note = "Cập nhật không thành công !";
                if (Error != "")
                {
                    n.Note += Error;
                }
                if (ErrorEmpty != "")
                {
                    n.Note += "  Bị rỗng :" + ErrorEmpty;
                }
                if (ErrorIsNumber != "")
                {
                    n.Note += "  Không là số :" + ErrorEmpty;
                }
            }
            n.AccountId             = AccountId;
            n.CreateDate            = DateTime.Now;
            n.Actived               = true;
            _context.Entry(n).State = System.Data.Entity.EntityState.Added;
            _context.SaveChanges();
            #endregion

            _context.Dispose();
            #endregion
        }
        public string Save(ImportMasterModel model, List <ImportDetailViewModel> detail, decimal TotalShippingWeight, decimal?GuestAmountPaid, DateTime ExchangeDate, int CreateReceipt, string UserName, int EmployeeId)
        {
            try
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    var currentTime = DateTime.Now;

                    #region ImportMaster
                    model.CreatedDate       = currentTime;
                    model.CreatedAccount    = UserName;
                    model.CreatedEmployeeId = EmployeeId;
                    model.InventoryTypeId   = EnumInventoryType.NC;
                    model.Paid             = GuestAmountPaid.HasValue ? GuestAmountPaid : 0;
                    model.ImportMasterCode = GetImportMasterCode();
                    //Thêm tổng công nợ cộng dồn = nợ cũ + nợ mới
                    //decimal? SuplierOldDebt = _context.ImportMasterModel
                    //                                  .Where(p => p.SupplierId == model.SupplierId)
                    //                                  .OrderByDescending(p => p.ImportMasterId)
                    //                                  .Select(p => p.RemainingAmountAccrued)
                    //                                  .FirstOrDefault();
                    decimal?SuplierOldDebt = _context.AM_DebtModel
                                             .Where(p => p.SupplierId == model.SupplierId)
                                             .OrderByDescending(p => p.TimeOfDebt)
                                             .Select(p => p.RemainingAmountAccrued)
                                             .FirstOrDefault();
                    SuplierOldDebt               = (SuplierOldDebt == null) ? 0 : SuplierOldDebt.Value;
                    model.RemainingAmount        = (model.RemainingAmount == null) ? 0 : model.RemainingAmount.Value;
                    model.RemainingAmountAccrued = SuplierOldDebt.Value + model.RemainingAmount.Value;

                    _context.Entry(model).State = System.Data.Entity.EntityState.Added;
                    _context.SaveChanges(); // LƯU TẠM ĐỂ LẤY IMPORTMASTERID (SẼ BỊ SCROLLBACK KHI XẢY RA LỖI)
                    #endregion

                    #region Kế toán
                    if (CreateReceipt == 1)
                    {
                        #region Thêm vào giao dịch kế toán
                        AM_TransactionModel AMmodel;

                        #region TH1 : Trả đủ

                        if (model.TotalPrice == GuestAmountPaid)
                        {
                            AMmodel = new AM_TransactionModel()
                            {
                                StoreId             = model.StoreId,
                                AMAccountId         = (_context.AM_AccountModel.Where(p => p.Code == EnumAccountCode.TM && p.AMAccountTypeCode == EnumAM_AccountType.TIENMAT && p.StoreId == model.StoreId).Select(p => p.AMAccountId)).FirstOrDefault(),
                                TransactionTypeCode = EnumTransactionType.NXNHAP,
                                ContactItemTypeCode = EnumContactType.NCC,
                                CustomerId          = null,
                                SupplierId          = model.SupplierId,
                                EmployeeId          = null,
                                OtherId             = null,
                                Amount                 = GuestAmountPaid,
                                OrderId                = null,
                                ImportMasterId         = model.ImportMasterId,
                                IEOtherMasterId        = null,
                                Note                   = model.Note,
                                CreateDate             = currentTime,
                                CreateEmpId            = EmployeeId,
                                RemainingAmountAccrued = model.RemainingAmountAccrued
                            };
                            _context.Entry(AMmodel).State = System.Data.Entity.EntityState.Added;
                            _context.SaveChanges();
                        }
                        #endregion

                        #region TH2 : Không trả lưu vào công nợ
                        else if (GuestAmountPaid == 0 || GuestAmountPaid == null)
                        {
                            AMmodel = new AM_TransactionModel()
                            {
                                StoreId             = model.StoreId,
                                AMAccountId         = (_context.AM_AccountModel.Where(p => p.Code == EnumAccountCode.PTNCC && p.AMAccountTypeCode == EnumAM_AccountType.CONGNO && p.StoreId == model.StoreId).Select(p => p.AMAccountId)).FirstOrDefault(),
                                TransactionTypeCode = EnumTransactionType.NXNHAP,
                                ContactItemTypeCode = EnumContactType.NCC,
                                CustomerId          = null,
                                SupplierId          = model.SupplierId,
                                EmployeeId          = null,
                                OtherId             = null,
                                Amount                 = model.TotalPrice,
                                OrderId                = null,
                                ImportMasterId         = model.ImportMasterId,
                                IEOtherMasterId        = null,
                                Note                   = model.Note,
                                CreateDate             = currentTime,
                                CreateEmpId            = EmployeeId,
                                RemainingAmountAccrued = model.RemainingAmountAccrued
                            };
                            _context.Entry(AMmodel).State = System.Data.Entity.EntityState.Added;
                            _context.SaveChanges();
                        }
                        #endregion

                        #region TH3 : Trả 1 phần
                        else
                        {
                            #region 1 phần (Tiền mặt hoặc chuyển khoản)
                            AMmodel = new AM_TransactionModel()
                            {
                                StoreId             = model.StoreId,
                                AMAccountId         = (_context.AM_AccountModel.Where(p => p.Code == EnumAccountCode.TM && p.AMAccountTypeCode == EnumAM_AccountType.TIENMAT && p.StoreId == model.StoreId).Select(p => p.AMAccountId)).FirstOrDefault(),
                                TransactionTypeCode = EnumTransactionType.NXNHAP,
                                ContactItemTypeCode = EnumContactType.NCC,
                                CustomerId          = null,
                                SupplierId          = model.SupplierId,
                                EmployeeId          = null,
                                OtherId             = null,
                                Amount                 = GuestAmountPaid,
                                OrderId                = null,
                                ImportMasterId         = model.ImportMasterId,
                                IEOtherMasterId        = null,
                                Note                   = model.Note,
                                CreateDate             = currentTime,
                                CreateEmpId            = EmployeeId,
                                RemainingAmountAccrued = model.RemainingAmountAccrued
                            };
                            _context.Entry(AMmodel).State = System.Data.Entity.EntityState.Added;
                            _context.SaveChanges();
                            #endregion

                            #region 1 phần đưa vào công nợ
                            AMmodel = new AM_TransactionModel()
                            {
                                StoreId             = model.StoreId,
                                AMAccountId         = (_context.AM_AccountModel.Where(p => p.Code == EnumAccountCode.PTNCC && p.AMAccountTypeCode == EnumAM_AccountType.CONGNO && p.StoreId == model.StoreId).Select(p => p.AMAccountId)).FirstOrDefault(),
                                TransactionTypeCode = EnumTransactionType.NXNHAP,
                                ContactItemTypeCode = EnumContactType.NCC,
                                CustomerId          = null,
                                SupplierId          = model.SupplierId,
                                EmployeeId          = null,
                                OtherId             = null,
                                Amount                 = model.TotalPrice - GuestAmountPaid,
                                OrderId                = null,
                                ImportMasterId         = model.ImportMasterId,
                                IEOtherMasterId        = null,
                                Note                   = model.Note,
                                CreateDate             = currentTime,
                                CreateEmpId            = EmployeeId,
                                RemainingAmountAccrued = model.RemainingAmountAccrued
                            };
                            _context.Entry(AMmodel).State = System.Data.Entity.EntityState.Added;
                            _context.SaveChanges();
                            #endregion
                        }
                        #endregion

                        #endregion
                    }
                    #endregion

                    #region Thêm AM_DebtModel (Số nợ còn lại)
                    if (model.RemainingAmount > 0)
                    {
                        var AMDebModel = new AM_DebtModel()
                        {
                            SupplierId             = model.SupplierId,
                            TimeOfDebt             = currentTime,
                            RemainingAmountAccrued = model.RemainingAmountAccrued,
                            ImportId            = model.ImportMasterId,
                            TransactionTypeCode = EnumTransactionType.NXNHAP
                        };
                        _context.Entry(AMDebModel).State = System.Data.Entity.EntityState.Added;
                        _context.SaveChanges();
                    }
                    #endregion

                    #region InventoryMaster
                    InventoryMasterModel InvenMaster = new InventoryMasterModel();
                    InvenMaster.WarehouseModelId      = model.WarehouseId;
                    InvenMaster.InventoryCode         = model.ImportMasterCode;
                    InvenMaster.InventoryTypeId       = EnumInventoryType.NC;
                    InvenMaster.CreatedDate           = model.CreatedDate;
                    InvenMaster.CreatedAccount        = model.CreatedAccount;
                    InvenMaster.CreatedEmployeeId     = model.CreatedEmployeeId;
                    InvenMaster.Actived               = true;
                    InvenMaster.BusinessId            = model.ImportMasterId;     // Id nghiệp vụ
                    InvenMaster.BusinessName          = "ImportMasterModel";      // Tên bảng nghiệp vụ
                    InvenMaster.ActionUrl             = "/ImportMaster/Details/"; // Đường dẫn ( cộng ID cho truy xuất)
                    InvenMaster.StoreId               = model.StoreId;
                    _context.Entry(InvenMaster).State = System.Data.Entity.EntityState.Added;
                    _context.SaveChanges(); // insert tạm để lấy InvenMasterID
                    #endregion

                    #region ExchangeRate
                    // Update ExchangeRate
                    var Exchangerate = _context.ExchangeRateModel
                                       .OrderByDescending(p => p.ExchangeDate)
                                       .Where(p => p.CurrencyId == model.CurrencyId &&
                                              p.ExchangeDate.Value.CompareTo(DateTime.Now) <= 0
                                              )
                                       .FirstOrDefault();
                    string DateDB  = string.Format("{0}-{1}-{2}", Exchangerate.ExchangeDate.Value.Year, Exchangerate.ExchangeDate.Value.Month, Exchangerate.ExchangeDate.Value.Day);
                    string DateNow = string.Format("{0}-{1}-{2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

                    if (DateDB == DateNow)
                    {
                        // update
                        Exchangerate.ExchangeRate          = (float)model.ExchangeRate.Value;
                        Exchangerate.ExchangeDate          = DateTime.Now;
                        _context.Entry(Exchangerate).State = System.Data.Entity.EntityState.Modified;
                    }
                    else
                    {
                        ExchangeRateModel Exchangeratemodel = new ExchangeRateModel()
                        {
                            CurrencyId   = model.CurrencyId,
                            ExchangeRate = (float)model.ExchangeRate.Value,
                            ExchangeDate = DateTime.Now,
                        };
                        // add
                        _context.Entry(Exchangeratemodel).State = System.Data.Entity.EntityState.Added;
                    }
                    _context.SaveChanges();

                    #endregion

                    #region Lst Product
                    if (detail != null)
                    {
                        //if (detail.GroupBy(p => p.ProductId).ToList().Count < detail.Count)
                        //{
                        //    //khong duoc trung san pham
                        //    return "Vui lòng không chọn thông tin sản phẩm trùng nhau !";
                        //}
                        foreach (var item in detail)
                        {
                            item.UnitCOGS = (item.Price * model.ExchangeRate) + item.ShippingFee;

                            #region Import Detail
                            ImportDetailModel detailmodel = new ImportDetailModel()
                            {
                                ImportMasterId     = model.ImportMasterId,
                                ProductId          = item.ProductId,
                                Qty                = item.Qty,
                                Price              = item.Price,
                                UnitShippingWeight = item.UnitShippingWeight,
                                UnitPrice          = item.UnitPrice,
                                ShippingFee        = item.ShippingFee,
                                UnitCOGS           = item.UnitCOGS,
                                Note               = item.Note
                            };
                            _context.Entry(detailmodel).State = System.Data.Entity.EntityState.Added;
                            _context.SaveChanges();
                            #endregion

                            #region  update bảng Product
                            var productmodel = _context.ProductModel.Where(p => p.ProductId == item.ProductId).FirstOrDefault();
                            //productmodel.ImportPrice = item.Price;
                            //productmodel.ShippingFee = item.ShippingFee;
                            //productmodel.COGS = item.UnitCOGS;
                            //productmodel.CurrencyId = model.CurrencyId;
                            //productmodel.ExchangeRate = model.ExchangeRate;
                            productmodel.ImportDate            = DateTime.Now;
                            _context.Entry(productmodel).State = System.Data.Entity.EntityState.Modified;
                            _context.SaveChanges();
                            #endregion
                        }

                        #region Insert InventoryDetail

                        #region groupby Importdetail
                        var detailgruoppd =
                            (from c in detail
                             group c by new
                        {
                            c.ProductId
                        } into gcs
                             select new ImportDetailViewModel()
                        {
                            ProductId = gcs.Key.ProductId,
                            Qty = gcs.Sum(p => p.Qty),
                            Price = gcs.Sum(p => p.Price),
                            UnitShippingWeight = gcs.Sum(p => p.UnitShippingWeight),
                            UnitPrice = gcs.Sum(p => p.UnitPrice),
                            ShippingFee = gcs.Sum(p => p.ShippingFee),
                            UnitCOGS = gcs.Sum(p => p.UnitCOGS)
                        }).ToList();
                        #endregion

                        foreach (var item in detailgruoppd)
                        {
                            item.UnitCOGS = (item.Price * model.ExchangeRate) + item.ShippingFee;
                            #region Insert
                            // Insert InventoryDetail
                            EndInventoryRepository EndInventoryRepo = new EndInventoryRepository(_context);
                            decimal tondau = EndInventoryRepo.GetQty(item.ProductId.Value);
                            var     tempt2 = _context.ProductModel.Where(p => p.ProductId == item.ProductId).FirstOrDefault();
                            decimal GiaVon = tempt2.COGS.HasValue ? tempt2.COGS.Value : 0;
                            InventoryDetailModel InvenDetail = new InventoryDetailModel()
                            {
                                InventoryMasterId = InvenMaster.InventoryMasterId,
                                ProductId         = item.ProductId,
                                BeginInventoryQty = tondau,
                                COGS = GiaVon,
                                //Price = item.Price,
                                ImportQty = item.Qty,
                                //ExportQty = 0,
                                UnitCOGS = GiaVon * item.Qty,
                                //UnitPrice = 0,
                                EndInventoryQty = tondau + item.Qty
                            };
                            _context.Entry(InvenDetail).State = System.Data.Entity.EntityState.Added;
                            _context.SaveChanges();
                            #endregion
                        }

                        #endregion
                        // Cập nhật lại Tổng giá vốn
                        model.SumCOGSOfOrderDetail  = detail.Sum(p => p.UnitCOGS * p.Qty);
                        _context.Entry(model).State = System.Data.Entity.EntityState.Modified;

                        _context.SaveChanges();
                        // đánh dấu Transaction hoàn tất
                        ts.Complete();

                        #region Cập nhật Tỉ giá và giá nhập,phí vận chuyển,giá vốn trên StoreProcedure

                        #endregion
                        return("success");
                    }
                    else
                    {
                        //chua nhap tt san pham
                        return("Vui lòng chọn thông tin sản phẩm");
                    }
                    #endregion
                }
            }
            catch
            {
                return("Xảy ra lỗi trong quá trình thêm mới sản phẩm từ nhà cung cấp");
            }
        }
Example #17
0
        //Xử lý đặt hàng
        public ActionResult BookingOrder(Daily_ChicCut_Pre_OrderViewModel orderModel, string Phone, DateTime BookingDate, List <int> ServiceNoteList)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(Phone) || string.IsNullOrEmpty(orderModel.FullName))
                {
                    return(Json(new { Message = "(*) Vui lòng nhập thông tin bắt buộc!" }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    #region //Tìm khách hàng qua sđt
                    var customer = _context.CustomerModel.Where(p => p.Phone == Phone).FirstOrDefault();
                    //Không có KH trong Db => thêm mới
                    if (customer == null)
                    {
                        CustomerModel cus = new CustomerModel();
                        //Thêm những field bắt buộc vào CustomerModel
                        cus.CustomerLevelId       = 1;
                        cus.FullName              = orderModel.FullName;
                        cus.ShortName             = orderModel.FullName;
                        cus.Phone                 = orderModel.Phone;
                        cus.Gender                = orderModel.Gender;
                        cus.Actived               = true;
                        cus.RegDate               = DateTime.Now;
                        _context.Entry(cus).State = System.Data.Entity.EntityState.Added;
                        _context.SaveChanges();
                        orderModel.CustomerId = cus.CustomerId;
                    }
                    //Có KH trong Db => cập nhật tên, giới tính dựa vào sđt
                    else
                    {
                        orderModel.CustomerId          = customer.CustomerId;
                        customer.ShortName             = orderModel.FullName;
                        customer.Gender                = orderModel.Gender;
                        _context.Entry(customer).State = System.Data.Entity.EntityState.Modified;
                        _context.SaveChanges();
                    }
                    #endregion
                }


                //KH chưa chọn khung giờ
                if (orderModel.BookingTime == TimeSpan.Zero)
                {
                    return(Json(new { Message1 = "(*) Khung giờ chưa được chọn! Vui lòng chọn khung giờ phục vụ." }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    //Mỗi sđt chỉ đặt được một lần trong ngày
                    var preOrder = _context.Daily_ChicCut_Pre_OrderModel.Where(p => p.Phone == Phone && DbFunctions.TruncateTime(p.AppointmentTime) == BookingDate.Date).FirstOrDefault();
                    if (preOrder != null)
                    {
                        return(Json(new { Message2 = "Số điện thoại này đã được đặt trong ngày!" }, JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        //KH đặt trước dịch vụ:
                        //- Cắt
                        //- Uốn
                        //- Duỗi
                        //- Nhuộm
                        List <string> ServiceNoteListString = new List <string>();
                        foreach (var item in ServiceNoteList)
                        {
                            string haircuts = item == 0 ? "Cắt" : (item == 1 ? "Uốn" : (item == 2 ? "Duỗi" : "Nhuộm"));
                            ServiceNoteListString.Add(haircuts);
                        }
                        orderModel.ServiceNote = String.Join(", ", ServiceNoteListString);

                        Daily_ChicCut_Pre_OrderModel order = new Daily_ChicCut_Pre_OrderModel();
                        //Thêm những field bắt buộc vào Daily_ChicCut_Pre_OrderModel
                        order.CustomerId   = orderModel.CustomerId;
                        order.FullName     = orderModel.FullName;
                        order.Gender       = orderModel.Gender;
                        order.Phone        = orderModel.Phone;
                        order.ServicesNote = orderModel.ServiceNote;
                        order.Note         = orderModel.Note;
                        //Đơn hàng đặt trước => OrderStatusId = 5
                        order.OrderStatusId = 5;
                        //Xử lý ngày giờ hẹn
                        orderModel.AppointmentTime = orderModel.BookingDate + orderModel.BookingTime;
                        order.AppointmentTime      = orderModel.AppointmentTime;
                        //Ngày giờ đặt
                        orderModel.CreatedDate = DateTime.Now;
                        order.CreatedDate      = orderModel.CreatedDate;
                        //Thêm vào Db
                        _context.Entry(order).State = System.Data.Entity.EntityState.Added;
                        _context.SaveChanges();
                        //Tạo số phiếu đặt từ PreOrderId
                        order.PreOrderCode = (order.PreOrderId % 1000).ToString("D3");

                        #region // Gửi SMS cho khách hàng
                        SendSMSRepository SMSRepo = new SendSMSRepository();
                        string            name    = order.FullName.LastIndexOf(' ') > 0 ? order.FullName.Substring(order.FullName.LastIndexOf(' ') + 1) : order.FullName;
                        name = Library.ConvertToNoMarkString(name);
                        if (!string.IsNullOrEmpty(name))
                        {
                            name = name.First().ToString().ToUpper() + name.Substring(1).ToLower();
                        }
                        string mes = string.Format(
                            "Cam on {0} {1} dat hen tai Chic Cut, thoi gian hen la: {2:HH:mm dd/MM/yyyy}. {0} vui long den dung gio da hen.",
                            order.Gender.HasValue && order.Gender.Value ? "anh" : "chi",
                            name,
                            order.AppointmentTime
                            );
                        AY_SMSCalendar smsModel = new AY_SMSCalendar()
                        {
                            EndDate        = DateTime.Now,
                            isSent         = true,
                            NumberOfFailed = 0,
                            SMSContent     = mes,
                            SMSTo          = order.Phone
                        };
                        _context.Entry(smsModel).State = System.Data.Entity.EntityState.Added;
                        #endregion
                        _context.SaveChanges();

                        SMSRepo.SendSMSModel(smsModel);

                        _context.SaveChanges();
                        return(Json(true, JsonRequestBehavior.AllowGet));
                    }
                }
            }
            else
            {
                return(Json(false, JsonRequestBehavior.AllowGet));
            }
        }