Exemplo n.º 1
0
        public void Add(DepartmentStockIn data)
        {
            string deptStr = string.Format("{0:000}", data.DepartmentId);
            string dateStr = data.StockInDate.ToString("yyMMdd");
            var criteria = new ObjectCriteria();
            criteria.AddGreaterCriteria("StockoutId", (long)0);

            var maxId = StockOutDAO.SelectSpecificType(criteria, Projections.Max("StockoutId"));
            var stockOutId = maxId == null ? 1 : Int64.Parse(maxId.ToString()) + 1;

            //var stockInPk = new DepartmentStockInPK { DepartmentId = data.DepartmentId, StockInId = stockOutId + "" };

            //data.DepartmentStockInPK = stockInPk;
            data.CreateDate = DateTime.Now;
            data.UpdateDate = DateTime.Now;
            data.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
            data.CreateId = ClientInfo.getInstance().LoggedUser.Name;

            StockOut stockOut = new StockOut();
            stockOut.StockoutId = stockOutId;
            stockOut.CreateDate = DateTime.Now;
            stockOut.UpdateDate = DateTime.Now;
            stockOut.StockOutDate = DateTime.Now;
            stockOut.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
            stockOut.CreateId = ClientInfo.getInstance().LoggedUser.Name;
            stockOut.NotUpdateMainStock = false;
            stockOut.DefectStatus = new StockDefectStatus { DefectStatusId = 0};
            stockOut.DelFlg = 0;
            stockOut.DepartmentId = data.DepartmentId;

            // we will get the stock to get the data
            IList productMasterIds = new ArrayList();
            foreach (DepartmentStockInDetail stockInDetail in data.DepartmentStockInDetails)
            {
                productMasterIds.Add(stockInDetail.Product.ProductMaster.ProductMasterId);
            }
            IList productIds = new ArrayList();
            foreach (DepartmentStockInDetail stockInDetail in data.DepartmentStockInDetails)
            {
                productIds.Add(stockInDetail.Product.ProductId);
            }

            criteria = new ObjectCriteria();
            criteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
            criteria.AddGreaterCriteria("Quantity", (long)0);
            //criteria.AddSearchInCriteria("ProductMaster.ProductMasterId", productMasterIds);
            criteria.AddSearchInCriteria("Product.ProductId", productIds);
            //criteria.AddOrder("ProductMaster.ProductMasterId", true);
            criteria.AddOrder("Product.ProductId", true);
            IList stockList = StockDAO.FindAll(criteria);

            IList updateStockList = new ArrayList();
            IList stockOutDetailList = new ArrayList();

            var maxSODetailId = StockOutDetailDAO.SelectSpecificType(new ObjectCriteria(), Projections.Max("StockOutDetailId"));
            long stockOutDetailId = (maxSODetailId == null ? 1 : Int64.Parse(maxSODetailId.ToString()) + 1);

            foreach (DepartmentStockInDetail stockInDetail in data.DepartmentStockInDetails)
            {
                long quantity = stockInDetail.Quantity;
                foreach (Stock stock in stockList)
                {
                    long stockInQty = 0;
                    //if (stock.ProductMaster.ProductMasterId.Equals(stockInDetail.Product.ProductMaster.ProductMasterId) && stock.Quantity > 0)
                    if (stock.Product.ProductId.Equals(stockInDetail.Product.ProductId) && stock.Quantity > 0)
                    {
                        if (quantity > stock.GoodQuantity)
                        {
                            throw new BusinessException("Mặt hàng: " + stock.ProductMaster.ProductName
                                + " - mã vạch: " + stock.Product.ProductId
                                + " không đủ hàng! Tồn: " + stockInDetail.StockQuantity + " , cần xuất: " + quantity);

                            stockInQty = stock.GoodQuantity;
                            quantity -= stock.GoodQuantity;
                            stock.GoodQuantity = 0;
                        }
                        else
                        {
                            stockInQty = quantity;
                            stock.GoodQuantity -= quantity;
                            quantity = 0;
                        }
                        stock.Quantity = stock.GoodQuantity + stock.ErrorQuantity + stock.DamageQuantity +
                                         stock.LostQuantity + stock.UnconfirmQuantity;
                        stock.UpdateDate = DateTime.Now;
                        stock.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                        updateStockList.Add(stock);

                        /*var pk = new StockOutDetailPK
                        {
                            //DepartmentId = data.DepartmentId,
                            ProductId = stock.Product.ProductId,
                            StockOutId = stockOutId
                        };*/

                        var detail = new StockOutDetail
                                         {
                                             //StockOutDetailPK = pk,
                            StockOutDetailId = stockOutDetailId++,
                            StockOutId = stockOutId,
                            StockOut = stockOut,
                            Product =  stock.Product,
                            ProductId = stock.Product.ProductId,
                            Price = stockInDetail.Price,
                            DelFlg = 0,
                            ExclusiveKey = 1,
                            Description = "Export goods",
                            DefectStatus = new StockDefectStatus { DefectStatusId = 0},
                            Quantity = stockInQty,
                            GoodQuantity = stockInQty,
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UpdateId = ClientInfo.getInstance().LoggedUser.Name,
                            CreateId = ClientInfo.getInstance().LoggedUser.Name,
                            ProductMaster = stock.ProductMaster,

                        };
                        /*var deptStock = new DepartmentStock
                        {
                            DepartmentStockPK = new DepartmentStockPK
                            {
                                DepartmentId = data.DepartmentId,
                                ProductId = stock.Product.ProductId
                            },
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UpdateId = ClientInfo.getInstance().LoggedUser.Name,
                            CreateId = ClientInfo.getInstance().LoggedUser.Name,
                            ProductMaster = stock.ProductMaster
                        };*/
                        stockOutDetailList.Add(detail);
                        if (quantity == 0)
                        {
                            break;
                        }
                    }
                }
                if (quantity > 0)
                {
                    if (data.DepartmentStockInPK != null)
                    {
                        data.DepartmentStockInPK.StockInId = null;
                    }
                    throw new BusinessException("Số lượng xuất kho lớn hơn số lượng trong kho : " + stockInDetail.Product.ProductId);
                }
            }
            // insert stock out and stockout detail
            stockOut.StockOutDetails = stockOutDetailList;
            if(ClientSetting.ExportConfirmation)
            {
                stockOut.ConfirmFlg = 1;
            }
            StockOutDAO.Add(stockOut);

            // Remove duplicate rows
            int count = 0;
            while (count < (stockOutDetailList.Count - 1))
            {
                StockOutDetail detail1 = (StockOutDetail)stockOutDetailList[count];
                detail1.CreateDate = DateTime.Now;
                detail1.UpdateDate = DateTime.Now;
                int maxCount = stockOutDetailList.Count - 1;
                while (maxCount > count)
                {
                    StockOutDetail detail2 = (StockOutDetail)stockOutDetailList[maxCount];

                    if (detail1.Product.ProductId.Equals(detail2.Product.ProductId))
                    {
                        detail1.Quantity += detail2.Quantity;
                        stockOutDetailList.RemoveAt(maxCount);
                    }
                    maxCount--;
                }
                count++;
            }

            foreach (StockOutDetail detail in stockOutDetailList)
            {
                StockOutDetailDAO.Add(detail);
            }

            if (!ClientSetting.ExportConfirmation)
            {
                // update stock
                foreach (Stock stock in updateStockList)
                {
                    StockDAO.Update(stock);
                }
            }
        }
