public void NotifyNewMultiDepartmentStockOut(Department department, DepartmentStockOut[] list, DepartmentPrice price)
        {
            if (CurrentDepartment.Get().DepartmentId != department.DepartmentId)
            {
                return;
            }

            IsDoingStockOut = true;
            ((MainForm)GlobalCache.Instance().MainForm).ServiceStatus.Text = " Đang nhận thông tin ...";

                ClientUtility.Log(logger, department.DepartmentId + " dang nhan hang.");
                foreach (DepartmentStockOut stockOut in list)
                {
                    try
                    {
                    DepartmentStockInHistoryPK departmentStockInHistoryPk = new DepartmentStockInHistoryPK
                    {
                        SourceDepartmentId = stockOut.DepartmentStockOutPK.DepartmentId,
                        DestDepartmentId = CurrentDepartment.Get().DepartmentId,
                        StockOutId = stockOut.DepartmentStockOutPK.StockOutId
                    };

                    ObjectCriteria deptHistCrit = new ObjectCriteria();
                    deptHistCrit.AddEqCriteria("DepartmentStockInHistoryPK.SourceDepartmentId", stockOut.DepartmentStockOutPK.DepartmentId);
                    deptHistCrit.AddEqCriteria("DepartmentStockInHistoryPK.StockOutId", stockOut.DepartmentStockOutPK.StockOutId);
                    deptHistCrit.AddEqCriteria("DepartmentStockInHistoryPK.DestDepartmentId", department.DepartmentId);

                    IList deptHistList = DepartmentStockInHistoryLogic.FindAll(deptHistCrit);
                    // if it has exist in history so don't need to continue
                    if (deptHistList != null && deptHistList.Count > 0)
                    {
                        continue;
                    }

                    DepartmentStockIn stockIn;
                    // convert from stock out to stock in
                    stockIn = new FastDepartmentStockInMapper().Convert(stockOut);
                    // call method to sync
                    LogicResult logicResult = DepartmentStockInLogic.SyncFromSubStock(stockIn);
                    if (logicResult.HasError)
                    {
                        if (logicResult.Messages != null)
                        {
                            foreach (string message in logicResult.Messages)
                            {
                                ClientUtility.Log(logger, message);
                            }
                        }
                        serverService.InformDepartmentStockOutFail(stockOut.DepartmentStockOutPK.DepartmentId,
                                                                      stockOut.OtherDepartmentId,
                                                                      stockOut.DepartmentStockOutPK.StockOutId);
                    }
                    else
                    {
                        ClientUtility.Log(logger,
                                          " Hoan tat va phan hoi ... " +
                                          stockOut.DepartmentStockOutPK.DepartmentId.ToString());

                        // add to stock in history for avoiding duplicate
                        departmentStockInHistoryPk.StockInId = stockIn.DepartmentStockInPK.StockInId;
                        DepartmentStockInHistory departmentStockInHistory = new DepartmentStockInHistory();
                        departmentStockInHistory.DepartmentStockInHistoryPK = departmentStockInHistoryPk;
                        departmentStockInHistory.Description = stockIn.ToString();
                        departmentStockInHistory.CreateDate = DateTime.Now;
                        departmentStockInHistory.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                        departmentStockInHistory.UpdateDate = DateTime.Now;
                        departmentStockInHistory.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                        DepartmentStockInHistoryLogic.Add(departmentStockInHistory);

                        serverService.InformDepartmentStockOutSuccess(stockOut.DepartmentStockOutPK.DepartmentId,
                                                                      stockOut.OtherDepartmentId,
                                                                      stockOut.DepartmentStockOutPK.StockOutId);
                        ((MainForm) GlobalCache.Instance().MainForm).ServiceStatus.Text = " Hoàn tất ! ";
                        ClientUtility.Log(logger, " Hoan tat!");
                    }
                    }
                    catch (Exception exp)
                    {
                        ClientUtility.Log(logger, exp.Message);
                    }
                }
            IsDoingStockOut = false;
        }
 /// <summary>
 /// Delete DepartmentStockOut from database.
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public void Delete(DepartmentStockOut data)
 {
     HibernateTemplate.Delete(data);
 }
        private void btnAddProduct_Click(object sender, EventArgs e)
        {
            // create DepartmentStockIn
            if (deptSO == null)
            {
                deptSO = new DepartmentStockOut();
            }
            deptSO.CreateDate = DateTime.Now;
            deptSO.UpdateDate = DateTime.Now;
            deptSO.CreateId = ClientInfo.getInstance().LoggedUser.Name;
            deptSO.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
            deptSO.ExclusiveKey = 0;
            //            int maxAddedItemsCount = int.Parse(numericUpDown.Text);
            //            for (int i = 0; i < maxAddedItemsCount; i++)
            //            {
            //                StockInDetail deptSIDet = CreateNewStockInDetail();
            //
            //            }

            deptSO.DepartmentStockOutDetails =
                ObjectConverter.ConvertToNonGenericList<DepartmentStockOutDetail>(deptSODetailList);
            bdsStockIn.EndEdit();

            //            for (int j = 0; j < maxAddedItemsCount; j++)
            //            {
            //                for (int i = 0; i <= SELL_PRICE_POS; i++)
            //                {
            //                    dgvDeptStockIn[i, deptSODetailList.Count - j - 1].ReadOnly = false;
            //                }
            //            }
        }
 private void button3_Click(object sender, EventArgs e)
 {
     deptSO = new DepartmentStockOut();
     deptSODetailList.Clear();
     //            txtDexcription.Text = "";
     //            txtPriceIn.Text = "";
     //            txtPriceOut.Text = "";
     txtSumProduct.Text = "";
     txtSumValue.Text = "";
     ClearSelectionOnListBox(lstColor);
     ClearSelectionOnListBox(lstSize);
     cboProductMasters.Text = "";
 }
 public void Delete(DepartmentStockOut data)
 {
     DepartmentStockOutDAO.Delete(data);
 }
 public void Update(DepartmentStockOut data)
 {
     DepartmentStockOutDAO.Update(data);
 }
        private void DepartmentStockInExtra_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'masterDB.Department' table. You can move, or remove it, as needed.
            this.departmentTableAdapter.Fill(this.masterDB.Department);
            IList list = new ArrayList();
            if (ClientSetting.IsSubStock())
            {
                list.Add(new StockDefectStatus {DefectStatusId = 7, DefectStatusName = "Xuất đi cửa hàng khác"});
                cboDepartment.Visible = true;
                label2.Visible = true;
            }
            /*else
            {*/
            list.Add(new StockDefectStatus { DefectStatusId = 4, DefectStatusName = "Xuất tạm để sửa hàng" });
            list.Add(new StockDefectStatus { DefectStatusId = 6, DefectStatusName = "Xuất trả về kho chính" });
            list.Add(new StockDefectStatus { DefectStatusId = 9, DefectStatusName = "Xuất hàng mẫu" });

            /*}*/

            cbbStockOutType.DataSource = list;
            cbbStockOutType.DisplayMember = "DefectStatusName";

            deptSODetailList = new DepartmentStockOutDetailCollection(bdsStockIn);
            bdsStockIn.DataSource = deptSODetailList;
            dgvDeptStockIn.DataError += new DataGridViewDataErrorEventHandler(dgvDeptStockIn_DataError);

            // create DepartmentStockIn
            if (deptSO == null)
            {
                deptSO = new DepartmentStockOut();
                deptSO.CreateDate = DateTime.Now;
                deptSO.UpdateDate = DateTime.Now;
                deptSO.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                deptSO.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                deptSO.ExclusiveKey = 0;
                CreateNewStockInDetail();
                //                btnBarcode.Visible = false;
                //                numericUpDownBarcode.Visible = false;
                //                btnPreview.Visible = false;
                // load products to extra combo box
                LoadProductMasterToComboBox();
                deptSODetailList.RemoveAt(0);
                bdsStockIn.EndEdit();

            }
            else
            {
                //                btnBarcode.Visible = true;
                //                numericUpDownBarcode.Visible = true;
                //                btnPreview.Visible = true;
                IList deptStockInDetails = deptSO.DepartmentStockOutDetails;
                foreach (DepartmentStockOutDetail detail in deptStockInDetails)
                {
                    if (detail.DelFlg == CommonConstants.DEL_FLG_NO)
                    {
                        deptSODetailList.Add(detail);
                        //detail.OldQuantity = detail.Quantity;
                    }
                }

                for (int i = 0; i < dgvDeptStockIn.Columns.Count; i++)
                {
                    dgvDeptStockIn.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                    if (i != QUANTITY_POS
                            && i != PRICE_POS
                            && i != SELL_PRICE_POS)
                    {
                        dgvDeptStockIn.Columns[i].ReadOnly = true;
                    }
                }
                //                txtDexcription.Text = deptSO.Description;
            }
            deptSO.DepartmentStockOutDetails =
                    ObjectConverter.ConvertToNonGenericList<DepartmentStockOutDetail>(deptSODetailList);

            departmentBindingSource.Filter = " DEPARTMENT_ID <> " + CurrentDepartment.Get().DepartmentId;
            departmentTableAdapter.Fill(masterDB.Department);
            departmentBindingSource.ResetBindings(false);
            cboDepartment.Refresh();
            cboDepartment.Invalidate();
        }
示例#8
0
        private bool DoStockOut(DataAccessLayer dal, Department department,DepartmentStockOut stockOut,bool negativeStock)
        {
            // check stock before insert
            foreach (DepartmentStockOutDetail outDetail in stockOut.DepartmentStockOutDetails)
            {
                // stock
                var id = dal.GetSingleValue("Select product_id from department_stock where product_id ='" + outDetail.Product.ProductId+"'");
                if (id == null || id.ToString() == string.Empty)
                {
                    // ERROR
                    throw new BusinessException("Khong co ma hang " + outDetail.Product.ProductId + "trong kho cua hang !");
                }
                else
                {
                    if (!negativeStock)
                    {
                        var varQty =
                            dal.GetSingleValue("Select good_quantity from department_stock where product_id ='" +
                                               outDetail.Product.ProductId + "'");
                        long goodQty = 0;
                        Int64.TryParse(varQty.ToString(), out goodQty);
                        long remainGoodQty = goodQty - outDetail.Quantity;
                        if (remainGoodQty < 0)
                        {
                            throw new BusinessException(outDetail.Product.ProductId +
                                                        " không còn đủ số lượng trong kho.");
                        }
                    }
                }

            }
            // get max stock in id

            var selectMaxIdSQL = " select max(stock_out_id) from department_stock_out";
            var maxId = dal.GetSingleValue(selectMaxIdSQL);
            var stockOutId = (maxId == null || maxId.ToString() == string.Empty ) ? 1 : Int64.Parse(maxId.ToString()) + 1;

            var selectMaxDetIdSQL = " select max(stock_out_detail_id) from department_stock_out_detail";
            var maxDetId = dal.GetSingleValue(selectMaxDetIdSQL);
            var stockOutDetId = (maxDetId == null || maxDetId.ToString() == string.Empty) ? 1 : Int64.Parse(maxDetId.ToString()) + 1;

            string insertStockOut = " insert into department_stock_out(department_id," +
                                   "stock_out_id," +
                                   "stock_out_date," +
                                   "description," +
                                   "defect_status_id," +
                                   "confirm_flg," +
                                   "other_department_id," +
                                   "create_date," +
                                   "create_id," +
                                   "update_date," +
                                   "update_id," +
                                   "del_flg," +
                                   "exclusive_key) " +
                                   " values(" + // values
                                   department.DepartmentId + "," +
                                   "'" + stockOutId + "'," +
                                   "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," +
                                   "' Xuat hang ve kho phu ' " + "," +
                                   7 + "," +
                                   0 + "," +
                                   stockOut.DepartmentStockOutPK.DepartmentId + "," +
                                   "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," +
                                   "'admin'," +
                                   "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," +
                                   "'admin'," +
                                   "0," +
                                   "1)";
            // insert department-stock-in
            ServerUtility.Log(logger,insertStockOut);
            dal.ExecuteQuery(insertStockOut);
            // insert department-stock-in-details
            foreach (DepartmentStockOutDetail outDetail in stockOut.DepartmentStockOutDetails)
            {
                //ProcessStockInDetail(inDetail, dalSalePoint);

                // insert department-stock-in-detail
                string insertStockOutDetail =
                    "insert into department_stock_out_detail(stock_out_detail_id," +
                    "department_id," +
                    "stock_out_id," +
                    "product_id," +
                    "product_master_id," +
                    "quantity," +
                    " good_quantity," +
                    " del_flg," +
                    "create_id," +
                    "create_date," +
                    "update_id," +
                    "update_date) " +
                    " values(" + // values
                    stockOutDetId + "," +
                    department.DepartmentId + "," +
                    stockOutId + ",'" +
                    outDetail.Product.ProductId + "','" +
                    outDetail.Product.ProductMaster.ProductMasterId + "'," +
                    outDetail.Quantity + "," +
                    outDetail.Quantity + "," +
                    "0," +
                    "'admin'," +
                    "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," +
                    "'admin'," +
                    "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')";
                ServerUtility.Log(logger,insertStockOutDetail);
                dal.ExecuteQuery(insertStockOutDetail);
                stockOutDetId += 1;
                // insert department-stock
                //string insertStock = "insert into stock(stock_id,product_id,product_master_id,quantity,create_date,good_quantity,create_id,del_flg) values(18854,'001419317H01','0000000014193',1,'2009-07-27 00:00:00',1,'admin',0)";
                // stock
                dal.ExecuteQuery(" update department_stock "
                              + " set quantity = quantity - " + outDetail.Quantity + " , "
                              + " good_quantity = good_quantity - " + outDetail.Quantity + " "
                              + " where product_id = '" + outDetail.Product.ProductId + "' "
                              + " and department_id = " + department.DepartmentId);

            }

            return true;
        }
