private int PerformInventories(PhieuKiemKeEditModel phieuKiemKes, bool createNew, bool balancingInventory)
        {
            var maPhieuKiemKe     = 0;
            var nhaThuoc          = this.GetNhaThuoc();
            var maNhaThuoc        = nhaThuoc.MaNhaThuoc;
            var maNhaThuocCha     = nhaThuoc.MaNhaThuocCha;
            var receiptRepo       = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, Entity.PhieuNhap> >();
            var deliveryRepo      = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, Entity.PhieuXuat> >();
            var receiptItemRepo   = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, Entity.PhieuNhapChiTiet> >();
            var deliveryItemRepo  = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, Entity.PhieuXuatChiTiet> >();
            var inventoryRepo     = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, Entity.PhieuKiemKe> >();
            var inventoryItemRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, Entity.PhieuKiemKeChiTiet> >();
            var drugRepo          = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, Entity.Thuoc> >();
            var drugService       = IoC.Container.Resolve <IDrugManagementService>();
            var inventoryItems    = new List <Entity.PhieuKiemKeChiTiet>();

            var drugCodes = phieuKiemKes.Items.Select(i => i.MaThuoc.ToLower()).ToList();
            var drugs     = drugRepo.GetAll().Where(i => drugCodes.Contains(i.MaThuoc.ToLower()) && (i.NhaThuoc_MaNhaThuoc == maNhaThuoc || i.NhaThuoc_MaNhaThuoc == maNhaThuocCha))
                            .ToDictionary(i => i.MaThuoc.ToLower(), i => new { i.ThuocId, i.DonViXuatLe_MaDonViTinh, i.GiaNhap });
            var drugIds = drugs.Select(i => i.Value.ThuocId).Distinct().ToArray();

            Entity.PhieuKiemKe phieuKiemKe = null;
            if (!createNew)
            {
                phieuKiemKe = inventoryRepo.GetAll().Where(i => i.MaPhieuKiemKe == phieuKiemKes.MaPhieuKiemKe).FirstOrDefault();
                inventoryItemRepo.Delete(i => i.PhieuKiemKe_MaPhieuKiemKe == phieuKiemKe.MaPhieuKiemKe);
                deliveryRepo.UpdateMany(i => i.MaPhieuXuat == phieuKiemKe.PhieuXuat_MaPhieuXuat, i => new Entity.PhieuXuat()
                {
                    RecordStatusID = (byte)RecordStatus.Deleted
                });
                receiptRepo.UpdateMany(i => i.MaPhieuNhap == phieuKiemKe.PhieuNhap_MaPhieuNhap, i => new Entity.PhieuNhap()
                {
                    RecordStatusID = (byte)RecordStatus.Deleted
                });
            }

            if (balancingInventory)
            {
                var nhaCungCap = EnsureNhaCungCapKiemKe(maNhaThuoc);
                var loaiKiemKe = EnsureLoaiXuatNhapKiemKe();

                var phieuXuat = new Entity.PhieuXuat()
                {
                    Created                 = createNew? DateTime.Now : phieuKiemKes.NgayTao,
                    CreatedBy_UserId        = WebSecurity.GetCurrentUserId,
                    NhaCungCap_MaNhaCungCap = nhaCungCap.MaNhaCungCap,
                    NhaThuoc_MaNhaThuoc     = maNhaThuoc,
                    SoPhieuXuat             = _generateAvaliableSoPhieuXuat(),
                    NgayXuat                = phieuKiemKes.NgayTao,
                    MaLoaiXuatNhap          = loaiKiemKe.MaLoaiXuatNhap,
                    PreNoteDate             = phieuKiemKes.NgayTao
                };

                deliveryRepo.Insert(phieuXuat);
                // kiem tra xem da co nha cung cap dieu chinh sau kiem ke chua?

                var phieuNhap = new Entity.PhieuNhap()
                {
                    Created                     = createNew ? DateTime.Now : phieuKiemKes.NgayTao,
                    CreatedBy_UserId            = WebSecurity.GetCurrentUserId,
                    NhaCungCap_MaNhaCungCap     = nhaCungCap.MaNhaCungCap,
                    NhaThuoc_MaNhaThuoc         = maNhaThuoc,
                    SoPhieuNhap                 = _generateAvaliableSoPhieuNhap(),
                    NgayNhap                    = phieuKiemKes.NgayTao,
                    LoaiXuatNhap_MaLoaiXuatNhap = loaiKiemKe.MaLoaiXuatNhap,
                    PreNoteDate                 = phieuKiemKes.NgayTao
                };
                receiptRepo.Insert(phieuNhap);

                if (createNew)
                {
                    phieuKiemKe = new Entity.PhieuKiemKe()
                    {
                        Created             = phieuKiemKes.NgayTao,
                        CreatedBy_UserId    = WebSecurity.GetCurrentUserId,
                        NhaThuoc_MaNhaThuoc = maNhaThuoc,
                        DaCanKho            = true,
                        SoPhieu             = _generateAvaliableSoPhieu()
                    };
                    inventoryRepo.Insert(phieuKiemKe);
                }
                else
                {
                    phieuXuat.Created           = phieuKiemKe.Created;
                    phieuXuat.CreatedBy_UserId  = phieuKiemKe.CreatedBy_UserId;
                    phieuXuat.Modified          = DateTime.Now;
                    phieuXuat.ModifiedBy_UserId = WebSecurity.GetCurrentUserId;

                    phieuNhap.Created           = phieuKiemKe.Created;
                    phieuNhap.CreatedBy_UserId  = phieuKiemKe.CreatedBy_UserId;
                    phieuNhap.Modified          = DateTime.Now;
                    phieuNhap.ModifiedBy_UserId = WebSecurity.GetCurrentUserId;

                    phieuKiemKe.Created           = phieuKiemKes.NgayTao;
                    phieuKiemKe.Modified          = DateTime.Now;
                    phieuKiemKe.ModifiedBy_UserId = WebSecurity.GetCurrentUserId;
                }
                phieuKiemKe.DaCanKho = true;

                var deliveryItems = new List <Entity.PhieuXuatChiTiet>();
                var receiptItems  = new List <Entity.PhieuNhapChiTiet>();

                var lastReceiptDrugPrices  = drugService.GetLastDrugPriceOnReceiptNotes(maNhaThuoc, drugIds);
                var lastDeliveryDrugPrices = drugService.GetLastDrugPriceOnDeliveryNotes(maNhaThuoc, drugIds);
                phieuKiemKes.Items.ForEach(e =>
                {
                    if (drugs.ContainsKey(e.MaThuoc.ToLower()))
                    {
                        var drugId      = drugs[e.MaThuoc.ToLower()].ThuocId;
                        var retailUnit  = drugs[e.MaThuoc.ToLower()].DonViXuatLe_MaDonViTinh;
                        var retailPrice = drugs[e.MaThuoc.ToLower()].GiaNhap;
                        inventoryItems.Add(new Entity.PhieuKiemKeChiTiet()
                        {
                            Thuoc_ThuocId = drugId,
                            ThucTe        = e.SoLuongThucTe,
                            TonKho        = e.SoLuongHeThong
                        });

                        var chenhLech = e.SoLuongThucTe.HasValue ? e.SoLuongHeThong - e.SoLuongThucTe : e.SoLuongHeThong;

                        if (chenhLech > 0)
                        {
                            // tao phieu xuat dieu chinh kiem ke
                            var dItem = new Entity.PhieuXuatChiTiet()
                            {
                                DonViTinh_MaDonViTinh = retailUnit.Value,
                                NhaThuoc_MaNhaThuoc   = maNhaThuoc,
                                SoLuong       = chenhLech.Value,
                                Thuoc_ThuocId = drugId,
                                GiaXuat       = retailPrice
                            };
                            deliveryItems.Add(dItem);
                            if (lastReceiptDrugPrices.ContainsKey(drugId))
                            {
                                //Tôi comment lại câu lệnh này để ông xem lại giá nhập gần nhất
                                dItem.GiaXuat = (Decimal)lastReceiptDrugPrices[drugId];
                            }
                        }
                        else if (chenhLech < 0)
                        {
                            // tao phieu nhap dieu chinh kiem ke
                            var rItem = new Entity.PhieuNhapChiTiet()
                            {
                                DonViTinh_MaDonViTinh = retailUnit,
                                NhaThuoc_MaNhaThuoc   = maNhaThuoc,
                                SoLuong       = chenhLech.Value * -1,
                                Thuoc_ThuocId = drugId,
                                GiaNhap       = retailPrice,
                                HanDung       = null
                            };
                            receiptItems.Add(rItem);
                            if (lastReceiptDrugPrices.ContainsKey(drugId))
                            {
                                //Tôi comment lại câu lệnh này để ông check lại phần giá nhập gần nhất
                                rItem.GiaNhap = (Decimal)lastReceiptDrugPrices[drugId];
                            }
                        }
                    }
                });
                phieuNhap.TongTien = receiptItems.Sum(e => e.SoLuong * e.GiaNhap);
                phieuNhap.DaTra    = phieuNhap.TongTien;
                phieuXuat.TongTien = deliveryItems.Sum(e => e.SoLuong * e.GiaXuat);
                phieuXuat.DaTra    = phieuXuat.TongTien;
                receiptRepo.Commit();

                maPhieuKiemKe = createNew ? phieuKiemKe.MaPhieuKiemKe : phieuKiemKes.MaPhieuKiemKe;
                inventoryItems.ForEach(i =>
                {
                    i.PhieuKiemKe_MaPhieuKiemKe = maPhieuKiemKe;
                });
                deliveryItems.ForEach(i =>
                {
                    i.PhieuXuat_MaPhieuXuat = phieuXuat.MaPhieuXuat;
                    i.IsModified            = true;
                });
                receiptItems.ForEach(i =>
                {
                    i.PhieuNhap_MaPhieuNhap = phieuNhap.MaPhieuNhap;
                    i.IsModified            = true;
                });

                maPhieuKiemKe = phieuKiemKe.MaPhieuKiemKe;
                NoteServiceHelper.ApplyAdditionalInfos(deliveryItems.ToArray());
                NoteServiceHelper.ApplyAdditionalInfos(receiptItems.ToArray());
                deliveryItemRepo.InsertMany(deliveryItems);
                receiptItemRepo.InsertMany(receiptItems);
                inventoryItemRepo.InsertMany(inventoryItems);
                inventoryRepo.UpdateMany(i => i.MaPhieuKiemKe == maPhieuKiemKe, i => new Entity.PhieuKiemKe()
                {
                    PhieuNhap_MaPhieuNhap = phieuNhap.MaPhieuNhap,
                    PhieuXuat_MaPhieuXuat = phieuXuat.MaPhieuXuat
                });
                BackgroundJobHelper.EnqueueMakeAffectedChangesRelatedDeliveryNotes(phieuXuat.MaPhieuXuat);
                BackgroundJobHelper.EnqueueMakeAffectedChangesRelatedReceiptNotes(phieuNhap.MaPhieuNhap);
            }
            else
            {
                if (createNew)
                {
                    phieuKiemKe = new Entity.PhieuKiemKe()
                    {
                        Created             = phieuKiemKes.NgayTao,
                        CreatedBy_UserId    = WebSecurity.GetCurrentUserId,
                        NhaThuoc_MaNhaThuoc = maNhaThuoc,
                        DaCanKho            = false,
                        SoPhieu             = phieuKiemKes.SoPhieu
                    };
                    inventoryRepo.Insert(phieuKiemKe);
                    inventoryRepo.Commit();
                }

                maPhieuKiemKe = createNew ? phieuKiemKe.MaPhieuKiemKe : phieuKiemKes.MaPhieuKiemKe;
                phieuKiemKes.Items.ForEach(e =>
                {
                    if (drugs.ContainsKey(e.MaThuoc.ToLower()))
                    {
                        var drugId = drugs[e.MaThuoc.ToLower()].ThuocId;
                        inventoryItems.Add(new Entity.PhieuKiemKeChiTiet()
                        {
                            Thuoc_ThuocId             = drugId,
                            ThucTe                    = e.SoLuongThucTe,
                            TonKho                    = e.SoLuongHeThong,
                            PhieuKiemKe_MaPhieuKiemKe = maPhieuKiemKe
                        });
                    }
                });
                inventoryItemRepo.InsertMany(inventoryItems);
            }
            if (maPhieuKiemKe > 0 && balancingInventory)
            {
                inventoryRepo.UpdateMany(i => i.MaPhieuKiemKe == maPhieuKiemKe, i => new Med.Entity.PhieuKiemKe()
                {
                    DaCanKho = true
                });
            }


            return(maPhieuKiemKe);
        }