Exemplo n.º 2
0
        public void Update(StockOut stockOut)
        {
            int listCount = stockOut.StockOutDetails.Count;
            int delCount = 0;
            if(stockOut.ConfirmFlg == 1)
            {
                stockOut.NotUpdateMainStock = true;
            }
            var maxStockOutDetailIdStr = StockOutDetailDAO.SelectSpecificType(null, Projections.Max("StockOutDetailId"));
            long maxStockOutDetailId = maxStockOutDetailIdStr != null ? Int64.Parse(maxStockOutDetailIdStr.ToString()) : 0;
            maxStockOutDetailId = maxStockOutDetailId + 1;
            IList productIds = new ArrayList();
            foreach (StockOutDetail stockOutDetail in stockOut.StockOutDetails)
            {
                productIds.Add(stockOutDetail.Product.ProductId);
            }
            var criteria = new ObjectCriteria();
            criteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
            criteria.AddSearchInCriteria("Product.ProductId", productIds);

            IList stockList = StockDAO.FindAll(criteria);
            foreach (StockOutDetail stockOutDetail in stockOut.StockOutDetails)
            {
                if (stockOutDetail.StockOutDetailId != 0)
                {
                    // if delete then delete it
                    if(stockOutDetail.DelFlg == 1)
                    {
                        StockOutDetailDAO.Delete(stockOutDetail);
                        delCount++;
                        continue;
                    }
                    // check number
                    var objectCriteria = new ObjectCriteria();
                    objectCriteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
                    objectCriteria.AddEqCriteria("Product.ProductId", stockOutDetail.Product.ProductId);

                    Stock stock = GetStock(stockOutDetail.Product.ProductId, stockList);
                    if (stock == null)
                    {
                        throw new BusinessException("Mặt hàng " + stockOutDetail.Product.ProductId + ", " +
                                                    stockOutDetail.Product.ProductFullName + " không có trong kho");
                    }

                    stockOutDetail.LostQuantity = 0;
                    stockOutDetail.UnconfirmQuantity = 0;

                    // xuất ra cửa hàng khác
                    if (stockOut.DefectStatus != null && stockOut.DefectStatus.DefectStatusId == 7)
                    {
                        stockOutDetail.Quantity = stockOutDetail.GoodQuantity;
                        stock.Quantity -= stockOutDetail.Quantity;

                        stockOutDetail.ErrorQuantity = 0;
                        stockOutDetail.DamageQuantity = 0;
                        stockOutDetail.LostQuantity = 0;
                        stockOutDetail.UnconfirmQuantity = 0;

                    }// xuất tạm
                    else if (stockOut.DefectStatus != null && stockOut.DefectStatus.DefectStatusId == 4)
                    {
                        // 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 = StockOutDetailDAO.FindAll(crit);
                        if (tempStockedOutList != null)
                        {

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

                        }

                        IList reStockList = StockInDetailDAO.FindReStock(stockOutDetail.Product.ProductId);
                        if (reStockList != null)
                        {
                            foreach (StockInDetail 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);
                        }

                        // update quantity
                        stockOutDetail.Quantity = stockOutDetail.ErrorQuantity;
                        //stockOutDetail.ErrorQuantity = 0;
                        stockOutDetail.GoodQuantity = 0;
                        stockOutDetail.UnconfirmQuantity = 0;
                        stockOutDetail.LostQuantity = 0;
                        stockOutDetail.DamageQuantity = 0;
                    }
                        // xuất trả về cho nhà sản xuất
                    else if (stockOut.DefectStatus != null && stockOut.DefectStatus.DefectStatusId == 5)
                    {
                        stockOutDetail.Quantity = stockOutDetail.GoodQuantity + stockOutDetail.ErrorQuantity;
                        stock.Quantity -= stockOutDetail.Quantity;
                        stock.ErrorQuantity -= stockOutDetail.ErrorQuantity;
                        stockOutDetail.UnconfirmQuantity = 0;
                        stockOutDetail.LostQuantity = 0;
                    }
                        // xuất hàng mẫu
                    else if (stockOut.DefectStatus != null && stockOut.DefectStatus.DefectStatusId == 9)
                    {
                        stockOutDetail.Quantity = stockOutDetail.GoodQuantity;
                        stockOutDetail.ErrorQuantity = 0;
                        stockOutDetail.UnconfirmQuantity = 0;
                        stockOutDetail.LostQuantity = 0;
                    }
                    else // xuat hang binh thuong
                    {
                        if(stockOutDetail.Quantity > 0
                            && (    stockOutDetail.GoodQuantity == 0
                                 && stockOutDetail.ErrorQuantity ==0
                                 && stockOutDetail.DamageQuantity == 0
                                 && stockOutDetail.LostQuantity == 0
                                 && stockOutDetail.UnconfirmQuantity == 0))
                        {
                            stockOutDetail.GoodQuantity = stockOutDetail.Quantity;
                        }
                        stockOutDetail.Quantity = stockOutDetail.GoodQuantity;
                        stock.Quantity -= stockOutDetail.Quantity;
                        stockOutDetail.ErrorQuantity = 0;
                        stockOutDetail.UnconfirmQuantity = 0;
                        stockOutDetail.LostQuantity = 0;

                    }
                    // if need to update main stock
                    if (!stockOut.NotUpdateMainStock)
                    {
                        stock.GoodQuantity -= stockOutDetail.GoodQuantity;
                        stock.UpdateDate = DateTime.Now;
                        stock.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                        StockDAO.Update(stock);

                        // update stock out create date
                        stockOut.CreateDate = DateTime.Now;
                        stockOut.UpdateDate = DateTime.Now;

                        stockOutDetail.CreateDate = DateTime.Now;
                        stockOutDetail.UpdateDate = DateTime.Now;
                    }

                    StockOutDetailDAO.Update(stockOutDetail);
                }
                else
                {
                    // check number
                    var objectCriteria = new ObjectCriteria();
                    objectCriteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
                    objectCriteria.AddEqCriteria("Product.ProductId", stockOutDetail.Product.ProductId);

                    Stock stock = GetStock(stockOutDetail.Product.ProductId, stockList);
                    if (stock == null)
                    {
                        throw new BusinessException("Mặt hàng " + stockOutDetail.Product.ProductId + ", " +
                                                    stockOutDetail.Product.ProductFullName + " không có trong kho");
                    }
                    stockOutDetail.LostQuantity = 0;
                    stockOutDetail.UnconfirmQuantity = 0;
                    // xuất ra cửa hàng khác
                    if (stockOut.DefectStatus != null && stockOut.DefectStatus.DefectStatusId == 7)
                    {
                        stockOutDetail.Quantity = stockOutDetail.GoodQuantity;
                        stock.Quantity -= stockOutDetail.Quantity;

                        stockOutDetail.ErrorQuantity = 0;
                        stockOutDetail.DamageQuantity = 0;
                        stockOutDetail.LostQuantity = 0;
                        stockOutDetail.UnconfirmQuantity = 0;

                    }
                    // xuất tạm
                    else if (stockOut.DefectStatus != null && stockOut.DefectStatus.DefectStatusId == 4)
                    {
                        // 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 = StockOutDetailDAO.FindAll(crit);
                        if (tempStockedOutList != null)
                        {

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

                        }

                        IList reStockList = StockInDetailDAO.FindReStock(stockOutDetail.Product.ProductId);
                        if (reStockList != null)
                        {
                            foreach (StockInDetail 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);
                        }

                        // update quantity
                        stockOutDetail.Quantity = stockOutDetail.ErrorQuantity;
                        //stockOutDetail.ErrorQuantity = 0;
                        stockOutDetail.GoodQuantity = 0;
                        stockOutDetail.UnconfirmQuantity = 0;
                        stockOutDetail.LostQuantity = 0;
                        stockOutDetail.DamageQuantity = 0;
                    }
                    // xuất trả về cho nhà sản xuất
                    else if (stockOut.DefectStatus != null && stockOut.DefectStatus.DefectStatusId == 5)
                    {
                        stockOutDetail.Quantity = stockOutDetail.GoodQuantity + stockOutDetail.ErrorQuantity;
                        stock.Quantity -= stockOutDetail.Quantity;
                        stock.ErrorQuantity -= stockOutDetail.ErrorQuantity;
                        stockOutDetail.UnconfirmQuantity = 0;
                        stockOutDetail.LostQuantity = 0;
                    }
                    // xuất hàng mẫu
                    else if (stockOut.DefectStatus != null && stockOut.DefectStatus.DefectStatusId == 9)
                    {
                        stockOutDetail.Quantity = stockOutDetail.GoodQuantity;
                        //stock.Quantity -= stockOutDetail.Quantity;
                        //stock.ErrorQuantity -= stockOutDetail.ErrorQuantity;
                        stockOutDetail.ErrorQuantity = 0;
                        stockOutDetail.UnconfirmQuantity = 0;
                        stockOutDetail.LostQuantity = 0;
                    }
                    // xuất hàng bình thường
                    else
                    {
                        if (stockOutDetail.Quantity > 0
                            && (stockOutDetail.GoodQuantity == 0
                                 && stockOutDetail.ErrorQuantity == 0
                                 && stockOutDetail.DamageQuantity == 0
                                 && stockOutDetail.LostQuantity == 0
                                 && stockOutDetail.UnconfirmQuantity == 0))
                        {
                            stockOutDetail.GoodQuantity = stockOutDetail.Quantity;
                        }
                        stockOutDetail.Quantity = stockOutDetail.GoodQuantity;
                        stock.Quantity -= stockOutDetail.Quantity;
                        stockOutDetail.ErrorQuantity = 0;
                        stockOutDetail.UnconfirmQuantity = 0;
                        stockOutDetail.LostQuantity = 0;
                    }
                    // if need to update main stock
                    if (!stockOut.NotUpdateMainStock)
                    {
                        stock.GoodQuantity -= stockOutDetail.GoodQuantity;
                        stock.UpdateDate = DateTime.Now;
                        stock.UpdateId = ClientInfo.getInstance().LoggedUser.Name;

                        StockDAO.Update(stock);

                        // update create date in order can get it when synchronizing
                        stockOut.CreateDate = DateTime.Now;
                        stockOut.UpdateDate = DateTime.Now;

                        stockOutDetail.CreateDate = DateTime.Now;
                        stockOutDetail.UpdateDate = DateTime.Now;

                    }

                    stockOutDetail.StockOut = stockOut;
                    stockOutDetail.StockOutDetailId = maxStockOutDetailId++;
                    stockOutDetail.StockOutId = stockOut.StockoutId;
                    stockOutDetail.ProductMaster = stockOutDetail.Product.ProductMaster;
                    StockOutDetailDAO.Add(stockOutDetail);
                }
            }

            if(delCount == listCount)
            {
                stockOut.DelFlg = 1;
            }

            if(stockOut.DelFlg!= 1)
            {
                StockOutDAO.Update(stockOut);
            }
            else
            {
                StockOutDAO.Delete(stockOut);
            }
        }
        public void SyncToMain(SyncFromDepartmentToMain sync)
        {
            // insert department stock temp
            if(sync.DepartmentStockTempList!=null && sync.DepartmentStockTempList.Count > 0)
            {
                foreach (DepartmentStockTemp departmentStockTemp in sync.DepartmentStockTempList)
                {
                    bool failed = false;
                    if (departmentStockTemp != null)
                    {
                        DepartmentStockTemp curDeptTemp = DepartmentStockTempDAO.FindById(departmentStockTemp.DepartmentStockTempPK);
                        if (curDeptTemp == null)
                        {
                            DepartmentStockTempDAO.Add(departmentStockTemp);
                        }
                        else
                        {
                            if(departmentStockTemp.Fixed == 1 && departmentStockTemp.DelFlg == 1)
                            {
                                curDeptTemp.Fixed = 1;
                                curDeptTemp.DelFlg = 1;
                                DepartmentStockTempDAO.Update(curDeptTemp);
                            }
                        }
                    }
                }
            }
            // insert timeline
            if (sync.DepartmentTimelineList != null && sync.DepartmentTimelineList.Count > 0)
            {
                foreach (DepartmentTimeline timeline in sync.DepartmentTimelineList)
                {
                    bool failed = false;
                    if (timeline != null)
                    {
                        DepartmentTimeline curTimeline = DepartmentTimelineDAO.FindById(timeline.DepartmentTimelinePK);
                        if (curTimeline == null)
                        {
                            DepartmentTimelineDAO.Add(timeline);
                        }
                        else
                        {
                            // error
                            //failed = true;
                        }
                    }
                }
            }

            // insert PO, PO Detail
            if (sync.PurchaseOrderList != null && sync.PurchaseOrderList.Count > 0)
            {
                foreach (PurchaseOrder po in sync.PurchaseOrderList)
                {
                    PurchaseOrder poTemp = PurchaseOrderDAO.FindById(po.PurchaseOrderPK);
                    if (poTemp == null)
                    {
                        PurchaseOrderDAO.Add(po);
                        foreach (PurchaseOrderDetail detail in po.PurchaseOrderDetails)
                        {
                            PurchaseOrderDetailDAO.Add(detail);
                        }
                    }
                    else
                    {
                        // Error
                        //failed = true;
                    }
                }
            }

            // insert dept stock out
            if (sync.DepartmentStockOutList != null && sync.DepartmentStockOutList.Count > 0)
            {
                IList productIds = new ArrayList();
                foreach (DepartmentStockOut po in sync.DepartmentStockOutList)
                {
                    if (po.DefectStatus.DefectStatusId == StockDefectStatus.SEND_BACK_TO_MAIN)
                    {
                        foreach (DepartmentStockOutDetail detail in po.DepartmentStockOutDetails)
                        {
                            if (NotInList(productIds, detail.Product.ProductId))
                            {
                                productIds.Add(detail.Product.ProductId);
                            }
                        }
                    }
                }
                IList stockList = new ArrayList();
                ObjectCriteria criteria = new ObjectCriteria();
                criteria.AddSearchInCriteria("Product.ProductId", productIds);
                stockList = StockDAO.FindAll(criteria);

                StockOutMapper mapper = new StockOutMapper();
                StockOutDetailMapper detailMapper = new StockOutDetailMapper();
                DeptRetProdStockInMapper drpsiMapper = new DeptRetProdStockInMapper();
                DeptRetProdStockInDetailMapper drpsiDetMapper = new DeptRetProdStockInDetailMapper();

                // save to main.
                string dateStr = DateTime.Now.ToString("yyMMdd");
                var SICriteria = new ObjectCriteria();
                var maxId = StockInDAO.SelectSpecificType(SICriteria, Projections.Max("StockInId"));
                var stockInId = maxId == null ? dateStr + "00001" : string.Format("{0:00000000000}", (Int64.Parse(maxId.ToString()) + 1));

                foreach (DepartmentStockOut po in sync.DepartmentStockOutList)
                {

                    /*if (po.DefectStatus.DefectStatusId == StockDefectStatus.SEND_BACK_TO_MAIN)
                    {
                        foreach (DepartmentStockOutDetail detail in po.DepartmentStockOutDetails)
                        {
                            productIds.Add(detail.Product.ProductId);
                        }
                    }*/
                    DepartmentStockOut poTemp = DepartmentStockOutDAO.FindById(po.DepartmentStockOutPK);
                    if (poTemp == null)
                    {
                        // ++ Add code for add an empty stock in : 20090906

                        po.StockOutDate = DateTime.Now;
                        DepartmentStockOutDAO.Add(po);

                        StockIn stockIn = drpsiMapper.Convert(po);
                        stockIn.StockInDate = DateTime.Now;
                        if (po.DefectStatus.DefectStatusId == StockDefectStatus.SEND_BACK_TO_MAIN)
                        {
                            stockIn.StockInType = 3; // stock in for stock out to manufacturers
                        }
                        stockIn.StockInDetails = new ArrayList();

                        foreach (DepartmentStockOutDetail detail in po.DepartmentStockOutDetails)
                        {
                            DepartmentStockOutDetailDAO.Add(detail);

                            // update stock if it's a dept stock out return to main ( defectstatus = 6 )
                            if (po.DefectStatus.DefectStatusId == StockDefectStatus.SEND_BACK_TO_MAIN
                                && stockList!=null
                                && stockList.Count > 0)
                            {
                                Stock stock = GetStockOfProduct(detail.Product,stockList);
                                if(stock!=null)
                                {
                                    stock.Quantity += detail.GoodQuantity + detail.ErrorQuantity;
                                    stock.GoodQuantity += detail.GoodQuantity;
                                    stock.ErrorQuantity += detail.ErrorQuantity;
                                    StockDAO.Update(stock);
                                }

                                StockInDetail detailStockIn = drpsiDetMapper.Convert(detail);
                                stockIn.StockInDetails.Add(detailStockIn);
                            }
                        }
                        if(stockIn.StockInDetails != null && stockIn.StockInDetails.Count > 0)
                        {

                            // save to main.
                            stockIn.StockInId = stockInId;
                            StockInDAO.Add(stockIn);

                            foreach (StockInDetail stockInDetail in stockIn.StockInDetails)
                            {
                                // add dept stock in
                                var detailPK = new StockInDetailPK { ProductId = stockInDetail.Product.ProductId, StockInId = stockInId };
                                stockInDetail.StockInDetailPK = detailPK;
                                StockInDetailDAO.Add(stockInDetail);
                            }
                            // create new stockInId
                            stockInId = string.Format("{0:00000000000}", (Int64.Parse(stockInId.ToString()) + 1));
                        }
                        // -- Add code for add an empty stock in : 20090906
                    }
                    else
                    {
                        // Error
                        //failed = true;
                    }
                }
            }

            // insert Dept stock in
            if (sync.DepartmentStockInList != null && sync.DepartmentStockInList.Count > 0)
            {
                foreach (DepartmentStockIn po in sync.DepartmentStockInList)
                {
                    DepartmentStockIn poTemp = DepartmentStockInDAO.FindById(po.DepartmentStockInPK);
                    if (poTemp == null)
                    {
                        DepartmentStockInDAO.Add(po);
                        foreach (DepartmentStockInDetail detail in po.DepartmentStockInDetails)
                        {
                            DepartmentStockInDetailDAO.Add(detail);
                        }
                    }
                    else
                    {
                        // Error
                    }
                }
            }

            // insert return po
            if (sync.ReturnPoList != null && sync.ReturnPoList.Count > 0)
            {
                foreach (ReturnPo po in sync.ReturnPoList)
                {
                    ReturnPo poTemp = ReturnPoDAO.FindById(po.ReturnPoPK);
                    if (poTemp == null)
                    {
                        ReturnPoDAO.Add(po);
                    }
                    else
                    {
                        // Error
                    }
                }
            }

            // insert stock history
            if (sync.DepartmentStockHistoryList != null && sync.DepartmentStockHistoryList.Count > 0)
            {
                foreach (DepartmentStockHistory po in sync.DepartmentStockHistoryList)
                {
                    DepartmentStockHistory poTemp = DepartmentStockHistoryDAO.FindById(po.DepartmentStockHistoryPK);
                    if (poTemp == null)
                    {
                        DepartmentStockHistoryDAO.Add(po);
                    }
                    else
                    {
                        // Error
                    }
                }
            }

            // insert or update dept stock
            if (sync.DepartmentStockList != null && sync.DepartmentStockList.Count > 0)
            {
                /*if (!failed)
                {*/
                    foreach (DepartmentStock po in sync.DepartmentStockList)
                    {

                        try
                        {
                            DepartmentStock poTemp = DepartmentStockDAO.FindById(po.DepartmentStockPK);
                            if (poTemp == null)
                            {
                                DepartmentStockDAO.Add(po);
                            }
                            else
                            {
                                poTemp.Quantity = po.Quantity;
                                poTemp.GoodQuantity = po.GoodQuantity;
                                poTemp.LostQuantity = po.LostQuantity;
                                poTemp.ErrorQuantity = po.ErrorQuantity;
                                poTemp.DamageQuantity = po.DamageQuantity;
                                poTemp.OldDamageQuantity = po.OldDamageQuantity;
                                poTemp.OldErrorQuantity = po.OldErrorQuantity;
                                poTemp.OldGoodQuantity = po.OldGoodQuantity;
                                poTemp.OldLostQuantity = po.OldLostQuantity;
                                poTemp.OldUnconfirmQuantity = po.OldUnconfirmQuantity;
                                poTemp.UnconfirmQuantity = po.UnconfirmQuantity;
                                poTemp.UpdateDate = DateTime.Now;
                                DepartmentStockDAO.Update(poTemp);
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                /*}*/
            }

            // sync dept cost
            if (sync.DepartmentCostList != null && sync.DepartmentCostList.Count > 0)
            {
                foreach (DepartmentCost departmentCost in sync.DepartmentCostList)
                {
                    DepartmentCost existDeptCost = DepartmentCostDAO.FindById(departmentCost.DepartmentCostPK);
                    if (existDeptCost == null)
                    {
                        DepartmentCostDAO.Add(departmentCost);
                    }
                }
            }

            // sync money
            if(sync.EmployeeMoneyList != null && sync.EmployeeMoneyList.Count > 0)
            {
                foreach (EmployeeMoney employeeMoney in sync.EmployeeMoneyList)
                {
                    EmployeeMoney existEmpMoney = EmployeeMoneyDAO.FindById(employeeMoney.EmployeeMoneyPK);
                    if (existEmpMoney == null)
                    {
                        EmployeeMoneyDAO.Add(employeeMoney);
                    }
                }
            }
        }
Exemplo n.º 4
0
        public void Delete(ProductMaster data)
        {
            long deptId = CurrentDepartment.Get().DepartmentId;
            // delete product master
            ProductMaster master = ProductMasterDAO.FindById(data.ProductMasterId);
            if (master != null)
            {
                master.UpdateDate = DateTime.Now;
                master.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                master.DelFlg = 1;
                ProductMasterDAO.Update(master);
            }

            // delete product
            var criteria = new ObjectCriteria();
            criteria.AddEqCriteria("ProductMaster.ProductMasterId", data.ProductMasterId);
            criteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
            IList products = ProductDAO.FindAll(criteria);
            IList productIds = new ArrayList();
            foreach (Product product in products)
            {
                product.UpdateDate = DateTime.Now;
                product.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                product.DelFlg = 1;
                ProductDAO.Update(product);
                productIds.Add(product.ProductId);
            }

            if (productIds.Count > 0)
            {
                // delete stock in detail
                criteria = new ObjectCriteria();
                criteria.AddEqCriteria("DepartmentStockInDetailPK.DepartmentId", deptId);
                criteria.AddSearchInCriteria("DepartmentStockInDetailPK.ProductId", productIds);
                IList stockInDetails = DepartmentStockInDetailDAO.FindAll(criteria);
                IList stockInIds = new ArrayList();
                foreach (DepartmentStockInDetail detail in stockInDetails)
                {
                    detail.UpdateDate = DateTime.Now;
                    detail.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                    detail.DelFlg = 1;
                    DepartmentStockInDetailDAO.Update(detail);
                    stockInIds.Add(detail.DepartmentStockInDetailPK.StockInId);
                }

                // delete stock in
                if (stockInIds.Count > 0)
                {
                    criteria = new ObjectCriteria();
                    criteria.AddEqCriteria("DepartmentStockInPK.DepartmentId", deptId);
                    criteria.AddSearchInCriteria("DepartmentStockInPK.StockInId", stockInIds);
                    IList stockIns = DepartmentStockInDAO.FindAll(criteria);
                    foreach (DepartmentStockIn stockIn in stockIns)
                    {
                        stockIn.UpdateDate = DateTime.Now;
                        stockIn.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                        stockIn.DelFlg = 1;
                        DepartmentStockInDAO.Update(stockIn);
                    }
                }

                // delete stock
                criteria = new ObjectCriteria();
                criteria.AddEqCriteria("DepartmentStockPK.DepartmentId", deptId);
                criteria.AddSearchInCriteria("DepartmentStockPK.ProductId", productIds);
                IList stocks = DepartmentStockDAO.FindAll(criteria);
                foreach (DepartmentStock stock in stocks)
                {
                    stock.UpdateDate = DateTime.Now;
                    stock.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                    stock.DelFlg = 1;
                    DepartmentStockDAO.Update(stock);
                }

                // delete purchase order detail
                criteria = new ObjectCriteria();
                criteria.AddEqCriteria("PurchaseOrderDetailPK.DepartmentId", deptId);
                criteria.AddEqCriteria("ProductMaster.ProductMasterId", data.ProductMasterId);
                IList purchaseOrderDetails = PurchaseOrderDetailDAO.FindAll(criteria);
                IList purchaseOrderIds = new ArrayList();
                foreach (PurchaseOrderDetail detail in purchaseOrderDetails)
                {
                    detail.UpdateDate = DateTime.Now;
                    detail.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                    detail.DelFlg = 1;
                    PurchaseOrderDetailDAO.Update(detail);
                    purchaseOrderIds.Add(detail.PurchaseOrderDetailPK.PurchaseOrderId);
                }

                // delete purchase order
                if (purchaseOrderIds.Count > 0)
                {
                    criteria = new ObjectCriteria();
                    criteria.AddEqCriteria("PurchaseOrderPK.DepartmentId", deptId);
                    criteria.AddSearchInCriteria("PurchaseOrderPK.PurchaseOrderId", purchaseOrderIds);
                    IList purchaseOrders = PurchaseOrderDAO.FindAll(criteria);
                    foreach (PurchaseOrder po in purchaseOrders)
                    {
                        po.UpdateDate = DateTime.Now;
                        po.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                        po.DelFlg = 1;
                        PurchaseOrderDAO.Update(po);
                    }
                }
            }

            // delete price
            var pricePk = new DepartmentPricePK{DepartmentId = deptId, ProductMasterId = data.ProductMasterId};
            var deptPrice = DepartmentPriceDAO.FindById(pricePk);
            if (deptPrice != null)
            {
                deptPrice.UpdateDate = DateTime.Now;
                deptPrice.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                deptPrice.DelFlg = 1;
                DepartmentPriceDAO.Update(deptPrice);
            }
        }
Exemplo n.º 5
0
        public PurchaseOrder Add(PurchaseOrder data)
        {
            /*var maxId = PurchaseOrderDAO.SelectSpecificType(null, Projections.Max("PurchaseOrderPK.PurchaseOrderId"));
            var purchaseOrderId = maxId == null ? 1 : (Int64.Parse(maxId.ToString()) + 1);*/
            string deptId = string.Format("{0:000}", CurrentDepartment.Get().DepartmentId);
            object maxId = PurchaseOrderDAO.SelectSpecificType(null, Projections.Max("PurchaseOrderPK.PurchaseOrderId"));
            string purchaseOrderId = "000000000001";
            if (maxId != null)
            {
                purchaseOrderId = string.Format("{0:000000000000000}", Int64.Parse(maxId.ToString()) + 1);
            }
            else
            {
                purchaseOrderId = deptId + "000000000001";
            }

            object maxReceptId = ReceiptDAO.SelectSpecificType(null, Projections.Max("ReceiptPK.ReceiptId"));
            string receiptId = "000000000001";
            if (maxReceptId != null)
            {
                receiptId = string.Format("{0:000000000000000}", Int64.Parse(maxReceptId.ToString()) + 1);
            }
            else
            {
                receiptId = deptId + "000000000001";
            }
            /*if(data.Receipts!= null && data.Receipts.Count > 0)
            {
                foreach (Receipt receipt in data.Receipts)
                {
                    receipt.ReceiptPK.ReceiptId = receiptId;
                    ReceiptDAO.Add(receipt);

                    // increase receiptId
                    receiptId = string.Format("{0:000000000000000}", Int64.Parse(receiptId.ToString()) + 1);
                }
            }*/
            /*var purchaseOrderId =
            if(purchaseOrderId==null)
            {
                string shortDateTime = DateTime.Now.ToString("yyMMdd");
                long departmentId = CurrentDepartment.Get().DepartmentId;
                purchaseOrderId = departmentId.ToString().PadLeft(3,'0') + shortDateTime + "0001";
            }
            else
            {
                // add max
                string purchaseCount = purchaseOrderId.Substring(purchaseOrderId.Length - 4);
                int nextPurchaseOrderIdNumber = int.Parse(purchaseCount) + 1;
                string nextPurchaseOrderId = nextPurchaseOrderIdNumber.ToString().PadLeft(4, '0');
                purchaseOrderId = purchaseOrderId.Substring(0, purchaseOrderId.Length - 4) + nextPurchaseOrderId;
            }*/
            PurchaseOrderPK purchaseOrderPk = new PurchaseOrderPK { DepartmentId = CurrentDepartment.Get().DepartmentId, PurchaseOrderId = purchaseOrderId };
            data.PurchaseOrderPK = purchaseOrderPk;
            data.UpdateDate = DateTime.Now;
            data.CreateDate = DateTime.Now;
            data.CreateId = ClientInfo.getInstance().LoggedUser.Name;
            data.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
            // add description
            string description = "";
            foreach (PurchaseOrderDetail detail in data.PurchaseOrderDetails)
            {
                description += detail.ProductMaster.ProductName+ " "+ System.Environment.NewLine;
            }
            data.PurchaseOrderDescription = description;

            // save customer
            Customer customer = data.Customer;

            bool isReturnOrder = IsReturnOrder(purchaseOrderPk.PurchaseOrderId,data.PurchaseOrderDetails);

            if(!isReturnOrder)
            {
                PurchaseOrderDAO.Add(data);
            }

            long id = 1;
            // create PurchaseOrderId for Undefined Purchase Order
            string undefinedPOId = null;
            long undefinedPODetailId = 1;
            foreach (PurchaseOrderDetail detail in data.PurchaseOrderDetails)
            {
                if (detail.PurchaseOrder != null
                   && detail.PurchaseOrder.PurchaseOrderPK!=null
                   && !string.IsNullOrEmpty(detail.PurchaseOrder.PurchaseOrderPK.PurchaseOrderId)
                   && detail.PurchaseOrder.PurchaseOrderPK.PurchaseOrderId.Equals("000"))
                {
                    undefinedPOId = deptId + "NA" + DateTime.Now.ToString("yyMMddHHmmss");
                    break;
                }
            }
            IDictionary<string,long> stockList = new Dictionary<string,long>();
            IDictionary<string, Product> productList = new Dictionary<string, Product>();
            foreach (PurchaseOrderDetail detail in data.PurchaseOrderDetails)
            {
                // nếu là hàng trả đổi
                if(     detail.PurchaseOrder!= null
                    && detail.PurchaseOrderDetailPK!= null
                    && !CheckUtility.IsNullOrEmpty(detail.PurchaseOrderDetailPK.PurchaseOrderId)
                    && !purchaseOrderId.Equals(detail.PurchaseOrder.PurchaseOrderPK.PurchaseOrderId)
                    )
                {
                    // Hàng trả đổi
                    ReturnPo po = new ReturnPo();
                    po.CreateDate = DateTime.Now;
                    po.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                    po.UpdateDate = DateTime.Now;
                    po.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                    ReturnPoPK poPK = new ReturnPoPK
                    {
                        DepartmentId = detail.PurchaseOrderDetailPK.DepartmentId,
                        PurchaseOrderId =
                            detail.PurchaseOrderDetailPK.PurchaseOrderId,
                        PurchaseOrderDetailId =
                            detail.PurchaseOrderDetailPK.PurchaseOrderDetailId,
                        CreateDate = DateTime.Now

                    };
                    po.ReturnPoPK = poPK;
                    po.Quantity = detail.Quantity;
                    if(detail.Price < 0)
                    {
                        po.Price = 0 - detail.Price;
                    }
                    else
                    {
                        po.Price = detail.Price;
                    }
                    po.ReturnDate = DateTime.Now;
                    po.Product = detail.Product;
                    if (detail.PurchaseOrder.PurchaseOrderPK.PurchaseOrderId.Equals("000"))
                    {
                        po.ReturnPoPK.PurchaseOrderId = undefinedPOId;
                        po.ReturnPoPK.PurchaseOrderDetailId = undefinedPODetailId++;

                    }
                    else
                    {

                        long originAmount = FindOriginAmount(detail);
                        if (originAmount == 0)
                        {
                            throw new BusinessException("Có lỗi ở hoá đơn gốc, đề nghị kiểm tra");
                        }
                        long returnedQuantity = (long) ReturnPoDAO.FindQuantityById(poPK);
                        long currentReturnQuantity = returnedQuantity + po.Quantity;
                        if (originAmount < currentReturnQuantity)
                        {
                            throw new BusinessException(
                                "Lỗi :" + detail.Product.ProductMaster.ProductName +
                                " .Tổng cộng :" + originAmount +
                                " .Đã trả : " + returnedQuantity +
                                " .Số lượng muốn trả: " + po.Quantity + " !");
                        }
                    }

                    ObjectCriteria stockCrit = new ObjectCriteria();
                    stockCrit.AddEqCriteria("DepartmentStockPK.ProductId", detail.Product.ProductId);
                    IList deptStockList = DepartmentStockDAO.FindAll(stockCrit);
                    if (deptStockList != null && deptStockList.Count > 0)
                    {

                        bool hasPrdFound = false;
                        foreach (string productId in stockList.Keys)
                        {
                            if (productId.Equals(detail.Product.ProductId))
                            {
                                long qty = stockList[productId];
                                qty = qty + detail.Quantity;
                                stockList[productId] = qty;
                                hasPrdFound = true;
                                break;
                            }
                        }
                        if (!hasPrdFound)
                        {
                            stockList.Add(detail.Product.ProductId,detail.Quantity);
                            productList.Add(detail.Product.ProductId,detail.Product);
                        }
                    }
                    else
                    {
                        throw new BusinessException("Không có mặt hàng này trong kho. Xin vui lòng kiểm tra dữ liệu");
                    }
                    if(!isReturnOrder)
                    {
                        po.NextPurchaseOrderId = purchaseOrderId;
                    }
                    ReturnPoDAO.Add(po);
                    // go to next detail
                    continue;
                }

                /*var sql = new StringBuilder(FIND_STOCK_SQL);
                // load the stock
                var criteria = new ObjectCriteria(true);
                criteria.AddEqCriteria("s.DelFlg", CommonConstants.DEL_FLG_NO)
                        .AddEqCriteria("s.DepartmentStockPK.DepartmentId", CurrentDepartment.Get().DepartmentId)
                        .AddEqCriteria("pm.ProductMasterId", detail.ProductMaster.ProductMasterId)
                        .AddEqCriteria("s.Product.ProductId",detail.Product.ProductId);
                foreach (SQLQueryCriteria crit in criteria.GetQueryCriteria())
                {
                    sql.Append(" AND ")
                       .Append(crit.PropertyName)
                       .Append(" ")
                       .Append(crit.SQLString)
                       .Append(" :")
                       .Append(crit.PropertyName)
                       .Append(" ");
                }
                sql.Append(" ORDER BY s.CreateDate ASC");*/
                bool hasFound = false;
                foreach (string productId in stockList.Keys)
                {
                   if(productId.Equals(detail.Product.ProductId))
                   {
                       long qty = stockList[productId];
                       qty = qty - detail.Quantity;
                       stockList[productId] = qty;
                       hasFound = true;
                       break;
                   }
                }
                if(!hasFound)
                {
                    stockList.Add(detail.Product.ProductId,0-detail.Quantity);
                    productList.Add(detail.Product.ProductId, detail.Product);
                }

                detail.CreateDate = DateTime.Now;
                detail.UpdateDate = DateTime.Now;
                detail.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                detail.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                var purchaseOrderDetailPk = new PurchaseOrderDetailPK{DepartmentId = CurrentDepartment.Get().DepartmentId, PurchaseOrderId = purchaseOrderId, PurchaseOrderDetailId = id++};
                detail.PurchaseOrderDetailPK = purchaseOrderDetailPk;
                detail.PurchaseOrder = data;
                PurchaseOrderDetailDAO.Add(detail);

                // create Receipt.
            }

            // if departmentstock needs update
            if(stockList.Keys.Count > 0)
            {
                IList departmentStockViewList = new ArrayList();
                // get stock by product master
                foreach (string productId in stockList.Keys)
                {
                    if(!InDepartmentStockViewList(departmentStockViewList,productId))
                    {
                        Product searchProduct = productList[productId];
                        ObjectCriteria pmCrit = new ObjectCriteria();
                        pmCrit.AddEqCriteria("ProductMaster.ProductMasterId", searchProduct.ProductMaster.ProductMasterId);
                        IList list = ProductDAO.FindAll(pmCrit);

                        IList searchPrdIds = new ArrayList();
                        foreach (Product product in list)
                        {
                            searchPrdIds.Add(product.ProductId);
                        }
                        ObjectCriteria crit = new ObjectCriteria();
                        crit.AddSearchInCriteria("DepartmentStockPK.ProductId", searchPrdIds);
                        IList deptStockList = DepartmentStockDAO.FindAll(crit);

                        DepartmentStockView stockView = new DepartmentStockView();
                        stockView.ProductMaster = searchProduct.ProductMaster;
                        SortByProductId(deptStockList);
                        stockView.DepartmentStocks = deptStockList;
                        departmentStockViewList.Add(stockView);
                    }
                }

                foreach (string productId in stockList.Keys)
                {
                    /*ObjectCriteria crit = new ObjectCriteria();
                    crit.AddEqCriteria("DepartmentStockPK.ProductId", productId);
                    IList list = DepartmentStockDAO.FindAll(crit);
                    if(list!=null && list.Count == 1)
                    {
                        DepartmentStock stock = (DepartmentStock) list[0];
                        stock.GoodQuantity += stockList[productId];
                        if (stock.GoodQuantity < 0)
                        {
                            // strange
                            throw new BusinessException("Số lượng trong kho không đáp ứng đủ số lượng bán cho sản phẩm có mã vạch: " + productId);
                        }
                        stock.Quantity += stockList[productId];
                        DepartmentStockDAO.Update(stock);
                    }
                    else
                    {
                        throw new DataLayerException(" Dữ liệu không đồng nhất");
                    }*/
                    if(InDepartmentStockViewList(departmentStockViewList,productId))
                    {

                        // get origin product id and minus first
                        DepartmentStockView view = GetDepartmentStockViewList(departmentStockViewList, productId);
                        long updateQty = stockList[productId];
                        DepartmentStock departmentStock = GetDepartmentStockFromView(view, productId);
                        // if stock has been negative
                        if (departmentStock.GoodQuantity < 0)
                        {
                            // accept negative quantity and process later
                            departmentStock.GoodQuantity += updateQty;
                            departmentStock.Quantity += updateQty;
                            continue;
                        }
                        long originUpdateQty = updateQty;
                        updateQty = departmentStock.GoodQuantity + updateQty;

                        // if not enough quantity and still remains update-needing quantity
                        if(updateQty < 0)
                        {
                            // empty the origin product id in stock
                            departmentStock.Quantity -= departmentStock.GoodQuantity;
                            departmentStock.GoodQuantity = 0;
                            // continue do minusing on other product id in stock;
                            foreach (DepartmentStock otherStock in view.DepartmentStocks)
                            {
                                if(otherStock.DepartmentStockPK.ProductId.Equals(departmentStock.DepartmentStockPK.ProductId))
                                {
                                    continue;
                                }
                                long backupUpdateQty = updateQty;
                                updateQty = otherStock.GoodQuantity + updateQty;
                                if(updateQty < 0)
                                {
                                    otherStock.Quantity -= otherStock.GoodQuantity;
                                    otherStock.GoodQuantity = 0;
                                }
                                else
                                {
                                    otherStock.GoodQuantity += backupUpdateQty;
                                    otherStock.Quantity += backupUpdateQty;
                                    break;
                                }
                            }
                            // if still remain, we accept the negative quantity
                            if(updateQty < 0)
                            {
                                departmentStock.GoodQuantity += updateQty;
                                departmentStock.Quantity += updateQty;
                            }
                        }
                        else // enough quantity
                        {
                            departmentStock.GoodQuantity += originUpdateQty;
                            departmentStock.Quantity += originUpdateQty;
                        }
                    }
                }

                // update stock
                foreach (DepartmentStockView departmentStockView in departmentStockViewList)
                {
                    foreach (DepartmentStock stock in departmentStockView.DepartmentStocks)
                    {
                        DepartmentStockDAO.Update(stock);
                    }
                }
            }

            return data;
        }
        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 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);
                    }
                }
            }
        }