示例#9
0
        public void NotifyRequestDepartmentStockOut(long departmentId)
        {
            //ClientUtility.Log(logger, departmentId + " requesting stock-out information.");
            if(serverService == null)
            {
                return;
            }
            ((MainForm)GlobalCache.Instance().MainForm).ServiceStatus.Text = " Đang nhận thông tin ...";
            ObjectCriteria objectCriteria = new ObjectCriteria();
            objectCriteria.AddEqCriteria("OtherDepartmentId", departmentId);
            objectCriteria.AddEqCriteria("ConfirmFlg", (long)3);

            IList list = DepartmentStockOutLogic.FindAll(objectCriteria);
            Department destDept  = new Department
                                       {
                                           DepartmentId = departmentId
                                       } ;
            if(list!= null && list.Count > 0 )
            {
                ClientUtility.Log(logger, " Co " + list.Count + " phieu xuat hang ve " + departmentId);
                ((MainForm)GlobalCache.Instance().MainForm).ServiceStatus.Text = " Gửi thông tin ...";
                foreach (DepartmentStockOut departmentStockOut in list)
                {
                    foreach (DepartmentStockOutDetail detail in departmentStockOut.DepartmentStockOutDetails)
                    {
                        string prdMasterId = detail.Product.ProductMaster.ProductMasterId;
                        DepartmentPricePK pricePk = new DepartmentPricePK
                        {
                            DepartmentId = 0,
                            ProductMasterId = prdMasterId
                        };
                        detail.DepartmentPrice = DepartmentPriceLogic.FindById(pricePk);
                    }
                }
                DepartmentStockOut[] array = new DepartmentStockOut[list.Count];
                int i = 0;
                foreach (DepartmentStockOut @out in list)
                {
                    array[i] = @out;
                    i++;
                }
                serverService.MakeMultiDepartmentStockOut(destDept,array, new DepartmentPrice());
                ClientUtility.Log(logger, departmentId + " da duoc gui thong tin xuat hang.");
            }
        }
 private void btnAddProduct_Click(object sender, EventArgs e)
 {
     // create DepartmentStockIn
     if (deptSO == null)
     {
         deptSO = new DepartmentStockOut();
     }
     deptSO.CreateDate = DateTime.Now;
     deptSO.UpdateDate = DateTime.Now;
     deptSO.CreateId = ClientInfo.getInstance().LoggedUser.Name;
     deptSO.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
     deptSO.ExclusiveKey = 0;
 }