Esempio n. 2
0
        public int SaveDeliveryNote(string drugStoreCode, int userId, List <DrugDeliveryItem> deliveryItems, double paymentAmount, int noteNumber,
                                    DateTime?noteDate, int?customerId, int?doctorId, string description)
        {
            if (deliveryItems == null || !deliveryItems.Any() || noteDate == null || noteNumber < 1)
            {
                return(0);
            }
            int retVal = 0;

            try
            {
                var dateTimeNow  = DateTime.Now;
                var newNoteDate  = new DateTime(noteDate.Value.Year, noteDate.Value.Month, noteDate.Value.Day, dateTimeNow.Hour, dateTimeNow.Minute, dateTimeNow.Second);
                var totalAmmount = deliveryItems.Sum(i => i.TotalAmount);
                //using (var tran = TransactionScopeHelper.CreateReadCommittedForWrite())
                {
                    var deliveryRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuXuat> >();
                    var realPayment  = paymentAmount;
                    if (Math.Abs(totalAmmount - paymentAmount) < MedConstants.EspAmount)
                    {
                        realPayment = totalAmmount;
                    }
                    if (paymentAmount > totalAmmount)
                    {
                        realPayment = totalAmmount;
                    }
                    var deliNote = new PhieuXuat()
                    {
                        Created             = DateTime.Now,
                        CreatedBy_UserId    = userId,
                        NhaThuoc_MaNhaThuoc = drugStoreCode,
                        TongTien            = (decimal)totalAmmount,
                        DaTra          = (decimal)realPayment,
                        DienGiai       = description,
                        MaLoaiXuatNhap = (int)NoteInOutType.Delivery,
                        NgayXuat       = newNoteDate,

                        SoPhieuXuat = GetNewDeliveryNoteNumber(drugStoreCode)
                    };
                    deliNote.IsDebt = (double)Math.Abs(deliNote.TongTien - deliNote.DaTra) > MedConstants.EspAmount;

                    if (customerId > 0)
                    {
                        deliNote.KhachHang_MaKhachHang = customerId;
                    }
                    if (doctorId > 0)
                    {
                        deliNote.BacSy_MaBacSy = doctorId;
                    }
                    deliveryRepo.Add(deliNote);
                    deliveryRepo.Commit();

                    var deliNoteItems = deliveryItems.Select(i => new PhieuXuatChiTiet()
                    {
                        Thuoc_ThuocId         = i.DrugId,
                        DonViTinh_MaDonViTinh = i.SelectedUnitId,
                        GiaXuat               = (decimal)i.Price,
                        IsModified            = true,
                        NhaThuoc_MaNhaThuoc   = drugStoreCode,
                        PhieuXuat_MaPhieuXuat = deliNote.MaPhieuXuat,
                        SoLuong               = (decimal)i.Quantity,
                        ChietKhau             = 0
                    }).ToList();
                    NoteServiceHelper.ApplyAdditionalInfos(deliNoteItems.ToArray());
                    var deliveryItemRepo = IoC.Container.Resolve <BaseRepositoryV2 <MedDbContext, PhieuXuatChiTiet> >();
                    deliveryItemRepo.InsertMany(deliNoteItems, true);

                    //tran.Complete();
                    retVal = deliNote.MaPhieuXuat;
                }
            }
            catch (Exception ex)
            {
                retVal = 0;
                FaultHandler.Instance.Handle(ex, this);
            }

            return(retVal);
        }