Exemplo n.º 8
0
        public PurchaseOrder Add(PurchaseOrder data)
        {
            string deptId = string.Format("{0:000}", CurrentDepartment.Get().DepartmentId);
            object maxId = PurchaseOrderDAO.SelectSpecificType(null, Projections.Max("PurchaseOrderPK.PurchaseOrderId"));
            string purchaseOrderId = "000000000001";
            if (maxId != null)
            {
                purchaseOrderId = string.Format("{0:000000000000000}", Int64.Parse(maxId.ToString()) + 1);
            }
            else
            {
                long tempId = ClientSetting.MaxPOId;
                if(tempId ==1)
                {
                    purchaseOrderId = deptId + "000000000001";
                }
                else
                {
                    purchaseOrderId = string.Format("{0:000000000000000}", Int64.Parse(tempId.ToString()) + 1);
                }

            }
            ClientSetting.MaxPOId = Int64.Parse(purchaseOrderId);
            ClientSetting.Save();
            object maxReceptId = ReceiptDAO.SelectSpecificType(null, Projections.Max("ReceiptPK.ReceiptId"));
            string receiptId = "000000000001";
            if (maxReceptId != null)
            {
                receiptId = string.Format("{0:000000000000000}", Int64.Parse(maxReceptId.ToString()) + 1);
            }
            else
            {
                receiptId = deptId + "000000000001";
            }

            PurchaseOrderPK purchaseOrderPk = new PurchaseOrderPK { DepartmentId = CurrentDepartment.Get().DepartmentId, PurchaseOrderId = purchaseOrderId };
            data.PurchaseOrderPK = purchaseOrderPk;
            data.UpdateDate = DateTime.Now;
            data.CreateDate = DateTime.Now;
            data.CreateId = ClientInfo.getInstance().LoggedUser.Name;
            data.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
            // add description
            string description = "";
            foreach (PurchaseOrderDetail detail in data.PurchaseOrderDetails)
            {
                description += detail.ProductMaster.ProductName+ " "+ System.Environment.NewLine;
            }
            data.PurchaseOrderDescription = description;

            // save customer
            Customer customer = data.Customer;

            bool isReturnOrder = IsReturnOrder(purchaseOrderPk.PurchaseOrderId,data.PurchaseOrderDetails);

            if(!isReturnOrder)
            {
                PurchaseOrderDAO.Add(data);
            }

            long id = 1;
            // create PurchaseOrderId for Undefined Purchase Order
            string undefinedPOId = null;
            long undefinedPODetailId = 1;
            foreach (PurchaseOrderDetail detail in data.PurchaseOrderDetails)
            {
                if (detail.PurchaseOrder != null
                   && detail.PurchaseOrder.PurchaseOrderPK!=null
                   && !string.IsNullOrEmpty(detail.PurchaseOrder.PurchaseOrderPK.PurchaseOrderId)
                   && detail.PurchaseOrder.PurchaseOrderPK.PurchaseOrderId.Equals("000"))
                {
                    undefinedPOId = deptId + "NA" + DateTime.Now.ToString("yyMMddHHmmss");
                    break;
                }
            }
            IDictionary<string,long> stockList = new Dictionary<string,long>();
            IDictionary<string, Product> productList = new Dictionary<string, Product>();
            foreach (PurchaseOrderDetail detail in data.PurchaseOrderDetails)
            {
                PurchaseOrderDetailPK currDetailKey = detail.PurchaseOrderDetailPK;
                // nếu là hàng trả đổi có xác định hóa đơn
                if(     detail.PurchaseOrder!= null
                    && currDetailKey != null
                    && !CheckUtility.IsNullOrEmpty(currDetailKey.PurchaseOrderId)
                    && !purchaseOrderId.Equals(detail.PurchaseOrder.PurchaseOrderPK.PurchaseOrderId)
                    )
                {
                    // Hàng trả đổi

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

                    ReturnPoPK poPK = new ReturnPoPK
                    {
                        DepartmentId = detail.PurchaseOrderDetailPK.DepartmentId,
                        PurchaseOrderId =
                            detail.PurchaseOrderDetailPK.PurchaseOrderId,
                        PurchaseOrderDetailId =
                            detail.PurchaseOrderDetailPK.PurchaseOrderDetailId,
                        CreateDate = DateTime.Now

                    };

                    po.ReturnPoPK = poPK;
                    po.Quantity = detail.Quantity;
                    if(detail.Price < 0)
                    {
                        po.Price = 0 - detail.Price;
                    }
                    else
                    {
                        po.Price = detail.Price;
                    }

                    po.ReturnDate = DateTime.Now;
                    po.Product = detail.Product;

                    // hàng trả không xác định
                    if (detail.PurchaseOrder.PurchaseOrderPK.PurchaseOrderId.Equals("000"))
                    {
                        po.ReturnPoPK.PurchaseOrderId = undefinedPOId;
                        po.ReturnPoPK.PurchaseOrderDetailId = undefinedPODetailId++;

                    }
                    else // hàng trả có xác định
                    {
                        // xác định số hàng đã trả so với hóa đơn gốc.
                        long originAmount = FindOriginAmount(detail);
                        if (originAmount == 0)
                        {
                            throw new BusinessException("Có lỗi ở hoá đơn gốc, đề nghị kiểm tra");
                        }
                        long returnedQuantity = (long) ReturnPoDAO.FindQuantityById(poPK);
                        long currentReturnQuantity = returnedQuantity + po.Quantity;
                        if (originAmount < currentReturnQuantity)
                        {
                            throw new BusinessException(
                                "Lỗi :" + detail.Product.ProductMaster.ProductName +
                                " .Tổng cộng :" + originAmount +
                                " .Đã trả : " + returnedQuantity +
                                " .Số lượng muốn trả: " + po.Quantity + " !");
                        }
                    }

                    ObjectCriteria stockCrit = new ObjectCriteria();
                    stockCrit.AddEqCriteria("DepartmentStockPK.ProductId", detail.Product.ProductId);
                    IList deptStockList = DepartmentStockDAO.FindAll(stockCrit);
                    if (deptStockList != null && deptStockList.Count > 0)
                    {

                        bool hasPrdFound = false;
                        foreach (string productId in stockList.Keys)
                        {
                            if (productId.Equals(detail.Product.ProductId))
                            {
                                long qty = stockList[productId];
                                qty = qty + detail.Quantity;
                                stockList[productId] = qty;
                                hasPrdFound = true;
                                break;
                            }
                        }
                        if (!hasPrdFound)
                        {
                            stockList.Add(detail.Product.ProductId,detail.Quantity);
                            productList.Add(detail.Product.ProductId,detail.Product);
                        }
                    }
                    else
                    {
                        throw new BusinessException("Không có mặt hàng này trong kho. Xin vui lòng kiểm tra dữ liệu");
                    }
                    if(!isReturnOrder)
                    {
                        po.NextPurchaseOrderId = purchaseOrderId;
                    }
                    ReturnPoDAO.Add(po);
                    // go to next detail
                    continue;
                }

                bool hasFound = false;
                foreach (string productId in stockList.Keys)
                {
                   if(productId.Equals(detail.Product.ProductId))
                   {
                       long qty = stockList[productId];
                       qty = qty - detail.Quantity;
                       stockList[productId] = qty;
                       hasFound = true;
                       break;
                   }
                }
                if(!hasFound)
                {
                    // add update quantity under a negative number
                    stockList.Add(detail.Product.ProductId,0-detail.Quantity);
                    productList.Add(detail.Product.ProductId, detail.Product);
                }

                detail.CreateDate = DateTime.Now;
                detail.UpdateDate = DateTime.Now;
                detail.CreateId = ClientInfo.getInstance().LoggedUser.Name;
                detail.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                var purchaseOrderDetailPk = new PurchaseOrderDetailPK{DepartmentId = CurrentDepartment.Get().DepartmentId, PurchaseOrderId = purchaseOrderId, PurchaseOrderDetailId = id++};
                detail.PurchaseOrderDetailPK = purchaseOrderDetailPk;
                detail.PurchaseOrder = data;
                PurchaseOrderDetailDAO.Add(detail);

                // create Receipt.
            }

            // if departmentstock needs update
            if(stockList.Keys.Count > 0)
            {
                IList departmentStockViewList = new ArrayList();
                // get stock by product master
                foreach (string productId in stockList.Keys)
                {
                    if(!InDepartmentStockViewList(departmentStockViewList,productId))
                    {
                        Product searchProduct = productList[productId];
                        ObjectCriteria pmCrit = new ObjectCriteria();
                        pmCrit.AddEqCriteria("ProductMaster.ProductMasterId", searchProduct.ProductMaster.ProductMasterId);
                        IList list = ProductDAO.FindAll(pmCrit);

                        IList searchPrdIds = new ArrayList();
                        foreach (Product product in list)
                        {
                            searchPrdIds.Add(product.ProductId);
                        }
                        ObjectCriteria crit = new ObjectCriteria();
                        crit.AddSearchInCriteria("DepartmentStockPK.ProductId", searchPrdIds);
                        IList deptStockList = DepartmentStockDAO.FindAll(crit);

                        DepartmentStockView stockView = new DepartmentStockView();
                        stockView.ProductMaster = searchProduct.ProductMaster;
                        ((ArrayList)deptStockList).Sort();
                        stockView.DepartmentStocks = deptStockList;
                        departmentStockViewList.Add(stockView);
                    }
                }

                bool allowTempNegativeSelling = false;
                // slide id selling
                foreach (string productId in stockList.Keys)
                {

                    if(InDepartmentStockViewList(departmentStockViewList,productId))
                    {

                        // get origin product id and minus first
                        DepartmentStockView view = GetDepartmentStockViewList(departmentStockViewList, productId);
                        long updateQty = stockList[productId];
                        long originUpdateQty = updateQty;
                        DepartmentStock departmentStock = GetDepartmentStockFromView(view, productId);
                        // if stock has been negative
                        if (departmentStock.GoodQuantity <= 0)
                        {
                            // FIX : Using negative update setting
                            // accept negative quantity and process later
                            if (ClientSetting.NegativeSelling)
                            {
                                departmentStock.GoodQuantity += updateQty;
                                departmentStock.Quantity += updateQty;
                                continue;
                            }

                            // END FIX
                        }
                        else // do minusing to stock
                        {
                            updateQty = departmentStock.GoodQuantity + updateQty;
                        }

                        // if not enough quantity and still remains update-needing quantity
                        if(updateQty < 0)
                        {
                            // empty the origin product id in stock
                            departmentStock.Quantity -= departmentStock.GoodQuantity;
                            departmentStock.GoodQuantity = 0;
                            // continue do minusing on other product id in stock;
                            foreach (DepartmentStock otherStock in view.DepartmentStocks)
                            {
                                if(otherStock.DepartmentStockPK.ProductId.Equals(departmentStock.DepartmentStockPK.ProductId))
                                {
                                    continue;
                                }
                                long backupUpdateQty = updateQty;
                                updateQty = otherStock.GoodQuantity + updateQty;
                                if(updateQty < 0)
                                {
                                    otherStock.Quantity -= otherStock.GoodQuantity;
                                    otherStock.GoodQuantity = 0;
                                }
                                else
                                {
                                    otherStock.GoodQuantity += backupUpdateQty;
                                    otherStock.Quantity += backupUpdateQty;
                                    break;
                                }
                            }
                            // FIX : Do not accept negative quantity
                            // if still remain, we accept the negative quantity
                            if(updateQty < 0)
                            {

                                if (!ClientSetting.NegativeSelling)
                                {
                                    throw new BusinessException("Mặt hàng " +
                                                                departmentStock.Product.ProductMaster.ProductName +
                                                                " đã hết.");
                                }
                                else
                                {
                                    if (allowTempNegativeSelling == false)
                                    {
                                        // confirm before save
                                        DialogResult isConfirmed = System.Windows.Forms.DialogResult.Cancel;
                                        if (!ClientSetting.ConfirmByEmployeeId)
                                        {
                                            LoginForm loginForm =
                                                GlobalUtility.GetFormObject<LoginForm>(FormConstants.CONFIRM_LOGIN_VIEW);
                                            loginForm.ConfirmNegativeSelling = true;
                                            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)
                                        {
                                            throw new BusinessException("Không xác nhận được nguoi gửi ....");
                                        }
                                        else
                                        {
                                            allowTempNegativeSelling = true;
                                        }
                                    }

                                    departmentStock.GoodQuantity += updateQty;
                                    departmentStock.Quantity += updateQty;
                                }
                            }
                            // END FIX
                        }
                        else // enough quantity
                        {
                            departmentStock.GoodQuantity += originUpdateQty;
                            departmentStock.Quantity += originUpdateQty;
                        }
                    }
                }

                // update stock
                foreach (DepartmentStockView departmentStockView in departmentStockViewList)
                {
                    foreach (DepartmentStock stock in departmentStockView.DepartmentStocks)
                    {
                        DepartmentStockDAO.Update(stock);
                    }
                }
            }

            return data;
        }
        public void AddStockInBack(DepartmentStockIn data)
        {
            long deptId = data.DepartmentStockInPK.DepartmentId;
            string deptStr = "000";
            if (deptId > 9999)
            {
                deptStr = deptId.ToString();
            }
            else
            {
                deptStr = string.Format("{0:000}", data.DepartmentStockInPK.DepartmentId);
            }
            string dateStr = data.StockInDate.ToString("yyMMdd");
            var criteria = new ObjectCriteria();
            string extraZero = "00000";
            if(deptId > 9999)
            {
                extraZero = "000";
            }
            criteria.AddGreaterCriteria("DepartmentStockInPK.StockInId", dateStr + deptStr + extraZero);
            var maxId = DepartmentStockInDAO.SelectSpecificType(criteria,
                                                                Projections.Max("DepartmentStockInPK.StockInId"));
            string startNum = "00001";
            if(deptId > 9999)
            {
                startNum = "001";
            }
            var stockInId = maxId == null
                                ? dateStr + deptStr + startNum
                                : string.Format("{0:00000000000000}", (Int64.Parse(maxId.ToString()) + 1));

            var stockInPk = new DepartmentStockInPK {DepartmentId = deptId, StockInId = stockInId + ""};

            data.DepartmentStockInPK = stockInPk;
            data.CreateDate = DateTime.Now;
            data.UpdateDate = DateTime.Now;
            data.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
            data.CreateId = ClientInfo.getInstance().LoggedUser.Name;
            DepartmentStockInDAO.Add(data);

            // we will get the stock to get the data
            IList productMasterIds = new ArrayList();
            IList productIds = new ArrayList();
            foreach (DepartmentStockInDetail stockInDetail in data.DepartmentStockInDetails)
            {
                productIds.Add(stockInDetail.Product.ProductId);
            }

            criteria = new ObjectCriteria();
            criteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
            criteria.AddSearchInCriteria("DepartmentStockPK.ProductId", productIds);
            criteria.AddOrder("Product.ProductId", true);
            IList stockList = DepartmentStockDAO.FindAll(criteria);

            IList updateStockList = new ArrayList();
            IList stockInDetailList = new ArrayList();
            foreach (DepartmentStockInDetail stockInDetail in data.DepartmentStockInDetails)
            {
                long quantity = stockInDetail.Quantity;
                DepartmentStockPK stockPk = new DepartmentStockPK
                                                {
                                                    DepartmentId = deptId,
                                                    ProductId = stockInDetail.Product.ProductId
                                                };
                DepartmentStock departmentStock = DepartmentStockDAO.FindById(stockPk);

                if (departmentStock.DepartmentStockPK.ProductId.Equals(stockInDetail.Product.ProductId))
                {
                        departmentStock.GoodQuantity += stockInDetail.Quantity;
                        departmentStock.Quantity += stockInDetail.Quantity;
                        departmentStock.UpdateDate = DateTime.Now;
                        departmentStock.UpdateId = ClientInfo.getInstance().LoggedUser.Name;

                        DepartmentStockDAO.Update(departmentStock);

                        var pk = new DepartmentStockInDetailPK
                                     {
                                         DepartmentId = data.DepartmentStockInPK.DepartmentId,
                                         ProductId = departmentStock.Product.ProductId,
                                         StockInId = stockInId
                                     };
                        stockInDetail.DepartmentStockInDetailPK = pk;
                        DepartmentStockInDetailDAO.Add(stockInDetail);
                }
            }
        }
