Exemple #1
0
        public ActionResult UpdateOrderPay(int OrderId)
        {
            try
            {
                var model = _context.Daily_ChicCut_OrderModel.Where(p => p.OrderId == OrderId).FirstOrDefault();
                if (model == null)
                {
                    return(Content("Không tìm thấy đơn hàng yêu cầu!"));
                }
                else
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        var currentTime = DateTime.Now;
                        List <Daily_ChicCut_OrderDetailModel> detail = model.Daily_ChicCut_OrderDetailModel.ToList();

                        #region                                                   // Insert InventoryMaster
                        InventoryMasterModel InvenMaster = new InventoryMasterModel();
                        InvenMaster.WarehouseModelId      = 1;                    //Kho 489 Hồng Bàng
                        InvenMaster.InventoryTypeId       = EnumInventoryType.XB; // xuất bán hàng
                        InvenMaster.InventoryCode         = string.Format("{0}-{1}", ConstantInventoryCode.MaDonHangTaoMoi, model.OrderId);
                        InvenMaster.CreatedDate           = currentTime;
                        InvenMaster.CreatedAccount        = currentAccount.UserName;
                        InvenMaster.CreatedEmployeeId     = currentEmployee.EmployeeId;
                        InvenMaster.StoreId               = 1000;                                 //Chic Cut Salon
                        InvenMaster.Actived               = true;
                        InvenMaster.BusinessId            = model.OrderId;                        // Id nghiệp vụ
                        InvenMaster.BusinessName          = "Daily_ChicCut_OrderModel";           // Tên bảng nghiệp vụ
                        InvenMaster.ActionUrl             = "/Daily_ChicCut_OrderModel/Details/"; // Đường dẫn ( cộng ID cho truy xuất)
                        _context.Entry(InvenMaster).State = System.Data.Entity.EntityState.Added;
                        _context.SaveChanges();                                                   // insert tạm để lấy InvenMasterID
                        #endregion

                        #region
                        /* Chi tiết định lượng : Qty = QDetail.Qty * Od.Qty,  Price = pdprice.Price * Od.Qty*/
                        var QDetailList = (
                            from Od in detail
                            join QMaster in _context.Master_ChicCut_QuantificationMasterModel on Od.ServiceId equals QMaster.ServiceId
                            join QDetail in _context.Master_ChicCut_QuantificationDetailModel on QMaster.QuantificationMasterId equals QDetail.QuantificationMasterId
                            join pd in _context.ProductModel on QDetail.ProductId equals pd.ProductId
                            //join pdprice in _context.ProductPriceModel on pd.ProductId equals pdprice.ProductId
                            where detail.Select(p => p.ServiceId).ToList().Contains(QMaster.ServiceId)
                            select new Master_ChicCut_QuantificationDetailViewModel()
                        {
                            ProductId = QDetail.ProductId,
                            Qty = QDetail.Qty * Od.Qty,
                            Price = 0    //pdprice.Price * Od.Qty,
                        }).ToList();
                        if (QDetailList != null && QDetailList.Count > 0)
                        {
                            foreach (var item in QDetailList)
                            {
                                EndInventoryRepository EndInventoryRepo = new EndInventoryRepository(_context);
                                decimal TonCuoiTrongHeThong             = EndInventoryRepo.GetQty(item.ProductId.Value);
                                InventoryDetailModel InvenDetail        = new InventoryDetailModel()
                                {
                                    InventoryMasterId = InvenMaster.InventoryMasterId,
                                    ProductId         = item.ProductId,
                                    BeginInventoryQty = TonCuoiTrongHeThong,
                                    //COGS = 0,
                                    Price = item.Price,
                                    //ImportQty = 0, // số lượng nhập = 0
                                    ExportQty = item.Qty,
                                    //UnitCOGS = 0, //Tổng giá vốn = [COGS] * [ImportQty] = 0
                                    UnitPrice       = item.Qty * item.Price,             //[ExportQty] *[Price]
                                    EndInventoryQty = TonCuoiTrongHeThong + 0 - item.Qty //Tồn cuối = [BeginInventoryQty] + [ImportQty] -  [ExportQty]
                                };
                                _context.Entry(InvenDetail).State = System.Data.Entity.EntityState.Added;
                            }
                        }
                        #endregion

                        model.OrderStatusId         = EnumDaily_ChicCut_OrderStatus.DaTinhTien;
                        _context.Entry(model).State = System.Data.Entity.EntityState.Modified;
                        _context.SaveChanges();
                        ts.Complete();
                        return(Content("success"));
                    }
                }
            }
            catch
            {
                return(Content("Xảy ra lỗi trong quá trình cập nhật trạng thái"));
            }
        }
