public async void InventoryCommandRecieverAsync() { InventoryDetailModel model = null; try { Loader.StartLoading(); model = await _dashboardService.GetInventoryAsync(AppSettings.SessionId); var RealmDb = Realm.GetInstance(RealmDbManager.GetRealmDbConfig()); RealmDb.Write(() => { foreach (var item in model.InventoryResponseModel) { RealmDb.Add(item); } }); StockInventoryCollection = model.InventoryResponseModel.Where(x => x.Status != "Empty").ToList(); EmptyInventoryCollection = model.InventoryResponseModel.Where(x => x.Status == "Empty").ToList(); StockTotals = StockInventoryCollection.Sum(x => x.Quantity); EmptyTotals = EmptyInventoryCollection.Sum(x => x.Quantity); } catch (Exception ex) { Crashes.TrackError(ex); } finally { model = null; Loader.StopLoading(); } }
public static InventoryDetailModel GetInventoryDetailByItemid(int itemid, string token, out string error) { string url = APIHelper.Baseurl + "/inventorydetail/item/" + itemid; InventoryDetailModel invm = APIHelper.Execute <InventoryDetailModel>(token, url, out error); return(invm); }
public static InventoryDetailModel GetInventoryDetailByItemid(int itemid, out string error) { LUSSISEntities entities = new LUSSISEntities(); error = ""; inventory inventory = new inventory(); InventoryDetailModel invdm = new InventoryDetailModel(); try { staticpoms = PurchaseOrderRepo.GetPurchaseOrderByStatus(ConPurchaseOrder.Status.PENDING, out error); staticcount = 1; inventory = entities.inventories.Where(p => p.itemid == itemid).FirstOrDefault <inventory>(); invdm = CovertDBInventorytoAPIInventoryDet(inventory); } catch (NullReferenceException) { error = ConError.Status.NOTFOUND; } catch (Exception e) { error = e.Message; } return(invdm); }
//bind all Inventory View lists in to a list public List <InventoryDetailModel> FillInventoryViewGrid(InventoryModel Imodel) { using (MySqlConnection sqlConn = new MySqlConnection(conString)) { sqlConn.Open(); String query = @"SELECT InventoryDetailsId, product.ProductId, ProductName,ProductType, InventoryQuantity, Cost, SellingRate,BuyingRate FROM inventoryDetails JOIN product On inventoryDetails.ProductId = product.ProductId WHERE InventoryId= " + Imodel.InventoryId + ""; MySqlCommand cmd = new MySqlCommand(query, sqlConn); MySqlDataReader mySqlDataReader = cmd.ExecuteReader(); List <InventoryDetailModel> inventoryViewModels = new List <InventoryDetailModel>(); while (mySqlDataReader.Read()) { InventoryDetailModel inventoryModel = new InventoryDetailModel(); inventoryModel.InventorydeatilsId = (int)mySqlDataReader["InventoryDetailsId"]; inventoryModel.ProductId = (int)mySqlDataReader["ProductId"]; inventoryModel.ProductName = mySqlDataReader["ProductName"].ToString(); inventoryModel.ProductType = mySqlDataReader["ProductType"].ToString(); inventoryModel.Quantity = Convert.ToDecimal(mySqlDataReader["InventoryQuantity"].ToString()); inventoryModel.Cost = Convert.ToDecimal(mySqlDataReader["Cost"].ToString()); inventoryModel.SellingRate = Convert.ToDecimal(mySqlDataReader["SellingRate"].ToString()); inventoryModel.BuyingRate = Convert.ToDecimal(mySqlDataReader["BuyingRate"].ToString()); inventoryViewModels.Add(inventoryModel); } mySqlDataReader.Close(); sqlConn.Close(); return(inventoryViewModels); } }
//bind all inventoryDetails lists in to a list in add inventory public List <InventoryDetailModel> FillInventoryDetailsGrid(int StoreId) { using (MySqlConnection sqlConn = new MySqlConnection(conString)) { sqlConn.Open(); int GetstoreId = StoreId; String query = "SELECT product.ProductId,ProductName, InventoryQuantity ,Cost , SellingRate , BuyingRate FROM inventorydetails Inner JOIN product On inventorydetails.ProductId = product.ProductId where InventoryId= " + GetstoreId + " ;"; MySqlCommand cmd = new MySqlCommand(query, sqlConn); MySqlDataReader mySqlDataReader = cmd.ExecuteReader(); List <InventoryDetailModel> inventoryDetailModels = new List <InventoryDetailModel>(); while (mySqlDataReader.Read()) { InventoryDetailModel inventoryDetailModel = new InventoryDetailModel(); inventoryDetailModel.ProductId = (int)mySqlDataReader["ProductId"]; // inventoryDetailModel.InventorydeatilsId = (int) mySqlDataReader["InventoryDetailsId"]; inventoryDetailModel.ProductName = mySqlDataReader["ProductName"].ToString(); inventoryDetailModel.Quantity = (decimal)mySqlDataReader["InventoryQuantity"]; inventoryDetailModel.Cost = (decimal)mySqlDataReader["Cost"]; inventoryDetailModel.SellingRate = (decimal)mySqlDataReader["SellingRate"]; inventoryDetailModel.BuyingRate = (decimal)mySqlDataReader["BuyingRate"]; inventoryDetailModels.Add(inventoryDetailModel); } mySqlDataReader.Close(); sqlConn.Close(); return(inventoryDetailModels); } }
//datagrid view cell click private void inventoryDetailsDataGridView_CellClick(object sender, DataGridViewCellEventArgs e) { if (inventoryDetailsGrid.CurrentRow != null) { selectedInventoryDetailModel = (InventoryDetailModel)inventoryDetailsGrid.CurrentRow.DataBoundItem; } }
private void InventoryReturnDataGridView_CellClick(object sender, DataGridViewCellEventArgs e) { if (InventoryReturnDataGridView.CurrentRow != null) { selectedInventoryDetailModel = (InventoryDetailModel)InventoryReturnDataGridView.CurrentRow.DataBoundItem; productName.Text = selectedInventoryDetailModel.ProductName; productQuantity.Text = selectedInventoryDetailModel.Quantity.ToString(); } }
public IHttpActionResult GetInventoryDetailByItemid(int itemid) { string error = ""; InventoryDetailModel dm = InventoryRepo.GetInventoryDetailByItemid(itemid, out error); if (error != "" || dm == null) { if (error == ConError.Status.NOTFOUND) { return(Content(HttpStatusCode.NotFound, "Inventory Not Found")); } return(Content(HttpStatusCode.BadRequest, error)); } return(Ok(dm)); }
// delete a Inventory item public int DeleteInventoryDetails(InventoryDetailModel inventoryDetailModel) { String query = "DELETE FROM inventorydetails WHERE `InventoryDetailsId` = " + inventoryDetailModel.InventorydeatilsId + ";"; using (MySqlConnection sqlCon = new MySqlConnection(conString)) { using (MySqlCommand cmd = new MySqlCommand(query, sqlCon)) { sqlCon.Open(); int k = cmd.ExecuteNonQuery(); sqlCon.Close(); return(k); } } }
// [Audit] public JsonResult SaveInventory(InventoryDetailModel model) { IResponseData <int> response = new ResponseData <int>(); try { var service = IoC.Container.Resolve <IInventoryAdjustmentService>(); // khởi tạo biến data = -1, sau khi lưu thành công set data = Mã Phiếu Kiểm Kê int data = -1; data = service.SaveInventory(MedSessionManager.CurrentDrugStoreCode, MedSessionManager.CurrentUserId, model); response.SetData(data); } catch (ValidationException ex) { response.SetErrors(ex.Errors); response.SetStatus(HttpStatusCode.PreconditionFailed); } return(Json(response)); }
public async Task <InventoryDetailModel> GetInventoryAsync(string sessionId) { InventoryDetailModel model = new InventoryDetailModel { Response = new KegIDResponse() }; try { string url = string.Format(Configuration.GetInventoryUrl, sessionId); var value = await App.kegIDClient.ExecuteServiceCall <KegIDResponse>(url, HttpMethodType.Get, string.Empty); model.InventoryResponseModel = !string.IsNullOrEmpty(value.Response) ? App.kegIDClient.DeserializeObject <IList <InventoryResponseModel> >(value.Response) : new List <InventoryResponseModel>(); model.Response.StatusCode = value.StatusCode; } catch (System.Exception) { } return(model); }
//add new data to inventory list public int AddToInventory(InventoryDetailModel inventoryDetailModel) { string query = "INSERT INTO inventorydetails (InventoryId,ProductId,InventoryQuantity,Cost) VALUES(@invetryId , @productid , @quantity ,@cost)"; using (MySqlConnection sqlConn = new MySqlConnection(conString)) { using (MySqlCommand cmd = new MySqlCommand(query, sqlConn)) { sqlConn.Open(); cmd.Parameters.AddWithValue("@invetryId", inventoryDetailModel.InventoryId); cmd.Parameters.AddWithValue("@productid", inventoryDetailModel.ProductId); cmd.Parameters.AddWithValue("@quantity", inventoryDetailModel.Quantity); cmd.Parameters.AddWithValue("@cost", inventoryDetailModel.Cost); int IsInserted = cmd.ExecuteNonQuery(); sqlConn.Close(); return(IsInserted); } } }
//Product Increase public int ProductIncrease(InventoryDetailModel inventoryDetailModel) { String query = @"UPDATE product SET Quantity= Quantity + @quantity WHERE ProductId = @productId "; using (MySqlConnection sqlConn = new MySqlConnection(conString)) { using (MySqlCommand cmd = new MySqlCommand(query, sqlConn)) { sqlConn.Open(); cmd.Parameters.AddWithValue("@quantity", inventoryDetailModel.Quantity); cmd.Parameters.AddWithValue("@productId", inventoryDetailModel.ProductId); int isUpdate = cmd.ExecuteNonQuery(); sqlConn.Close(); return(isUpdate); } } }
//Inventory Decrease public int InventoryDecrease(InventoryDetailModel inventoryDetailModel) { String query = @"UPDATE inventorydetails SET InventoryQuantity= InventoryQuantity - @quantity WHERE InventoryDetailsId = @InventoryDetailsId "; using (MySqlConnection sqlConn = new MySqlConnection(conString)) { using (MySqlCommand cmd = new MySqlCommand(query, sqlConn)) { sqlConn.Open(); cmd.Parameters.AddWithValue("@InventoryDetailsId", inventoryDetailModel.InventorydeatilsId); cmd.Parameters.AddWithValue("@quantity", inventoryDetailModel.Quantity); int isUpdate = cmd.ExecuteNonQuery(); sqlConn.Close(); return(isUpdate); } } }
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)); }
// lấy thông tin chi tiết Phiếu Kiểm kê public InventoryDetailModel GetInventoryDetailInfo(String maNhaThuoc, int?Id) { var phieuKiemKeRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuKiemKe> >().GetAll(); var phieuKiemKeChiTietRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuKiemKeChiTiet> >().GetAll(); var userProfileRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, UserProfile> >().GetAll(); var thuocRepo = _dataFilterService.GetValidDrugs(maNhaThuoc); var nhomThuocRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, NhomThuoc> >().GetAll(); var donViTinhRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, DonViTinh> >().GetAll(); var phieuNhapRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuNhap> >().GetAll(); var phieuXuatRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuXuat> >().GetAll(); var phieuNhapChiTietRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuNhapChiTiet> >().GetAll(); var phieuXuatChiTietRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuXuatChiTiet> >().GetAll(); // join bảng PhieuKiemKe và PhieuKiemKeChiTiet để lấy thông tin phiếu var inventoryDetailQuery = from pkk in phieuKiemKeRepo where (pkk.MaPhieuKiemKe == Id && pkk.RecordStatusID == (byte)RecordStatus.Activated) join up in userProfileRepo on pkk.CreatedBy_UserId equals up.UserId select new InventoryDetailModel { Id = pkk.MaPhieuKiemKe, FullName = up.TenDayDu, CreateTime = pkk.Created.Value, DaCanKho = pkk.DaCanKho, NhaThuoc_MaNhaThuoc = pkk.NhaThuoc_MaNhaThuoc }; InventoryDetailModel inventoryDetailResult = inventoryDetailQuery.FirstOrDefault(); if (inventoryDetailResult == null) { return(inventoryDetailResult); } // lấy thông tin thuốc, nhóm thuốc, đơn vị tính var medicineDetailQuery = from pkk in phieuKiemKeRepo join pkkct in phieuKiemKeChiTietRepo on pkk.MaPhieuKiemKe equals pkkct.PhieuKiemKe_MaPhieuKiemKe join t in thuocRepo on pkkct.Thuoc_ThuocId equals t.ThuocId join nt in nhomThuocRepo on t.NhomThuoc_MaNhomThuoc equals nt.MaNhomThuoc join dvt in donViTinhRepo on t.DonViXuatLe_MaDonViTinh equals dvt.MaDonViTinh where (pkk.MaPhieuKiemKe == Id && pkk.RecordStatusID == (byte)RecordStatus.Activated && pkkct.RecordStatusID == (byte)RecordStatus.Activated && nt.MaNhaThuoc == maNhaThuoc && dvt.MaNhaThuoc == maNhaThuoc) select new ThuocModel { MaNhomThuoc = nt.MaNhomThuoc, TenNhomThuoc = nt.TenNhomThuoc, ThuocId = t.ThuocId, MaThuoc = t.MaThuoc, TenThuoc = t.TenThuoc, TonKho = pkkct.TonKho, ThucTe = pkkct.ThucTe, TenDonViTinh = dvt.TenDonViTinh, Gia = pkkct.DonGia, SoLo = pkkct.SoLo, HanDung = pkkct.HanDung }; inventoryDetailResult.MedicineList = medicineDetailQuery.OrderBy(x => x.TenNhomThuoc).ToList(); // TH phiếu đã cân kho, lấy thông tin của các phiếu cân kho sau kiểm kê if (inventoryDetailResult.DaCanKho) { // lấy thông tin phiếu Nhập nếu có var phieuNhapQuery = from pkk in phieuKiemKeRepo where (pkk.MaPhieuKiemKe == Id && pkk.RecordStatusID == (byte)RecordStatus.Activated) join pn in phieuNhapRepo on pkk.PhieuNhap_MaPhieuNhap equals pn.MaPhieuNhap join pnct in phieuNhapChiTietRepo on pn.MaPhieuNhap equals pnct.PhieuNhap_MaPhieuNhap into pngr select new PhieuCanKhoItem { MaPhieu = pn.MaPhieuNhap, SoPhieu = pn.SoPhieuNhap, LoaiPhieu = NoteInOutType.Receipt, //"Phiếu Nhập", SoLuong = pngr.Count(), }; var phieuNhapResult = phieuNhapQuery.FirstOrDefault(); // lấy thông tin phiếu xuất nếu có var phieuXuatQuery = from pkk in phieuKiemKeRepo where (pkk.MaPhieuKiemKe == Id && pkk.RecordStatusID == (byte)RecordStatus.Activated) join px in phieuXuatRepo on pkk.PhieuXuat_MaPhieuXuat equals px.MaPhieuXuat join pxct in phieuXuatChiTietRepo on px.MaPhieuXuat equals pxct.PhieuXuat_MaPhieuXuat into pngr select new PhieuCanKhoItem { MaPhieu = px.MaPhieuXuat, SoPhieu = px.SoPhieuXuat, LoaiPhieu = NoteInOutType.Delivery, //"Phiếu Xuất", SoLuong = pngr.Distinct().Count(), }; var phieuXuatResult = phieuXuatQuery.FirstOrDefault(); // nếu có phiếu nhập và phiếu xuất, thêm vào phieuCanKhoItems var phieuCanKhoItems = new List <PhieuCanKhoItem>(); if (phieuNhapResult != null) { phieuCanKhoItems.Add(phieuNhapResult); } if (phieuXuatResult != null) { phieuCanKhoItems.Add(phieuXuatResult); } inventoryDetailResult.PhieuCanKhoChiTiet = phieuCanKhoItems; } // Nếu các thuốc trong phiếu không có thông tin giá/số lô/hạn dùng => lấy thông tin từ phiếu nhập gần nhất List <int> drugIdsOfInventory = inventoryDetailResult.MedicineList.Select(x => x.ThuocId).ToList(); var phieuNhapChiTietQueryable = _dataFilterService.GetValidReceiptNoteItems(maNhaThuoc); // lấy danh sách phiếu nhập của các thuốc có trong phiếu đã tạo var phieuNhapChiTietQuery = from pnct in phieuNhapChiTietQueryable where drugIdsOfInventory.Contains(pnct.DrugId) orderby pnct.NoteDate descending select new { pnct.DrugId, pnct.Price, pnct.SerialNumber, pnct.ExpiredDate }; var phieuNhapChiTietQueryResult = phieuNhapChiTietQuery.ToList(); inventoryDetailResult.MedicineList.ForEach(x => { if (phieuNhapChiTietQueryResult != null) { var pnct = phieuNhapChiTietQueryResult.Where(a => a.DrugId == x.ThuocId).FirstOrDefault(); x.Gia = x.Gia == 0 ? (decimal)pnct.Price : x.Gia; x.SoLo = x.SoLo ?? pnct.SerialNumber; x.HanDung = !x.HanDung.HasValue ? pnct.ExpiredDate : x.HanDung; } // nếu hạn dùng của thuốc < min date quy đinh thì không hiển thị hạn dùng x.HanDung = (x.HanDung.HasValue && x.HanDung <= MedConstants.MinProductionDataDate) ? null : x.HanDung; }); return(inventoryDetailResult); }
// cap nhat gia/lo/han dung cho tung thuoc o trong Phieu kiem ke public void UpdateDrugSerialNoAndExpDate(String maNhaThuoc, InventoryEditModel inventoryEditModel) { int inventoryId = inventoryEditModel.InventoryId; // return khi ma phieu kiem ke khong hop le if (inventoryId <= 0) { return; } bool canKho = inventoryEditModel.DaCanKho; decimal gia = inventoryEditModel.Gia; string soLo = inventoryEditModel.SoLo; DateTime?hanDung = inventoryEditModel.HanDung; var phieuKiemKeRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuKiemKe> >().GetAll(); var phieuKiemKeChiTietRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuKiemKeChiTiet> >(); var phieuNhapChiTietRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuNhapChiTiet> >(); var phieuXuatChiTietRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuXuatChiTiet> >(); InventoryDetailModel inventoryDetailModel = GetInventoryDetailInfo(maNhaThuoc, inventoryId); var thuocId = inventoryDetailModel.MedicineList.Where(x => x.MaThuoc == inventoryEditModel.MaThuoc).FirstOrDefault().ThuocId; // lay thong tin phieu kiem ke chi tiet theo PhieuKiemKe_MaPhieuKiemKe va Thuoc_ThuocId var pkkctQuery = from pkkct in phieuKiemKeChiTietRepo.GetAll() where (pkkct.PhieuKiemKe_MaPhieuKiemKe == inventoryId && pkkct.RecordStatusID == (byte)RecordStatus.Activated && pkkct.Thuoc_ThuocId == thuocId) select pkkct; var pkkctQueryResult = pkkctQuery.FirstOrDefault(); PhieuKiemKeChiTiet phieuKiemKeChiTietEntity = pkkctQueryResult; phieuKiemKeChiTietEntity.DonGia = gia; phieuKiemKeChiTietEntity.SoLo = soLo; phieuKiemKeChiTietEntity.HanDung = hanDung; // cap nhat gia/lo/han vao bang PhieuKiemKeChiTiets phieuKiemKeChiTietRepo.Update(phieuKiemKeChiTietEntity); phieuKiemKeChiTietRepo.Commit(); // TH phieu da can kho, cap nhat gia/lo/han trong phieu Nhap/xuat chi tiet if (canKho) { inventoryDetailModel.PhieuCanKhoChiTiet.ForEach(p => { // TH Phieu Nhap thì update giá nhập/lô/hạn dùng vào phiếu nhập chi tiết if (p.LoaiPhieu == NoteInOutType.Receipt && p.SoLuong > 0) { // tim Phieu Nhap Chi Tiet theo MaPhieu va thuocId var pnctQuery = from pnct in phieuNhapChiTietRepo.GetAll() where (pnct.PhieuNhap_MaPhieuNhap == p.MaPhieu && pnct.Thuoc_ThuocId == thuocId) select pnct; var pnctQueryResult = pnctQuery.FirstOrDefault(); if (pnctQueryResult != null) { PhieuNhapChiTiet phieuNhapChiTietEntity = pnctQueryResult; phieuNhapChiTietEntity.GiaNhap = gia; phieuNhapChiTietEntity.SoLo = soLo; phieuNhapChiTietEntity.HanDung = hanDung; phieuNhapChiTietRepo.Update(phieuNhapChiTietEntity); phieuNhapChiTietRepo.Commit(); } } // TH Phieu Xuat thì update giá xuất if (p.LoaiPhieu == NoteInOutType.Delivery && p.SoLuong > 0) { // tim Phieu Xuat Chi Tiet theo MaPhieu va thuocId var pxctQuery = from pxct in phieuXuatChiTietRepo.GetAll() where (pxct.PhieuXuat_MaPhieuXuat == p.MaPhieu && pxct.Thuoc_ThuocId == thuocId) select pxct; var pxctQueryResult = pxctQuery.FirstOrDefault(); if (pxctQueryResult != null) { PhieuXuatChiTiet phieuXuatChiTietEntity = pxctQueryResult; phieuXuatChiTietEntity.GiaXuat = gia; phieuXuatChiTietRepo.Update(phieuXuatChiTietEntity); phieuXuatChiTietRepo.Commit(); } } }); } }
//product Decrease call public int GetProductDecrease(InventoryDetailModel inventoryDetailModel) { return(inventoryGateway.ProductDecrease(inventoryDetailModel)); }
//Delete Inventory public int DeleteInvetory(InventoryDetailModel inventoryDetailModel) { return(inventoryGateway.DeleteInventoryDetails(inventoryDetailModel)); }
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")); } }
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")); } }
private static InventoryDetailModel CovertDBInventorytoAPIInventoryDet(inventory inv) { string error = ""; LUSSISEntities entities = new LUSSISEntities(); // to show the recommended order qty int?recommededorderqty = 0; // if the stock is less than or equal reorder level if (inv.stock <= inv.reorderlevel) { // the recommended order qty will be the minimum reorder level and reorder qty and the total qty stock of outstanding req recommededorderqty = (inv.reorderlevel - inv.stock) + inv.reorderqty; List <OutstandingItemModel> outs = OutstandingReqDetailRepo.GetAllPendingOutstandingItems(out error); List <PurchaseOrderModel> poms = new List <PurchaseOrderModel>(); if (error == "" && outs != null) { try { if (staticpoms == null) { staticpoms = new List <PurchaseOrderModel>(); } bool PendingPOExists = false; if (staticcount < 4) { poms = staticpoms; foreach (PurchaseOrderModel pom in poms) { int count = 0; count = pom.podms.Where(x => x.Itemid == inv.itemid).Count(); if (count > 0) { PendingPOExists = true; staticcount++; break; } } } else { PendingPOExists = true; } if (PendingPOExists) { recommededorderqty = 0; } else { int itemlist = outs.Where(p => p.ItemId == inv.itemid).Count <OutstandingItemModel>(); if (itemlist > 0) { OutstandingItemModel outItem = outs.Where(p => p.ItemId == inv.itemid).FirstOrDefault <OutstandingItemModel>(); recommededorderqty += outItem.Total; } } } catch (Exception e) { error = e.Message; } } } InventoryDetailModel invdm = new InventoryDetailModel(inv.invid, inv.itemid, inv.item.description, inv.stock, inv.reorderlevel, inv.reorderqty, inv.item.catid, inv.item.category.name, inv.item.description, inv.item.uom, recommededorderqty, inv.item.category.shelflocation, inv.item.category.shelflevel); return(invdm); }
//Inventory Decrease call public int InventoryDecreaseCall(InventoryDetailModel inventoryDetailModel) { return(inventoryGateway.InventoryDecrease(inventoryDetailModel)); }
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")); } }
//add to inventory details grid viiew public int AddToInvetoryDetails(InventoryDetailModel inventoryDetailModel) { return(inventoryGateway.AddToInventory(inventoryDetailModel)); }
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"); } }
//#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")); } }
// luu thong tin Phieu Kiem Ke (ca truong hop tao moi + update) public int SaveInventory(String maNhaThuoc, int userId, InventoryDetailModel model) { var phieuKiemKeRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuKiemKe> >(); var phieuKiemKeChiTietRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuKiemKeChiTiet> >(); var phieuNhapRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuNhap> >(); var phieuXuatRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuXuat> >(); var phieuNhapChiTietRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuNhapChiTiet> >(); var phieuXuatChiTietRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuXuatChiTiet> >(); var validDrugRepo = _dataFilterService.GetValidDrugs(maNhaThuoc); bool canKho = model.DaCanKho; // add thêm giá trị giờ phút vào ngày tạo model.CreateTime = model.CreateTime.WithCurrentTime(); // return value = mã phiếu nếu lưu phiếu thành công int retval = 0; var inventoryDrugCodes = model.MedicineList.Select(i => i.MaThuoc.ToLower()).ToList(); var inventoryDrugQuery = from d in validDrugRepo where (inventoryDrugCodes.Contains(d.MaThuoc.ToLower())) select new { d.MaThuoc, d.ThuocId, d.DonViXuatLe_MaDonViTinh, d.GiaNhap }; var inventoryDrugQueryResult = inventoryDrugQuery.ToDictionary(x => x.MaThuoc.ToLower(), x => new { x.ThuocId, x.DonViXuatLe_MaDonViTinh, x.GiaNhap }); // tạo 1 đối tượng phiếu kiểm kê và lưu/cập nhật đối tượng này vào bảng PhieuKiemKes trong DB PhieuKiemKe phieuKiemKe = null; // TH tạo phiếu kiểm kê mới if (model.Id == 0) { phieuKiemKe = new PhieuKiemKe { NhaThuoc_MaNhaThuoc = maNhaThuoc, CreatedBy_UserId = userId, Created = model.CreateTime, DaCanKho = canKho, RecordStatusID = (byte)RecordStatus.Activated }; phieuKiemKeRepo.Insert(phieuKiemKe); phieuKiemKeRepo.Commit(); } // TH update phiếu đã tạo else { var pkkQuery = from pkk in phieuKiemKeRepo.GetAll() where (pkk.MaPhieuKiemKe == model.Id) select pkk; phieuKiemKe = pkkQuery.FirstOrDefault(); phieuKiemKe.Modified = DateTime.Now; phieuKiemKe.DaCanKho = canKho; phieuKiemKe.ModifiedBy_UserId = userId; phieuKiemKeRepo.Update(phieuKiemKe); phieuKiemKeRepo.Commit(); } retval = phieuKiemKe.MaPhieuKiemKe; // TH chọn cân kho, tạo phiếu điều chỉnh sau kiểm kê if (canKho) { // tạo phiếu nhập mới var nhaCungCap = EnsureNhaCungCapKiemKe(maNhaThuoc, userId); var loaiKiemKe = EnsureLoaiXuatNhapKiemKe(); var receiptService = IoC.Container.Resolve <IReceiptNoteService>(); var deliveryService = IoC.Container.Resolve <IDeliveryNoteService>(); var phieuNhap = new PhieuNhap() { Created = DateTime.Now, CreatedBy_UserId = userId, NhaCungCap_MaNhaCungCap = nhaCungCap.MaNhaCungCap, NhaThuoc_MaNhaThuoc = maNhaThuoc, SoPhieuNhap = receiptService.GetNewReceiptNoteNumber(maNhaThuoc), NgayNhap = phieuKiemKe.Created, LoaiXuatNhap_MaLoaiXuatNhap = loaiKiemKe.MaLoaiXuatNhap }; phieuNhapRepo.Insert(phieuNhap); // tạo phiếu xuất mới var phieuXuat = new PhieuXuat() { Created = DateTime.Now, CreatedBy_UserId = userId, NhaCungCap_MaNhaCungCap = nhaCungCap.MaNhaCungCap, NhaThuoc_MaNhaThuoc = maNhaThuoc, SoPhieuXuat = deliveryService.GetNewDeliveryNoteNumber(maNhaThuoc), NgayXuat = phieuKiemKe.Created, MaLoaiXuatNhap = loaiKiemKe.MaLoaiXuatNhap }; phieuXuatRepo.Insert(phieuXuat); var phieuXuatChiTiets = new List <PhieuXuatChiTiet>(); var phieuNhapChiTiets = new List <PhieuNhapChiTiet>(); model.MedicineList.ForEach(e => { var chenhLech = e.ThucTe.HasValue ? e.TonKho - e.ThucTe : e.TonKho; var drugId = inventoryDrugQueryResult[e.MaThuoc.ToLower()].ThuocId; var maDonViTinh = inventoryDrugQueryResult[e.MaThuoc.ToLower()].DonViXuatLe_MaDonViTinh; var gia = inventoryDrugQueryResult[e.MaThuoc.ToLower()].GiaNhap; if (chenhLech > 0) { // tao phieu xuat dieu chinh kiem ke var dItem = new PhieuXuatChiTiet() { DonViTinh_MaDonViTinh = maDonViTinh.Value, NhaThuoc_MaNhaThuoc = maNhaThuoc, SoLuong = chenhLech.Value, Thuoc_ThuocId = drugId, GiaXuat = e.Gia != 0 ? e.Gia : gia, }; phieuXuatChiTiets.Add(dItem); } else if (chenhLech < 0) { // tao phieu nhap dieu chinh kiem ke var rItem = new PhieuNhapChiTiet() { DonViTinh_MaDonViTinh = maDonViTinh, NhaThuoc_MaNhaThuoc = maNhaThuoc, SoLuong = chenhLech.Value * -1, Thuoc_ThuocId = drugId, GiaNhap = e.Gia != 0 ? e.Gia : gia, SoLo = e.SoLo, HanDung = e.HanDung, }; phieuNhapChiTiets.Add(rItem); } }); // tính tổng tiền và đã trả cho phiếu nhập xuất rồi insert bản ghi vào DB phieuNhap.TongTien = phieuNhapChiTiets.Sum(a => a.SoLuong * a.GiaNhap); phieuNhap.DaTra = phieuNhap.TongTien; phieuXuat.TongTien = phieuXuatChiTiets.Sum(a => a.SoLuong * a.GiaXuat); phieuXuat.DaTra = phieuXuat.TongTien; phieuNhapRepo.Commit(); phieuXuatRepo.Commit(); // cập nhật mã phiếu nhập/xuất vào phiếu nhập xuất chi tiết phieuNhapChiTiets.ForEach(i => { i.PhieuNhap_MaPhieuNhap = phieuNhap.MaPhieuNhap; i.IsModified = true; }); phieuXuatChiTiets.ForEach(i => { i.PhieuXuat_MaPhieuXuat = phieuXuat.MaPhieuXuat; i.IsModified = true; }); phieuNhapChiTietRepo.InsertMany(phieuNhapChiTiets); phieuNhapChiTietRepo.Commit(); phieuXuatChiTietRepo.InsertMany(phieuXuatChiTiets); phieuXuatChiTietRepo.Commit(); // cập nhật mã phiếu nhập/xuất vào Phiếu kiểm kê phieuKiemKeRepo.UpdateMany(i => i.MaPhieuKiemKe == retval, i => new PhieuKiemKe() { PhieuNhap_MaPhieuNhap = phieuNhap.MaPhieuNhap, PhieuXuat_MaPhieuXuat = phieuXuat.MaPhieuXuat }); phieuKiemKeRepo.Commit(); } // TH phiếu đã lưu thì xóa các bản ghi phiếu kiểm kê chi tiết cũ if (model.Id > 0) { phieuKiemKeChiTietRepo.Delete(i => i.PhieuKiemKe_MaPhieuKiemKe == model.Id); phieuKiemKeChiTietRepo.Commit(); } List <PhieuKiemKeChiTiet> phieuKiemKeChiTiets = new List <PhieuKiemKeChiTiet>(); foreach (var thuoc in model.MedicineList) { phieuKiemKeChiTiets.Add(new PhieuKiemKeChiTiet { PhieuKiemKe_MaPhieuKiemKe = retval, Thuoc_ThuocId = inventoryDrugQueryResult[thuoc.MaThuoc.ToLower()].ThuocId, TonKho = thuoc.TonKho, ThucTe = thuoc.ThucTe, DonGia = thuoc.Gia, SoLo = thuoc.SoLo, HanDung = thuoc.HanDung, RecordStatusID = (byte)RecordStatus.Activated }); } phieuKiemKeChiTietRepo.InsertMany(phieuKiemKeChiTiets); phieuKiemKeChiTietRepo.Commit(); return(retval); }
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)); } }
// luu thong tin Phieu Kiem Ke (ca truong hop tao moi + update) public int SaveInventory(String maNhaThuoc, String maNhaThuocCha, int userId, InventoryDetailModel model) { var phieuKiemKeRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuKiemKe> >(); var phieuKiemKeChiTietRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuKiemKeChiTiet> >(); var phieuNhapRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuNhap> >(); var phieuXuatRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuXuat> >(); var phieuNhapChiTietRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuNhapChiTiet> >(); var phieuXuatChiTietRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuXuatChiTiet> >(); var drugRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, Thuoc> >(); bool canKho = model.IsCompareStore; var currentDate = DateTime.Now; model.CreateTime = model.CreateTime.AddHours(currentDate.Hour).AddMinutes(currentDate.Minute).AddSeconds(currentDate.Second); int retval = 0; var drugCodes = model.MedicineList.Select(i => i.MaThuoc.ToLower()).ToList(); var query = from d in drugRepo.GetAll() where (drugCodes.Contains(d.MaThuoc.ToLower()) && (d.NhaThuoc_MaNhaThuoc == maNhaThuoc || d.NhaThuoc_MaNhaThuoc == maNhaThuocCha)) select new { d.MaThuoc, d.ThuocId, d.DonViXuatLe_MaDonViTinh, d.GiaNhap }; var drugs = query.ToDictionary(x => x.MaThuoc.ToLower(), x => new { x.ThuocId, x.DonViXuatLe_MaDonViTinh, x.GiaNhap }); // tạo 1 đối tượng phiếu kiểm kê và lưu/cập nhật đối tượng này vào bảng PhieuKiemKes trong DB PhieuKiemKe phieuKiemKe = null; // TH tạo phiếu kiểm kê mới if (model.Id == 0) { phieuKiemKe = new PhieuKiemKe { //MaPhieuKiemKe = model.Id, NhaThuoc_MaNhaThuoc = maNhaThuoc, CreatedBy_UserId = userId, Created = model.CreateTime, DaCanKho = canKho, RecordStatusId = (int)RecordStatus.Activated }; phieuKiemKeRepo.Insert(phieuKiemKe); phieuKiemKeRepo.Commit(); } // TH update phiếu đã tạo else { var pkkQuery = from pkk in phieuKiemKeRepo.GetAll() where (pkk.MaPhieuKiemKe == model.Id) select pkk; phieuKiemKe = pkkQuery.FirstOrDefault(); phieuKiemKe.Modified = DateTime.Now; phieuKiemKe.DaCanKho = canKho; phieuKiemKe.ModifiedBy_UserId = userId; phieuKiemKeRepo.Update(phieuKiemKe); phieuKiemKeRepo.Commit(); } retval = phieuKiemKe.MaPhieuKiemKe; // TH chọn cân kho, tạo phiếu điều chỉnh sau kiểm kê if (canKho) { // tạo phiếu nhập mới var nhaCungCap = EnsureNhaCungCapKiemKe(maNhaThuoc, userId); var loaiKiemKe = EnsureLoaiXuatNhapKiemKe(); var phieuNhap = new PhieuNhap() { Created = DateTime.Now, CreatedBy_UserId = userId, NhaCungCap_MaNhaCungCap = nhaCungCap.MaNhaCungCap, NhaThuoc_MaNhaThuoc = maNhaThuoc, SoPhieuNhap = _generateAvaliableSoPhieuNhap(maNhaThuoc), NgayNhap = phieuKiemKe.Created, LoaiXuatNhap_MaLoaiXuatNhap = loaiKiemKe.MaLoaiXuatNhap }; phieuNhapRepo.Insert(phieuNhap); //phieuNhapRepo.Commit(); // tạo phiếu xuất mới var phieuXuat = new Entity.PhieuXuat() { Created = DateTime.Now, CreatedBy_UserId = userId, NhaCungCap_MaNhaCungCap = nhaCungCap.MaNhaCungCap, NhaThuoc_MaNhaThuoc = maNhaThuoc, SoPhieuXuat = _generateAvaliableSoPhieuXuat(maNhaThuoc), NgayXuat = phieuKiemKe.Created, MaLoaiXuatNhap = loaiKiemKe.MaLoaiXuatNhap }; phieuXuatRepo.Insert(phieuXuat); //phieuXuatRepo.Commit(); var phieuXuatChiTiets = new List <PhieuXuatChiTiet>(); var phieuNhapChiTiets = new List <PhieuNhapChiTiet>(); model.MedicineList.ForEach(e => { var chenhLech = e.ThucTe.HasValue ? e.TonKho - e.ThucTe : e.TonKho; var drugId = drugs[e.MaThuoc.ToLower()].ThuocId; var maDonViTinh = drugs[e.MaThuoc.ToLower()].DonViXuatLe_MaDonViTinh; var gia = drugs[e.MaThuoc.ToLower()].GiaNhap; if (chenhLech > 0) { // tao phieu xuat dieu chinh kiem ke var dItem = new PhieuXuatChiTiet() { DonViTinh_MaDonViTinh = maDonViTinh.Value, NhaThuoc_MaNhaThuoc = maNhaThuoc, SoLuong = chenhLech.Value, Thuoc_ThuocId = drugId, GiaXuat = e.Gia != 0 ? e.Gia : gia, //PhieuXuat_MaPhieuXuat = phieuXuat.MaPhieuXuat }; phieuXuatChiTiets.Add(dItem); } else if (chenhLech < 0) { // tao phieu nhap dieu chinh kiem ke var rItem = new PhieuNhapChiTiet() { DonViTinh_MaDonViTinh = maDonViTinh, NhaThuoc_MaNhaThuoc = maNhaThuoc, SoLuong = chenhLech.Value * -1, Thuoc_ThuocId = drugId, GiaNhap = e.Gia != 0 ? e.Gia : gia, SoLo = e.SoLo, HanDung = e.HanDung, //PhieuNhap_MaPhieuNhap = phieuNhap.MaPhieuNhap }; phieuNhapChiTiets.Add(rItem); } }); phieuNhap.TongTien = phieuNhapChiTiets.Sum(a => a.SoLuong * a.GiaNhap); phieuNhap.DaTra = phieuNhap.TongTien; phieuXuat.TongTien = phieuXuatChiTiets.Sum(a => a.SoLuong * a.GiaXuat); phieuXuat.DaTra = phieuXuat.TongTien; phieuNhapRepo.Commit(); phieuXuatRepo.Commit(); phieuNhapChiTiets.ForEach(i => { i.PhieuNhap_MaPhieuNhap = phieuNhap.MaPhieuNhap; i.IsModified = true; }); phieuXuatChiTiets.ForEach(i => { i.PhieuXuat_MaPhieuXuat = phieuXuat.MaPhieuXuat; i.IsModified = true; }); phieuNhapChiTietRepo.InsertMany(phieuNhapChiTiets); phieuNhapChiTietRepo.Commit(); phieuXuatChiTietRepo.InsertMany(phieuXuatChiTiets); phieuXuatChiTietRepo.Commit(); phieuKiemKeRepo.UpdateMany(i => i.MaPhieuKiemKe == retval, i => new PhieuKiemKe() { PhieuNhap_MaPhieuNhap = phieuNhap.MaPhieuNhap, PhieuXuat_MaPhieuXuat = phieuXuat.MaPhieuXuat }); phieuKiemKeRepo.Commit(); } // tạo 1 đối tượng PhieuKiemKeChiTiet // update table PhieuKiemKeChiTiets if (model.Id > 0) { phieuKiemKeChiTietRepo.Delete(i => i.PhieuKiemKe_MaPhieuKiemKe == model.Id); phieuKiemKeChiTietRepo.Commit(); } List <PhieuKiemKeChiTiet> phieuKiemKeChiTiets = new List <PhieuKiemKeChiTiet>(); foreach (var thuoc in model.MedicineList) { phieuKiemKeChiTiets.Add(new PhieuKiemKeChiTiet { PhieuKiemKe_MaPhieuKiemKe = retval, Thuoc_ThuocId = drugs[thuoc.MaThuoc.ToLower()].ThuocId, TonKho = thuoc.TonKho, ThucTe = thuoc.ThucTe, DonGia = thuoc.Gia, SoLo = thuoc.SoLo, HanDung = thuoc.HanDung, RecordStatusId = (int)RecordStatus.Activated }); } phieuKiemKeChiTietRepo.InsertMany(phieuKiemKeChiTiets); phieuKiemKeChiTietRepo.Commit(); return(retval); }