Exemplo n.º 10
0
        public void Sync(DepartmentStockIn data)
        {
            DepartmentStockIn DepartmentStockIn = DepartmentStockInDAO.FindById(data.DepartmentStockInPK);
            if (DepartmentStockIn == null)
            {
                DepartmentStockInDAO.Add(data);
            }
            else
            {
                ObjectCriteria criteria = new ObjectCriteria();

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

            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)
            {
                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);
                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 criteria = new ObjectCriteria();
                criteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
                criteria.AddEqCriteria("DepartmentPricePK.DepartmentId", (long)0);
                criteria.AddSearchInCriteria("DepartmentPricePK.ProductMasterId", productMasterIds);
                IList deptPriceList = DepartmentPriceDAO.FindAll(criteria);
                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++;
                }
            }

            if (productIds.Count > 0)
            {
                var criteria = new ObjectCriteria();
                criteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
                criteria.AddEqCriteria("DepartmentStockPK.DepartmentId", data.DepartmentStockInPK.DepartmentId);
                criteria.AddSearchInCriteria("DepartmentStockPK.ProductId", productIds);
                IList stockList = DepartmentStockDAO.FindAll(criteria);
                int i = 0;
                foreach (string productId in productIds)
                {
                    DepartmentStock stock = null;
                    foreach (DepartmentStock price1 in stockList)
                    {
                        if (price1.DepartmentStockPK.ProductId.Equals(productId))
                        {
                            stock = price1;
                            //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++;
                }
            }

            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);
                        }
                    }
                }
            }
        }