示例#11
0
 public void NotifyNewDepartmentStockOut(Department department, DepartmentStockOut stockOut, DepartmentPrice price)
 {
     // don't need to implement
 }
        public void Sync(SyncFromMainToDepartment syncFromMainToDepartment)
        {
            IList prdMasterUpdateList = new ArrayList();
            IList needUpdateStocks = new ArrayList();
            IList needAddNewStocks = new ArrayList();
            // fix departmentStock first

            IList deptStockTemps = syncFromMainToDepartment.DepartmentStockTemps;
            if (deptStockTemps != null && deptStockTemps.Count > 0)
            {
                DepartmentStockOut deptStockOut = new DepartmentStockOut();
                object maxDSOId = DepartmentStockOutDAO.SelectSpecificType(null,
                                                                           Projections.Max(
                                                                               "DepartmentStockOutPK.StockOutId"));
                long maxDeptStockOutId = (maxDSOId != null ? (long) maxDSOId + 1 : 1);

                object maxDetId = DepartmentStockOutDetailDAO.SelectSpecificType(null,
                                                                                 Projections.Max("DepartmentStockOutDetailPK.StockOutDetailId"));
                long maxDeptStockOutDetId = (maxDetId != null ? (long) maxDetId + 1 : 1);
                deptStockOut.DepartmentStockOutPK = new DepartmentStockOutPK
                                                        {
                                                            DepartmentId = CurrentDepartment.Get().DepartmentId,
                                                            StockOutId = maxDeptStockOutId

                                                        };
                deptStockOut.DefectStatus = new StockDefectStatus {DefectStatusId = 5}; // xuat tra ve nha san xuat
                deptStockOut.ConfirmFlg = 1; // can xac nhan tu kho chinh

                deptStockOut.StockOutDate = DateTime.Now;
                deptStockOut.CreateDate = DateTime.Now;
                deptStockOut.UpdateDate = DateTime.Now;
                deptStockOut.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                deptStockOut.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                deptStockOut.DepartmentStockOutDetails = new ArrayList();
                foreach (DepartmentStockTemp deptStockTemp in deptStockTemps)
                {

                    // find the stock checking
                    DepartmentStockTemp processedDeptStockTemp =
                    DepartmentStockTempDAO.FindById(deptStockTemp.DepartmentStockTempPK);

                    // if exist, then check whether was it processed.
                    if(processedDeptStockTemp!=null)
                    {
                        // if processed
                        if(processedDeptStockTemp.Fixed == 1)
                        {
                            continue; // process to next stock checking row
                        }
                    }
                    else // not exist, maybe error ..
                    {
                        continue; // process to next stock checking row
                    }

                    long realQty = deptStockTemp.GoodQuantity + deptStockTemp.ErrorQuantity +
                                   deptStockTemp.DamageQuantity +
                                   deptStockTemp.LostQuantity + deptStockTemp.UnconfirmQuantity;
                    if (realQty < deptStockTemp.Quantity)
                    {
                        long returnToStockQty = deptStockTemp.Quantity - realQty;
                        DepartmentStockOutDetail deptSODet = new DepartmentStockOutDetail();
                        deptSODet.DepartmentStockOutDetailPK = new DepartmentStockOutDetailPK();
                        deptSODet.DepartmentStockOutDetailPK.DepartmentId = CurrentDepartment.Get().DepartmentId;
                        deptSODet.DepartmentStockOutDetailPK.StockOutDetailId = maxDeptStockOutDetId++;
                        /*deptSODet.StockOutDetailId = maxDeptStockOutDetId++;*/
                        deptSODet.Product = deptStockTemp.Product;
                        deptSODet.ProductMaster = deptStockTemp.ProductMaster;
                        deptSODet.DepartmentStockOut = deptStockOut;
                        deptSODet.Description = "Số liệu dư được xuất về nhà sản xuất hủy";
                        deptSODet.CreateDate = DateTime.Now;
                        deptSODet.UpdateDate = DateTime.Now;
                        deptSODet.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                        deptSODet.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                        deptSODet.StockOutId = deptStockOut.DepartmentStockOutPK.StockOutId;
                        deptSODet.DepartmentId = deptStockOut.DepartmentStockOutPK.DepartmentId;

                        deptSODet.GoodQuantity = returnToStockQty;
                        deptSODet.Quantity = returnToStockQty;
                        deptSODet.DefectStatus = new StockDefectStatus {DefectStatusId = 5}; // xuat tra ve nha san xuat
                        deptStockOut.DepartmentStockOutDetails.Add(deptSODet);
                    }
                    DepartmentStockPK stockPk = new DepartmentStockPK
                                                    {
                                                        DepartmentId = deptStockTemp.DepartmentStockTempPK.DepartmentId,
                                                        ProductId = deptStockTemp.DepartmentStockTempPK.ProductId
                                                    };
                    DepartmentStock stock = DepartmentStockDAO.FindById(stockPk);

                    if (stock != null)
                    {
                        prdMasterUpdateList.Add(stock.Product.ProductMaster);
                        long differGoodQty = stock.Quantity - deptStockTemp.Quantity;
                        stock.GoodQuantity = deptStockTemp.GoodQuantity + differGoodQty;
                        if(deptStockTemp.GoodQuantity > deptStockTemp.Quantity) // stock them vo
                        {
                            // lay so luong nguyen thuy de co the cong them khi stock in vao cua hang
                            stock.GoodQuantity = stock.Quantity;
                        }
                        stock.ErrorQuantity = deptStockTemp.ErrorQuantity;
                        stock.LostQuantity = deptStockTemp.LostQuantity;
                        stock.DamageQuantity = deptStockTemp.DamageQuantity;
                        stock.UnconfirmQuantity = deptStockTemp.UnconfirmQuantity;
                        stock.Quantity = stock.GoodQuantity + stock.ErrorQuantity + stock.LostQuantity +
                                         stock.DamageQuantity + stock.UnconfirmQuantity;
                        needUpdateStocks.Add(stock);
                    }

                    deptStockTemp.DelFlg = 1;
                    processedDeptStockTemp.Fixed = 1;
                    processedDeptStockTemp.DelFlg = 1;
                    DepartmentStockTempDAO.Update(processedDeptStockTemp);
                }
                if (deptStockOut.DepartmentStockOutDetails.Count > 0)
                {
                    DepartmentStockOutDAO.Add(deptStockOut);
                    foreach (DepartmentStockOutDetail detail in deptStockOut.DepartmentStockOutDetails)
                    {
                        DepartmentStockOutDetailDAO.Add(detail);
                    }
                }
            }

            IList stockOutList = syncFromMainToDepartment.StockOutList;
            long deptId = syncFromMainToDepartment.Department.DepartmentId;
            string deptStr = "000";
            if(deptId > 9999)
            {
                deptStr = deptId.ToString();
            }
            else
            {
               deptStr = string.Format("{0:000}", deptId);
            }

            string dateStr = DateTime.Now.ToString("yyMMdd");
            var criteria = new ObjectCriteria();
            if(deptId > 9999)
            {
                criteria.AddGreaterCriteria("DepartmentStockInPK.StockInId", dateStr + deptStr + "000");
            }
            else
            {
                criteria.AddGreaterCriteria("DepartmentStockInPK.StockInId", dateStr + deptStr + "00000");
            }

            var maxId = DepartmentStockInDAO.SelectSpecificType(criteria, Projections.Max("DepartmentStockInPK.StockInId"));

            var stockInId ="";
            if(deptId > 9999)
            {
                stockInId = maxId == null ? dateStr + deptStr + "001" : string.Format("{0:00000000000000}", (Int64.Parse(maxId.ToString()) + 1));
            }
            else
            {
                stockInId = maxId == null ? dateStr + deptStr + "00001" : string.Format("{0:00000000000000}", (Int64.Parse(maxId.ToString()) + 1));
            }

            long nextDeptStockInId = Int64.Parse(stockInId);
            foreach (StockOut stockOut in stockOutList)
            {
                // convert stock out to department stock in
                DepartmentStockInMapper mapper = new DepartmentStockInMapper();
                DepartmentStockIn data = mapper.Convert(stockOut);
                data.Department = syncFromMainToDepartment.Department;
                // sync department stock in
                data.DepartmentStockInPK.StockInId = string.Format("{0:00000000000000}",nextDeptStockInId++);
                /*DepartmentStockIn DepartmentStockIn = DepartmentStockInDAO.FindById(data.DepartmentStockInPK);
                if (DepartmentStockIn == null)
                {
                    DepartmentStockInDAO.Add(data);
                }*/
                StockOut oldStockOut = StockOutDAO.FindById(stockOut.StockoutId);
                if (oldStockOut == null)
                {
                    StockOutDAO.Add(stockOut);
                    DepartmentStockInDAO.Add(data);
                }
                else
                {
                    //ObjectCriteria criteria = new ObjectCriteria();

                    // currently we do not accept update stock in
                    continue;
                    // amend for debug
                    //DepartmentStockInDAO.Update(data);
                }

                // sync department stock in detail
                IList productMasterIds = new ArrayList();
                IList productIds = new ArrayList();
                IList priceList = new ArrayList();
                IList whosalePriceList = new ArrayList();
                IList quantityList = new ArrayList();

                // put master data first
                foreach (DepartmentStockInDetail detail in data.DepartmentStockInDetails)
                {
                    detail.DepartmentStockInDetailPK.StockInId = data.DepartmentStockInPK.StockInId;
                    if (detail.Product.ProductMaster.ProductColor != null)
                    {
                        ProductColor color = ProductColorDAO.FindById(detail.Product.ProductMaster.ProductColor.ColorId);
                        if (color == null)
                        {
                            ProductColorDAO.Add(detail.Product.ProductMaster.ProductColor);
                        }
                    }
                    if (detail.Product.ProductMaster.ProductSize != null)
                    {
                        ProductSize size = ProductSizeDAO.FindById(detail.Product.ProductMaster.ProductSize.SizeId);
                        if (size == null)
                        {
                            ProductSizeDAO.Add(detail.Product.ProductMaster.ProductSize);
                        }
                    }
                    ProductType Type = ProductTypeDAO.FindById(detail.Product.ProductMaster.ProductType.TypeId);
                    if (detail.Product.ProductMaster.ProductType != null)
                    {
                        if (Type == null)
                        {
                            ProductTypeDAO.Add(detail.Product.ProductMaster.ProductType);
                        }
                    }
                    if (detail.Product.ProductMaster.Country != null)
                    {
                        Country Country = CountryDAO.FindById(detail.Product.ProductMaster.Country.CountryId);
                        if (Country == null)
                        {
                            CountryDAO.Add(detail.Product.ProductMaster.Country);
                        }
                    }
                    if (detail.Product.ProductMaster.Distributor != null)
                    {
                        Distributor Distributor =
                            DistributorDAO.FindById(detail.Product.ProductMaster.Distributor.DistributorId);
                        if (Distributor == null)
                        {
                            DistributorDAO.Add(detail.Product.ProductMaster.Distributor);
                        }
                    }
                    if (detail.Product.ProductMaster.Packager != null)
                    {
                        Packager Packager = PackagerDAO.FindById(detail.Product.ProductMaster.Packager.PackagerId);
                        if (Packager == null)
                        {
                            PackagerDAO.Add(detail.Product.ProductMaster.Packager);
                        }
                    }
                    if (detail.Product.ProductMaster.Manufacturer != null)
                    {
                        Manufacturer Manufacturer =
                            ManufacturerDAO.FindById(detail.Product.ProductMaster.Manufacturer.ManufacturerId);
                        if (Manufacturer == null)
                        {
                            ManufacturerDAO.Add(detail.Product.ProductMaster.Manufacturer);
                        }
                    }

                    //ProductMaster ProductMaster = ProductMasterDAO.FindById(detail.Product.ProductMaster.ProductMasterId);
                    ProductMaster ProductMaster = GetProductMaster(detail.Product.ProductMaster,prdMasterUpdateList);
                    if (ProductMaster == null)
                    {
                        ProductMasterDAO.Add(detail.Product.ProductMaster);
                    }
                    else
                    {

                        ProductMaster.Country = detail.Product.ProductMaster.Country;
                        ProductMaster.Packager = detail.Product.ProductMaster.Packager;
                        ProductMaster.ProductColor = detail.Product.ProductMaster.ProductColor;
                        ProductMaster.ProductFullName = detail.Product.ProductMaster.ProductFullName;
                        ProductMaster.ProductName = detail.Product.ProductMaster.ProductName;
                        ProductMaster.ProductSize = detail.Product.ProductMaster.ProductSize;
                        ProductMaster.ProductType = detail.Product.ProductMaster.ProductType;
                        ProductMaster.UpdateDate = detail.Product.ProductMaster.UpdateDate;
                        ProductMaster.UpdateId = detail.Product.ProductMaster.UpdateId;
                        ProductMaster.CreateDate = detail.Product.ProductMaster.CreateDate;
                        ProductMaster.CreateId = detail.Product.ProductMaster.CreateId;
                        ProductMaster.Distributor = detail.Product.ProductMaster.Distributor;
                        ProductMaster.Manufacturer = detail.Product.ProductMaster.Manufacturer;
                        ProductMaster.ImagePath = detail.Product.ProductMaster.ImagePath;
                        ProductMaster.ExclusiveKey = detail.Product.ProductMaster.ExclusiveKey;
                        ProductMasterDAO.Update(ProductMaster);
                    }
                    if (!productMasterIds.Contains(detail.Product.ProductMaster.ProductMasterId))
                    {
                        productMasterIds.Add(detail.Product.ProductMaster.ProductMasterId);
                        priceList.Add(detail.Price);
                        whosalePriceList.Add(detail.OnStorePrice);
                    }

                    Product Product = ProductDAO.FindById(detail.Product.ProductId);
                    if (Product == null)
                    {
                        ProductDAO.Add(detail.Product);
                    }
                    else
                    {
                        Product.UpdateDate = detail.Product.UpdateDate;
                        Product.UpdateId = detail.Product.UpdateId;
                        Product.CreateDate = detail.Product.CreateDate;
                        Product.CreateId = detail.Product.CreateId;
                        Product.ProductMaster = detail.Product.ProductMaster;
                        Product.Quantity = detail.Product.Quantity;
                        Product.Price = detail.Product.Price;
                        ProductDAO.Update(Product);
                    }

                    if (!productIds.Contains(detail.Product.ProductId))
                    {
                        productIds.Add(detail.Product.ProductId);
                        quantityList.Add(detail.Quantity);
                    }

                    DepartmentStockInDetail DepartmentStockInDetail =
                        DepartmentStockInDetailDAO.FindById(detail.DepartmentStockInDetailPK);
                    if (DepartmentStockInDetail == null)
                    {
                        DepartmentStockInDetailDAO.Add(detail);
                    }
                    else
                    {
                        DepartmentStockInDetail.UpdateDate = detail.UpdateDate;
                        DepartmentStockInDetail.UpdateId = detail.UpdateId;
                        DepartmentStockInDetail.CreateDate = detail.CreateDate;
                        DepartmentStockInDetail.CreateId = detail.CreateId;
                        DepartmentStockInDetail.Quantity = DepartmentStockInDetail.Quantity;
                        DepartmentStockInDetail.Price = DepartmentStockInDetail.Price;

                        DepartmentStockInDetailDAO.Update(DepartmentStockInDetail);
                    }
                }

                // update price
                if (productMasterIds.Count > 0)
                {
                    /*IList NotDupPMList = new ArrayList();
                    NotDupPMList = CreateNotDuplicateList(productMasterIds);*/
                    var objectCriteria = new ObjectCriteria();
                    objectCriteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
                    objectCriteria.AddEqCriteria("DepartmentPricePK.DepartmentId", (long)0);
                    objectCriteria.AddSearchInCriteria("DepartmentPricePK.ProductMasterId", productMasterIds);
                    IList deptPriceList = DepartmentPriceDAO.FindAll(objectCriteria);
                    int i = 0;
                    IList newPriceList = new ArrayList();
                    foreach (string productMasterId in productMasterIds)
                    {
                        DepartmentPrice price = null;
                        bool found = false;
                        foreach (DepartmentPrice price1 in deptPriceList)
                        {
                            if (price1.DepartmentPricePK.ProductMasterId.Equals(productMasterId))
                            {
                                //price = price1;
                                found = true;
                                price1.Price = (Int64)priceList[i];
                                price1.WholeSalePrice = (Int64) whosalePriceList[i];
                                break;
                            }
                        }
                        if (!found)
                        {
                            foreach (DepartmentPrice price1 in newPriceList)
                            {
                                if (price1.DepartmentPricePK.ProductMasterId.Equals(productMasterId))
                                {
                                    //price = price1;
                                    found = true;
                                    price1.Price = (Int64) priceList[i];
                                    price1.WholeSalePrice = (Int64) whosalePriceList[i];
                                    break;
                                }
                            }
                        }
                        //if (price == null)
                        if (!found)
                        {
                            price = new DepartmentPrice
                            {
                                DepartmentPricePK = new DepartmentPricePK { DepartmentId = 0, ProductMasterId = productMasterId },
                                Price = (Int64)priceList[i],
                                WholeSalePrice = (Int64)whosalePriceList[i],
                                CreateDate = DateTime.Now,
                                CreateId = ClientInfo.getInstance().LoggedUser.Name,
                                UpdateDate = DateTime.Now,
                                UpdateId = ClientInfo.getInstance().LoggedUser.Name
                            };
                            newPriceList.Add(price);
                            //DepartmentPriceDAO.Add(price);
                        }
                        /*else
                        {
                            price.UpdateDate = DateTime.Now;
                            price.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                            DepartmentPriceDAO.Update(price);
                        }*/
                        i++;
                    }
                    // patch for update stock
                        try
                        {
                            foreach (DepartmentPrice price in deptPriceList)
                            {
                                DepartmentPriceDAO.Update(price);
                            }
                            foreach (DepartmentPrice price in newPriceList)
                            {
                                DepartmentPriceDAO.Add(price);
                            }
                        }
                        catch (Exception)
                        {

                        }
                }

                // mix 2 lists
                // find lack productIds
                IList lackProductIds = new ArrayList();
                if(productIds.Count > 0)
                {
                    foreach (string productId in productIds)
                    {
                        bool hasFound = false;
                        foreach (DepartmentStock departmentStock in needUpdateStocks)
                        {
                            if(productId.Equals(departmentStock.DepartmentStockPK.ProductId))
                            {
                                hasFound = true;
                                break;
                            }
                        }
                        if(!hasFound)
                        {
                            lackProductIds.Add(productId);
                        }
                    }
                /*}

                if (productIds.Count > 0)
                {*/
                    if (lackProductIds.Count > 0)
                    {
                        var objectCrit1 = new ObjectCriteria();
                        objectCrit1.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
                        objectCrit1.AddEqCriteria("DepartmentStockPK.DepartmentId",
                                                  data.DepartmentStockInPK.DepartmentId);

                        objectCrit1.AddSearchInCriteria("DepartmentStockPK.ProductId", lackProductIds);
                        IList stockList = DepartmentStockDAO.FindAll(objectCrit1);
                        if(stockList!= null && stockList.Count > 0)
                        {
                            foreach (DepartmentStock departmentStock in stockList)
                            {
                                needUpdateStocks.Add(departmentStock);
                            }
                        }
                    }
                    int i = 0;
                    foreach (string productId in productIds)
                    {
                        DepartmentStock stock = null;
                        foreach (DepartmentStock needUpdateStock in needUpdateStocks)
                        {
                            if (needUpdateStock.DepartmentStockPK.ProductId.Equals(productId))
                            {
                                stock = needUpdateStock;
                                //stock.Quantity += (Int64)quantityList[i];
                                needUpdateStock.GoodQuantity += (Int64)quantityList[i];
                                needUpdateStock.Quantity += (Int64)quantityList[i];
                                break;
                            }
                        }
                        if (stock == null)
                        {
                            // check in add new stock
                            foreach (DepartmentStock newStock in needAddNewStocks)
                            {
                                if(newStock.DepartmentStockPK.ProductId.Equals(productId))
                                {
                                    stock = newStock;
                                    //stock.Quantity += (Int64)quantityList[i];
                                    newStock.GoodQuantity += (Int64)quantityList[i];
                                    newStock.Quantity += (Int64)quantityList[i];
                                    break;
                                }
                            }
                            // if not found in addnewStock so we create new stock
                            if (stock == null)
                            {
                                stock = new DepartmentStock
                                            {
                                                DepartmentStockPK =
                                                    new DepartmentStockPK
                                                        {
                                                            DepartmentId = data.DepartmentStockInPK.DepartmentId,
                                                            ProductId = productId
                                                        },
                                                Quantity = (Int64) quantityList[i],
                                                GoodQuantity = (Int64) quantityList[i],
                                                CreateDate = DateTime.Now,
                                                CreateId = ClientInfo.getInstance().LoggedUser.Name,
                                                UpdateDate = DateTime.Now,
                                                UpdateId = ClientInfo.getInstance().LoggedUser.Name
                                            };
                                needAddNewStocks.Add(stock);
                            }
                            /*try
                            {
                                stock = new DepartmentStock
                                {
                                    DepartmentStockPK = new DepartmentStockPK { DepartmentId = data.DepartmentStockInPK.DepartmentId, ProductId = productId },
                                    Quantity = (Int64)quantityList[i],
                                    GoodQuantity = (Int64)quantityList[i],
                                    CreateDate = DateTime.Now,
                                    CreateId = ClientInfo.getInstance().LoggedUser.Name,
                                    UpdateDate = DateTime.Now,
                                    UpdateId = ClientInfo.getInstance().LoggedUser.Name
                                };
                                DepartmentStockDAO.Add(stock);
                            }
                            catch (Exception)
                            {

                            }*/

                        }
                        /*else
                        {
                            stock.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                            stock.UpdateDate = DateTime.Now;
                            DepartmentStockDAO.Update(stock);
                        }*/
                        i++;
                    }
                }

            }

            // update stock
            foreach (DepartmentStock stock in needUpdateStocks)
            {
                    stock.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                    stock.UpdateDate = DateTime.Now;
                    DepartmentStockDAO.Update(stock);
            }
            // add new stock
            foreach (DepartmentStock addNewStock in needAddNewStocks)
            {
                DepartmentStockDAO.Add(addNewStock);
            }

            // update common data

            if (syncFromMainToDepartment.Department != null)
            {
                Department dept = DepartmentDAO.FindById(syncFromMainToDepartment.Department.DepartmentId);
                if (dept == null)
                {
                    DepartmentDAO.Add(syncFromMainToDepartment.Department);
                }
                else
                {
                    //dept.Active = data.Department.Active;
                    dept.Address = syncFromMainToDepartment.Department.Address;
                    dept.DepartmentName = syncFromMainToDepartment.Department.DepartmentName;
                    dept.ManagerId = syncFromMainToDepartment.Department.ManagerId;
                    dept.StartDate = syncFromMainToDepartment.Department.StartDate;
                    DepartmentDAO.Update(dept);
                }
                foreach (Employee employee in syncFromMainToDepartment.Department.Employees)
                {
                    Employee emp = EmployeeDAO.FindById(employee.EmployeePK);
                    if (emp == null)
                    {
                        EmployeeDAO.Add(employee);
                        if (employee.EmployeeInfo != null)
                        {
                            EmployeeDetailDAO.Add(employee.EmployeeInfo);
                        }
                    }
                    else
                    {
                        emp.DelFlg = employee.DelFlg;
                        EmployeeDAO.Update(emp);
                        if (employee.EmployeeInfo != null)
                        {
                            EmployeeDetailDAO.Update(employee.EmployeeInfo);
                        }
                    }
                }
            }

            if(syncFromMainToDepartment.UserInfoList!=null && syncFromMainToDepartment.UserInfoList.Count > 0)
            {
                IList needCreateRoleList = new ArrayList();
                IList needCheckRoleList = new ArrayList();
                IList roleList = RoleDAO.FindAll();

                foreach (LoginModel model in syncFromMainToDepartment.UserInfoList)
                {
                    foreach (RoleModel role in model.Roles)
                    {
                        needCheckRoleList.Add(role);
                    }
                }

                // check role
                foreach (RoleModel roleModel in needCheckRoleList)
                {
                    bool hasFound = false;
                    foreach (RoleModel existRole in roleList)
                    {
                        if (existRole.Id == roleModel.Id)
                        {
                            if (!existRole.Name.Equals(roleModel.Name)) existRole.Name = roleModel.Name;
                            hasFound = true;
                            break;
                        }
                    }

                    if (!hasFound)
                        {
                            bool addedToCreateList = false;
                            foreach (RoleModel needCreateRole in needCreateRoleList)
                            {
                                if(roleModel.Id == needCreateRole.Id)
                                {
                                    addedToCreateList = true;
                                    break;
                                }
                            }
                            if (!addedToCreateList) needCreateRoleList.Add(roleModel);
                        }

                }
                foreach (RoleModel model in roleList)
                {
                    RoleDAO.Update(model);
                }
                foreach (RoleModel model in needCreateRoleList)
                {
                    RoleDAO.Add(model);
                }
                foreach (LoginModel model in syncFromMainToDepartment.UserInfoList)
                {

                    LoginModel dbUserModel = LoginDAO.FindById(model.Username);
                    if (dbUserModel != null)
                    {
                        dbUserModel.Username = model.Username;
                        if (!dbUserModel.Password.Equals(model.Password))
                        {
                            if (DateTime.Compare(dbUserModel.UpdateDate, model.UpdateDate) < 0)
                            {
                                dbUserModel.Password = model.Password;
                            }
                        }
                        dbUserModel.Roles = model.Roles;
                        dbUserModel.EmployeeInfo = model.EmployeeInfo;
                        dbUserModel.Suspended = model.Suspended;
                        dbUserModel.Deleted = model.Deleted;

                        LoginDAO.Update(dbUserModel);
                    }
                    else
                    {
                        LoginDAO.Add(model);
                    }
                }
            }
        }
        public void Sync(SyncFromMainToDepartment syncFromMainToDepartment)
        {
            IList prdMasterUpdateList = new ArrayList();
            IList needUpdateStocks = new ArrayList();
            // fix departmentStock first

            IList deptStockTemps = syncFromMainToDepartment.DepartmentStockTemps;
            if (deptStockTemps != null && deptStockTemps.Count > 0)
            {
                DepartmentStockOut deptStockOut = new DepartmentStockOut();
                object maxDSOId = DepartmentStockOutDAO.SelectSpecificType(null,
                                                                           Projections.Max(
                                                                               "DepartmentStockOutPK.StockOutId"));
                long maxDeptStockOutId = (maxDSOId != null ? (long) maxDSOId + 1 : 1);

                object maxDetId = DepartmentStockOutDetailDAO.SelectSpecificType(null,
                                                                                 Projections.Max("StockOutDetailId"));
                long maxDeptStockOutDetId = (maxDetId != null ? (long) maxDetId + 1 : 1);
                deptStockOut.DepartmentStockOutPK = new DepartmentStockOutPK
                                                        {
                                                            DepartmentId = CurrentDepartment.Get().DepartmentId,
                                                            StockOutId = maxDeptStockOutId

                                                        };
                deptStockOut.DefectStatus = new StockDefectStatus {DefectStatusId = 5}; // xuat tra ve nha san xuat
                deptStockOut.ConfirmFlg = 1; // can xac nhan tu kho chinh

                deptStockOut.StockOutDate = DateTime.Now;
                deptStockOut.CreateDate = DateTime.Now;
                deptStockOut.UpdateDate = DateTime.Now;
                deptStockOut.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                deptStockOut.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                deptStockOut.DepartmentStockOutDetails = new ArrayList();
                foreach (DepartmentStockTemp deptStockTemp in deptStockTemps)
                {
                    long realQty = deptStockTemp.GoodQuantity + deptStockTemp.ErrorQuantity +
                                   deptStockTemp.DamageQuantity +
                                   deptStockTemp.LostQuantity + deptStockTemp.UnconfirmQuantity;
                    if (realQty < deptStockTemp.Quantity)
                    {
                        long returnToStockQty = deptStockTemp.Quantity - realQty;
                        DepartmentStockOutDetail deptSODet = new DepartmentStockOutDetail();
                        deptSODet.StockOutDetailId = maxDeptStockOutDetId++;
                        deptSODet.Product = deptStockTemp.Product;
                        deptSODet.ProductMaster = deptStockTemp.ProductMaster;
                        deptSODet.DepartmentStockOut = deptStockOut;
                        deptSODet.Description = "Số liệu dư được xuất về nhà sản xuất hủy";
                        deptSODet.CreateDate = DateTime.Now;
                        deptSODet.UpdateDate = DateTime.Now;
                        deptSODet.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                        deptSODet.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                        deptSODet.StockOutId = deptStockOut.DepartmentStockOutPK.StockOutId;
                        deptSODet.DepartmentId = deptStockOut.DepartmentStockOutPK.DepartmentId;

                        deptSODet.GoodQuantity = returnToStockQty;
                        deptSODet.Quantity = returnToStockQty;
                        deptSODet.DefectStatus = new StockDefectStatus {DefectStatusId = 5}; // xuat tra ve nha san xuat
                        deptStockOut.DepartmentStockOutDetails.Add(deptSODet);
                    }
                    DepartmentStockPK stockPk = new DepartmentStockPK
                                                    {
                                                        DepartmentId = deptStockTemp.DepartmentStockTempPK.DepartmentId,
                                                        ProductId = deptStockTemp.DepartmentStockTempPK.ProductId
                                                    };
                    DepartmentStock stock = DepartmentStockDAO.FindById(stockPk);

                    if (stock != null)
                    {
                        prdMasterUpdateList.Add(stock.Product.ProductMaster);
                        long differGoodQty = stock.Quantity - deptStockTemp.Quantity;
                        stock.GoodQuantity = deptStockTemp.GoodQuantity + differGoodQty;
                        if(deptStockTemp.GoodQuantity > deptStockTemp.Quantity) // stock them vo
                        {
                            // lay so luong nguyen thuy de co the cong them khi stock in vao cua hang
                            stock.GoodQuantity = stock.Quantity;
                        }
                        stock.ErrorQuantity = deptStockTemp.ErrorQuantity;
                        stock.LostQuantity = deptStockTemp.LostQuantity;
                        stock.DamageQuantity = deptStockTemp.DamageQuantity;
                        stock.UnconfirmQuantity = deptStockTemp.UnconfirmQuantity;
                        stock.Quantity = stock.GoodQuantity + stock.ErrorQuantity + stock.LostQuantity +
                                         stock.DamageQuantity + stock.UnconfirmQuantity;
                        needUpdateStocks.Add(stock);
                    }
                    deptStockTemp.DelFlg = 1;
                    DepartmentStockTempDAO.Update(deptStockTemp);
                }
                if (deptStockOut.DepartmentStockOutDetails.Count > 0)
                {
                    DepartmentStockOutDAO.Add(deptStockOut);
                    foreach (DepartmentStockOutDetail detail in deptStockOut.DepartmentStockOutDetails)
                    {
                        DepartmentStockOutDetailDAO.Add(detail);
                    }
                }
            }

            IList stockOutList = syncFromMainToDepartment.StockOutList;

            string deptStr = string.Format("{0:000}", syncFromMainToDepartment.Department.DepartmentId);
            string dateStr = DateTime.Now.ToString("yyMMdd");
            var criteria = new ObjectCriteria();
            criteria.AddGreaterCriteria("DepartmentStockInPK.StockInId", dateStr + deptStr + "00000");
            var maxId = DepartmentStockInDAO.SelectSpecificType(criteria, Projections.Max("DepartmentStockInPK.StockInId"));

            var stockInId = maxId == null ? dateStr + deptStr + "00001" : string.Format("{0:00000000000000}", (Int64.Parse(maxId.ToString()) + 1));
            long nextDeptStockInId = Int64.Parse(stockInId);
            foreach (StockOut stockOut in stockOutList)
            {
                // convert stock out to department stock in
                DepartmentStockInMapper mapper = new DepartmentStockInMapper();
                DepartmentStockIn data = mapper.Convert(stockOut);
                data.Department = syncFromMainToDepartment.Department;
                // sync department stock in
                data.DepartmentStockInPK.StockInId = string.Format("{0:00000000000000}",nextDeptStockInId++);
                /*DepartmentStockIn DepartmentStockIn = DepartmentStockInDAO.FindById(data.DepartmentStockInPK);
                if (DepartmentStockIn == null)
                {
                    DepartmentStockInDAO.Add(data);
                }*/
                StockOut oldStockOut = StockOutDAO.FindById(stockOut.StockoutId);
                if (oldStockOut == null)
                {
                    StockOutDAO.Add(stockOut);
                    DepartmentStockInDAO.Add(data);
                }
                else
                {
                    //ObjectCriteria criteria = new ObjectCriteria();

                    // currently we do not accept update stock in
                    continue;
                    // amend for debug
                    //DepartmentStockInDAO.Update(data);
                }

                // sync department stock in detail
                IList productMasterIds = new ArrayList();
                IList productIds = new ArrayList();
                IList priceList = new ArrayList();
                IList quantityList = new ArrayList();

                // put master data first
                foreach (DepartmentStockInDetail detail in data.DepartmentStockInDetails)
                {
                    detail.DepartmentStockInDetailPK.StockInId = data.DepartmentStockInPK.StockInId;
                    if (detail.Product.ProductMaster.ProductColor != null)
                    {
                        ProductColor color = ProductColorDAO.FindById(detail.Product.ProductMaster.ProductColor.ColorId);
                        if (color == null)
                        {
                            ProductColorDAO.Add(detail.Product.ProductMaster.ProductColor);
                        }
                    }
                    if (detail.Product.ProductMaster.ProductSize != null)
                    {
                        ProductSize Size = ProductSizeDAO.FindById(detail.Product.ProductMaster.ProductSize.SizeId);
                        if (Size == null)
                        {
                            ProductSizeDAO.Add(detail.Product.ProductMaster.ProductSize);
                        }
                    }
                    if (detail.Product.ProductMaster.ProductType != null)
                    {
                        ProductType Type = ProductTypeDAO.FindById(detail.Product.ProductMaster.ProductType.TypeId);
                        if (Type == null)
                        {
                            ProductTypeDAO.Add(detail.Product.ProductMaster.ProductType);
                        }
                    }
                    if (detail.Product.ProductMaster.Country != null)
                    {
                        Country Country = CountryDAO.FindById(detail.Product.ProductMaster.Country.CountryId);
                        if (Country == null)
                        {
                            CountryDAO.Add(detail.Product.ProductMaster.Country);
                        }
                    }
                    if (detail.Product.ProductMaster.Distributor != null)
                    {
                        Distributor Distributor =
                            DistributorDAO.FindById(detail.Product.ProductMaster.Distributor.DistributorId);
                        if (Distributor == null)
                        {
                            DistributorDAO.Add(detail.Product.ProductMaster.Distributor);
                        }
                    }
                    if (detail.Product.ProductMaster.Packager != null)
                    {
                        Packager Packager = PackagerDAO.FindById(detail.Product.ProductMaster.Packager.PackagerId);
                        if (Packager == null)
                        {
                            PackagerDAO.Add(detail.Product.ProductMaster.Packager);
                        }
                    }
                    if (detail.Product.ProductMaster.Manufacturer != null)
                    {
                        Manufacturer Manufacturer =
                            ManufacturerDAO.FindById(detail.Product.ProductMaster.Manufacturer.ManufacturerId);
                        if (Manufacturer == null)
                        {
                            ManufacturerDAO.Add(detail.Product.ProductMaster.Manufacturer);
                        }
                    }

                    //ProductMaster ProductMaster = ProductMasterDAO.FindById(detail.Product.ProductMaster.ProductMasterId);
                    ProductMaster ProductMaster = GetProductMaster(detail.Product.ProductMaster,prdMasterUpdateList);
                    if (ProductMaster == null)
                    {
                        ProductMasterDAO.Add(detail.Product.ProductMaster);
                    }
                    else
                    {

                        ProductMaster.Country = detail.Product.ProductMaster.Country;
                        ProductMaster.Packager = detail.Product.ProductMaster.Packager;
                        ProductMaster.ProductColor = detail.Product.ProductMaster.ProductColor;
                        ProductMaster.ProductFullName = detail.Product.ProductMaster.ProductFullName;
                        ProductMaster.ProductName = detail.Product.ProductMaster.ProductName;
                        ProductMaster.ProductSize = detail.Product.ProductMaster.ProductSize;
                        ProductMaster.ProductType = detail.Product.ProductMaster.ProductType;
                        ProductMaster.UpdateDate = detail.Product.ProductMaster.UpdateDate;
                        ProductMaster.UpdateId = detail.Product.ProductMaster.UpdateId;
                        ProductMaster.CreateDate = detail.Product.ProductMaster.CreateDate;
                        ProductMaster.CreateId = detail.Product.ProductMaster.CreateId;
                        ProductMaster.Distributor = detail.Product.ProductMaster.Distributor;
                        ProductMaster.Manufacturer = detail.Product.ProductMaster.Manufacturer;
                        ProductMaster.ImagePath = detail.Product.ProductMaster.ImagePath;
                        ProductMaster.ExclusiveKey = detail.Product.ProductMaster.ExclusiveKey;
                        ProductMasterDAO.Update(ProductMaster);
                    }
                    if (!productMasterIds.Contains(detail.Product.ProductMaster.ProductMasterId))
                    {
                        productMasterIds.Add(detail.Product.ProductMaster.ProductMasterId);
                        priceList.Add(detail.Price);
                    }

                    Product Product = ProductDAO.FindById(detail.Product.ProductId);
                    if (Product == null)
                    {
                        ProductDAO.Add(detail.Product);
                    }
                    else
                    {
                        Product.UpdateDate = detail.Product.UpdateDate;
                        Product.UpdateId = detail.Product.UpdateId;
                        Product.CreateDate = detail.Product.CreateDate;
                        Product.CreateId = detail.Product.CreateId;
                        Product.ProductMaster = detail.Product.ProductMaster;
                        Product.Quantity = detail.Product.Quantity;
                        Product.Price = detail.Product.Price;
                        ProductDAO.Update(Product);
                    }

                    if (!productIds.Contains(detail.Product.ProductId))
                    {
                        productIds.Add(detail.Product.ProductId);
                        quantityList.Add(detail.Quantity);
                    }

                    DepartmentStockInDetail DepartmentStockInDetail =
                        DepartmentStockInDetailDAO.FindById(detail.DepartmentStockInDetailPK);
                    if (DepartmentStockInDetail == null)
                    {
                        DepartmentStockInDetailDAO.Add(detail);
                    }
                    else
                    {
                        DepartmentStockInDetail.UpdateDate = detail.UpdateDate;
                        DepartmentStockInDetail.UpdateId = detail.UpdateId;
                        DepartmentStockInDetail.CreateDate = detail.CreateDate;
                        DepartmentStockInDetail.CreateId = detail.CreateId;
                        DepartmentStockInDetail.Quantity = DepartmentStockInDetail.Quantity;
                        DepartmentStockInDetail.Price = DepartmentStockInDetail.Price;

                        DepartmentStockInDetailDAO.Update(DepartmentStockInDetail);
                    }
                }

                // update price
                if (productMasterIds.Count > 0)
                {
                    var objectCriteria = new ObjectCriteria();
                    objectCriteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
                    objectCriteria.AddEqCriteria("DepartmentPricePK.DepartmentId", (long)0);
                    objectCriteria.AddSearchInCriteria("DepartmentPricePK.ProductMasterId", productMasterIds);
                    IList deptPriceList = DepartmentPriceDAO.FindAll(objectCriteria);
                    int i = 0;
                    foreach (string productMasterId in productMasterIds)
                    {
                        DepartmentPrice price = null;
                        foreach (DepartmentPrice price1 in deptPriceList)
                        {
                            if (price1.DepartmentPricePK.ProductMasterId.Equals(productMasterId))
                            {
                                price = price1;
                                price.Price = (Int64)priceList[i];
                                break;
                            }
                        }
                        if (price == null)
                        {
                            price = new DepartmentPrice
                            {
                                DepartmentPricePK = new DepartmentPricePK { DepartmentId = 0, ProductMasterId = productMasterId },
                                Price = (Int64)priceList[i],
                                CreateDate = DateTime.Now,
                                CreateId = ClientInfo.getInstance().LoggedUser.Name,
                                UpdateDate = DateTime.Now,
                                UpdateId = ClientInfo.getInstance().LoggedUser.Name
                            };
                            DepartmentPriceDAO.Add(price);
                        }
                        else
                        {
                            price.UpdateDate = DateTime.Now;
                            price.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                            DepartmentPriceDAO.Update(price);
                        }
                        i++;
                    }
                }

                // mix 2 lists
                // find lack productIds
                IList lackProductIds = new ArrayList();
                if(productIds.Count > 0)
                {
                    foreach (string productId in productIds)
                    {
                        bool hasFound = false;
                        foreach (DepartmentStock departmentStock in needUpdateStocks)
                        {
                            if(productId.Equals(departmentStock.DepartmentStockPK.ProductId))
                            {
                                hasFound = true;
                                break;
                            }
                        }
                        if(!hasFound)
                        {
                            lackProductIds.Add(productId);
                        }
                    }
                }

                if (productIds.Count > 0)
                {
                    if (lackProductIds.Count > 0)
                    {
                        var objectCrit1 = new ObjectCriteria();
                        objectCrit1.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
                        objectCrit1.AddEqCriteria("DepartmentStockPK.DepartmentId",
                                                  data.DepartmentStockInPK.DepartmentId);

                        objectCrit1.AddSearchInCriteria("DepartmentStockPK.ProductId", productIds);
                        IList stockList = DepartmentStockDAO.FindAll(objectCrit1);
                        if(stockList!= null && stockList.Count > 0)
                        {
                            foreach (DepartmentStock departmentStock in stockList)
                            {
                                needUpdateStocks.Add(departmentStock);
                            }
                        }
                    }
                    int i = 0;
                    foreach (string productId in productIds)
                    {
                        DepartmentStock stock = null;
                        foreach (DepartmentStock needUpdateStock in needUpdateStocks)
                        {
                            if (needUpdateStock.DepartmentStockPK.ProductId.Equals(productId))
                            {
                                stock = needUpdateStock;
                                //stock.Quantity += (Int64)quantityList[i];
                                stock.GoodQuantity += (Int64)quantityList[i];
                                stock.Quantity += (Int64)quantityList[i];
                                break;
                            }
                        }
                        if (stock == null)
                        {
                            stock = new DepartmentStock
                            {
                                DepartmentStockPK = new DepartmentStockPK { DepartmentId = data.DepartmentStockInPK.DepartmentId, ProductId = productId },
                                Quantity = (Int64)quantityList[i],
                                GoodQuantity = (Int64)quantityList[i],
                                CreateDate = DateTime.Now,
                                CreateId = ClientInfo.getInstance().LoggedUser.Name,
                                UpdateDate = DateTime.Now,
                                UpdateId = ClientInfo.getInstance().LoggedUser.Name
                            };
                            DepartmentStockDAO.Add(stock);
                        }
                        /*else
                        {
                            stock.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                            stock.UpdateDate = DateTime.Now;
                            DepartmentStockDAO.Update(stock);
                        }*/
                        i++;
                    }
                }
                // update stock
                foreach (DepartmentStock stock in needUpdateStocks)
                {
                    stock.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                    stock.UpdateDate = DateTime.Now;
                    DepartmentStockDAO.Update(stock);
                }

                if (data.Department != null)
                {
                    Department dept = DepartmentDAO.FindById(data.Department.DepartmentId);
                    if (dept == null)
                    {
                        DepartmentDAO.Add(data.Department);
                    }
                    else
                    {
                        //dept.Active = data.Department.Active;
                        dept.Address = data.Department.Address;
                        dept.DepartmentName = data.Department.DepartmentName;
                        dept.ManagerId = data.Department.ManagerId;
                        dept.StartDate = data.Department.StartDate;
                        DepartmentDAO.Update(dept);
                    }
                    foreach (Employee employee in data.Department.Employees)
                    {
                        Employee emp = EmployeeDAO.FindById(employee.EmployeePK);
                        if (emp == null)
                        {
                            EmployeeDAO.Add(employee);
                            if (employee.EmployeeInfo != null)
                            {
                                EmployeeDetailDAO.Add(employee.EmployeeInfo);
                            }
                        }
                        else
                        {
                            emp.DelFlg = employee.DelFlg;
                            EmployeeDAO.Update(emp);
                            if (employee.EmployeeInfo != null)
                            {
                                EmployeeDetailDAO.Update(employee.EmployeeInfo);
                            }
                        }
                    }
                }

            }
        }
