Пример #1
0
        public List <Product> SearchingProduct(ProductSearchCriteria productSearchCriteria)
        {
            IQueryable <Product> query   = null;
            BaoHienDBDataContext context = BaoHienRepository.GetBaoHienDBDataContext();

            if (context != null)
            {
                query = from p in context.Products
                        join pt in context.ProductTypes on p.ProductType equals pt.Id
                        where (p.Status == null) && (productSearchCriteria.ProductTypeId == null || pt.Id == productSearchCriteria.ProductTypeId)
                        select p;
            }
            if (productSearchCriteria.ProductCode != null)
            {
                query = query.Where(p => p.ProductCode.ToLower().Contains(productSearchCriteria.ProductCode));
            }
            if (productSearchCriteria.ProductName != null)
            {
                query = query.Where(p => p.ProductName.ToLower().Contains(productSearchCriteria.ProductName));
            }
            if (query != null)
            {
                return(query.ToList());
            }
            return(null);
        }
Пример #2
0
        private void loadSomeData()
        {
            ProductAttributeService productAttrService = new ProductAttributeService();

            products = new BindingList <ProductAttributeModel>(productAttrService.GetProductAndAttribute());
            units    = new BindingList <MeasurementUnit>(unitService.GetMeasurementUnits());
            if (entranceStock != null)
            {
                txtCode.Text = entranceStock.EntranceCode;
                txtNote.Text = entranceStock.Note;
                txtDate.Text = entranceStock.CreatedDate.ToString(BHConstant.DATE_FORMAT);
                txtUser.Text = entranceStock.SystemUser.FullName;
            }
            else
            {
                if (Global.CurrentUser != null)
                {
                    txtUser.Text = Global.CurrentUser.FullName;
                }
                txtUser.Enabled = false;
                txtDate.Text    = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate().ToString(BHConstant.DATE_FORMAT);
                txtCode.Text    = Global.GetTempSeedID(BHConstant.PREFIX_FOR_ENTRANCE);
            }
            txtDate.Enabled = false;
            txtUser.Enabled = false;
        }
Пример #3
0
        public List <ProductType> SearchingProductType(ProductTypeSearchCriteria productTypeSearchCriteria)
        {
            IQueryable <ProductType> query   = null;
            BaoHienDBDataContext     context = BaoHienRepository.GetBaoHienDBDataContext();

            if (context != null)
            {
                query = from pt in context.ProductTypes
                        where (pt.Status == null)
                        select pt;
            }
            if (productTypeSearchCriteria.ProductTypeCode != null)
            {
                query = query.Where(p => p.TypeCode.ToLower().Contains(productTypeSearchCriteria.ProductTypeCode));
            }
            if (productTypeSearchCriteria.ProductTypeName != null)
            {
                query = query.Where(p => p.TypeName.ToLower().Contains(productTypeSearchCriteria.ProductTypeName));
            }

            if (query != null)
            {
                return(query.ToList());
            }
            return(null);
        }
        private void ExportFile()
        {
            Global.checkDirSaveFile();
            var doc = new Document(PageSize.A4, 20, 20, 10, 10);

            PdfWriter       docWriter = PdfWriter.GetInstance(doc, new FileStream(BHConstant.SAVE_IN_DIRECTORY + @"\Kho.pdf", FileMode.Create));
            PdfWriterEvents writerEvent;

            Image watermarkImage = Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + @"logo.png");

            watermarkImage.SetAbsolutePosition(doc.PageSize.Width / 2 - 70, 600);
            writerEvent         = new PdfWriterEvents(watermarkImage);
            docWriter.PageEvent = writerEvent;

            doc.Open();

            doc.Add(FormatConfig.ParaRightBeforeHeader("In ngày : " + BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate().ToString(BHConstant.DATETIME_FORMAT)));
            doc.Add(FormatConfig.ParaHeader("BÁO CÁO KHO VÀ THÀNH PHẨM"));

            doc.Add(FormatConfig.ParaRightBelowHeader("(" + textForPrint + ")"));
            if (modeReport != 1)
            {
                doc.Add(ProductsTable());
            }
            else
            {
                doc.Add(FormatConfig.ParaCommonInfo("Sản phẩm : ", textInfo));
                doc.Add(ProductDetailTable());
            }
            doc.Add(FormatConfig.ParaCommonInfo("Ghi chú : ", String.Concat(Enumerable.Repeat("...", 96))));

            doc.Close();
        }