Exemplo n.º 11
0
        public DepartmentStockIn Add(DepartmentStockIn data)
        {
            string deptStr = "";
            if(ClientSetting.IsSubStock())
            {
                deptStr = string.Format("{0:00000}", data.DepartmentStockInPK.DepartmentId);
            }
            else
            {
                deptStr = string.Format("{0:000}", data.DepartmentStockInPK.DepartmentId);
            }

            string dateStr = data.StockInDate.ToString("yyMMdd");
            var criteria = new ObjectCriteria();
            if(ClientSetting.IsSubStock())
            {
                criteria.AddGreaterCriteria("DepartmentStockInPK.StockInId", dateStr + deptStr + "000");
            }
            else
            {
                criteria.AddGreaterCriteria("DepartmentStockInPK.StockInId", dateStr + deptStr + "00000");
            }

            var maxId = DepartmentStockInDAO.SelectSpecificType(criteria, Projections.Max("DepartmentStockInPK.StockInId"));
            string stockInId = "";
            if(ClientSetting.IsSubStock())
            {
                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));
            }

            var stockInPk = new DepartmentStockInPK {DepartmentId = data.DepartmentId, StockInId = stockInId + ""};

            data.DepartmentStockInPK = stockInPk;
            data.CreateDate = DateTime.Now;
            data.UpdateDate = DateTime.Now;
            data.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
            data.CreateId = ClientInfo.getInstance().LoggedUser.Name;
            DepartmentStockInDAO.Add(data);

            // we will get the stock to get the data
            IList productMasterIds = new ArrayList();
            foreach (DepartmentStockInDetail stockInDetail in data.DepartmentStockInDetails)
            {
                productMasterIds.Add(stockInDetail.Product.ProductMaster.ProductMasterId);
            }

            criteria = new ObjectCriteria();
            criteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
            criteria.AddGreaterCriteria("Quantity", (long)0);
            criteria.AddSearchInCriteria("ProductMaster.ProductMasterId", productMasterIds);
            criteria.AddOrder("ProductMaster.ProductMasterId", true);
            criteria.AddOrder("Product.ProductId", true);
            IList stockList = DepartmentStockDAO.FindAll(criteria);

            IList updateStockList = new ArrayList();
            IList stockInDetailList = new ArrayList();
            foreach (DepartmentStockInDetail stockInDetail in data.DepartmentStockInDetails)
            {
                long quantity = stockInDetail.Quantity;
                foreach (DepartmentStock stock in stockList)
                {
                    long stockInQty = 0;
                   if (stock.Product.ProductId.Equals(stockInDetail.ProductId) && stock.Quantity >= 0)
                    {
                        /*if (quantity >= stock.Quantity)
                        {
                            stockInQty = stock.Quantity;
                            quantity -= stock.Quantity;
                            stock.Quantity = 0;
                        }
                        else
                        {
                            stockInQty = quantity;
                            stock.Quantity -= quantity;
                            quantity = 0;
                        }*/
                        if (quantity >= stock.GoodQuantity)
                        {
                            stockInQty = stock.GoodQuantity;
                            quantity -= stock.GoodQuantity;
                            stock.GoodQuantity = 0;
                        }
                        else
                        {
                            stockInQty = quantity;
                            stock.GoodQuantity -= quantity;
                            quantity = 0;
                        }
                        stock.Quantity = stock.GoodQuantity + stock.ErrorQuantity + stock.DamageQuantity +
                                         stock.LostQuantity + stock.UnconfirmQuantity;
                        stock.UpdateDate = DateTime.Now;
                        stock.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                        updateStockList.Add(stock);
                        var pk = new DepartmentStockInDetailPK
                                   {
                                       DepartmentId = data.DepartmentId,
                                       ProductId = stock.Product.ProductId,
                                       StockInId = stockInId
                                   };
                        var detail = new DepartmentStockInDetail
                        {
                            DepartmentStockInDetailPK = pk,
                            Quantity = stockInQty,
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UpdateId = ClientInfo.getInstance().LoggedUser.Name,
                            CreateId = ClientInfo.getInstance().LoggedUser.Name,
                            ProductMaster = stock.ProductMaster
                        };
                        var deptStock = new DepartmentStock
                                            {
                                                DepartmentStockPK = new DepartmentStockPK
                                                                        {
                                                                            DepartmentId = data.DepartmentId,
                                                                            ProductId = stock.Product.ProductId
                                                                        },
                                                CreateDate = DateTime.Now,
                                                UpdateDate = DateTime.Now,
                                                UpdateId = ClientInfo.getInstance().LoggedUser.Name,
                                                CreateId = ClientInfo.getInstance().LoggedUser.Name,
                                                ProductMaster = stock.ProductMaster
                                            };
                        stockInDetailList.Add(detail);
                        if (quantity == 0)
                        {
                            break;
                        }
                    }
                }
                if (quantity > 0)
                {
                    data.DepartmentStockInPK.StockInId = null;
                    throw new BusinessException("Số lượng xuất kho lớn hơn số lượng trong kho");
                }
            }

            foreach (DepartmentStockInDetail detail in stockInDetailList)
            {
                DepartmentStockInDetailDAO.Add(detail);
            }

            foreach (Stock stock in updateStockList)
            {
                StockDAO.Update(stock);
            }
            return data;
        }