示例#14
0
        public void MakeMultiDepartmentStockOut(Department department, DepartmentStockOut[] stockOutList, DepartmentPrice price)
        {
            ServerUtility.Log(logger, " Xuat hang di " + department.DepartmentId);
            _callbackList.ForEach(
                delegate(IDepartmentStockOutCallback callback)
                {
                    try
                    {
                        // dispatch stock-out to department
                        callback.NotifyNewMultiDepartmentStockOut(department, stockOutList, price);
                    }
                    catch (Exception)
                    {

                    }
                });
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(
                "Bạn hãy kiểm tra kỹ trước khi lưu số liệu bởi vì sau khi lưu sẽ không thay đổi được nữa. Bạn có chắc chắn muốn lưu ?","Xác nhận",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if(result == System.Windows.Forms.DialogResult.No)
            {
                return;
            }
            // first remove all blank row
            int count = 0;
            int length = deptSODetailList.Count;
            for (int i = 0; i < length - count; i++)
            {
                DepartmentStockOutDetail detail = deptSODetailList[i];
                if (string.IsNullOrEmpty(detail.Product.ProductMaster.ProductMasterId)
                    && string.IsNullOrEmpty(detail.Product.ProductMaster.ProductName))
                {
                    deptSODetailList.RemoveAt(i - count);
                    count++;
                }
            }

            if (deptSODetailList.Count == 0)
            {
                MessageBox.Show("Không có sản phẩm nào để nhập kho!!!!");
                return;
            }

            // validate quantity
            int line = 1;
            foreach (DepartmentStockOutDetail detail in deptSODetailList)
            {
                foreach (DepartmentStock stock in departmentStockList)
                {
                    if (detail.Product.ProductId.Equals(stock.Product.ProductId))
                    {
                        if (detail.GoodQuantity < 0 || detail.GoodQuantity > stock.GoodQuantity)
                        {
                            MessageBox.Show("Lỗi ở dòng " + line + " : Số lượng Tốt phải là số dương nhỏ hơn hoặc bằng " + stock.GoodQuantity);
                            return;
                        }
                        if (detail.LostQuantity < 0 || detail.LostQuantity > stock.LostQuantity)
                        {
                            MessageBox.Show("Lỗi ở dòng " + line + " : Số lượng Mất phải là số dương nhỏ hơn hoặc bằng " + stock.LostQuantity);
                            return;
                        }
                        if (detail.DamageQuantity < 0 || detail.DamageQuantity > stock.DamageQuantity)
                        {
                            MessageBox.Show("Lỗi ở dòng " + line + " : Số lượng Lỗi phải là số dương nhỏ hơn hoặc bằng " + stock.DamageQuantity);
                            return;
                        }
                        if (detail.ErrorQuantity < 0 || detail.ErrorQuantity > stock.ErrorQuantity)
                        {
                            MessageBox.Show("Lỗi ở dòng " + line + " : Số lượng Hư phải là số dương nhỏ hơn hoặc bằng " + stock.ErrorQuantity);
                            return;
                        }
                    }
                }
                if ((detail.DefectStatus.DefectStatusId == 4 && detail.ErrorQuantity == 0)
                    || (detail.DefectStatus.DefectStatusId == 6 && detail.DamageQuantity + detail.GoodQuantity + detail.ErrorQuantity == 0)
                    || (detail.DefectStatus.DefectStatusId == 7 && detail.GoodQuantity == 0))
                {
                    MessageBox.Show("Lỗi ở dòng " + line + " : Số lượng xuất phải lớn hơn 0.");
                    return;
                }
                line++;
            }

            if (deptSO == null)
            {
                deptSO = new DepartmentStockOut();
            }
            bool isNeedClearData = deptSO.DepartmentStockOutPK == null || deptSO.DepartmentStockOutPK.StockOutId == 0;
            deptSO.StockOutDate = dtpImportDate.Value;
            deptSO.DefectStatus = (StockDefectStatus)cbbStockOutType.SelectedItem;
            deptSO.DepartmentStockOutDetails = deptSODetailList;
            //            deptSO.Description = txtDexcription.Text;
            var eventArgs = new DepartmentStockOutEventArgs();
            eventArgs.DepartmentStockOut = deptSO;
            EventUtility.fireEvent(SaveStockOutEvent, this, eventArgs);
            if (eventArgs.EventResult != null)
            {
                MessageBox.Show("Lưu thành công");
                if (isNeedClearData)
                {
                    deptSO = new DepartmentStockOut();
                    deptSODetailList.Clear();
            //                    txtDexcription.Text = "";
            //                    txtPriceIn.Text = "";
            //                    txtPriceOut.Text = "";
                    txtSumProduct.Text = "";
                    txtSumValue.Text = "";
                    ClearSelectionOnListBox(lstColor);
                    ClearSelectionOnListBox(lstSize);
                    //CreateNewStockInDetail();
                }
            }
            else
            {
                //MessageBox.Show("Có lỗi khi lưu");
            }
        }
示例#16
0
        public void MakeRawDepartmentStockOut(Department department, DepartmentStockOut stockOut, DepartmentPrice price)
        {
            DataAccessLayer dalSubStock = new DataAccessLayer(Properties.Settings.Default.SubStockDB);
            DataAccessLayer dalSalePoint = new DataAccessLayer(Properties.Settings.Default.SalePointDB);

            //DataAccessLayer dalSalePoint = new DataAccessLayer("achay");

            /*try
            {*/

            try
            {

                DepartmentStockIn stockIn = new FastDepartmentStockInMapper().Convert(stockOut);
                // get max stock in id
                string deptStr = "";
                string extraZero = "";
                string startNum = "";

                if(department.DepartmentId > 999)
                {
                    deptStr = department.DepartmentId.ToString();
                    extraZero = "000";
                    startNum = "001";
                }
                else
                {
                    deptStr = string.Format("{0:000}", department.DepartmentId);
                    extraZero = "00000";
                    startNum = "00001";
                }

                string dateStr = DateTime.Now.ToString("yyMMdd");
                var selectMaxIdSQL = " select max(stock_in_id) from department_stock_in where stock_in_id > '" + dateStr + deptStr + extraZero + "'";

                ServerUtility.Log(logger, selectMaxIdSQL);
                //var maxId = dalSalePoint.GetSingleValue(selectMaxIdSQL);
                var maxId = dalSalePoint.GetSingleValue(selectMaxIdSQL);
                string stockInId = "";
                if(maxId == null || maxId.ToString() == string.Empty)
                {
                    stockInId = dateStr + deptStr + startNum;
                }
                else
                {
                    stockInId = string.Format("{0:00000000000000}", (Int64.Parse(maxId.ToString()) + 1));
                }

                // search in department_stock_in_history
                string selectHistory = " select stock_in_id from department_stock_in_history "
                                       + " where SOURCE_DEPARTMENT_ID = " + stockOut.DepartmentStockOutPK.DepartmentId
                                       + " and stock_out_id = " + stockOut.DepartmentStockOutPK.StockOutId;
                ServerUtility.Log(logger, selectHistory);
                var existStockInId = dalSalePoint.GetSingleValue(selectHistory);
                if (existStockInId == null || existStockInId.ToString() == string.Empty)
                {
                    string insertHistory = " insert into department_stock_in_history(stock_out_id,source_department_id,stock_in_id,dest_department_id,description,create_id,create_date,update_id,update_date ) values( "
                                           + stockOut.DepartmentStockOutPK.StockOutId + ","
                                           + stockOut.DepartmentStockOutPK.DepartmentId + ",'"
                                           + stockInId + "',"
                                           + stockIn.DepartmentStockInPK.DepartmentId + ",'"
                                           + " Xuat hang xuong cua hang " + "',"
                                           + "'admin'" + ","
                                           + "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',"
                                           + "'admin'" + ","
                                           + "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "');";
                    ServerUtility.Log(logger, insertHistory);
                    dalSalePoint.ExecuteQuery(insertHistory);
                }
                else
                {
                    InformMessage(stockOut.DepartmentStockOutPK.StockOutId,SUBTODEPT, true,
                    stockOut.DepartmentStockOutPK.StockOutId + " đã đến " + stockOut.OtherDepartmentId + " trước đó. Không thể truyền lại !");
                    return;
                }

                DoStockIn(dalSalePoint, department, stockIn, true);
                InformMessage(stockOut.DepartmentStockOutPK.StockOutId,SUBTODEPT, false,
                    stockOut.DepartmentStockOutPK.DepartmentId +  " đã truyền "+ stockOut.DepartmentStockOutPK.StockOutId +" xuống " + stockOut.OtherDepartmentId + " thành công !");
            }
            catch (Exception exception)
            {
                ServerUtility.Log(logger,exception.Message);
                ServerUtility.Log(logger, exception.StackTrace);
                InformMessage(stockOut.DepartmentStockOutPK.StockOutId,SUBTODEPT, true,
                    stockOut.DepartmentStockOutPK.DepartmentId + " đã truyền " + stockOut.DepartmentStockOutPK.StockOutId + " xuống " + stockOut.OtherDepartmentId + " thất bại !");
            }
        }
        private void DepartmentStockInExtra_Load(object sender, EventArgs e)
        {
            IList list = new ArrayList();
            list.Add(new StockDefectStatus { DefectStatusId = 4, DefectStatusName = "Xuất tạm để sửa hàng"});
            list.Add(new StockDefectStatus { DefectStatusId = 6, DefectStatusName = "Xuất trả về kho chính" });
            //list.Add(new StockDefectStatus { DefectStatusId = 7, DefectStatusName = "Xuất đi cửa hàng khác" });

            cbbStockOutType.DataSource = list;
            cbbStockOutType.DisplayMember = "DefectStatusName";

            deptSODetailList = new DepartmentStockOutDetailCollection(bdsStockIn);
            bdsStockIn.DataSource = deptSODetailList;
            dgvDeptStockIn.DataError += new DataGridViewDataErrorEventHandler(dgvDeptStockIn_DataError);

            // create DepartmentStockIn
            if (deptSO == null)
            {
                deptSO = new DepartmentStockOut();
                deptSO.CreateDate = DateTime.Now;
                deptSO.UpdateDate = DateTime.Now;
                deptSO.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                deptSO.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                deptSO.ExclusiveKey = 0;
                CreateNewStockInDetail();
            //                btnBarcode.Visible = false;
            //                numericUpDownBarcode.Visible = false;
            //                btnPreview.Visible = false;
                // load products to extra combo box
                LoadProductMasterToComboBox();
                deptSODetailList.RemoveAt(0);
                bdsStockIn.EndEdit();

            }
            else
            {
            //                btnBarcode.Visible = true;
            //                numericUpDownBarcode.Visible = true;
            //                btnPreview.Visible = true;
                IList deptStockInDetails = deptSO.DepartmentStockOutDetails;
                foreach (DepartmentStockOutDetail detail in deptStockInDetails)
                {
                    if (detail.DelFlg == CommonConstants.DEL_FLG_NO)
                    {
                        deptSODetailList.Add(detail);
                        //detail.OldQuantity = detail.Quantity;
                    }
                }

                for (int i = 0; i < dgvDeptStockIn.Columns.Count; i++)
                {
                    dgvDeptStockIn.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                    if (i != QUANTITY_POS
                            && i != PRICE_POS
                            && i != SELL_PRICE_POS)
                    {
                        dgvDeptStockIn.Columns[i].ReadOnly = true;
                    }
                }
            //                txtDexcription.Text = deptSO.Description;
            }
            deptSO.DepartmentStockOutDetails =
                    ObjectConverter.ConvertToNonGenericList<DepartmentStockOutDetail>(deptSODetailList);
        }
        public DepartmentStockOut Add(DepartmentStockOut stockOut)
        {
            stockOut.CreateDate = DateTime.Now;
            stockOut.CreateId = ClientInfo.getInstance().LoggedUser.Name;
            stockOut.UpdateDate = DateTime.Now;
            stockOut.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
            stockOut.DelFlg = 0;
            stockOut.StockOutDate = DateTime.Now;
            long maxStockOutId = this.FindMaxId();
            maxStockOutId = maxStockOutId + 1;

            stockOut.DepartmentStockOutPK = new DepartmentStockOutPK();
            stockOut.DepartmentStockOutPK.StockOutId = maxStockOutId;
            stockOut.DepartmentStockOutPK.DepartmentId = CurrentDepartment.Get().DepartmentId;

            DepartmentStockOutDAO.Add(stockOut);
            var maxStockOutDetailIdStr = DepartmentStockOutDetailDAO.SelectSpecificType(null, Projections.Max("DepartmentStockOutDetailPK.StockOutDetailId"));
            long maxStockOutDetailId = maxStockOutDetailIdStr != null ? Int64.Parse(maxStockOutDetailIdStr.ToString()) : 0;
            maxStockOutDetailId = maxStockOutDetailId + 1;
            IList productIds = new ArrayList();
            foreach (DepartmentStockOutDetail stockOutDetail in stockOut.DepartmentStockOutDetails)
            {
                productIds.Add(stockOutDetail.Product.ProductId);
            }

            var criteria = new ObjectCriteria();
            criteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
            criteria.AddEqCriteria("DepartmentStockPK.DepartmentId", CurrentDepartment.Get().DepartmentId);
            criteria.AddSearchInCriteria("Product.ProductId", productIds);
            IList stockList = DepartmentStockDAO.FindAll(criteria);
            foreach (DepartmentStockOutDetail stockOutDetail in stockOut.DepartmentStockOutDetails)
            {
                // check number
                var objectCriteria = new ObjectCriteria();
                objectCriteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
                objectCriteria.AddEqCriteria("Product.ProductId", stockOutDetail.Product.ProductId);
                DepartmentStock stock = GetStock(stockOutDetail.Product.ProductId, stockList);
                stockOutDetail.LostQuantity = 0;
                stockOutDetail.UnconfirmQuantity = 0;
                if (stockOutDetail.DefectStatus != null)
                {
                    // xuất qua cửa hàng khác
                    if (stockOutDetail.DefectStatus.DefectStatusId == 7)
                    {
                        stockOutDetail.Quantity = stockOutDetail.GoodQuantity;
                        stock.Quantity -= stockOutDetail.Quantity;
                        stock.GoodQuantity -= stockOutDetail.GoodQuantity;

                        stockOutDetail.ErrorQuantity = 0;
                        stockOutDetail.DamageQuantity = 0;
                        stockOutDetail.UnconfirmQuantity = 0;
                        stockOutDetail.LostQuantity = 0;
                    }
                    // xuất tạm để sửa
                    else if (stockOutDetail.DefectStatus.DefectStatusId == 4)
                    {
                        stockOutDetail.Quantity = stockOutDetail.ErrorQuantity;

                        //stockOutDetail.ErrorQuantity = 0;
                        stockOutDetail.GoodQuantity = 0;
                        stockOutDetail.LostQuantity = 0;
                        stockOutDetail.UnconfirmQuantity = 0;

                        // check whether it's has temp stockout enough ?

                        long totaltempErrorStockOut = 0;
                        long totalReStockCount = 0;

                        ObjectCriteria crit = new ObjectCriteria();
                        crit.AddEqCriteria("Product.ProductId", stockOutDetail.Product.ProductId)
                            .AddEqCriteria("DefectStatus.DefectStatusId", (long)4)
                            .AddEqCriteria("DelFlg", (long)0);
                        IList tempStockedOutList = DepartmentStockOutDetailDAO.FindAll(crit);
                        if (tempStockedOutList != null)
                        {

                            foreach (DepartmentStockOutDetail outDetail in tempStockedOutList)
                            {
                                totaltempErrorStockOut += outDetail.Quantity;
                            }

                        }

                        IList reStockList = DepartmentStockInDetailDAO.FindReStock(stockOutDetail.Product.ProductId);
                        if (reStockList != null)
                        {
                            foreach (DepartmentStockInDetail stockInDetail in reStockList)
                            {
                                totalReStockCount += stockInDetail.Quantity;
                            }
                        }
                        totaltempErrorStockOut = totaltempErrorStockOut - totalReStockCount;
                        if (stockOutDetail.ErrorQuantity > stock.ErrorQuantity - totaltempErrorStockOut)
                        {
                            throw new BusinessException("Lỗi: Mặt hàng " + stockOutDetail.Product.ProductFullName + ", mã vạch "
                                           + stockOutDetail.Product.ProductId + " có tồn " + stock.ErrorQuantity + ", đã xuất tạm " + totaltempErrorStockOut +
                                           ", và đang xuất " + stockOutDetail.ErrorQuantity);
                        }
                    }
                    // xuất trả về kho chính
                    else if (stockOutDetail.DefectStatus.DefectStatusId == 6)
                    {
                        stockOutDetail.Quantity = stockOutDetail.GoodQuantity + stockOutDetail.ErrorQuantity;
                        stock.Quantity -= stockOutDetail.Quantity;
                        stock.ErrorQuantity -= stockOutDetail.ErrorQuantity;
                        stock.GoodQuantity -= stockOutDetail.GoodQuantity;

                        stockOutDetail.LostQuantity = 0;
                        stockOutDetail.UnconfirmQuantity = 0;
                    }
                    // xuất hàng mẫu
                    else if (stockOutDetail.DefectStatus.DefectStatusId == 9)
                    {
                        stockOutDetail.Quantity = stockOutDetail.GoodQuantity;
                        //stock.Quantity -= stockOutDetail.Quantity;
                        //stock.ErrorQuantity -= stockOutDetail.ErrorQuantity;
                        //stock.GoodQuantity -= stockOutDetail.GoodQuantity;
                        stockOutDetail.ErrorQuantity = 0;
                        stockOutDetail.LostQuantity = 0;
                        stockOutDetail.UnconfirmQuantity = 0;
                    }
                }

                if (stockOutDetail.DefectStatus.DefectStatusId != 9)
                {
                    // if does not allow negative export then check quantity in stock.
                    if (!ClientSetting.NegativeExport)
                    {
                        if (stock.Quantity < 0 || stock.GoodQuantity < 0)
                        {
                            throw new BusinessException("Hang trong kho khong du de xuat");
                        }
                    }
                }
                    ClientUtility.Log(logger, stock.ProductId + " remains quantity is " + stock.Quantity);
                    stock.UpdateDate = DateTime.Now;
                    stock.UpdateId = ClientInfo.getInstance().LoggedUser.Name;

                    DepartmentStockDAO.Update(stock);

                stockOutDetail.DepartmentStockOut = stockOut;
                stockOutDetail.DepartmentStockOutDetailPK = new DepartmentStockOutDetailPK();
                stockOutDetail.DepartmentStockOutDetailPK.DepartmentId = CurrentDepartment.Get().DepartmentId;
                stockOutDetail.DepartmentStockOutDetailPK.StockOutDetailId = maxStockOutDetailId++;
                stockOutDetail.DepartmentId = CurrentDepartment.Get().DepartmentId;
                stockOutDetail.StockOutId = stockOut.DepartmentStockOutPK.StockOutId;
                stockOutDetail.ProductMaster = stockOutDetail.Product.ProductMaster;
                DepartmentStockOutDetailDAO.Add(stockOutDetail);
            }
            return stockOut;
        }
 public void NotifyNewDepartmentStockOut(Department department, DepartmentStockOut stockOut, DepartmentPrice price)
 {
     // do nothing
     //MessageBox.Show("Send back OK !");
 }
        public void ProcessErrorGoods(IList stockList, IList returnGoodsList, IList tempStockOutList, IList destroyGoodsList)
        {
            var maxStockOutDetailIdStr = DepartmentStockOutDAO.SelectSpecificType(null, Projections.Max("DepartmentStockOutPK.StockOutId"));
            long maxId = maxStockOutDetailIdStr != null ? Int64.Parse(maxStockOutDetailIdStr.ToString()) : 0;
            maxId += 1;

            object maxDetailObj = DepartmentStockOutDetailDAO.SelectSpecificType(null, Projections.Max("StockOutDetailId"));
            long maxDetailId = maxDetailObj != null ? (long)maxDetailObj : 0;
            maxDetailId += 1;

            DepartmentStockOut destroytSO = new DepartmentStockOut();
            destroytSO.CreateDate = DateTime.Now;
            destroytSO.CreateId = ClientInfo.getInstance().LoggedUser.Name;
            destroytSO.UpdateDate = DateTime.Now;
            destroytSO.UpdateId = ClientInfo.getInstance().LoggedUser.Name;

            destroytSO.StockOutDate = DateTime.Now;
            destroytSO.DefectStatus = new StockDefectStatus { DefectStatusId = 8, DefectStatusName = " Huỷ hàng hư và mất" };

            destroytSO.DepartmentStockOutPK = new DepartmentStockOutPK();
            destroytSO.DepartmentStockOutPK.StockOutId = maxId++;
            destroytSO.DepartmentStockOutPK.DepartmentId = CurrentDepartment.Get().DepartmentId;
            destroytSO.ExclusiveKey = 1;
            if (destroyGoodsList.Count > 0)
            {
                foreach (DepartmentStockOutDetail stockOutDetail in destroyGoodsList)
                {

                    stockOutDetail.GoodQuantity = 0;
                    stockOutDetail.ErrorQuantity = 0;
                    stockOutDetail.CreateDate = DateTime.Now;
                    stockOutDetail.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                    stockOutDetail.UpdateDate = DateTime.Now;
                    stockOutDetail.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                    stockOutDetail.DepartmentStockOut = destroytSO;
                    stockOutDetail.StockOutId = destroytSO.DepartmentStockOutPK.StockOutId;
                    stockOutDetail.DepartmentId = destroytSO.DepartmentStockOutPK.DepartmentId;
                    stockOutDetail.DelFlg = 0;
                    stockOutDetail.ExclusiveKey = 1;
                    stockOutDetail.Description = " Huỷ hàng hư và mất";

                    // update defect
                    // update quantity of stock
                    DepartmentStock defect = GetDefectFromStockOut(stockOutDetail, stockList);
                    if (defect == null)
                    {
                        throw new BusinessException("Hàng xuất không tồn tại trong cơ sở dữ liệu, mục hàng lỗi");
                    }
                    defect.LostQuantity -= stockOutDetail.LostQuantity;
                    defect.DamageQuantity -= stockOutDetail.DamageQuantity;
                    defect.Quantity -= stockOutDetail.Quantity;

                    DepartmentStockDAO.Update(defect);
                }
                destroytSO.DepartmentStockOutDetails = destroyGoodsList;
                DepartmentStockOutDAO.Add(destroytSO);

                foreach (DepartmentStockOutDetail detail in destroyGoodsList)
                {
                    detail.DepartmentStockOutDetailPK = new DepartmentStockOutDetailPK();
                    detail.DepartmentStockOutDetailPK.DepartmentId = CurrentDepartment.Get().DepartmentId;
                    detail.DepartmentStockOutDetailPK.StockOutDetailId = maxDetailId++;
                    DepartmentStockOutDetailDAO.Add(detail);
                }
            }

            // -------------- return to main stock ------------
            DepartmentStockOut returnSO = new DepartmentStockOut();
            returnSO.CreateDate = DateTime.Now;
            returnSO.CreateId = ClientInfo.getInstance().LoggedUser.Name;
            returnSO.UpdateDate = DateTime.Now;
            returnSO.UpdateId = ClientInfo.getInstance().LoggedUser.Name;

            returnSO.StockOutDate = DateTime.Now;
            returnSO.DefectStatus = new StockDefectStatus { DefectStatusId = 6 }; // trả về kho chính
            returnSO.DepartmentStockOutPK = new DepartmentStockOutPK();
            returnSO.DepartmentStockOutPK.StockOutId = maxId++;
            returnSO.DepartmentStockOutPK.DepartmentId = CurrentDepartment.Get().DepartmentId;
            returnSO.ExclusiveKey = 1;

            if (returnGoodsList.Count > 0)
            {
                foreach (DepartmentStockOutDetail stockOutDetail in returnGoodsList)
                {
                    stockOutDetail.Quantity = stockOutDetail.ErrorQuantity;
                    stockOutDetail.GoodQuantity = 0;
                    stockOutDetail.LostQuantity = 0;
                    stockOutDetail.DamageQuantity = 0;
                    stockOutDetail.CreateDate = DateTime.Now;
                    stockOutDetail.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                    stockOutDetail.UpdateDate = DateTime.Now;
                    stockOutDetail.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                    stockOutDetail.DepartmentStockOut = returnSO;
                    stockOutDetail.StockOutId = returnSO.DepartmentStockOutPK.StockOutId;
                    stockOutDetail.DepartmentId = returnSO.DepartmentStockOutPK.DepartmentId;
                    stockOutDetail.DelFlg = 0;
                    stockOutDetail.ExclusiveKey = 1;
                    stockOutDetail.Description = " Trả về cho kho chính";

                    DepartmentStock defect = GetDefectFromStockOut(stockOutDetail, stockList);
                    if (defect == null)
                    {
                        throw new BusinessException("Hàng xuất không tồn tại trong cơ sở dữ liệu, mục hàng lỗi");
                    }
                    defect.ErrorQuantity -= stockOutDetail.ErrorQuantity;
                    defect.Quantity -= stockOutDetail.Quantity;
                    DepartmentStockDAO.Update(defect);
                }
                returnSO.DepartmentStockOutDetails = returnGoodsList;
                DepartmentStockOutDAO.Add(returnSO);

                //maxDetailId += 1;
                foreach (DepartmentStockOutDetail detail in returnGoodsList)
                {
                    detail.DepartmentStockOutDetailPK = new DepartmentStockOutDetailPK();
                    detail.DepartmentStockOutDetailPK.DepartmentId = CurrentDepartment.Get().DepartmentId;
                    detail.DepartmentStockOutDetailPK.StockOutDetailId = maxDetailId++;
                    DepartmentStockOutDetailDAO.Add(detail);
                }
            }
            // -------------- temporary stock out
            DepartmentStockOut tempSO = new DepartmentStockOut();
            tempSO.CreateDate = DateTime.Now;
            tempSO.CreateId = ClientInfo.getInstance().LoggedUser.Name;
            tempSO.UpdateDate = DateTime.Now;
            tempSO.UpdateId = ClientInfo.getInstance().LoggedUser.Name;

            tempSO.StockOutDate = DateTime.Now;
            tempSO.DefectStatus = new StockDefectStatus { DefectStatusId = 4 };
            tempSO.DepartmentStockOutPK = new DepartmentStockOutPK();
            tempSO.DepartmentStockOutPK.StockOutId = maxId++;
            tempSO.DepartmentStockOutPK.DepartmentId = CurrentDepartment.Get().DepartmentId;
            tempSO.ExclusiveKey = 1;
            if (tempStockOutList.Count > 0)
            {
                foreach (DepartmentStockOutDetail stockOutDetail in tempStockOutList)
                {
                    stockOutDetail.Quantity = stockOutDetail.ErrorQuantity;
                    stockOutDetail.GoodQuantity = 0;
                    stockOutDetail.LostQuantity = 0;
                    stockOutDetail.DamageQuantity = 0;
                    stockOutDetail.CreateDate = DateTime.Now;
                    stockOutDetail.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                    stockOutDetail.UpdateDate = DateTime.Now;
                    stockOutDetail.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                    stockOutDetail.DepartmentStockOut = tempSO;
                    stockOutDetail.StockOutId = tempSO.DepartmentStockOutPK.StockOutId;
                    stockOutDetail.DepartmentId = tempSO.DepartmentStockOutPK.DepartmentId;
                    stockOutDetail.DelFlg = 0;
                    stockOutDetail.ExclusiveKey = 1;
                    stockOutDetail.Description = " Trả hàng cho nhà sản xuất";

                    DepartmentStock stock = GetDefectFromStockOut(stockOutDetail, stockList);
                    if (stock == null)
                    {
                        throw new BusinessException("Hàng xuất không tồn tại trong cơ sở dữ liệu, mục hàng lỗi");
                    }

                    // check whether it's has temp stockout enough ?

                    long totaltempErrorStockOut = 0;
                    long totalReStockCount = 0;

                    ObjectCriteria crit = new ObjectCriteria();
                    crit.AddEqCriteria("Product.ProductId", stockOutDetail.Product.ProductId)
                        .AddEqCriteria("DefectStatus.DefectStatusId", (long)4)
                        .AddEqCriteria("DelFlg", (long)0);
                    IList tempStockedOutList = DepartmentStockOutDetailDAO.FindAll(crit);
                    if (tempStockedOutList != null)
                    {

                        foreach (DepartmentStockOutDetail outDetail in tempStockedOutList)
                        {
                            totaltempErrorStockOut += outDetail.Quantity;
                        }

                    }

                    IList reStockList = DepartmentStockInDetailDAO.FindReStock(stockOutDetail.Product.ProductId);
                    if (reStockList != null)
                    {
                        foreach (DepartmentStockInDetail stockInDetail in reStockList)
                        {
                            totalReStockCount += stockInDetail.Quantity;
                        }
                    }
                    totaltempErrorStockOut = totaltempErrorStockOut - totalReStockCount;
                    if (stockOutDetail.ErrorQuantity > stock.ErrorQuantity - totaltempErrorStockOut)
                    {
                        throw new BusinessException("Lỗi: Mặt hàng " + stockOutDetail.Product.ProductFullName + ", mã vạch "
                                       + stockOutDetail.Product.ProductId + " có tồn " + stock.ErrorQuantity + ", đã xuất tạm " + totaltempErrorStockOut +
                                       ", và đang xuất " + stockOutDetail.ErrorQuantity);
                    }
                    /*defect.ErrorQuantity -= stockOutDetail.ErrorQuantity;
                    defect.Quantity -= stockOutDetail.Quantity;
                    DepartmentStockDAO.Update(defect);*/
                }
                tempSO.DepartmentStockOutDetails = tempStockOutList;
                DepartmentStockOutDAO.Add(tempSO);

                //maxDetailId += 1;
                foreach (DepartmentStockOutDetail detail in tempStockOutList)
                {
                    detail.DepartmentStockOutDetailPK = new DepartmentStockOutDetailPK();
                    detail.DepartmentStockOutDetailPK.DepartmentId = CurrentDepartment.Get().DepartmentId;
                    detail.DepartmentStockOutDetailPK.StockOutDetailId = maxDetailId++;
                    DepartmentStockOutDetailDAO.Add(detail);
                }
            }
        }
 public void NotifyNewMultiDepartmentStockOut(Department department, DepartmentStockOut[] list, DepartmentPrice price)
 {
 }
        private void DoPrinting(DepartmentStockOut deptStockOut)
        {
            streamList = new List<Stream>();
            // push data to local report
            DeptStockOutInvoice = new LocalReport();
            DeptStockOutInvoice.ReportEmbeddedResource = "AppFrameClient.Report.DepartmentStockOutInvoice.rdlc";

            ReportDataSource DeptStockOutRDS = new ReportDataSource("AppFrameClient_ViewModel_DepartmentStockOutView");
            BindingSource bdsHeader = new BindingSource();
            DepartmentStockOutView deptSOView = new DepartmentStockOutViewMapper().Convert(deptStockOut);
            deptSOView.EmployeeName = txtCustomerName.Text.Trim();
            if(rdoWholesale.Checked)
            {
                deptSOView.StockOutKind = "BÁN SỈ";
            }
            else
            {
                deptSOView.StockOutKind = "BÁN LẺ";
            }
            bdsHeader.DataSource = deptSOView;
            DeptStockOutRDS.Value = bdsHeader;
            DeptStockOutInvoice.DataSources.Add(DeptStockOutRDS);

            ReportDataSource DeptStockOutDetailRDS = new ReportDataSource("AppFrameClient_ViewModel_DepartmentStockOutDetailView");
            BindingSource bdsDetails = new BindingSource();
            DepartmentStockOutViewDetailMapper detailMapper = new DepartmentStockOutViewDetailMapper();
            IList<DepartmentStockOutDetailView> viewList = new List<DepartmentStockOutDetailView>();
            foreach (DepartmentStockOutDetail outDetail in deptStockOut.DepartmentStockOutDetails)
            {
                DepartmentStockOutDetailView detailView = detailMapper.Convert(outDetail);
                if(rdoWholesale.Checked)
                {
                    detailView.Price = outDetail.DepartmentPrice.WholeSalePrice;
                }
                else
                {
                    detailView.Price = outDetail.DepartmentPrice.Price;
                }

                viewList.Add(detailView);
            }
            // remove duplicate
            int count = viewList.Count;
            for (int i = 0; i < count; i++ )
            {
                DepartmentStockOutDetailView detailView = viewList[i];
                int last = count - 1;
                while(last >i)
                {
                    DepartmentStockOutDetailView otherView = viewList[last];
                    if(otherView.ProductName.Equals(detailView.ProductName))
                       //&& otherView.ColorName.Equals(detailView.ColorName) )
                    {
                        detailView.Quantity += otherView.Quantity;
                        detailView.GoodCount += otherView.GoodCount;

                        viewList.RemoveAt(last);
                        count -= 1;
                    }
                    last -= 1;
                }
            }
                bdsDetails.DataSource = viewList;
            DeptStockOutDetailRDS.Value = bdsDetails;
            DeptStockOutInvoice.DataSources.Add(DeptStockOutDetailRDS);

            // do printing
            streamList.Clear();
            //const string printerName = "Epson TM-T88IV";
            string printerName = ClientSetting.PrinterName;
            PrintDocument printDoc = new PrintDocument();
            printDoc.PrinterSettings.PrinterName = printerName;

            if (!printDoc.PrinterSettings.IsValid)
            {
                MessageBox.Show(String.Format("Can't find printer \"{0}\".", printerName));
                return;
            }
            PageSettings pageSettings = printDoc.PrinterSettings.DefaultPageSettings;
            pageSettings.PrinterResolution.X = 180;
            pageSettings.PrinterResolution.Y = 180;

            string deviceInfo =
            "<DeviceInfo>" +
            "  <OutputFormat>EMF</OutputFormat>" +
            "  <PageWidth>8.2in</PageWidth>" +
            "  <PageHeight>5.5in</PageHeight>" +
            "  <DpiX>180</DpiX>" +
            "  <DpiY>180</DpiY>" +
            "  <MarginTop>0.0in</MarginTop>" +
            "  <MarginLeft>0.0in</MarginLeft>" +
            "  <MarginRight>0.0in</MarginRight>" +
            "  <MarginBottom>0.0in</MarginBottom>" +
            "</DeviceInfo>";
            Warning[] warnings;
            if (DeptStockOutInvoice == null)
            {
                return;
            }
            DeptStockOutInvoice.Refresh();
            DeptStockOutInvoice.Render("Image", deviceInfo, CreateStream, out warnings);
            if (streamList.Count > 0)
            {
                foreach (Stream stream in streamList)
                {
                    stream.Position = 0;
                }
            }

            printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);
            printDoc.EndPrint += new PrintEventHandler(printDoc_EndPrint);
            printDoc.Print();
        }
 /// <summary>
 /// Update DepartmentStockOut to database.
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public void Update(DepartmentStockOut data)
 {
     HibernateTemplate.Update(data);
 }
        private void btnSave_Click(object sender, EventArgs e)
        {
            ShowMessage("Đang lưu .... ");
            DialogResult result = MessageBox.Show(lblCommandDescription.Text +".Chắc chắn muốn lưu ?",
                "Xác nhận",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if(result == System.Windows.Forms.DialogResult.No)
            {
                return;
            }

            // first remove all blank row
            int count = 0;
            int length = deptSODetailList.Count;
            for (int i = 0; i < length - count; i++)
            {
                DepartmentStockOutDetail detail = deptSODetailList[i];
                if (string.IsNullOrEmpty(detail.Product.ProductMaster.ProductMasterId)
                    && string.IsNullOrEmpty(detail.Product.ProductMaster.ProductName))
                {
                    deptSODetailList.RemoveAt(i - count);
                    count++;
                }
            }

            if (deptSODetailList.Count == 0)
            {
                MessageBox.Show("Không có sản phẩm nào để nhập kho!!!!");
                return;
            }

            // validate quantity
            int line = 1;
            foreach (DepartmentStockOutDetail detail in deptSODetailList)
            {
                foreach (DepartmentStock stock in departmentStockList)
                {
                    if (detail.Product.ProductId.Equals(stock.Product.ProductId))
                    {
                        // TEMP FIXING FOR EXPORT NEGATIVE STOCK
                        if (!ClientSetting.NegativeExport)
                        {
                            if (detail.GoodQuantity <= 0 || detail.GoodQuantity > stock.GoodQuantity)
                            {
                                MessageBox.Show("Lỗi ở dòng " + line +
                                                " : Số lượng Xuất phải là số dương nhỏ hơn hoặc bằng " +
                                                stock.GoodQuantity);
                                dgvDeptStockIn.CurrentCell = dgvDeptStockIn[7, line-1];
                                return;
                            }
                        }
                        if (detail.LostQuantity < 0 || detail.LostQuantity > stock.LostQuantity)
                        {
                            MessageBox.Show("Lỗi ở dòng " + line + " : Số lượng Mất phải là số dương nhỏ hơn hoặc bằng " + stock.LostQuantity);
                            dgvDeptStockIn.CurrentCell = dgvDeptStockIn[7, line-1];
                            return;
                        }
                        if (detail.DamageQuantity < 0 || detail.DamageQuantity > stock.DamageQuantity)
                        {
                            MessageBox.Show("Lỗi ở dòng " + line + " : Số lượng Lỗi phải là số dương nhỏ hơn hoặc bằng " + stock.DamageQuantity);
                            dgvDeptStockIn.CurrentCell = dgvDeptStockIn[7, line-1];
                            return;
                        }
                        if (detail.ErrorQuantity < 0 || detail.ErrorQuantity > stock.ErrorQuantity)
                        {
                            MessageBox.Show("Lỗi ở dòng " + line + " : Số lượng Hư phải là số dương nhỏ hơn hoặc bằng " + stock.ErrorQuantity);
                            dgvDeptStockIn.CurrentCell = dgvDeptStockIn[7, line-1];
                            return;
                        }
                    }
                }

                if ((detail.DefectStatus.DefectStatusId == 4 && detail.ErrorQuantity == 0)
                    || (detail.DefectStatus.DefectStatusId == 6 && detail.DamageQuantity + detail.GoodQuantity + detail.ErrorQuantity == 0)
                    || (detail.DefectStatus.DefectStatusId == 7 && detail.GoodQuantity == 0))
                {
                    MessageBox.Show("Lỗi ở dòng " + line + " : Số lượng xuất phải lớn hơn 0.");
                    dgvDeptStockIn.CurrentCell = dgvDeptStockIn[0, line];
                    return;
                }
                line++;
            }

            if (deptSO == null)
            {
                deptSO = new DepartmentStockOut();
            }
            bool isNeedClearData = deptSO.DepartmentStockOutPK == null || deptSO.DepartmentStockOutPK.StockOutId == 0;
            deptSO.StockOutDate = DateTime.Now;
            deptSO.DefectStatus = (StockDefectStatus)cbbStockOutType.SelectedItem;
            deptSO.OtherDepartmentId = ((Department)cboDepartment.SelectedItem).DepartmentId;
            deptSO.DepartmentStockOutDetails = new ArrayList();
            foreach (DepartmentStockOutDetail outDetail in deptSODetailList)
            {
                deptSO.DepartmentStockOutDetails.Add(outDetail);
            }
            //deptSO.DepartmentStockOutDetails = deptSODetailList;
            //deptSO.ConfirmFlg = 3;

                foreach (DepartmentStockOutDetail outDetail in deptSO.DepartmentStockOutDetails)
                {
                    if (rdoWholesale.Checked) // if ban si
                    {
                        outDetail.Description = "1";
                    }
                    else
                    {
                        outDetail.Description = "0";
                    }
                }

            //            deptSO.Description = txtDexcription.Text;
            var eventArgs = new DepartmentStockOutEventArgs();
            eventArgs.DepartmentStockOut = deptSO;

            // confirm before save
            DialogResult isConfirmed = System.Windows.Forms.DialogResult.Cancel;
            if (!ClientSetting.ConfirmByEmployeeId)
            {
                LoginForm loginForm = GlobalUtility.GetFormObject<LoginForm>(FormConstants.CONFIRM_LOGIN_VIEW);
                loginForm.StartPosition = FormStartPosition.CenterScreen;
                isConfirmed = loginForm.ShowDialog();
            }
            else
            {
                EmployeeCheckingForm employeeCheckingForm = GlobalUtility.GetFormObject<EmployeeCheckingForm>(FormConstants.EMPLOYEE_CHECKING_VIEW);
                employeeCheckingForm.StartPosition = FormStartPosition.CenterScreen;
                isConfirmed = employeeCheckingForm.ShowDialog();
            }
            if(isConfirmed!= System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("Không xác nhận được nguoi gửi ....", "Lỗi",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }

            // continue stock out
            if(rdoFastStockOut.Checked)
            {
                ShowMessage("Đang truyền thông tin .... ");
                try
                {
                    if(eventArgs.EventResult!=null)
                    {
                        //EventUtility.fireAsyncEvent(DispatchDepartmentStockOut, this, eventArgs, new AsyncCallback(EndEvent));
                        EventUtility.fireEvent(SaveStockOutEvent, this, eventArgs);
                        EventUtility.fireEvent(DispatchDepartmentStockOut, this, eventArgs);
                    }

                }
                catch (Exception)
                {
                    lblInformation.ForeColor = Color.Red;
                    lblInformation.Text = " Không kết nối được với máy cửa hàng! ";
                    deptSO = new DepartmentStockOut();
                    deptSODetailList.Clear();
                    //                    txtDexcription.Text = "";
                    //                    txtPriceIn.Text = "";
                    //                    txtPriceOut.Text = "";
                    txtSumProduct.Text = "";
                    txtSumValue.Text = "";
                    return;
                }
            }

            if(rdoStockOut.Checked)
            {
                EventUtility.fireEvent(SaveStockOutEvent, this, eventArgs);
                if (eventArgs.DepartmentStockOut.DepartmentStockOutPK == null || eventArgs.DepartmentStockOut.DepartmentStockOutPK.StockOutId == 0)
                {
                    ShowError(lblInformation, "Có lỗi phát sinh làm chương trình không in được. Liên hệ nhà quản trị.");
                }
                if (eventArgs.EventResult != null)
                {
                    EventUtility.fireEvent(PrepareDepartmentStockOutForPrintEvent, this, eventArgs);
                    // do printing
                    DoPrinting(eventArgs.DepartmentStockOut);
                }

            }
            if (eventArgs.EventResult != null)
            {
                /*if(!rdoFastStockOut.Checked)
                {*/
                    lblInformation.Text = "Lưu thành công";
                /*}*/

                if (isNeedClearData)
                {
                    lblInformation.ForeColor = Color.Blue;
                    deptSO = new DepartmentStockOut();
                    deptSODetailList.Clear();
                    txtSumProduct.Text = "";
                    txtSumValue.Text = "";
                    ClearSelectionOnListBox(lstColor);
                    ClearSelectionOnListBox(lstSize);

                }
            }
            else
            {
                //MessageBox.Show("Có lỗi khi lưu");
                lblInformation.ForeColor = Color.Red;
                lblInformation.Text = "Lưu thất bại ...";
            }
            if(LocalCache.Instance().PreviousUser !=null)
            {
                ClientInfo.getInstance().LoggedUser = LocalCache.Instance().PreviousUser;
                LocalCache.Instance().PreviousUser = null;
            }
            txtBarcode.Focus();
        }
 /// <summary>
 /// Add DepartmentStockOut to database.
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public DepartmentStockOut Add(DepartmentStockOut data)
 {
     HibernateTemplate.Save(data);
     return data;
 }
        private void DepartmentStockInExtra_Load(object sender, EventArgs e)
        {
            timer1.Start();
            cbbStockOutType.Enabled = false;
            btnReset.Enabled = false;
            cboProductMasters.Enabled = false;

            rdoFastStockOut.Checked = true;
            rdoRetail.Checked = true;
            IList list = new ArrayList();
            if (ClientSetting.IsSubStock())
            {
                list.Add(new StockDefectStatus {DefectStatusId = 7, DefectStatusName = "Xuất đi cửa hàng khác"});
            }
            else
            {
                list.Add(new StockDefectStatus { DefectStatusId = 4, DefectStatusName = "Xuất tạm để sửa hàng" });
                list.Add(new StockDefectStatus { DefectStatusId = 6, DefectStatusName = "Xuất trả về kho chính" });

            }
            DepartmentStockOutEventArgs eventArgs = new DepartmentStockOutEventArgs();
            EventUtility.fireEvent(LoadAllDepartments,this,eventArgs);
            string directDept = "";
            string marketDept = "";
            if(eventArgs.DepartmentsList!= null && eventArgs.DepartmentsList.Count > 0)
            {
                BindingSource bdsDepartment = new BindingSource();
                bdsDepartment.DataSource = typeof (Department);
                cboDepartment.DataSource = bdsDepartment;
                cboDepartment.DisplayMember = "DepartmentName";
                foreach (Department department in eventArgs.DepartmentsList)
                {
                    if (department.DepartmentId != CurrentDepartment.Get().DepartmentId)
                    {
                        /*if (!ClientSetting.IsSubStock())
                        {*/
                            bdsDepartment.Add(department);
                        /*}
                        else
                        {
                            string departmentId = department.DepartmentId.ToString();
                            string currentSubStock = CurrentDepartment.Get().DepartmentId.ToString();
                            if(currentSubStock.StartsWith(departmentId))
                            {
                                bdsDepartment.Add(department);
                                directDept = department.DepartmentName;
                            }
                            if(ClientSetting.MarketDept.Equals(departmentId))
                            {
                                bdsDepartment.Add(department);
                                marketDept = department.DepartmentName;
                            }
                        }*/

                    }
                }
                bdsDepartment.EndEdit();
                cboDepartment.Refresh();
                cboDepartment.Invalidate();
            }

            cbbStockOutType.DataSource = list;
            cbbStockOutType.DisplayMember = "DefectStatusName";
            /*if(!string.IsNullOrEmpty(directDept))
            {
                rdoFastStockOut.Text = " Xuất đến " + directDept;
            }*/
            /*foreach (Department department in cboDepartment.Items)
            {
                string departmentId = department.DepartmentId.ToString();
                string currentSubStock = CurrentDepartment.Get().DepartmentId.ToString();
                if (currentSubStock.StartsWith(departmentId))
                {
                    cboDepartment.SelectedItem = department;
                    cboDepartment.Enabled = false;
                    break;
                }
            }*/

            rdoFastStockOut_CheckedChanged(null, null);
            rdoStockOut_CheckedChanged(null, null);
            deptSODetailList = new DepartmentStockOutDetailCollection(bdsStockIn);
            bdsStockIn.DataSource = deptSODetailList;
            dgvDeptStockIn.DataError += new DataGridViewDataErrorEventHandler(dgvDeptStockIn_DataError);

            // create DepartmentStockIn
            if (deptSO == null)
            {
                deptSO = new DepartmentStockOut();
                deptSO.CreateDate = DateTime.Now;
                deptSO.UpdateDate = DateTime.Now;
                deptSO.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                deptSO.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                deptSO.ExclusiveKey = 0;
                CreateNewStockInDetail();
            //                btnBarcode.Visible = false;
            //                numericUpDownBarcode.Visible = false;
            //                btnPreview.Visible = false;
                // load products to extra combo box
                LoadProductMasterToComboBox();
                deptSODetailList.RemoveAt(0);
                bdsStockIn.EndEdit();

            }
            else
            {
            //                btnBarcode.Visible = true;
            //                numericUpDownBarcode.Visible = true;
            //                btnPreview.Visible = true;
                IList deptStockInDetails = deptSO.DepartmentStockOutDetails;
                foreach (DepartmentStockOutDetail detail in deptStockInDetails)
                {
                    if (detail.DelFlg == CommonConstants.DEL_FLG_NO)
                    {
                        deptSODetailList.Add(detail);
                        //detail.OldQuantity = detail.Quantity;
                    }
                }

                for (int i = 0; i < dgvDeptStockIn.Columns.Count; i++)
                {
                    dgvDeptStockIn.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                    if (i != QUANTITY_POS
                            && i != PRICE_POS
                            && i != SELL_PRICE_POS)
                    {
                        dgvDeptStockIn.Columns[i].ReadOnly = true;
                    }
                }
            //                txtDexcription.Text = deptSO.Description;
            }
            deptSO.DepartmentStockOutDetails =
                    ObjectConverter.ConvertToNonGenericList<DepartmentStockOutDetail>(deptSODetailList);

            UpdateStockOutDescription();
            cboDepartment.Enabled = false;
            GlobalMessage message = (GlobalMessage)GlobalUtility.GetObject("GlobalMessage");
            message.HasNewMessageEvent += new EventHandler<GlobalMessageEventArgs>(Instance_HasNewMessageEvent);
        }
 public void NotifyNewDepartmentStockOut(Department department, DepartmentStockOut stockOut, DepartmentPrice price)
 {
 }