Пример #5
0
        private void ExportFile()
        {
            Global.checkDirSaveFile();
            var             doc       = new Document(PageSize.A4, 20, 20, 10, 10);
            PdfWriter       docWriter = PdfWriter.GetInstance(doc, new FileStream(BHConstant.SAVE_IN_DIRECTORY + @"\KHang.pdf", FileMode.Create));
            PdfWriterEvents writerEvent;

            Image watermarkImage = Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + @"logo.png");

            watermarkImage.SetAbsolutePosition(doc.PageSize.Width / 2 - 70, 550);
            writerEvent         = new PdfWriterEvents(watermarkImage);
            docWriter.PageEvent = writerEvent;

            doc.Open();

            doc.Add(FormatConfig.ParaRightBeforeHeader("In ngày : " + BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate().ToString(BHConstant.DATETIME_FORMAT)));
            doc.Add(FormatConfig.ParaHeader("DANH SÁCH KHÁCH HÀNG"));

            PdfPTable table = FormatConfig.Table(7, new float[] { 0.5f, 2f, 1.3f, 1.3f, 2f, 1.6f, 1.3f });

            table.AddCell(FormatConfig.TableCellHeader("STT"));
            table.AddCell(FormatConfig.TableCellHeader("Tên khách hàng"));
            table.AddCell(FormatConfig.TableCellHeader("Mã KH"));
            table.AddCell(FormatConfig.TableCellHeader("SĐT Cty"));
            table.AddCell(FormatConfig.TableCellHeader("Địa chỉ"));
            table.AddCell(FormatConfig.TableCellHeader("Người liên lạc"));
            table.AddCell(FormatConfig.TableCellHeader("SĐT"));

            for (int i = 0; i < customers.Count; i++)
            {
                table.AddCell(FormatConfig.TableCellBody((i + 1).ToString(), PdfPCell.ALIGN_CENTER));
                table.AddCell(FormatConfig.TableCellBody(customers[i].CustomerName, PdfPCell.ALIGN_LEFT));
                table.AddCell(FormatConfig.TableCellBody(customers[i].CustCode, PdfPCell.ALIGN_LEFT));
                table.AddCell(FormatConfig.TableCellBody(customers[i].Phone, PdfPCell.ALIGN_LEFT));
                table.AddCell(FormatConfig.TableCellBody(customers[i].Address, PdfPCell.ALIGN_LEFT));
                table.AddCell(FormatConfig.TableCellBody(customers[i].ContactPerson, PdfPCell.ALIGN_LEFT));
                table.AddCell(FormatConfig.TableCellBody(customers[i].ContactPersonPhone, PdfPCell.ALIGN_LEFT));
            }
            doc.Add(table);
            doc.Add(FormatConfig.ParaCommonInfo("Ghi chú : ", String.Concat(Enumerable.Repeat("...", 96))));

            doc.Close();
        }