Exemplo n.º 12
0
        public LogicResult SyncFromSubStock(DepartmentStockIn stockIn)
        {
            LogicResult result = new LogicResult();
            result.HasError = false;
            string deptStr = string.Format("{0:000}", stockIn.DepartmentStockInPK.DepartmentId);
            string dateStr = stockIn.StockInDate.ToString("yyMMdd");
            var crit = new ObjectCriteria();
            crit.AddGreaterCriteria("DepartmentStockInPK.StockInId", dateStr + deptStr + "00000");
            var maxId = DepartmentStockInDAO.SelectSpecificType(crit, Projections.Max("DepartmentStockInPK.StockInId"));
            var stockInId = maxId == null ? dateStr + deptStr + "00001" : string.Format("{0:00000000000000}", (Int64.Parse(maxId.ToString()) + 1));

            var stockInPk = new DepartmentStockInPK
                                                    { DepartmentId = stockIn.DepartmentStockInPK.DepartmentId,
                                                      StockInId = stockInId + ""
                                                    };
            stockIn.DepartmentStockInPK = stockInPk;

            IList productMasterIds = new ArrayList();
            IList productIds = new ArrayList();
            IList priceList = new ArrayList();
            IList quantityList = new ArrayList();

            if(stockIn.DepartmentStockInDetails== null || stockIn.DepartmentStockInDetails.Count == 0)
            {
                result.HasError = true;
                result.Messages = new ArrayList();
                result.Messages.Add("Stock-in do not have details ?!?!");
                return result;
            }
            try
            {
                DepartmentStockIn DepartmentStockIn = DepartmentStockInDAO.FindById(stockIn.DepartmentStockInPK);
                if (DepartmentStockIn == null)
                {
                    DepartmentStockInDAO.Add(stockIn);
                }
                else
                {
                    ObjectCriteria criteria = new ObjectCriteria();

                    // currently we do not accept update department-stock-in in
                    //return;
                    // amend for debug
                    return result;
                }
                // put master data first
                foreach (DepartmentStockInDetail detail in stockIn.DepartmentStockInDetails)
                {
                    detail.DepartmentStockInDetailPK.StockInId = 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);
                    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 criteria = new ObjectCriteria();
                    criteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
                    criteria.AddEqCriteria("DepartmentPricePK.DepartmentId", (long)0);
                    criteria.AddSearchInCriteria("DepartmentPricePK.ProductMasterId", productMasterIds);
                    IList deptPriceList = DepartmentPriceDAO.FindAll(criteria);
                    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++;
                    }
                }

                if (productIds.Count > 0)
                {
                    var criteria = new ObjectCriteria();
                    criteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
                    criteria.AddEqCriteria("DepartmentStockPK.DepartmentId", stockIn.DepartmentStockInPK.DepartmentId);
                    criteria.AddSearchInCriteria("DepartmentStockPK.ProductId", productIds);
                    IList stockList = DepartmentStockDAO.FindAll(criteria);
                    int i = 0;
                    foreach (string productId in productIds)
                    {
                        DepartmentStock stock = null;
                        foreach (DepartmentStock price1 in stockList)
                        {
                            if (price1.DepartmentStockPK.ProductId.Equals(productId))
                            {
                                stock = price1;
                                //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 = stockIn.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++;
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                result.HasError = true;
                result.Messages = new ArrayList();
                result.Messages.Add(ex.Message);
                return result;
            }
        }
        public void SyncToMain(SyncFromDepartmentToMain sync)
        {
            // insert department stock temp
            if(sync.DepartmentStockTempList!=null && sync.DepartmentStockTempList.Count > 0)
            {
                foreach (DepartmentStockTemp departmentStockTemp in sync.DepartmentStockTempList)
                {
                    bool failed = false;
                    if (departmentStockTemp != null)
                    {
                        DepartmentStockTemp curDeptTemp = DepartmentStockTempDAO.FindById(departmentStockTemp.DepartmentStockTempPK);
                        if (curDeptTemp == null)
                        {
                            DepartmentStockTempDAO.Add(departmentStockTemp);
                        }
                        else
                        {
                            if(departmentStockTemp.Fixed == 1 && departmentStockTemp.DelFlg == 1)
                            {
                                curDeptTemp.Fixed = 1;
                                curDeptTemp.DelFlg = 1;
                                DepartmentStockTempDAO.Update(curDeptTemp);
                            }
                        }
                    }
                }
            }
            // insert timeline
            if (sync.DepartmentTimelineList != null && sync.DepartmentTimelineList.Count > 0)
            {
                foreach (DepartmentTimeline timeline in sync.DepartmentTimelineList)
                {
                    bool failed = false;
                    if (timeline != null)
                    {
                        DepartmentTimeline curTimeline = DepartmentTimelineDAO.FindById(timeline.DepartmentTimelinePK);
                        if (curTimeline == null)
                        {
                            DepartmentTimelineDAO.Add(timeline);
                        }
                        else
                        {
                            // error
                            //failed = true;
                        }
                    }
                }
            }

            // insert PO, PO Detail
            if (sync.PurchaseOrderList != null && sync.PurchaseOrderList.Count > 0)
            {
                foreach (PurchaseOrder po in sync.PurchaseOrderList)
                {
                    PurchaseOrder poTemp = PurchaseOrderDAO.FindById(po.PurchaseOrderPK);
                    if (poTemp == null)
                    {
                        PurchaseOrderDAO.Add(po);
                        foreach (PurchaseOrderDetail detail in po.PurchaseOrderDetails)
                        {
                            PurchaseOrderDetailDAO.Add(detail);
                        }
                    }
                    else
                    {
                        // Error
                        //failed = true;
                    }
                }
            }

            // insert dept stock out
            if (sync.DepartemntStockOutList != null && sync.DepartemntStockOutList.Count > 0)
            {
                foreach (DepartmentStockOut po in sync.DepartemntStockOutList)
                {
                    IList productIds = new ArrayList();
                    IList stockList = null;
                    if (po.DefectStatus.DefectStatusId == StockDefectStatus.SEND_BACK_TO_MAIN)
                    {
                        foreach (DepartmentStockOutDetail detail in po.DepartmentStockOutDetails)
                        {
                            productIds.Add(detail.Product.ProductId);
                        }
                        ObjectCriteria criteria = new ObjectCriteria();
                        criteria.AddSearchInCriteria("Product.ProductId", productIds);
                        stockList = StockDAO.FindAll(criteria);
                    }
                    DepartmentStockOut poTemp = DepartmentStockOutDAO.FindById(po.DepartmentStockOutPK);
                    if (poTemp == null)
                    {
                        po.StockOutDate = DateTime.Now;
                        DepartmentStockOutDAO.Add(po);

                        foreach (DepartmentStockOutDetail detail in po.DepartmentStockOutDetails)
                        {
                            DepartmentStockOutDetailDAO.Add(detail);

                            // update stock if it's a dept stock out return to main ( defectstatus = 6 )
                            if (po.DefectStatus.DefectStatusId == StockDefectStatus.SEND_BACK_TO_MAIN
                                && stockList!=null
                                && stockList.Count > 0)
                            {
                                Stock stock = GetStockOfProduct(detail.Product,stockList);
                                if(stock!=null)
                                {
                                    stock.Quantity += detail.GoodQuantity + detail.ErrorQuantity;
                                    stock.GoodQuantity += detail.GoodQuantity;
                                    stock.ErrorQuantity += detail.ErrorQuantity;
                                    StockDAO.Update(stock);
                                }
                            }
                        }
                    }
                    else
                    {
                        // Error
                        //failed = true;
                    }
                }
            }

            // insert Dept stock in
            if (sync.DepartmentStockInList != null && sync.DepartmentStockInList.Count > 0)
            {
                foreach (DepartmentStockIn po in sync.DepartmentStockInList)
                {
                    DepartmentStockIn poTemp = DepartmentStockInDAO.FindById(po.DepartmentStockInPK);
                    if (poTemp == null)
                    {
                        DepartmentStockInDAO.Add(po);
                        foreach (DepartmentStockInDetail detail in po.DepartmentStockInDetails)
                        {
                            DepartmentStockInDetailDAO.Add(detail);
                        }
                    }
                    else
                    {
                        // Error
                    }
                }
            }

            // insert return po
            if (sync.ReturnPoList != null && sync.ReturnPoList.Count > 0)
            {
                foreach (ReturnPo po in sync.ReturnPoList)
                {
                    ReturnPo poTemp = ReturnPoDAO.FindById(po.ReturnPoPK);
                    if (poTemp == null)
                    {
                        ReturnPoDAO.Add(po);
                    }
                    else
                    {
                        // Error
                    }
                }
            }

            // insert stock history
            if (sync.DepartmentStockHistoryList != null && sync.DepartmentStockHistoryList.Count > 0)
            {
                foreach (DepartmentStockHistory po in sync.DepartmentStockHistoryList)
                {
                    DepartmentStockHistory poTemp = DepartmentStockHistoryDAO.FindById(po.DepartmentStockHistoryPK);
                    if (poTemp == null)
                    {
                        DepartmentStockHistoryDAO.Add(po);
                    }
                    else
                    {
                        // Error
                    }
                }
            }

            // insert or update dept stock
            if (sync.DepartmentStockList != null && sync.DepartmentStockList.Count > 0)
            {
                /*if (!failed)
                {*/
                    foreach (DepartmentStock po in sync.DepartmentStockList)
                    {
                        DepartmentStock poTemp = DepartmentStockDAO.FindById(po.DepartmentStockPK);
                        if (poTemp == null)
                        {
                            DepartmentStockDAO.Add(po);
                        }
                        else
                        {
                            poTemp.Quantity = po.Quantity;
                            poTemp.GoodQuantity = po.GoodQuantity;
                            poTemp.LostQuantity = po.LostQuantity;
                            poTemp.ErrorQuantity = po.ErrorQuantity;
                            poTemp.DamageQuantity = po.DamageQuantity;
                            poTemp.OldDamageQuantity = po.OldDamageQuantity;
                            poTemp.OldErrorQuantity = po.OldErrorQuantity;
                            poTemp.OldGoodQuantity = po.OldGoodQuantity;
                            poTemp.OldLostQuantity = po.OldLostQuantity;
                            poTemp.OldUnconfirmQuantity = po.OldUnconfirmQuantity;
                            poTemp.UnconfirmQuantity = po.UnconfirmQuantity;
                            poTemp.UpdateDate = DateTime.Now;
                            DepartmentStockDAO.Update(poTemp);
                        }
                    }
                /*}*/
            }
        }
Exemplo n.º 14
0
        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);
                            }
                        }
                    }
                }

            }
        }