Exemple #2
0
        public ActionResult Save(ReturnMasterModel model, List <ReturnDetailViewModel> detail, decimal?GuestAmountPaid, int CreateReceipt = 1)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        var currentTime = DateTime.Now;

                        #region Lưu ReturnMaster
                        model.CreatedDate    = currentTime;
                        model.CreatedAccount = currentAccount.UserName;
                        AccountModel Account = _context.AccountModel.Where(p => p.UserName == model.CreatedAccount).FirstOrDefault();
                        model.CreatedEmployeeId = Account.EmployeeId;
                        model.InventoryTypeId   = EnumInventoryType.XC;                      //Xuất - Trả hàng cho nhà cung cấp
                        model.Paid             = GuestAmountPaid.HasValue ? GuestAmountPaid : 0;
                        model.ReturnMasterCode = GetReturnCode();
                        model.Actived          = true;

                        #endregion

                        var importModel = _context.ImportMasterModel.Where(p => p.ImportMasterId == model.ImportMasterId).FirstOrDefault();

                        #region Tính số dư còn lại
                        decimal?SuplierOldDebt = _context.AM_DebtModel
                                                 .Where(p => p.SupplierId == importModel.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 ReturnMASTERID (SẼ BỊ SCROLLBACK KHI XẢY RA LỖI)
                        #endregion

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

                            #region TH1 : nhận đủ

                            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.NXXUAT,
                                    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            = currentEmployee.EmployeeId,
                                    RemainingAmountAccrued = model.RemainingAmountAccrued
                                };
                                _context.Entry(AMmodel).State = System.Data.Entity.EntityState.Added;
                                _context.SaveChanges();
                            }
                            #endregion

                            #region TH2 : Không nhận 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.NXXUAT,
                                    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            = currentEmployee.EmployeeId,
                                    RemainingAmountAccrued = model.RemainingAmountAccrued
                                };
                                _context.Entry(AMmodel).State = System.Data.Entity.EntityState.Added;
                                _context.SaveChanges();
                            }
                            #endregion

                            #region TH3 : nhận 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.NXXUAT,
                                    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            = currentEmployee.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.NXXUAT,
                                    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            = currentEmployee.EmployeeId,
                                    RemainingAmountAccrued = model.RemainingAmountAccrued
                                };
                                _context.Entry(AMmodel).State = System.Data.Entity.EntityState.Added;
                                _context.SaveChanges();
                                #endregion
                            }
                            #endregion

                            #endregion
                        }

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

                        #region Lưu InventoryMaster
                        InventoryMasterModel InvenMaster = new InventoryMasterModel();
                        InvenMaster.WarehouseModelId      = model.WarehouseId;
                        InvenMaster.InventoryCode         = model.ReturnMasterCode;
                        InvenMaster.InventoryTypeId       = EnumInventoryType.XC;                  //Xuất - Trả hàng cho nhà cung cấp
                        InvenMaster.CreatedDate           = model.CreatedDate;
                        InvenMaster.CreatedAccount        = model.CreatedAccount;
                        InvenMaster.CreatedEmployeeId     = model.CreatedEmployeeId;
                        InvenMaster.Actived               = true;
                        InvenMaster.BusinessId            = model.ReturnMasterId;              // Id nghiệp vụ
                        InvenMaster.BusinessName          = "ReturnMasterModel";               // Tên bảng nghiệp vụ
                        InvenMaster.ActionUrl             = "/ReturnMaster/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 duyệt list lưu ReturnDetail và InvenrotyDetail
                        decimal TotalQty = 0;
                        foreach (var item in detail)
                        {
                            if (item.ReturnQty > 0) // Chỉ tính Số lượng trả > 0
                            {
                                TotalQty += item.ReturnQty.Value;
                                #region Lưu ReturnDetailModel
                                //// Lấy ReturnedQty mới nhất
                                //var tempLanDaTraCuoi = (from detal in _context.ReturnDetailModel
                                //            join master in _context.ReturnMasterModel on detal.ReturnMasterId equals master.ReturnMasterId
                                //            orderby detal.ReturnDetailId descending
                                //            where master.Actived == true && detal.ProductId == item.ProductId
                                //            select new
                                //            {
                                //                LanDaTraCuoi = detal.ReturnedQty.Value
                                //            }).FirstOrDefault();
                                decimal CogsInOd = _context.ImportDetailModel.Where(p => p.ImportMasterId == model.ImportMasterId && p.ProductId == item.ProductId).Select(p => p.UnitCOGS.Value).FirstOrDefault();
                                item.UnitCOGS = CogsInOd;
                                ReturnDetailModel detailmodel = new ReturnDetailModel()
                                {
                                    ReturnMasterId = model.ReturnMasterId,
                                    ProductId      = item.ProductId,
                                    ImportQty      = item.ImportQty,
                                    //ReturnedQty = (tempLanDaTraCuoi == null ? 0 + (item.ReturnQty.HasValue ? item.ReturnQty : 0) : tempLanDaTraCuoi.LanDaTraCuoi + (item.ReturnQty.HasValue ? item.ReturnQty : 0)),
                                    ReturnedQty        = item.ReturnedQty,
                                    InventoryQty       = item.InventoryQty,
                                    ReturnQty          = item.ReturnQty.HasValue ? item.ReturnQty : 0,
                                    Price              = item.Price,
                                    UnitShippingWeight = item.UnitShippingWeight,
                                    UnitPrice          = item.UnitPrice,
                                    Note        = item.Note,
                                    ShippingFee = item.ShippingFee,
                                    UnitCOGS    = item.UnitCOGS
                                };
                                //_context.Entry(detailmodel).State = System.Data.Entity.EntityState.Added;
                                model.ReturnDetailModel.Add(detailmodel);
                                _context.SaveChanges();
                                #endregion

                                #region Lưu InventoryDetail
                                //var temp = _context.InventoryDetailModel.OrderByDescending(p => p.InventoryDetailId).Where(p => p.ProductId == item.ProductId).Select(p => p.EndInventoryQty).FirstOrDefault();
                                //var temp = (from detal in _context.InventoryDetailModel
                                //            join master in _context.InventoryMasterModel on detal.InventoryMasterId equals master.InventoryMasterId
                                //            orderby detal.InventoryDetailId descending
                                //            where master.Actived == true && detal.ProductId == item.ProductId
                                //            select new
                                //            {
                                //                TonCuoi = detal.EndInventoryQty.Value
                                //            }).FirstOrDefault();

                                //decimal tondau;
                                //if (temp != null)
                                //{
                                //    tondau = Convert.ToInt32(temp.TonCuoi);
                                //}
                                //else
                                //{
                                //    tondau = 0;
                                //}
                                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 = 0,
                                    ExportQty = item.ReturnQty.HasValue ? item.ReturnQty : 0,// Xuất
                                    //UnitCOGS = GiaVon * (item.ReturnQty.HasValue ? item.ReturnQty : 0),
                                    UnitPrice       = item.UnitPrice.HasValue ? item.UnitPrice : 0,
                                    EndInventoryQty = tondau - (item.ReturnQty.HasValue ? item.ReturnQty : 0)
                                };
                                _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.Where(p => p.ReturnQty > 0).Sum(p => p.UnitCOGS * p.ReturnQty);
                        model.TotalQty              = TotalQty;
                        _context.Entry(model).State = System.Data.Entity.EntityState.Modified;
                        _context.SaveChanges();

                        ts.Complete();                        // hoàn tất và thực sự lưu vào db
                        return(Json("success", JsonRequestBehavior.AllowGet));
                    }
                }
                catch
                {
                    return(Json(Resources.LanguageResource.AddErrorMessage, JsonRequestBehavior.AllowGet));
                }
            }
            else
            {
                return(Json(Resources.LanguageResource.AddErrorMessage, JsonRequestBehavior.AllowGet));
            }
        }