Пример #6
0
        private void ExportFile()
        {
            Global.checkDirSaveFile();
            var             doc       = new Document(PageSize.A4, 20, 20, 10, 10);
            PdfWriter       docWriter = PdfWriter.GetInstance(doc, new FileStream(BHConstant.SAVE_IN_DIRECTORY + @"\CongNo.pdf", FileMode.Create));
            PdfWriterEvents writerEvent;

            Image watermarkImage = Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + @"logo.png");

            watermarkImage.SetAbsolutePosition(doc.PageSize.Width / 2 - 70, 500);
            writerEvent         = new PdfWriterEvents(watermarkImage);
            docWriter.PageEvent = writerEvent;

            doc.Open();
            if (modeReport == 1)
            {
                doc.Add(FormatConfig.ParaRightBeforeHeaderRight(BHConstant.COMPANY_NAME));
                doc.Add(FormatConfig.ParaRightBeforeHeaderRight(BHConstant.COMPANY_ADDRESS));
                doc.Add(FormatConfig.ParaRightBeforeHeaderRight("ĐT: " + BHConstant.COMPANY_PHONE + " Fax: " + BHConstant.COMPANY_FAX));
            }

            doc.Add(FormatConfig.ParaRightBeforeHeader("In ngày : " + BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate().ToString(BHConstant.DATETIME_FORMAT)));
            doc.Add(FormatConfig.ParaHeader("BÁO CÁO CÔNG NỢ"));

            doc.Add(FormatConfig.ParaRightBelowHeader("(" + textForPrint + ")"));
            if (modeReport != 1)
            {
                doc.Add(CustomersTable());
            }
            else
            {
                doc.Add(FormatConfig.ParaCommonInfo("Kính gửi : ", customerPrint.CustomerName));
                doc.Add(FormatConfig.ParaCommonInfo("Địa chỉ : ", customerPrint.Address));
                doc.Add(FormatConfig.ParaCommonInfo("ĐT : ", customerPrint.Phone + " Fax: " + customerPrint.Fax));
                doc.Add(CustomerDetailTable());
            }
            doc.Add(FormatConfig.ParaCommonInfo("", "Quý khách hàng kiểm tra và đối chiếu, nếu có thắc mắc vui lòng liên hệ số điện thoại trên."));
            doc.Add(FormatConfig.ParaCommonInfo("", "Chân thành cảm ơn sự hợp tác của quí khách."));
            doc.Add(FormatConfig.ParaCommonInfo("Ghi chú : ", String.Concat(Enumerable.Repeat("...", 96))));

            doc.Close();
        }
        public string AddSeedID(string prefix)
        {
            DateTime systime = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate();
            SeedID   seed    = SelectSeedIDByWhere(x => x.Prefix == prefix && x.CreateDate.Date == systime.Date)
                               .OrderByDescending(x => x.ID).FirstOrDefault();
            SeedID newseed = new SeedID
            {
                CreateDate = systime,
                Prefix     = prefix
            };
            int max_id = 1;

            if (seed != null)
            {
                max_id = Convert.ToInt32(seed.Value) + 1;
            }
            newseed.Value  = max_id.ToString();
            newseed.Result = newseed.Prefix + newseed.CreateDate.Date.ToString("ddMMyy") +
                             String.Concat(Enumerable.Repeat("0", BHConstant.MAX_ID - max_id.ToString().Length)) + max_id.ToString();
            OnAddItem <SeedID>(newseed);
            return(newseed.Result);
        }
Пример #8
0
 private void loadSomeData()
 {
     if (customers == null)
     {
         CustomerService customerService = new CustomerService();
         customers = customerService.GetCustomers().OrderBy(x => x.CustCode).ToList();
         customers.Insert(0, new Customer()
         {
             Id = 0, CustCode = "", CustomerName = ""
         });
     }
     if (customers != null)
     {
         cbxCustomer.AutoCompleteMode   = AutoCompleteMode.SuggestAppend;
         cbxCustomer.AutoCompleteSource = AutoCompleteSource.ListItems;
         cbxCustomer.DataSource         = customers;
         cbxCustomer.DisplayMember      = "CustCode";
         cbxCustomer.ValueMember        = "Id";
     }
     if (bill != null)
     {
         txtAmount.Text            = Global.formatVNDCurrencyText(bill.Amount.ToString());
         txtAmount.Enabled         = false;
         txtCreatedDate.Text       = bill.CreatedDate.ToString(BHConstant.DATE_FORMAT);
         txtNote.Text              = bill.Note;
         txtOrderCode.Text         = bill.BillCode;
         cbxCustomer.SelectedValue = bill.CustId;
         cbxCustomer.Enabled       = false;
         btnSave.Text              = "OK";
     }
     else
     {
         txtCreatedDate.Text = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate().ToString(BHConstant.DATE_FORMAT);
         txtOrderCode.Text   = Global.GetTempSeedID(BHConstant.PREFIX_FOR_BILLING);
     }
     txtCreatedDate.Enabled = false;
 }
Пример #9
0
        public static string GetTempSeedID(string prefix)
        {
            string result = prefix + BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate().ToString("ddMMyy") + "----";

            return(result);
        }