Exemplo n.º 15
0
        public void Add(DepartmentStockIn data)
        {
            string deptStr = string.Format("{0:000}", data.DepartmentId);
            string dateStr = data.StockInDate.ToString("yyMMdd");
            var criteria = new ObjectCriteria();
            criteria.AddGreaterCriteria("StockoutId", (long)0);

            var maxId = StockOutDAO.SelectSpecificType(criteria, Projections.Max("StockoutId"));
            var stockOutId = maxId == null ? 1 : Int64.Parse(maxId.ToString()) + 1;

            //var stockInPk = new DepartmentStockInPK { DepartmentId = data.DepartmentId, StockInId = stockOutId + "" };

            //data.DepartmentStockInPK = stockInPk;
            data.CreateDate = DateTime.Now;
            data.UpdateDate = DateTime.Now;
            data.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
            data.CreateId = ClientInfo.getInstance().LoggedUser.Name;

            StockOut stockOut = new StockOut();
            stockOut.StockoutId = stockOutId;
            stockOut.CreateDate = DateTime.Now;
            stockOut.UpdateDate = DateTime.Now;
            stockOut.StockOutDate = DateTime.Now;
            stockOut.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
            stockOut.CreateId = ClientInfo.getInstance().LoggedUser.Name;
            stockOut.NotUpdateMainStock = false;
            stockOut.DefectStatus = new StockDefectStatus { DefectStatusId = 0};
            stockOut.DelFlg = 0;
            stockOut.DepartmentId = data.DepartmentId;

            // we will get the stock to get the data
            IList productMasterIds = new ArrayList();
            foreach (DepartmentStockInDetail stockInDetail in data.DepartmentStockInDetails)
            {
                productMasterIds.Add(stockInDetail.Product.ProductMaster.ProductMasterId);
            }

            criteria = new ObjectCriteria();
            criteria.AddEqCriteria("DelFlg", CommonConstants.DEL_FLG_NO);
            criteria.AddGreaterCriteria("Quantity", (long)0);
            criteria.AddSearchInCriteria("ProductMaster.ProductMasterId", productMasterIds);
            criteria.AddOrder("ProductMaster.ProductMasterId", true);
            criteria.AddOrder("Product.ProductId", true);
            IList stockList = StockDAO.FindAll(criteria);

            IList updateStockList = new ArrayList();
            IList stockOutDetailList = new ArrayList();

            var maxSODetailId = StockOutDetailDAO.SelectSpecificType(new ObjectCriteria(), Projections.Max("StockOutDetailId"));
            long stockOutDetailId = (maxSODetailId == null ? 1 : Int64.Parse(maxSODetailId.ToString()) + 1);

            /*if(stockOutIds!= null && ((long)stockOutIds) > 0)
            {
                stockOutDetailId = (long) stockOutIds + 1;
            }
            MessageBox.Show(stockOutDetailId)*/
            /*if (stockOutIds != null && 1 == ((IList)stockOutIds).Count)
            {
                stockOutDetailId = (long)((IList)stockOutIds)[0] + 1;
            }*/

            foreach (DepartmentStockInDetail stockInDetail in data.DepartmentStockInDetails)
            {
                long quantity = stockInDetail.Quantity;
                foreach (Stock stock in stockList)
                {
                    long stockInQty = 0;
                    if (stock.ProductMaster.ProductMasterId.Equals(stockInDetail.Product.ProductMaster.ProductMasterId) && stock.Quantity > 0)
                    {
                        if (quantity >= stock.GoodQuantity)
                        {
                            stockInQty = stock.GoodQuantity;
                            quantity -= stock.GoodQuantity;
                            stock.GoodQuantity = 0;
                        }
                        else
                        {
                            stockInQty = quantity;
                            stock.GoodQuantity -= quantity;
                            quantity = 0;
                        }
                        stock.Quantity = stock.GoodQuantity + stock.ErrorQuantity + stock.DamageQuantity +
                                         stock.LostQuantity + stock.UnconfirmQuantity;
                        stock.UpdateDate = DateTime.Now;
                        stock.UpdateId = ClientInfo.getInstance().LoggedUser.Name;
                        updateStockList.Add(stock);

                        /*var pk = new StockOutDetailPK
                        {
                            //DepartmentId = data.DepartmentId,
                            ProductId = stock.Product.ProductId,
                            StockOutId = stockOutId
                        };*/

                        var detail = new StockOutDetail
                                         {
                                             //StockOutDetailPK = pk,
                            StockOutDetailId = stockOutDetailId++,
                            StockOutId = stockOutId,
                            StockOut = stockOut,
                            Product =  stock.Product,
                            ProductId = stock.Product.ProductId,
                            Price = stockInDetail.Price,
                            DelFlg = 0,
                            ExclusiveKey = 1,
                            Description = "Export goods",
                            DefectStatus = new StockDefectStatus { DefectStatusId = 0},
                            Quantity = stockInQty,
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UpdateId = ClientInfo.getInstance().LoggedUser.Name,
                            CreateId = ClientInfo.getInstance().LoggedUser.Name,
                            ProductMaster = stock.ProductMaster,

                        };
                        /*var deptStock = new DepartmentStock
                        {
                            DepartmentStockPK = new DepartmentStockPK
                            {
                                DepartmentId = data.DepartmentId,
                                ProductId = stock.Product.ProductId
                            },
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UpdateId = ClientInfo.getInstance().LoggedUser.Name,
                            CreateId = ClientInfo.getInstance().LoggedUser.Name,
                            ProductMaster = stock.ProductMaster
                        };*/
                        stockOutDetailList.Add(detail);
                        if (quantity == 0)
                        {
                            break;
                        }
                    }
                }
                if (quantity > 0)
                {
                    data.DepartmentStockInPK.StockInId = null;
                    throw new BusinessException("Số lượng xuất kho lớn hơn số lượng trong kho");
                }
            }
            // insert stock out and stockout detail
            stockOut.StockOutDetails = stockOutDetailList;
            StockOutDAO.Add(stockOut);
            foreach (StockOutDetail detail in stockOutDetailList)
            {
                StockOutDetailDAO.Add(detail);
            }

            // update stock
            foreach (Stock stock in updateStockList)
            {
                StockDAO.Update(stock);
            }
        }