Exemple #3
0
        public ActionResult Autoimex(int id)
        {
            WarehouseInventoryMasterModel model = _context.WarehouseInventoryMasterModel
                                                  .Where(p => p.WarehouseInventoryMasterId == id && p.Actived == true && p.CreatedIEOther == false)
                                                  .FirstOrDefault();
            // Bước 1 : insert IEOtherMaster
            // Bước 2 : insert IEOtherDetail : dựa vào AmountDifference để nhập hay xuất kho

            var Resuilt = "";

            if (model == null)
            {
                Resuilt = "Không tìm thấy đơn hàng yêu cầu !";
            }
            else
            {
                try
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        #region insert IEOtherMaster
                        IEOtherRepository  IEOtherRepository  = new IEOtherRepository(_context);
                        IEOtherMasterModel IEOtherMasterModel = new IEOtherMasterModel()
                        {
                            IEOtherMasterCode = IEOtherRepository.GetIEOtherCodePKK(),
                            WarehouseId       = model.WarehouseId.Value,
                            InventoryTypeId   = EnumInventoryType.KK,
                            Note              = "Bù trừ kiểm kho khớp với hệ thống ",
                            CreatedDate       = DateTime.Now,
                            CreatedAccount    = currentAccount.UserName,
                            CreatedEmployeeId = currentEmployee.EmployeeId,
                            Actived           = true
                        };
                        _context.Entry(IEOtherMasterModel).State = System.Data.Entity.EntityState.Added;
                        _context.SaveChanges();
                        #endregion

                        #region InventoryMasterModel
                        int idStore = _context.WarehouseModel.Where(p => p.WarehouseId == model.WarehouseId).Select(p => p.StoreId.Value).FirstOrDefault();
                        InventoryMasterModel InvenMaster = new InventoryMasterModel()
                        {
                            StoreId           = idStore,
                            WarehouseModelId  = model.WarehouseId,
                            InventoryTypeId   = EnumInventoryType.KK,
                            InventoryCode     = IEOtherMasterModel.IEOtherMasterCode,
                            CreatedDate       = IEOtherMasterModel.CreatedDate,
                            CreatedAccount    = IEOtherMasterModel.CreatedAccount,
                            CreatedEmployeeId = IEOtherMasterModel.CreatedEmployeeId,
                            Actived           = true,
                            BusinessId        = IEOtherMasterModel.IEOtherMasterId, // Id nghiệp vụ
                            BusinessName      = "IEOtherMasterModel",               // Tên bảng nghiệp vụ
                            ActionUrl         = "/IEOtherMaster/Details/"           // Đường dẫn ( cộng ID cho truy xuất)
                        };
                        _context.Entry(InvenMaster).State = System.Data.Entity.EntityState.Added;
                        _context.SaveChanges(); // insert tạm để lấy InvenMasterID
                        #endregion

                        #region Duyệt WarehouseInventoryDetailModel insert vào InventoryDetailModel
                        var LstWarehouseInventoryDetailModel = _context.WarehouseInventoryDetailModel
                                                               .Where(p => p.WarehouseInventoryMasterId == model.WarehouseInventoryMasterId)
                                                               .OrderByDescending(p => p.WarehouseInventoryDetailId)
                                                               .ToList();
                        foreach (var item in LstWarehouseInventoryDetailModel)
                        {
                            if (item.AmountDifference != 0)
                            {
                                #region Kiểm tra tồn # database
                                var temp = (from detal in _context.InventoryDetailModel
                                            join master in _context.InventoryMasterModel on detal.InventoryMasterId equals master.InventoryMasterId
                                            orderby detal.InventoryDetailId descending
                                            where master.Actived == true && detal.ProductId == item.ProductId
                                            select new
                                {
                                    TonCuoi = detal.EndInventoryQty.Value
                                }).FirstOrDefault();
                                decimal TonTrongDatabase = temp != null ? temp.TonCuoi : 0;
                                if (item.Inventory != TonTrongDatabase)
                                {
                                    return(Json("Số lượng tồn không chính xác, vui lòng nhấn nút 'Xem' để cập nhật lại", JsonRequestBehavior.AllowGet));
                                }
                                #endregion

                                #region IEOtherDetailModel
                                IEOtherDetailModel detailmodel = new IEOtherDetailModel()
                                {
                                    IEOtherMasterId    = IEOtherMasterModel.IEOtherMasterId,
                                    ProductId          = item.ProductId,
                                    ImportQty          = item.AmountDifference > 0 ? item.AmountDifference : 0, // Nhập kho sp thừa , xuất kho sp thiếu
                                    ExportQty          = item.AmountDifference < 0 ? Math.Abs(item.AmountDifference.Value) : 0,
                                    Price              = 0,
                                    UnitShippingWeight = 0,
                                    UnitPrice          = 0
                                };
                                _context.Entry(detailmodel).State = System.Data.Entity.EntityState.Added;
                                _context.SaveChanges();
                                #endregion

                                #region Insert InventoryDetail

                                decimal tondau;
                                tondau = TonTrongDatabase;
                                if (item.AmountDifference > 0) // Nhập
                                {
                                    InventoryDetailModel InvenDetail = new InventoryDetailModel()
                                    {
                                        InventoryMasterId = InvenMaster.InventoryMasterId,
                                        ProductId         = item.ProductId,
                                        BeginInventoryQty = tondau,
                                        COGS            = 0, // nhập
                                        Price           = 0, // => Xuất
                                        ImportQty       = item.AmountDifference,
                                        ExportQty       = 0,
                                        UnitCOGS        = 0, // nhập
                                        UnitPrice       = 0, // => Xuất
                                        EndInventoryQty = tondau + item.AmountDifference
                                    };
                                    _context.Entry(InvenDetail).State = System.Data.Entity.EntityState.Added;
                                    _context.SaveChanges();
                                }
                                else
                                {
                                    InventoryDetailModel InvenDetail = new InventoryDetailModel()
                                    {
                                        InventoryMasterId = InvenMaster.InventoryMasterId,
                                        ProductId         = item.ProductId,
                                        BeginInventoryQty = tondau,
                                        COGS            = 0, // nhập
                                        Price           = 0, // => Xuất
                                        ImportQty       = 0,
                                        ExportQty       = Math.Abs(item.AmountDifference.Value),
                                        UnitCOGS        = 0, // nhập
                                        UnitPrice       = 0, // => Xuất
                                        EndInventoryQty = tondau - Math.Abs(item.AmountDifference.Value)
                                    };
                                    _context.Entry(InvenDetail).State = System.Data.Entity.EntityState.Added;
                                    _context.SaveChanges();
                                }
                                #endregion
                            }
                        }
                        #endregion

                        model.CreatedIEOther        = true;
                        _context.Entry(model).State = System.Data.Entity.EntityState.Modified;
                        _context.SaveChanges();
                        ts.Complete();
                        Resuilt = "success";
                    }
                }
                catch
                {
                    Resuilt = "Xảy ra lỗi trong quá trình tạo xuất nhập kho!";
                }
            }
            return(Json(Resuilt, JsonRequestBehavior.AllowGet));
        }
        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");
            }
        }