Пример #10
0
        private void DeleteOrder(DataGridViewCellEventArgs e)
        {
            DialogResult result = MessageBox.Show("Bạn muốn xóa đơn hàng này?", "Xoá đơn hàng", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                DataGridViewRow currentRow = dgwOrderList.Rows[e.RowIndex];

                OrderService orderService = new OrderService();
                int          id           = ObjectHelper.GetValueFromAnonymousType <int>(currentRow.DataBoundItem, "Id");
                Order        order        = orderService.GetOrder(id);
                DateTime     systime      = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate();

                #region CustomerLog

                CustomerLogService cls = new CustomerLogService();
                CustomerLog        cl  = cls.GetCustomerLog(order.OrderCode);
                bool kq = true;
                if (cl != null)
                {
                    kq = cls.DeleteCustomerLog(cl.Id);
                }

                #endregion

                #region ProductLog

                ProductLogService  productLogService = new ProductLogService();
                OrderDetailService orderDetailService = new OrderDetailService();
                List <OrderDetail> details = orderDetailService.SelectOrderDetailByWhere(x => x.OrderId == order.Id).ToList();
                ProductLog         pl, newpl;
                foreach (OrderDetail item in details)
                {
                    pl    = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                    newpl = new ProductLog()
                    {
                        ProductId    = item.ProductId,
                        AttributeId  = item.AttributeId,
                        UnitId       = item.UnitId,
                        BeforeNumber = pl.AfterNumber,
                        Amount       = item.NumberUnit,
                        AfterNumber  = pl.AfterNumber + item.NumberUnit,
                        RecordCode   = order.OrderCode,
                        Status       = BHConstant.DEACTIVE_STATUS,
                        Direction    = BHConstant.DIRECTION_IN,
                        UpdatedDate  = systime
                    };
                    productLogService.AddProductLog(newpl);
                }
                productLogService.DeactiveProductLog(order.OrderCode);

                #endregion

                #region EmployeeLog

                int salerId = (int)order.Customer.SalerId;
                if (salerId > 0)
                {
                    EmployeeLogService els      = new EmployeeLogService();
                    EmployeeLog        order_el = els.SelectEmployeeLogByWhere(x => x.RecordCode == order.OrderCode).FirstOrDefault();
                    if (order_el != null)
                    {
                        els.DeleteEmployeeLog(order_el.Id);
                    }
                }

                #endregion

                if (!orderService.DeleteOrder(id) && kq)
                {
                    MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                loadOrderList();
            }
        }
Пример #11
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (validator1.Validate() && cbxCustomer.SelectedValue != null && cbxCustomer.SelectedIndex > 0)
            {
                BillService billService = new BillService();
                if (bill == null)
                {
                    double amount    = 0;
                    string amountStr = string.IsNullOrEmpty(txtAmount.WorkingText) ? txtAmount.Text : txtAmount.WorkingText;
                    double.TryParse(amountStr, out amount);
                    DateTime systime = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate();
                    int      userId  = 0;
                    if (Global.CurrentUser != null)
                    {
                        userId = Global.CurrentUser.Id;
                    }
                    else
                    {
                        MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    SeedService ss = new SeedService();
                    bill = new Bill
                    {
                        BillCode    = ss.AddSeedID(BHConstant.PREFIX_FOR_BILLING),
                        Note        = txtNote.Text,
                        CreatedDate = systime,
                        Amount      = amount,
                        CustId      = cbxCustomer.SelectedValue != null ? (int)cbxCustomer.SelectedValue : 0,
                        UserId      = userId
                    };

                    bool result            = billService.AddBill(bill);
                    CustomerLogService cls = new CustomerLogService();
                    CustomerLog        cl  = new CustomerLog
                    {
                        CustomerId  = bill.CustId,
                        RecordCode  = bill.BillCode,
                        Amount      = bill.Amount,
                        Direction   = BHConstant.DIRECTION_IN,
                        CreatedDate = systime
                    };
                    result = cls.AddCustomerLog(cl);
                    if (result)
                    {
                        MessageBox.Show("Phiếu thanh toán đã được thêm!");
                    }
                    else
                    {
                        MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                if (this.CallFromUserControll != null && this.CallFromUserControll is BillList)
                {
                    ((BillList)this.CallFromUserControll).loadBillList();
                }
                this.Close();
                return;
            }
            MessageBox.Show("Vui lòng kiểm tra các thông tin cần thiết!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }
Пример #12
0
        private void dgwRequestList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (sender is DataGridView)
            {
                DataGridViewCell cell = ((DataGridView)sender).CurrentCell;
                if (cell.ColumnIndex == ((DataGridView)sender).ColumnCount - 1)
                {
                    DialogResult result = MessageBox.Show("Bạn có muốn xóa phiếu sản xuât này?",
                                                          "Xoá phiếu sản xuât",
                                                          MessageBoxButtons.YesNo,
                                                          MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        DataGridViewRow currentRow = dgwRequestList.Rows[e.RowIndex];

                        ProductionRequestService       productionRequestService       = new ProductionRequestService();
                        ProductionRequestDetailService productionRequestDetailService = new ProductionRequestDetailService();
                        int id = ObjectHelper.GetValueFromAnonymousType <int>(currentRow.DataBoundItem, "Id");
                        ProductionRequest pr = productionRequestService.GetProductionRequest(id);
                        List <ProductionRequestDetail> productionRequestDetails = productionRequestDetailService.GetProductionRequestDetails().Where(p => p.ProductionRequestId == id).ToList();
                        bool     ret     = false;
                        DateTime systime = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate();

                        ProductLogService productLogService = new ProductLogService();
                        string            msg = "";
                        int        error = 0, amount = 0;
                        ProductLog pl, newpl;
                        foreach (ProductionRequestDetail item in productionRequestDetails)
                        {
                            pl     = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            amount = (item.Direction == BHConstant.DIRECTION_OUT) ? -item.NumberUnit : item.NumberUnit;
                            if (pl.AfterNumber - amount < 0)
                            {
                                if (error == 0)
                                {
                                    msg  += "Những sản phẩm sau đã bị XÓA nhưng không đảm bảo dữ liệu trong kho:\n";
                                    error = 1;
                                }
                                msg += "- " + productLogService.GetNameOfProductLog(pl) + " : " + item.NumberUnit + "\n";
                            }
                        }
                        if (error > 0)
                        {
                            MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        foreach (ProductionRequestDetail item in productionRequestDetails)
                        {
                            pl     = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            amount = (item.Direction == BHConstant.DIRECTION_OUT) ? -item.NumberUnit : item.NumberUnit;
                            newpl  = new ProductLog()
                            {
                                ProductId    = item.ProductId,
                                AttributeId  = item.AttributeId,
                                UnitId       = item.UnitId,
                                BeforeNumber = pl.AfterNumber,
                                Amount       = item.NumberUnit,
                                AfterNumber  = pl.AfterNumber - amount,
                                RecordCode   = pr.ReqCode,
                                Status       = BHConstant.DEACTIVE_STATUS,
                                Direction    = !item.Direction,
                                UpdatedDate  = systime
                            };
                            productLogService.AddProductLog(newpl);
                        }
                        productLogService.DeactiveProductLog(pr.ReqCode);
                        if (!productionRequestService.DeleteProductionRequest(id))
                        {
                            MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        loadProductionRequestList();
                    }
                }
            }
        }
Пример #13
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.validator1.Validate() && ValidateData())
            {
                DateTime systime = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate();
                int      userId  = 0;
                if (Global.CurrentUser != null)
                {
                    userId = Global.CurrentUser.Id;
                }
                else
                {
                    MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (entranceStock != null && isUpdating)//update
                {
                    #region Fix Update

                    string              msg = "";
                    int                 error = 0, amount_change = 0;
                    ProductLog          pl, newpl;
                    EntranceStockDetail esd;
                    // Check update old data
                    List <EntranceStockDetail> deleted_details = old_details.Where(x => !entranceStockDetails.Select(y => y.ProductId.ToString() + '_' +
                                                                                                                     y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                                                                                                                                                                                    x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                    foreach (EntranceStockDetail item in deleted_details)
                    {
                        pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                        if (pl.AfterNumber - item.NumberUnit < 0)
                        {
                            if (error == 0)
                            {
                                msg  += "Những sản phẩm sau đã bị XÓA nhưng không đảm bảo dữ liệu trong kho:\n";
                                error = 1;
                            }
                            msg += "- " + productLogService.GetNameOfProductLog(pl) + " : " + item.NumberUnit + "\n";
                        }
                    }

                    List <EntranceStockDetail> updated_details = old_details.Where(x => entranceStockDetails.Select(y => y.ProductId.ToString() + '_' +
                                                                                                                    y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                                                                                                                                                                                   x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                    foreach (EntranceStockDetail item in updated_details)
                    {
                        pl  = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                        esd = entranceStockDetails.Where(x => x.ProductId == item.ProductId && x.AttributeId == item.AttributeId &&
                                                         x.UnitId == item.UnitId).FirstOrDefault();
                        amount_change = Convert.ToInt32(esd.NumberUnit - item.NumberUnit);
                        if (amount_change < 0 && pl.AfterNumber + amount_change < 0) // Giam so luong nhap
                        {
                            if (error < 2)
                            {
                                msg  += "Những sản phẩm sau đã bị SỬA nhưng không đảm bảo dữ liệu trong kho:\n";
                                error = 2;
                            }
                            msg += "- " + productLogService.GetNameOfProductLog(pl) + " : " + amount_change.ToString() + "\n";
                        }
                    }

                    if (error > 0)
                    {
                        MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    try
                    {
                        entranceStock.UserId      = userId;
                        entranceStock.Note        = txtNote.Text;
                        entranceStock.UpdatedDate = systime;

                        EntranceStockDetailService entranceStockDetailService = new EntranceStockDetailService();
                        foreach (EntranceStockDetail item in deleted_details)
                        {
                            pl    = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            newpl = new ProductLog()
                            {
                                ProductId    = item.ProductId,
                                AttributeId  = item.AttributeId,
                                UnitId       = item.UnitId,
                                BeforeNumber = pl.AfterNumber,
                                Amount       = item.NumberUnit,
                                AfterNumber  = pl.AfterNumber - item.NumberUnit,
                                RecordCode   = entranceStock.EntranceCode,
                                Status       = BHConstant.ACTIVE_STATUS,
                                Direction    = BHConstant.DIRECTION_OUT,
                                UpdatedDate  = systime
                            };
                            productLogService.AddProductLog(newpl);
                        }
                        foreach (EntranceStockDetail od in entranceStockDetails)
                        {
                            od.EntranceStockId = entranceStock.Id;
                            if (od.ProductId > 0 && od.AttributeId > 0 && od.UnitId > 0)
                            {
                                EntranceStockDetail tmp_ode = old_details.Where(x => x.ProductId == od.ProductId &&
                                                                                x.AttributeId == od.AttributeId && x.UnitId == od.UnitId && x.EntranceStockId == entranceStock.Id).FirstOrDefault();
                                if (tmp_ode != null)
                                {
                                    double amount = od.NumberUnit - tmp_ode.NumberUnit;
                                    entranceStockDetailService.UpdateEntranceStockDetail(od);
                                    //Save in Production Log
                                    if (amount != 0)
                                    {
                                        pl    = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                        newpl = new ProductLog()
                                        {
                                            ProductId    = od.ProductId,
                                            AttributeId  = od.AttributeId,
                                            UnitId       = od.UnitId,
                                            BeforeNumber = pl.AfterNumber,
                                            Amount       = Math.Abs(amount),
                                            AfterNumber  = pl.AfterNumber + amount,
                                            RecordCode   = entranceStock.EntranceCode,
                                            Status       = BHConstant.ACTIVE_STATUS,
                                            Direction    = amount > 0 ? BHConstant.DIRECTION_IN : BHConstant.DIRECTION_OUT,
                                            UpdatedDate  = systime
                                        };
                                        productLogService.AddProductLog(newpl);
                                    }
                                }
                                else
                                {
                                    bool ret = (od.Id != null && od.Id > 0) ? entranceStockDetailService.UpdateEntranceStockDetail(od)
                                        : entranceStockDetailService.AddEntranceStockDetail(od);
                                    //Save in Production Log
                                    pl    = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                    newpl = new ProductLog()
                                    {
                                        ProductId    = od.ProductId,
                                        AttributeId  = od.AttributeId,
                                        UnitId       = od.UnitId,
                                        BeforeNumber = pl.AfterNumber,
                                        Amount       = od.NumberUnit,
                                        AfterNumber  = pl.AfterNumber + od.NumberUnit,
                                        RecordCode   = entranceStock.EntranceCode,
                                        Status       = BHConstant.ACTIVE_STATUS,
                                        Direction    = BHConstant.DIRECTION_IN,
                                        UpdatedDate  = systime
                                    };
                                    productLogService.AddProductLog(newpl);
                                }
                            }
                        }

                        EntranceStockService entranceStockService = new EntranceStockService();
                        bool result = entranceStockService.UpdateEntranceStock(entranceStock);

                        if (result)
                        {
                            MessageBox.Show("Phiếu nhập kho đã được cập nhật thành công");
                        }
                        else
                        {
                            MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        this.Close();
                    }
                    catch { }
                    #endregion
                }
                else//add new
                {
                    #region New

                    SeedService ss = new SeedService();
                    entranceStock = new EntranceStock
                    {
                        EntranceCode = ss.AddSeedID(BHConstant.PREFIX_FOR_ENTRANCE),
                        UserId       = userId,
                        CreatedDate  = systime,
                        Note         = txtNote.Text
                    };
                    EntranceStockService entranceStockService = new EntranceStockService();
                    bool result     = entranceStockService.AddEntranceStock(entranceStock);
                    long newOrderId = BaoHienRepository.GetMaxId <EntranceStock>();
                    EntranceStockDetailService entranceStockDetailService = new EntranceStockDetailService();
                    foreach (EntranceStockDetail od in entranceStockDetails)
                    {
                        if (od.ProductId > 0 && od.AttributeId > 0 && od.UnitId > 0)
                        {
                            od.EntranceStockId = (int)newOrderId;
                            bool ret = entranceStockDetailService.AddEntranceStockDetail(od);
                            if (!ret)
                            {
                                MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }

                            //Save in Product Log
                            ProductLog pl    = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                            ProductLog newpl = new ProductLog()
                            {
                                ProductId    = od.ProductId,
                                AttributeId  = od.AttributeId,
                                UnitId       = od.UnitId,
                                BeforeNumber = pl.AfterNumber,
                                Amount       = od.NumberUnit,
                                AfterNumber  = pl.AfterNumber + od.NumberUnit,
                                RecordCode   = entranceStock.EntranceCode,
                                Status       = BHConstant.ACTIVE_STATUS,
                                Direction    = BHConstant.DIRECTION_IN,
                                UpdatedDate  = systime
                            };
                            productLogService.AddProductLog(newpl);
                        }
                    }
                    if (result)
                    {
                        MessageBox.Show("Phiếu nhập kho đã được tạo thành công");
                    }
                    else
                    {
                        MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    this.Close();

                    #endregion
                }
            }
        }
        private void dgwStockEntranceList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (sender is DataGridView)
            {
                DataGridViewCell cell = ((DataGridView)sender).CurrentCell;
                if (cell.ColumnIndex == ((DataGridView)sender).ColumnCount - 1)
                {
                    DialogResult result = MessageBox.Show("Bạn có muốn xóa phiếu nhập kho này?",
                                                          "Xoá phiếu nhập kho",
                                                          MessageBoxButtons.YesNo,
                                                          MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        DateTime        systime    = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate();
                        DataGridViewRow currentRow = dgwStockEntranceList.Rows[e.RowIndex];

                        EntranceStockService entranceStockService = new EntranceStockService();
                        int           id = ObjectHelper.GetValueFromAnonymousType <int>(currentRow.DataBoundItem, "Id");
                        EntranceStock es = entranceStockService.GetEntranceStock(id);

                        ProductLogService          productLogService          = new ProductLogService();
                        EntranceStockDetailService entranceStockDetailService = new EntranceStockDetailService();
                        List <EntranceStockDetail> details = entranceStockDetailService.SelectEntranceStockDetailByWhere(x => x.EntranceStockId == es.Id).ToList();
                        string     msg = "";
                        int        error = 0;
                        ProductLog pl, newpl;
                        foreach (EntranceStockDetail item in details)
                        {
                            pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            if (pl.AfterNumber - item.NumberUnit < 0)
                            {
                                if (error == 0)
                                {
                                    msg  += "Những sản phẩm sau đã bị XÓA nhưng không đảm bảo dữ liệu trong kho:\n";
                                    error = 1;
                                }
                                msg += "- " + productLogService.GetNameOfProductLog(pl) + " : " + item.NumberUnit + "\n";
                            }
                        }
                        if (error > 0)
                        {
                            MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        try
                        {
                            foreach (EntranceStockDetail item in details)
                            {
                                pl    = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                                newpl = new ProductLog()
                                {
                                    ProductId    = item.ProductId,
                                    AttributeId  = item.AttributeId,
                                    UnitId       = item.UnitId,
                                    BeforeNumber = pl.AfterNumber,
                                    Amount       = item.NumberUnit,
                                    AfterNumber  = pl.AfterNumber - item.NumberUnit,
                                    RecordCode   = es.EntranceCode,
                                    Status       = BHConstant.DEACTIVE_STATUS,
                                    Direction    = BHConstant.DIRECTION_OUT,
                                    UpdatedDate  = systime
                                };
                                productLogService.AddProductLog(newpl);
                            }
                            productLogService.DeactiveProductLog(es.EntranceCode);
                            if (!entranceStockService.DeleteEntranceStock(id))
                            {
                                MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        catch { }
                        loadEntranceStockList();
                    }
                }
            }
        }