Exemple #5
0
        public ActionResult Import(HttpPostedFileBase excelfile, int?StoreId)
        {
            try
            {
                if (excelfile == null || excelfile.ContentLength == 0)
                {
                    ViewBag.Import = "Bạn vui lòng chọn 1 file excel";
                    CreateViewBag();
                    return(View("Index"));
                }
                else
                {
                    using (var package = new ExcelPackage(excelfile.InputStream))
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                        var            rowCnt    = worksheet.Dimension.End.Row - 4;
                        int            col       = 1;
                        for (int row = 5; worksheet.Cells[row, col].Value != null; row++)
                        {
                            #region kiểm tra giá trị null
                            if (string.IsNullOrEmpty(worksheet.Cells[row, 3].Text) ||
                                string.IsNullOrEmpty(worksheet.Cells[row, 4].Text) ||
                                string.IsNullOrEmpty(worksheet.Cells[row, 5].Text) ||
                                string.IsNullOrEmpty(worksheet.Cells[row, 14].Text) ||
                                string.IsNullOrEmpty(worksheet.Cells[row, 15].Text) ||
                                string.IsNullOrEmpty(worksheet.Cells[row, 16].Text) ||
                                string.IsNullOrEmpty(worksheet.Cells[row, 17].Text) ||
                                string.IsNullOrEmpty(worksheet.Cells[row, 18].Text) ||
                                string.IsNullOrEmpty(worksheet.Cells[row, 19].Text) ||
                                string.IsNullOrEmpty(worksheet.Cells[row, 20].Text) ||
                                string.IsNullOrEmpty(worksheet.Cells[row, 21].Text) ||
                                string.IsNullOrEmpty(worksheet.Cells[row, 22].Text) ||
                                string.IsNullOrEmpty(worksheet.Cells[row, 23].Text))
                            {
                                ViewBag.Import = "vui lòng nhập các thông tin bắt buộc tại dòng " + row + "!";
                                CreateViewBag();
                                return(View("Index"));
                            }
                            #endregion
                            #region gán giatri
                            string  ProductCode       = worksheet.Cells[row, 3].Value.ToString();
                            string  ProductName       = worksheet.Cells[row, 4].Value.ToString();
                            int     ProductTypeId     = int.Parse(worksheet.Cells[row, 5].Value.ToString());
                            decimal ImportPrice       = Decimal.Parse(worksheet.Cells[row, 14].Value.ToString());
                            int     CurrencyId        = int.Parse(worksheet.Cells[row, 15].Value.ToString());;
                            decimal ExchangeRate      = Decimal.Parse(worksheet.Cells[row, 16].Value.ToString());
                            decimal ShippingFee       = Decimal.Parse(worksheet.Cells[row, 17].Value.ToString());
                            decimal COGS              = Decimal.Parse(worksheet.Cells[row, 18].Value.ToString());
                            decimal pprice1           = Decimal.Parse(worksheet.Cells[row, 19].Value.ToString());
                            decimal pprice2           = Decimal.Parse(worksheet.Cells[row, 20].Value.ToString());
                            decimal pprice3           = Decimal.Parse(worksheet.Cells[row, 21].Value.ToString());
                            decimal BeginInventoryQty = Decimal.Parse(worksheet.Cells[row, 22].Value.ToString());
                            bool    Actived           = bool.Parse(worksheet.Cells[row, 23].Value.ToString());
                            #endregion
                            #region cập nhật
                            if (worksheet.Cells[row, 2].Text != "")
                            {
                                ProductModel p         = new ProductModel();
                                int          ProductId = Int32.Parse(worksheet.Cells[row, 2].Value.ToString());
                                p = _context.ProductModel.Where(pp => pp.ProductId == ProductId).FirstOrDefault();
                                if (p != null)
                                {
                                    p.ProductCode   = ProductCode;
                                    p.ProductName   = ProductName;
                                    p.ProductTypeId = ProductTypeId;
                                    if (worksheet.Cells[row, 6].Text != "")
                                    {
                                        p.CategoryId = int.Parse(worksheet.Cells[row, 6].Value.ToString());
                                    }
                                    ;
                                    p.SEOProductName = Library.ConvertToNoMarkString(p.ProductName);
                                    p.CreatedDate    = DateTime.Now;
                                    p.CreatedAccount = currentAccount.UserName;
                                    if (worksheet.Cells[row, 7].Text != "")
                                    {
                                        p.OriginOfProductId = int.Parse(worksheet.Cells[row, 7].Value.ToString());
                                    }
                                    ;
                                    if (worksheet.Cells[row, 8].Text != "")
                                    {
                                        p.PolicyInStockId = int.Parse(worksheet.Cells[row, 8].Value.ToString());
                                    }
                                    ;
                                    if (worksheet.Cells[row, 9].Text != "")
                                    {
                                        p.PolicyOutOfStockId = int.Parse(worksheet.Cells[row, 9].Value.ToString());
                                    }
                                    ;
                                    if (worksheet.Cells[row, 10].Text != "")
                                    {
                                        p.LocationOfProductId = int.Parse(worksheet.Cells[row, 10].Value.ToString());
                                    }
                                    ;
                                    if (worksheet.Cells[row, 11].Text != "")
                                    {
                                        p.ProductStatusId = int.Parse(worksheet.Cells[row, 11].Value.ToString());
                                    }
                                    ;
                                    if (worksheet.Cells[row, 12].Text != "")
                                    {
                                        p.ShippingWeight = int.Parse(worksheet.Cells[row, 12].Value.ToString());
                                    }
                                    ;
                                    if (worksheet.Cells[row, 13].Text != "")
                                    {
                                        p.UnitId = int.Parse(worksheet.Cells[row, 13].Value.ToString());
                                    }
                                    ;
                                    p.ImportPrice  = ImportPrice;
                                    p.CurrencyId   = CurrencyId;
                                    p.ExchangeRate = ExchangeRate;
                                    p.ShippingFee  = ShippingFee;
                                    p.COGS         = COGS;
                                    //p.StoreId = Store;
                                    ProductRepository ProductRepository = new ProductRepository(_context);
                                    p.ProductStoreCode = ProductRepository.GetProdcutStoreCode(StoreId.Value, p.ProductTypeId.Value, p.CategoryId.Value);
                                    //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;
                                    //Kiểm tra Field Kích hoạt
                                    p.Actived           = Actived;
                                    p.BeginInventoryQty = BeginInventoryQty;

                                    _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(p).State      = System.Data.Entity.EntityState.Modified;
                                    _context.SaveChanges();
                                }
                                else
                                {
                                    ViewBag.Import = "Không tìm thấy sản phẩm dòng " + row + " !";
                                    CreateViewBag();
                                    return(View("Index"));
                                }
                            }
                            #endregion
                            #region Thêm mới
                            else //Thêm mới
                            {
                                ProductModel p = new ProductModel();
                                p.ProductCode   = ProductCode;
                                p.ProductName   = ProductName;
                                p.ProductTypeId = ProductTypeId;
                                if (worksheet.Cells[row, 6].Text != "")
                                {
                                    p.CategoryId = int.Parse(worksheet.Cells[row, 5].Value.ToString());
                                }
                                ;
                                p.SEOProductName = Library.ConvertToNoMarkString(p.ProductName);
                                p.CreatedDate    = DateTime.Now;
                                p.CreatedAccount = currentAccount.UserName;
                                if (worksheet.Cells[row, 7].Text != "")
                                {
                                    p.OriginOfProductId = int.Parse(worksheet.Cells[row, 7].Value.ToString());
                                }
                                ;
                                if (worksheet.Cells[row, 8].Text != "")
                                {
                                    p.PolicyInStockId = int.Parse(worksheet.Cells[row, 8].Value.ToString());
                                }
                                ;
                                if (worksheet.Cells[row, 9].Text != "")
                                {
                                    p.PolicyOutOfStockId = int.Parse(worksheet.Cells[row, 9].Value.ToString());
                                }
                                ;
                                if (worksheet.Cells[row, 10].Text != "")
                                {
                                    p.LocationOfProductId = int.Parse(worksheet.Cells[row, 10].Value.ToString());
                                }
                                ;
                                if (worksheet.Cells[row, 11].Text != "")
                                {
                                    p.ProductStatusId = int.Parse(worksheet.Cells[row, 11].Value.ToString());
                                }
                                ;
                                if (worksheet.Cells[row, 12].Text != "")
                                {
                                    p.ShippingWeight = int.Parse(worksheet.Cells[row, 12].Value.ToString());
                                }
                                ;
                                if (worksheet.Cells[row, 13].Text != "")
                                {
                                    p.UnitId = int.Parse(worksheet.Cells[row, 13].Value.ToString());
                                }
                                ;
                                p.ImportPrice  = ImportPrice;
                                p.CurrencyId   = CurrencyId;
                                p.ExchangeRate = ExchangeRate;
                                p.ShippingFee  = ShippingFee;
                                p.COGS         = COGS;
                                //p.StoreId = Store;
                                ProductRepository ProductRepository = new ProductRepository(_context);
                                p.ProductStoreCode  = ProductRepository.GetProdcutStoreCode(StoreId.Value, p.ProductTypeId.Value, p.CategoryId.Value);
                                p.Actived           = Actived;
                                p.CreatedAccount    = currentAccount.UserName;
                                p.BeginInventoryQty = BeginInventoryQty;
                                AccountModel      Account           = _context.AccountModel.Where(pp => pp.UserName == p.CreatedAccount).FirstOrDefault();
                                IEOtherRepository IEOtherRepository = new IEOtherRepository(_context);
                                _context.Entry(p).State = System.Data.Entity.EntityState.Added;
                                _context.SaveChanges();

                                //Product Price 1
                                ProductPriceModel price1 = new ProductPriceModel()
                                {
                                    Price           = pprice1,
                                    CustomerLevelId = 1,
                                    ProductId       = p.ProductId
                                };
                                _context.Entry(price1).State = System.Data.Entity.EntityState.Added;
                                _context.SaveChanges();

                                // Product Price 2
                                ProductPriceModel price2 = new ProductPriceModel()
                                {
                                    Price           = pprice2,
                                    CustomerLevelId = 2,
                                    ProductId       = p.ProductId
                                };
                                _context.Entry(price2).State = System.Data.Entity.EntityState.Added;
                                _context.SaveChanges();

                                // Product Price 3
                                ProductPriceModel price3 = new ProductPriceModel()
                                {
                                    Price           = pprice3,
                                    CustomerLevelId = 3,
                                    ProductId       = p.ProductId
                                };

                                _context.Entry(price3).State = System.Data.Entity.EntityState.Added;
                                _context.SaveChanges();

                                //Kiểm tra Field Kích hoạt
                                if (p.BeginInventoryQty != 0)
                                {
                                    // Lưu vào IEOtherMasterModel
                                    IEOtherMasterModel IEMaster = new IEOtherMasterModel()
                                    {
                                        IEOtherMasterCode = IEOtherRepository.GetIEOtherCode(),
                                        WarehouseId       = p.BeginWarehouseId.Value,
                                        InventoryTypeId   = EnumInventoryType.ĐK,
                                        Note              = "Tồn đầu",
                                        CreatedDate       = DateTime.Now,
                                        CreatedAccount    = currentAccount.UserName,
                                        Actived           = true,
                                        CreatedEmployeeId = Account.EmployeeId,
                                        TotalPrice        = p.BeginInventoryQty * p.COGS
                                    };
                                    _context.Entry(IEMaster).State = System.Data.Entity.EntityState.Added;
                                    _context.SaveChanges();

                                    // Lưu vào IEOtherDetailModel
                                    IEOtherDetailModel detailmodel = new IEOtherDetailModel()
                                    {
                                        IEOtherMasterId    = IEMaster.IEOtherMasterId,
                                        ProductId          = p.ProductId,
                                        ImportQty          = p.BeginInventoryQty,
                                        ExportQty          = 0,
                                        Price              = p.COGS,
                                        UnitShippingWeight = (decimal)(p.ShippingWeight.HasValue ? p.ShippingWeight.Value : 1) * p.BeginInventoryQty,
                                        UnitPrice          = p.BeginInventoryQty * p.COGS,
                                        Note = IEMaster.Note
                                    };
                                    _context.Entry(detailmodel).State = System.Data.Entity.EntityState.Added;
                                    _context.SaveChanges();

                                    // Lưu vào InventoyMaster
                                    InventoryMasterModel InvenMaster = new InventoryMasterModel()
                                    {
                                        StoreId           = p.StoreId,
                                        InventoryTypeId   = EnumInventoryType.ĐK,
                                        WarehouseModelId  = p.BeginWarehouseId,
                                        InventoryCode     = IEMaster.IEOtherMasterCode,
                                        CreatedDate       = IEMaster.CreatedDate,
                                        CreatedAccount    = IEMaster.CreatedAccount,
                                        CreatedEmployeeId = IEMaster.CreatedEmployeeId,
                                        Actived           = true,
                                        BusinessId        = IEMaster.IEOtherMasterId, // Id nghiệp vụ
                                        BusinessName      = "IEOtherMasterModel",     // Tên bảng nghiệp vụ
                                        ActionUrl         = "/IEOtherMaster/Details/" // Đường dẫn ( cộng ID cho truy xuất)
                                    };
                                    _context.Entry(InvenMaster).State = System.Data.Entity.EntityState.Added;
                                    _context.SaveChanges();

                                    // Lưu vào InventoryDetailModel
                                    InventoryDetailModel InvenDetail = new InventoryDetailModel()
                                    {
                                        InventoryMasterId = InvenMaster.InventoryMasterId,
                                        ProductId         = p.ProductId,
                                        BeginInventoryQty = p.BeginInventoryQty,
                                        COGS            = p.COGS, // nhập
                                        Price           = 0,      // => Xuất
                                        ImportQty       = p.BeginInventoryQty,
                                        ExportQty       = 0,
                                        UnitCOGS        = p.COGS * p.BeginInventoryQty, // nhập
                                        UnitPrice       = 0,                            // => Xuất
                                        EndInventoryQty = p.BeginInventoryQty
                                    };
                                    _context.Entry(InvenDetail).State = System.Data.Entity.EntityState.Added;
                                    _context.SaveChanges();
                                }
                            }
                            #endregion
                        }
                    }

                    //Thread thread = new Thread(() => ImportThread(excelfile, StoreId));
                    //thread.Start();
                    //ViewBag.Import = "Đang Import ...";
                    ViewBag.Import = "Import thành công !";
                    CreateViewBag();
                    return(View("Index"));
                }
            }
            catch //(Exception ex)
            {
                ViewBag.Import = "Lỗi! Vui lòng liên hệ kĩ thuật viên để được giúp đỡ !";
                CreateViewBag();
                return(View("Index"));
            }
        }
        public ActionResult Save(OrderReturnModel model, List <OrderReturnDetailViewModel> detail, decimal?GuestAmountPaid, int CreateReceipt)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        var currentTime = DateTime.Now;
                        #region Thêm vào OrderReturnModel
                        model.CreatedDate    = currentTime;
                        model.CreatedAccount = currentAccount.UserName;
                        AccountModel Account = _context.AccountModel.Where(p => p.UserName == model.CreatedAccount).FirstOrDefault();
                        model.CreatedEmployeeId = Account.EmployeeId;
                        //// Tìm giá trị STT order code
                        model.OrderReturnMasterCode = GetReturnCode();
                        if (model.PaymentMethodId == EnumPaymentMethod.TienMat)
                        {
                            model.Paid          = GuestAmountPaid;
                            model.MoneyTransfer = 0;
                        }
                        else if (model.PaymentMethodId == EnumPaymentMethod.ChuyenKhoan)
                        {
                            model.Paid          = 0;
                            model.MoneyTransfer = GuestAmountPaid;
                        }
                        else if (model.PaymentMethodId == EnumPaymentMethod.CongNo)
                        {
                            model.Paid          = 0;
                            model.MoneyTransfer = 0;
                        }
                        else
                        {
                            return(Content("Phương thức thanh toán không hợp lệ !"));
                        }

                        #endregion

                        var orderModel = _context.OrderMasterModel.Where(p => p.OrderId == model.OrderId).FirstOrDefault();

                        #region Tính số dư còn lại
                        decimal?CustomerOldDebt = _context.AM_DebtModel
                                                  .Where(p => p.CustomerId == orderModel.CustomerId)
                                                  .OrderByDescending(p => p.TimeOfDebt)
                                                  .Select(p => p.RemainingAmountAccrued)
                                                  .FirstOrDefault();
                        CustomerOldDebt              = (CustomerOldDebt == null) ? 0 : CustomerOldDebt.Value;
                        model.RemainingAmount        = (model.RemainingAmount == null) ? 0 : model.RemainingAmount.Value;
                        model.RemainingAmountAccrued = CustomerOldDebt.Value - model.RemainingAmount.Value;

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

                        if (CreateReceipt == 1)
                        {
                            #region Thêm vào giao dịch kế toán
                            AM_TransactionModel AMmodel;
                            int MaKH = (_context.OrderMasterModel.Where(p => p.OrderId == model.OrderId).Select(p => p.CustomerId).FirstOrDefault());
                            #region TH1 : Trả đủ

                            if (model.TotalPrice == GuestAmountPaid)
                            {
                                AMmodel = new AM_TransactionModel()
                                {
                                    StoreId     = model.StoreId,
                                    AMAccountId = model.PaymentMethodId == EnumPaymentMethod.TienMat ?
                                                  (_context.AM_AccountModel.Where(p => p.Code == EnumAccountCode.TM && p.AMAccountTypeCode == EnumAM_AccountType.TIENMAT && p.StoreId == model.StoreId).Select(p => p.AMAccountId)).FirstOrDefault()
                                                       : (_context.AM_AccountModel.Where(p => p.Code == EnumAccountCode.NH && p.AMAccountTypeCode == EnumAM_AccountType.NGANHANG && p.StoreId == model.StoreId).Select(p => p.AMAccountId)).FirstOrDefault(),
                                    TransactionTypeCode = EnumTransactionType.BHTRA,
                                    ContactItemTypeCode = EnumContactType.KH,
                                    CustomerId          = MaKH,
                                    SupplierId          = null,
                                    EmployeeId          = null,
                                    OtherId             = null,
                                    Amount                 = GuestAmountPaid,
                                    OrderId                = model.OrderId,
                                    ImportMasterId         = null,
                                    IEOtherMasterId        = null,
                                    Note                   = model.Note,
                                    CreateDate             = currentTime,
                                    CreateEmpId            = currentEmployee.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.PTKH && p.AMAccountTypeCode == EnumAM_AccountType.CONGNO && p.StoreId == model.StoreId).Select(p => p.AMAccountId)).FirstOrDefault(),
                                    TransactionTypeCode = EnumTransactionType.BHTRA,
                                    ContactItemTypeCode = EnumContactType.KH,
                                    CustomerId          = MaKH,
                                    SupplierId          = null,
                                    EmployeeId          = null,
                                    OtherId             = null,
                                    Amount                 = model.TotalPrice,
                                    OrderId                = model.OrderId,
                                    ImportMasterId         = null,
                                    IEOtherMasterId        = null,
                                    Note                   = model.Note,
                                    CreateDate             = currentTime,
                                    CreateEmpId            = currentEmployee.EmployeeId,
                                    RemainingAmountAccrued = model.RemainingAmountAccrued
                                };
                                _context.Entry(AMmodel).State = System.Data.Entity.EntityState.Added;
                                // model.PaymentMethodId == EnumPamentMethod.CongNo
                                model.PaymentMethodId       = EnumPaymentMethod.CongNo;
                                _context.Entry(model).State = System.Data.Entity.EntityState.Modified;

                                _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 = model.PaymentMethodId == EnumPaymentMethod.TienMat ?
                                                  (_context.AM_AccountModel.Where(p => p.Code == EnumAccountCode.TM && p.AMAccountTypeCode == EnumAM_AccountType.TIENMAT && p.StoreId == model.StoreId).Select(p => p.AMAccountId)).FirstOrDefault()
                                                       : (_context.AM_AccountModel.Where(p => p.Code == EnumAccountCode.NH && p.AMAccountTypeCode == EnumAM_AccountType.NGANHANG && p.StoreId == model.StoreId).Select(p => p.AMAccountId)).FirstOrDefault(),
                                    TransactionTypeCode = EnumTransactionType.BHTRA,
                                    ContactItemTypeCode = EnumContactType.KH,
                                    CustomerId          = MaKH,
                                    SupplierId          = null,
                                    EmployeeId          = currentEmployee.EmployeeId,
                                    OtherId             = null,
                                    Amount                 = GuestAmountPaid,
                                    OrderId                = model.OrderId,
                                    ImportMasterId         = null,
                                    IEOtherMasterId        = null,
                                    Note                   = model.Note,
                                    CreateDate             = currentTime,
                                    CreateEmpId            = currentEmployee.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.PTKH && p.AMAccountTypeCode == EnumAM_AccountType.CONGNO && p.StoreId == model.StoreId).Select(p => p.AMAccountId)).FirstOrDefault(),
                                    TransactionTypeCode = EnumTransactionType.BHTRA,
                                    ContactItemTypeCode = EnumContactType.KH,
                                    CustomerId          = MaKH,
                                    SupplierId          = null,
                                    EmployeeId          = null,
                                    OtherId             = null,
                                    Amount                 = model.TotalPrice - GuestAmountPaid,
                                    OrderId                = model.OrderId,
                                    ImportMasterId         = null,
                                    IEOtherMasterId        = null,
                                    Note                   = model.Note,
                                    CreateDate             = currentTime,
                                    CreateEmpId            = currentEmployee.EmployeeId,
                                    RemainingAmountAccrued = model.RemainingAmountAccrued
                                };
                                _context.Entry(AMmodel).State = System.Data.Entity.EntityState.Added;
                                _context.SaveChanges();
                                #endregion
                            }
                            #endregion



                            #endregion
                        }

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

                        #region Thêm vào InventoryMaster
                        // Insert InventoryMaster
                        InventoryMasterModel InvenMaster = new InventoryMasterModel();
                        InvenMaster.WarehouseModelId      = model.WarehouseId;
                        InvenMaster.InventoryTypeId       = EnumInventoryType.NB;// Nhập - Khách trả hàng
                        InvenMaster.InventoryCode         = model.OrderReturnMasterCode;
                        InvenMaster.CreatedDate           = model.CreatedDate;
                        InvenMaster.CreatedAccount        = model.CreatedAccount;
                        InvenMaster.CreatedEmployeeId     = model.CreatedEmployeeId;
                        InvenMaster.StoreId               = model.StoreId;
                        InvenMaster.Actived               = true;
                        InvenMaster.BusinessId            = model.OrderId;                 // Id nghiệp vụ
                        InvenMaster.BusinessName          = "OrderReturnMaster";           // Tên bảng nghiệp vụ
                        InvenMaster.ActionUrl             = "/OrderReturnMaster/Details/"; // Đường dẫn ( cộng ID cho truy xuất)
                        _context.Entry(InvenMaster).State = System.Data.Entity.EntityState.Added;
                        _context.SaveChanges();                                            // insert tạm để lấy InvenMasterID
                        #endregion

                        #region duyệt list lưu OrderReturnDetailModel và InvenrotyDetail
                        decimal TotalQty = 0;
                        foreach (var item in detail)
                        {
                            if (item.ReturnQuantity > 0) // Chỉ tính Số lượng trả > 0
                            {
                                TotalQty += item.ReturnQuantity.Value;
                                #region Lưu OrderReturnDetailModel
                                decimal CogsInOd = _context.OrderDetailModel.Where(p => p.OrderId == model.OrderId && p.ProductId == item.ProductId).Select(p => p.COGS.Value).FirstOrDefault();
                                item.COGS = CogsInOd;
                                OrderReturnDetailModel detailmodel = new OrderReturnDetailModel()
                                {
                                    OrderReturnId    = model.OrderReturnMasterId,
                                    ProductId        = item.ProductId,
                                    SellQuantity     = item.SellQuantity,
                                    ReturnedQuantity = item.ReturnQuantity, // cần xem lại
                                    ReturnQuantity   = item.ReturnQuantity,
                                    Price            = item.Price,
                                    UnitPrice        = item.UnitPrice,
                                    Note             = item.Note,
                                    ReturnReason     = item.ReturnReason,
                                    COGS             = item.COGS
                                };
                                _context.Entry(detailmodel).State = System.Data.Entity.EntityState.Added;
                                _context.SaveChanges();
                                #endregion

                                #region Lưu InventoryDetail
                                // tính tồn đầu
                                EndInventoryRepository EndInventoryRepo = new EndInventoryRepository(_context);
                                decimal tondau = EndInventoryRepo.GetQty(item.ProductId.Value);

                                InventoryDetailModel InvenDetail = new InventoryDetailModel()
                                {
                                    InventoryMasterId = InvenMaster.InventoryMasterId,
                                    ProductId         = item.ProductId,
                                    BeginInventoryQty = tondau,
                                    COGS = CogsInOd,
                                    //Price = item.Price,
                                    ImportQty = item.ReturnQuantity,
                                    //ExportQty = 0,
                                    UnitCOGS = item.ReturnQuantity * CogsInOd,
                                    //UnitPrice = item.ReturnQuantity * item.Price, //[ImportQty] *[Price]
                                    EndInventoryQty = tondau + item.ReturnQuantity//Tồn cuối = [BeginInventoryQty] + [ImportQty] -  [ExportQty]
                                };
                                _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.Where(p => p.ReturnQuantity > 0).Sum(p => p.COGS * p.ReturnQuantity);
                        model.TotalQty              = TotalQty;
                        _context.Entry(model).State = System.Data.Entity.EntityState.Modified;
                        _context.SaveChanges();
                        ts.Complete();
                        return(Content("success"));
                    }
                }
                else
                {
                    return(Content("Vui lòng kiểm tra lại thông tin không hợp lệ"));
                }
            }
            catch
            {
                return(Content("Xảy ra lỗi trong quá trình thêm mới đơn hàng"));
            }
        }
        //#region GetUnitShippingWeight
        //public ActionResult GetUnitShippingWeight(int SelectedProductid)
        //{
        //    var UnitShippingWeight = _context
        //               .ProductModel
        //               .Where(p => p.ProductId == SelectedProductid)
        //               .Select(p => new
        //               {
        //                   Price = p.ImportPrice,
        //                   ShippingWeight = p.ShippingWeight,
        //                   ShippingFee = p.ShippingFee
        //               })
        //               .FirstOrDefault();
        //    return Json(UnitShippingWeight, JsonRequestBehavior.AllowGet);
        //}
        //#endregion
        #region Save

        public ActionResult Save(IEOtherMasterModel model, List <IEOtherDetailViewModel> detail)
        {
            try
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    model.CreatedDate    = DateTime.Now;
                    model.CreatedAccount = currentAccount.UserName;
                    AccountModel Account = _context.AccountModel.Where(p => p.UserName == model.CreatedAccount).FirstOrDefault();
                    model.CreatedEmployeeId = Account.EmployeeId;
                    int CustomerId = Convert.ToInt32(model.CustomerName);
                    #region XÁc nhận mã IEOtherMasterCode 1 lần nữa trước khi insert
                    // Insert InventoryMaster
                    InventoryMasterModel InvenMaster = new InventoryMasterModel();
                    //Xác định Nhập hay xuất
                    var IsImport = _context.InventoryTypeModel.Where(p => p.InventoryTypeId == model.InventoryTypeId).FirstOrDefault();
                    IEOtherRepository IEOtherRepository = new IEOtherRepository(_context);
                    model.IEOtherMasterCode = IEOtherRepository.GetIEOtherCode(IsImport.isImport.Value);
                    #endregion
                    model.CustomerName          = _context.CustomerModel.Where(p => p.CustomerId == CustomerId).Select(p => p.FullName).FirstOrDefault();
                    _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)
                    if (IsImport.isImport == true)
                    {
                        InvenMaster.InventoryTypeId = EnumInventoryType.NK;
                    }
                    else
                    {
                        InvenMaster.InventoryTypeId = EnumInventoryType.XK;
                    }
                    InvenMaster.WarehouseModelId      = model.WarehouseId;
                    InvenMaster.InventoryCode         = model.IEOtherMasterCode;
                    InvenMaster.CreatedDate           = model.CreatedDate;
                    InvenMaster.CreatedAccount        = model.CreatedAccount;
                    InvenMaster.CreatedEmployeeId     = model.CreatedEmployeeId;
                    InvenMaster.Actived               = true;
                    InvenMaster.BusinessId            = model.IEOtherMasterId;     // Id nghiệp vụ
                    InvenMaster.BusinessName          = "IEOtherMasterModel";      // Tên bảng nghiệp vụ
                    InvenMaster.ActionUrl             = "/IEOtherMaster/Details/"; // Đường dẫn ( cộng ID cho truy xuất)
                    _context.Entry(InvenMaster).State = System.Data.Entity.EntityState.Added;
                    _context.SaveChanges();                                        // insert tạm để lấy InvenMasterID
                    if (detail != null)
                    {
                        if (detail.GroupBy(p => p.ProductId).ToList().Count < detail.Count)
                        {
                            //khong duoc trung san pham
                            return(Content("Vui lòng không chọn thông tin sản phẩm trùng nhau"));
                        }
                        foreach (var item in detail)
                        {
                            IEOtherDetailModel detailmodel = new IEOtherDetailModel()
                            {
                                IEOtherMasterId = model.IEOtherMasterId,
                                ProductId       = item.ProductId,
                                //Qty = item.Qty,
                                ImportQty          = IsImport.isImport == true? item.Qty : 0,
                                ExportQty          = IsImport.isImport == false? item.Qty : 0,
                                Price              = item.Price,
                                UnitShippingWeight = item.UnitShippingWeight,
                                UnitPrice          = item.UnitPrice,
                                Note = item.Note
                            };
                            //_context.Entry(detailmodel).State = System.Data.Entity.EntityState.Added;
                            _context.Entry(detailmodel).State = System.Data.Entity.EntityState.Added;

                            // Insert InventoryDetail
                            //var temp = _context.InventoryDetailModel.OrderByDescending(p => p.InventoryDetailId).Where(p => p.ProductId == item.ProductId).Select(p => p.EndInventoryQty).FirstOrDefault();
                            var temp = (from detal in _context.InventoryDetailModel
                                        join master in _context.InventoryMasterModel on detal.InventoryMasterId equals master.InventoryMasterId
                                        orderby detal.InventoryDetailId descending
                                        where master.Actived == true && detal.ProductId == item.ProductId
                                        select new
                            {
                                TonCuoi = detal.EndInventoryQty.Value
                            }).FirstOrDefault();
                            decimal tondau;
                            if (temp != null)
                            {
                                tondau = Convert.ToInt32(temp.TonCuoi);
                            }
                            else
                            {
                                tondau = 0;
                            }
                            var     tempt2 = _context.ProductModel.Where(p => p.ProductId == item.ProductId).FirstOrDefault();
                            decimal GiaVon = tempt2.COGS.Value;
                            if (IsImport.isImport == true)
                            {
                                InventoryDetailModel InvenDetail = new InventoryDetailModel()
                                {
                                    InventoryMasterId = InvenMaster.InventoryMasterId,
                                    ProductId         = item.ProductId,
                                    BeginInventoryQty = tondau,
                                    COGS = GiaVon,// nhập
                                    //Price = 0, // => Xuất
                                    ImportQty = item.Qty,
                                    //ExportQty = 0,
                                    UnitCOGS = GiaVon * item.Qty, // nhập
                                    //UnitPrice = 0, // => Xuất
                                    EndInventoryQty = tondau + item.Qty
                                };
                                _context.Entry(InvenDetail).State = System.Data.Entity.EntityState.Added;
                            }
                            else
                            {
                                InventoryDetailModel InvenDetail = new InventoryDetailModel()
                                {
                                    InventoryMasterId = InvenMaster.InventoryMasterId,
                                    ProductId         = item.ProductId,
                                    BeginInventoryQty = tondau,
                                    //COGS = 0,// nhập
                                    Price = item.Price, // => Xuất
                                    //ImportQty = 0,
                                    ExportQty = item.Qty,
                                    //UnitCOGS = 0, // nhập
                                    UnitPrice       = item.Price * item.Qty, // => Xuất
                                    EndInventoryQty = tondau - item.Qty
                                };
                                _context.Entry(InvenDetail).State = System.Data.Entity.EntityState.Added;
                            }
                        }
                        _context.SaveChanges();
                        // đánh dấu Transaction hoàn tất
                        ts.Complete();
                        return(Content("success"));
                    }
                    else
                    {
                        //chua nhap tt san pham
                        return(Content("Vui lòng chọn thông tin sản phẩm"));
                    }
                }
            }
            catch
            {
                return(Content("Xảy ra lỗi trong quá trình thêm mới nhà cung cấp"));
            }
        }