public void Delete_IdExisting_ReturnsDeletedProductStockWithSpecifiedId()
        {
            //Arrange
            int          existingId = 12;
            ProductStock expected   = new ProductStock
            {
                Id      = existingId,
                Product = new Product {
                    Id = 5
                },
                ProductSize = new ProductSize {
                    Id = 3
                },
                Quantity = 94
            };

            Mock <IProductStockRepository> productStockRepository = new Mock <IProductStockRepository>();

            productStockRepository.Setup(repo => repo.Delete(existingId)).
            Returns(expected);
            Mock <IProductRepository>     productRepository     = new Mock <IProductRepository>();
            Mock <IProductSizeRepository> productSizeRepository = new Mock <IProductSizeRepository>();

            IProductStockService productStockService = new ProductStockService(productStockRepository.Object,
                                                                               productRepository.Object,
                                                                               productSizeRepository.Object);

            //Act
            ProductStock actual = productStockService.Delete(existingId);

            //Assert
            Assert.Equal(expected, actual);
        }
Esempio n. 2
0
        public List <ProductStock> GetProductsByKeywords(string wareid, string keywords, string agentid, string clientid)
        {
            DataSet ds = StockDAL.BaseProvider.GetProductsByKeywords(wareid, keywords, clientid);

            List <ProductStock> list = new List <ProductStock>();

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ProductStock model = new ProductStock();
                model.FillData(dr);
                model.SaleAttrValueString = "";
                if (!string.IsNullOrEmpty(model.SaleAttrValue))
                {
                    string[] attrs = model.SaleAttrValue.Split(',');
                    foreach (string attrid in attrs)
                    {
                        if (!string.IsNullOrEmpty(attrid))
                        {
                            var attr  = new ProductsBusiness().GetProductAttrByID(attrid.Split(':')[0], clientid);
                            var value = attr.AttrValues.Where(m => m.ValueID == attrid.Split(':')[1]).FirstOrDefault();
                            if (attr != null && value != null)
                            {
                                model.SaleAttrValueString += attr.AttrName + ":" + value.ValueName + ",";
                            }
                        }
                    }
                    if (model.SaleAttrValueString.Length > 0)
                    {
                        model.SaleAttrValueString = model.SaleAttrValueString.Substring(0, model.SaleAttrValueString.Length - 1);
                    }
                }
                list.Add(model);
            }
            return(list);
        }
        public void Update_IdNonExisting_ThrowsArgumentException()
        {
            //Arrange
            ProductStock nonExistingProductStock = new ProductStock
            {
                Id          = 10,
                Product     = null,
                ProductSize = null,
                Quantity    = 120
            };

            ProductStock nullProductStock = null;

            Mock <IProductStockRepository> productStockRepository = new Mock <IProductStockRepository>();

            productStockRepository.Setup(repo => repo.Read(nonExistingProductStock.Id)).
            Returns(nullProductStock);
            Mock <IProductRepository>     productRepository     = new Mock <IProductRepository>();
            Mock <IProductSizeRepository> productSizeRepository = new Mock <IProductSizeRepository>();
            IProductStockService          productStockService   = new ProductStockService(productStockRepository.Object,
                                                                                          productRepository.Object,
                                                                                          productSizeRepository.Object);

            //Act
            Action actual = () => productStockService.Update(nonExistingProductStock);

            //Assert
            Assert.Throws <ArgumentException>(actual);
        }
        public void Create_IdSpecified_ThrowsArgumentException()
        {
            //Arrange
            ProductStock invalidProductStock = new ProductStock
            {
                Id      = 5,
                Product = new Product {
                    Id = 5
                },
                ProductSize = new ProductSize {
                    Id = 3
                },
                Quantity = 120
            };

            Mock <IProductStockRepository> productStockRepository = new Mock <IProductStockRepository>();
            Mock <IProductRepository>      productRepository      = new Mock <IProductRepository>();
            Mock <IProductSizeRepository>  productSizeRepository  = new Mock <IProductSizeRepository>();
            IProductStockService           productStockService    = new ProductStockService(productStockRepository.Object,
                                                                                            productRepository.Object,
                                                                                            productSizeRepository.Object);

            //Act
            Action actual = () => productStockService.Create(invalidProductStock);

            //Assert
            Assert.Throws <ArgumentException>(actual);
        }
        public void Update_ProductStockValid_ReturnsUpdatedProductStock()
        {
            //Arrange
            ProductStock validProductStock = new ProductStock
            {
                Id          = 10,
                Product     = null,
                ProductSize = null,
                Quantity    = 120
            };
            ProductStock expected = validProductStock;

            Mock <IProductStockRepository> productStockRepository = new Mock <IProductStockRepository>();

            productStockRepository.Setup(repo => repo.Read(validProductStock.Id)).
            Returns(validProductStock);
            productStockRepository.Setup(repo => repo.Update(validProductStock)).
            Returns(expected);
            Mock <IProductRepository>     productRepository     = new Mock <IProductRepository>();
            Mock <IProductSizeRepository> productSizeRepository = new Mock <IProductSizeRepository>();

            IProductStockService productStockService = new ProductStockService(productStockRepository.Object,
                                                                               productRepository.Object,
                                                                               productSizeRepository.Object);

            //Act
            ProductStock actual = productStockService.Update(validProductStock);

            //Assert
            Assert.Equal(expected, actual);
        }
        /// <summary>
        /// 修改ProductStock表的状态
        /// </summary>
        /// <param name="stockCode">箱体编号</param>
        /// <param name="goodID">物品编号</param>
        /// <param name="flag">是否为正常状态 True 是 False 不是</param>
        /// <param name="error">出错时返回错误信息,无错时返回null</param>
        /// <returns>成功返回True</returns>
        public bool UpdateProductStockStatus(string stockCode, string goodID, bool flag, out string error)
        {
            error = "";

            DepotManagementDataContext dataContxt = CommentParameter.DepotDataContext;

            var updateProduct = from b in dataContxt.ProductStock
                                where b.ProductCode == stockCode &&
                                b.GoodsID == int.Parse(goodID)
                                select b;

            if (updateProduct.Count() != 1)
            {
                error = "数据错误!";
                return(false);
            }
            else
            {
                ProductStock stock = updateProduct.Single();

                stock.IsNatural = flag;

                dataContxt.SubmitChanges();

                return(true);
            }
        }
        public bool isAvailableTest([PexAssumeUnderTest] ProductStock target, int id)
        {
            bool result = target.isAvailable(id);

            return(result);
            // TODO: add assertions to method ProductStockTest.isAvailableTest(ProductStock, Int32)
        }
Esempio n. 8
0
        public IEnumerable <T> FindNormalStock(List <Dictionary <string, object> > keyValueParam)
        {
            var result = new List <ProductStock>();

            using (DBClass = new MSSQLDatabase())
            {
                var cmd = DBClass.GetStoredProcedureCommand("APP_GET_ALL_STOCK_WITH_NORMAL_STOCK") as SqlCommand;
                RoutinesParameterSetter.Set(ref cmd, keyValueParam);
                var reader = DBClass.ExecuteReader(cmd);
                while (reader.Read())
                {
                    var stock = new ProductStock();
                    stock.StockID         = int.Parse(reader[0].ToString());
                    stock.ProductID       = int.Parse(reader[1].ToString());
                    stock.ProductCode     = reader[2].ToString();
                    stock.ProductName     = reader[3].ToString();
                    stock.DepartementName = reader[4].ToString();
                    stock.StartQuantity   = decimal.Parse(reader[5].ToString());
                    stock.CurrentQuantity = decimal.Parse(reader[6].ToString());
                    stock.MinimumQuantity = decimal.Parse(reader[7].ToString());
                    result.Add(stock);
                }
            }
            return(result as List <T>);
        }
        public int newIDTest([PexAssumeUnderTest] ProductStock target)
        {
            int result = target.newID();

            return(result);
            // TODO: add assertions to method ProductStockTest.newIDTest(ProductStock)
        }
        public ProductStock ConstructorTest()
        {
            ProductStock target = new ProductStock();

            return(target);
            // TODO: add assertions to method ProductStockTest.ConstructorTest()
        }
        public int getStockTest([PexAssumeUnderTest] ProductStock target, int id)
        {
            int result = target.getStock(id);

            return(result);
            // TODO: add assertions to method ProductStockTest.getStockTest(ProductStock, Int32)
        }
        private void ValidateOrderLines(Order order)
        {
            if (order.OrderLines == null)
            {
                throw new ArgumentException("OrderLines is null");
            }
            List <ProductStock> allProductStock = _productStockRepository.ReadAll().ToList();

            order.OrderLines.ForEach(ol =>
            {
                if (ol.ProductStock == null)
                {
                    throw new ArgumentException($"ProductStock of OrderLine is null");
                }

                if (ol.Quantity <= 0)
                {
                    throw new ArgumentException($"Quantity of OrderLine is equal or less then zero.");
                }

                if (ol.Quantity > ol.ProductStock.Quantity)
                {
                    throw new ArgumentException("OrderLine Quantity bigger then ProductStock Quantity");
                }

                ProductStock productStock = allProductStock.Find(p => p.Id == ol.ProductStock.Id);
                ol.ProductStock           = productStock ?? throw new ArgumentException($"Cannot find ProductStock with the Id {ol.ProductStock.Id}");
            }
                                     );
        }
        public void Create_ProductSizeNonExisting_ThrowsArgumentException()
        {
            //Arrange
            ProductStock invalidProductStock = new ProductStock
            {
                Product = new Product {
                    Id = 5
                },
                ProductSize = new ProductSize {
                    Id = 3
                },
                Quantity = 120
            };

            ProductSize nullProductSize = null;

            Mock <IProductStockRepository> productStockRepository = new Mock <IProductStockRepository>();
            Mock <IProductRepository>      productRepository      = new Mock <IProductRepository>();

            productRepository.Setup(repo => repo.Read(invalidProductStock.Product.Id)).
            Returns(invalidProductStock.Product);
            Mock <IProductSizeRepository> productSizeRepository = new Mock <IProductSizeRepository>();

            productSizeRepository.Setup(repo => repo.Read(invalidProductStock.ProductSize.Id)).
            Returns(nullProductSize);
            IProductStockService productStockService = new ProductStockService(productStockRepository.Object,
                                                                               productRepository.Object,
                                                                               productSizeRepository.Object);

            //Act
            Action actual = () => productStockService.Create(invalidProductStock);

            //Assert
            Assert.Throws <ArgumentException>(actual);
        }
Esempio n. 14
0
        public async Task <IActionResult> PutProductStock([FromRoute] Guid id, [FromBody] ProductStock productStock)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != productStock.ID)
            {
                return(BadRequest());
            }

            _context.Entry(productStock).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductStockExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public ActionResult UpdateStockQTY(int stockID, int stockQTY, int minStock)
        {
            try
            {
                ProductStock _PS = db.ProductStocks.Find(stockID);

                _PS.StockID        = stockID;
                _PS.ProductID      = _PS.ProductID;
                _PS.ProductSizeID  = _PS.ProductSizeID;
                _PS.ProductColorID = _PS.ProductColorID;
                _PS.StockQTY       = stockQTY;
                _PS.MinStock       = minStock;
                _PS.CreateDate     = _PS.CreateDate;

                db.Entry(_PS).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();

                return(Json(new
                {
                    State = true,
                    Message = "庫存量改動成功!!",
                }));
            }
            catch (Exception ex)
            {
                return(Json(new
                {
                    State = false,
                    Message = ex.ToString(),
                }));
            }
        }
Esempio n. 16
0
        public ProductStockTest()
        {
            this.productStock = new ProductStock();
            this.product      = new Product("Test", 10, 200);

            this.productStock.Add(this.product);
        }
 public void SetUpProduct()
 {
     // Arrange
     this.productStock  = new ProductStock();
     this.firstProduct  = new Product(PRODUCT_LABEL, 10, 1);
     this.secondProduct = new Product(ANOTHER_PRODUCT_LABEL, 5, 10);
 }
Esempio n. 18
0
        public async Task <IActionResult> AddEditProductStock(int id, ProductStockViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Opps something wrong");
                return(View(model));
            }
            if (id > 0)
            {
                ProductStock productStock = await _unitOfWork.Repository <ProductStock>().GetByIdAsync(id);

                productStock.InQuantity   = model.InQuantity;
                productStock.OutQuantity  = model.OutQuantity;
                productStock.ModifiedDate = DateTime.Now;
                productStock.ProductId    = model.ProductId;
                productStock.Remarks      = model.Remarks;
                await _unitOfWork.Repository <ProductStock>().UpdateAsync(productStock);
            }
            else
            {
                ProductStock productStock = new ProductStock
                {
                    InQuantity   = model.InQuantity,
                    OutQuantity  = model.OutQuantity,
                    AddedDate    = DateTime.Now,
                    ModifiedDate = DateTime.Now,
                    ProductId    = model.ProductId,
                    Remarks      = model.Remarks
                };
                await _unitOfWork.Repository <ProductStock>().InsertAsync(productStock);
            }
            return(RedirectToAction(nameof(AddEditProductStock)));
        }
Esempio n. 19
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,ProductId,Stock,PriceId")] ProductStock productStock)
        {
            if (id != productStock.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.UpdateProductStockAsync(productStock);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ProductStockExists(productStock.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(productStock));
        }
Esempio n. 20
0
        public ViewResult ShowStockTable(string category, int brand)
        {
            if (categoryRepository.Categories.Where(c => c.Name == category).FirstOrDefault() == null)
            {
                List <ProductWithStockViewModel> entireProductStockList = new List <ProductWithStockViewModel>();
                foreach (var product in repository.Products)
                {
                    var stock = stockRepository.Stocks.FirstOrDefault(s => s.ProductIdent == product.ProductID);
                    if (stock == null)
                    {
                        stock = new ProductStock();
                    }
                    entireProductStockList.Add(new ProductWithStockViewModel {
                        ProductID = product.ProductID, Name = product.Name, ProductStockID = stock.ProductStockID, Booked = stock.Booked, InStock = stock.InStock
                    });
                }
                return(View(entireProductStockList));
            }
            IQueryable <Product>             productList      = repository.Products.Where(p => p.Category == category).Where(p => p.Brand == brand).AsQueryable();
            List <ProductWithStockViewModel> productStockList = new List <ProductWithStockViewModel>();

            foreach (var product in productList)
            {
                var stock = stockRepository.Stocks.FirstOrDefault(s => s.ProductIdent == product.ProductID);
                if (stock == null)
                {
                    stock = new ProductStock();
                }
                productStockList.Add(new ProductWithStockViewModel {
                    ProductID = product.ProductID, Name = product.Name, ProductStockID = stock.ProductStockID, Booked = stock.Booked, InStock = stock.InStock
                });
            }

            return(View(productStockList));
        }
Esempio n. 21
0
        private async Task <StockResponse> ReturnMockData()
        {
            await _logger.WarningAsync("BackendStockService: External call skipped, mocking response.");

            StockResponse stockResponse = new StockResponse();

            stockResponse.ProductStocks = new List <ProductStock>();

            ShopAbc shopAbc = _shopAbcRepository.Table
                              .Where(s => s.AbcId == "1")
                              .Select(s => s).FirstOrDefault();
            var urlRecords = await _urlRecordService.GetAllUrlRecordsAsync();

            var shopUrl = urlRecords.Where(u => u.EntityName == "Shop" && u.EntityId == shopAbc.ShopId)
                          .Select(u => u.Slug)
                          .FirstOrDefault();

            ProductStock mockShop = new ProductStock()
            {
                Shop      = await _shopService.GetShopByIdAsync(shopAbc.ShopId),
                ShopUrl   = shopUrl,
                Available = true,
                Quantity  = 1
            };

            stockResponse.ProductStocks.Add(mockShop);

            return(stockResponse);
        }
Esempio n. 22
0
        public ActionResult Edit(int psid, int stockqty, int minqty)
        {
            try
            {
                ProductStock pc = db.ProductStocks.Find(psid);

                pc.StockQTY = stockqty;
                pc.MinStock = minqty;

                db.Entry(pc).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                return(Json(new
                {
                    Status = false,
                    Message = ex.ToString(),
                }));
            }

            return(Json(new
            {
                Status = true,
            }));
        }
Esempio n. 23
0
        private void productStockDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            ProductStock ps = new ProductStock();

            switch (e.ColumnIndex)
            {
            case 1:      //存檔
                try
                {
                    ps.StockID = ((ProductStock)productStockBindingSource.Current).StockID;

                    int addQty;

                    if (!int.TryParse(productStockDataGridView[5, e.RowIndex].Value.ToString(), out addQty))
                    {
                        addQty = 0;
                    }
                    //MessageBox.Show($"cell={productStockDataGridView[5, e.RowIndex].Value} => addQty= {addQty}");
                    var q = dbContext.ProductStocks.Find(ps.StockID);

                    q.StockQTY = ((ProductStock)productStockBindingSource.Current).StockQTY + addQty;

                    this.dbContext.SaveChanges();

                    ResetData();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
                break;
            }
        }
        public void updateStockTestThrowsNullReferenceException17()
        {
            ProductStock productStock;

            productStock = new ProductStock();
            this.updateStockTest(productStock, 0, 0);
        }
        public void Setup()
        {
            this.stock   = new ProductStock();
            this.product = new Product("someLabel", 10m, 1);

            this.stock.Add(this.product);
        }
Esempio n. 26
0
        public ProductStock GetProductStock(int pID)
        {
            ProductStock productStock = null;

            try
            {
                var sql = "SELECT [ID],[ProductID],[Number],[Limit],[CreateDate],[CreateUserID],[LastUpdateUserID],[LastUpdateDate] FROM ProductStock";
                var dt  = SQLHelper.GetTable(sql);

                productStock = new ProductStock
                {
                    ID      = Convert.ToInt32(dt.Rows[0]["ID"]),
                    Product = new Product
                    {
                        PID = Convert.IsDBNull(dt.Rows[0]["ProductID"]) ? 0 : Convert.ToInt32(dt.Rows[0]["ProductID"])
                    },
                    Number = Convert.IsDBNull(dt.Rows[0]["Number"]) ? 0 : Convert.ToInt32(dt.Rows[0]["Number"]),
                    Limit  = Convert.IsDBNull(dt.Rows[0]["Limit"]) ? 0 : Convert.ToInt32(dt.Rows[0]["Limit"]),
                };
            }
            catch (Exception ex)
            {
            }
            return(productStock);
        }
Esempio n. 27
0
        public JsonResult SaveProductStock(ProductStock stock)
        {
            POS.Helper.AppHelper.ReturnMessage retMessage = new AppHelper.ReturnMessage();
            POSEntities db = new POSEntities();

            retMessage.IsSuccess = true;

            if (stock.ProductQtyId > 0)
            {
                db.Entry(stock).State = EntityState.Modified;
                retMessage.Messagae   = "Update Success!";
            }
            else
            {
                db.ProductStocks.Add(stock);
                retMessage.Messagae = "Save Success!";
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception)
            {
                retMessage.IsSuccess = false;
            }

            return(Json(retMessage, JsonRequestBehavior.AllowGet));
        }
Esempio n. 28
0
        private void productStockDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            ProductStock ps = new ProductStock();

            switch (e.ColumnIndex)
            {
            case 1:      //存檔
                try
                {
                    ps.StockID = ((ProductStock)productStockBindingSource.Current).StockID;

                    var q = dbContext.ProductStocks.Find(ps.StockID);

                    q.StockQTY = ((ProductStock)productStockBindingSource.Current).StockQTY;

                    this.dbContext.SaveChanges();

                    ResetData();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
                break;
            }
        }
Esempio n. 29
0
        public List <ProductStock> GetProductStock()
        {
            var list = new List <ProductStock>();

            try
            {
                var sql = "SELECT [ID],[ProductID],[Number],[Limit],[CreateDate],[CreateUserID],[LastUpdateUserID],[LastUpdateDate] FROM ProductStock";
                var dt  = SQLHelper.GetTable(sql);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var obj = new ProductStock
                    {
                        ID      = Convert.ToInt32(dt.Rows[i]["ID"]),
                        Product = new Product
                        {
                            PID = Convert.IsDBNull(dt.Rows[i]["ProductID"]) ? 0 : Convert.ToInt32(dt.Rows[i]["ProductID"])
                        },
                        Number = Convert.IsDBNull(dt.Rows[i]["Number"]) ? 0 : Convert.ToInt32(dt.Rows[i]["Number"]),
                        Limit  = Convert.IsDBNull(dt.Rows[i]["Limit"]) ? 0 : Convert.ToInt32(dt.Rows[i]["Limit"]),
                    };
                    list.Add(obj);
                }
            }
            catch (Exception ex)
            {
            }
            return(list);
        }
Esempio n. 30
0
        public void TestRemovingAProductNotifesAllObservers()
        {
            ProductStock             productStock = new ProductStock();
            MockProductStockObserver mockProductStockObserverOne = new MockProductStockObserver();
            MockProductStockObserver mockProductStockObserverTwo = new MockProductStockObserver();

            productStock.RegisterObserver(mockProductStockObserverOne);
            productStock.RegisterObserver(mockProductStockObserverTwo);

            productStock.Remove(Products.Cola);

            Assert.AreEqual(1, mockProductStockObserverOne.NumberOfTimesProductStockUpdatedWasCalled);
            Assert.AreEqual(Products.Cola, mockProductStockObserverOne.LastProductPassedToProductStockUpdated);

            Assert.AreEqual(1, mockProductStockObserverTwo.NumberOfTimesProductStockUpdatedWasCalled);
            Assert.AreEqual(Products.Cola, mockProductStockObserverTwo.LastProductPassedToProductStockUpdated);

            productStock.Remove(Products.Candy);

            Assert.AreEqual(2, mockProductStockObserverOne.NumberOfTimesProductStockUpdatedWasCalled);
            Assert.AreEqual(Products.Candy, mockProductStockObserverOne.LastProductPassedToProductStockUpdated);

            Assert.AreEqual(2, mockProductStockObserverTwo.NumberOfTimesProductStockUpdatedWasCalled);
            Assert.AreEqual(Products.Candy, mockProductStockObserverTwo.LastProductPassedToProductStockUpdated);
        }
 public void Update(ProductStock productStock)
 {
     var dprod = _productsRepo.All().SingleOrDefault(prod => prod.Id == productStock.Id);
     if (dprod != null) {
         dprod.UnitsInStock = productStock.UnitsInStock;
         _productsRepo.AddOrUpdate(dprod);
     }
 }
Esempio n. 32
0
       //Obtiene el Stock de un producto, Ubicacion, cantodad segun un metodo (ZONE, LIFO, FIFO) 
       public String GetStrProductStock(ProductStock productStock, PickMethod pickMethod)
       {
           //Query sobre label entity de tipo producto y activa, sacando la unidad base
           //Order tue query over  ZONE, FIFO, LIFO , FEFO segun el PickingMethod

           string result = "";

           //Label label = new Label
           //{
           //    Product = product,
           //    Bin = bin
           //};

           IList<ProductStock> list = Factory.DaoLabel().GetStock(productStock, pickMethod, 20);

           if (list == null || list.Count == 0)
               return "";

           foreach (ProductStock ps in list)
               result += ps.Bin.BinCode + "(" + ps.Stock.ToString() + "), ";

           return result;
       }
Esempio n. 33
0
        private int CreateNoCountAdjLines(ProductStock r, string user, Document posAdj, int curLine)
        {

            Label  targetLabel = Factory.DaoLabel().Select(new Label { Bin = new Bin { BinID = r.Bin.BinID }, 
                LabelType = new DocumentType { DocTypeID = LabelType.BinLocation } }).First();

            //Creando la linea del Ajuste
            DocumentLine addLine = new DocumentLine
            {
                Product = r.Product,
                Quantity = r.Stock, //Math.Abs(binTask.QtyDiff),
                ModifiedBy = user,
                CreationDate = DateTime.Now,
                CreatedBy = user,
                ModDate = DateTime.Now,
                Unit = r.Product.BaseUnit,
                LineStatus = new Status { StatusID = DocStatus.New },
                IsDebit = true,
                UnitBaseFactor = r.Product.BaseUnit.BaseAmount,
                BinAffected = r.Bin.BinCode + ((r.Label != null) ? r.Label.LabelCode : ""),
                Location = posAdj.Location,
                Note = r.Bin.BinCode,
                Date1 = DateTime.Now
            };

            addLine.Document = posAdj;
            addLine.LineNumber = curLine;
            addLine = SaveAdjustmentTransaction(addLine, targetLabel, false);

            if (addLine.Note == "Adjust OK.")
                return curLine + 1;
            else
                return curLine;
        }
Esempio n. 34
0
        //Obtiene la info del stock del ERP y actualiza el inventario
        //Detallado o global dejando todo en MAIN
        public void UpdateWMSStockFromERP(Company company, bool detailed)
        {
            if (company == null)
            {
                ExceptionMngr.WriteEvent("GetStockComparation Company " + company.Name, ListValues.EventType.Fatal, null, null, ListValues.ErrorCategory.Business);
                return;
            }
            SetConnectMngr(company);


            //bool detailed = true; //indica si obtiene el stock a nivel de BIN
            ProductStock data;
            Node storedNode = WType.GetNode(new Node { NodeID = NodeType.Stored });
            IList<ProductStock> erpStock;


            IList<Location> locationList = Factory.DaoLocation().Select(new Location { Company = company });

            Console.WriteLine("Locations: " + locationList.Count.ToString());

            foreach (Location location in locationList)
            {

                if (location.LocationID == 107 || location.LocationID == 103)
                    continue;

                try
                {
                    data = new ProductStock { Bin = new Bin { Location = location } };
                    erpStock = ErpFactory.Documents().GetErpStock(data, detailed);

                    if (erpStock == null || erpStock.Count == 0)
                        continue;


                    Console.WriteLine("Location: " + location.Name + " => " + erpStock.Count + " records");
                    //Console.ReadKey();

                    foreach (ProductStock ps in erpStock.Where(f => f.Stock > 0))
                        try
                        {
                            UpdateStock(ps, storedNode, "Stock Update From ERP");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("UpdateStock: " + ex.Message);
                        }

                }
                catch (Exception ex)
                { Console.WriteLine("GetErpStock: " + ex.Message); }
            }

        }
Esempio n. 35
0
        private void UpdateStock(ProductStock ps, Node storedNode, string comment)
        {


            if (!string.IsNullOrEmpty(ps.Bin.BinCode))
            {
                try { ps.Bin = Factory.DaoBin().Select(ps.Bin).First(); }
                catch (Exception ex)
                { //El bin no Existe
                    //Console.WriteLine(ps.Product.ProductCode + " => " + ps.Bin.BinCode);
                    Console.WriteLine(ex.Message);
                    //Console.ReadKey();
                    Status active = Factory.DaoStatus().Select(new Status { StatusID = EntityStatus.Active }).First();
                    ps.Bin.CreatedBy = WmsSetupValues.SystemUser;
                    ps.Bin.CreationDate = DateTime.Now;
                    ps.Bin.IsFromErp = true;
                    ps.Bin.Status = active;
                    ps.Bin.Rank = 0;
                    Console.WriteLine("Creating Bin: " + ps.Bin.BinCode);
                    ps.Bin = Factory.DaoBin().Save(ps.Bin);
                }
            }
            else
                ps.Bin = WType.GetBin(new Bin { BinCode = DefaultBin.MAIN, Location = ps.Bin.Location });

            //Procesando el Stock.
            DocumentLine line = new DocumentLine
            {
                Product = ps.Product,
                Quantity = ps.Stock,
                Unit = ps.Product.BaseUnit,
                CreatedBy = WmsSetupValues.SystemUser
            };

            (new TransactionMngr()).IncreaseQtyIntoBin(line, storedNode, ps.Bin, comment, true, DateTime.Now, null, null);


        }
Esempio n. 36
0
 public void AddToProductStocks(ProductStock productStock)
 {
     base.AddObject("ProductStocks", productStock);
 }
Esempio n. 37
0
        public IList<ProductStock> GetStockComparation(ProductStock data, Company company)
        {
            if (company == null)
            {
                ExceptionMngr.WriteEvent("GetStockComparation Company " + company.Name, ListValues.EventType.Fatal, null, null, ListValues.ErrorCategory.Business);
                return null;
            }
            SetConnectMngr(company);


            bool detailed = false;
            //Obtiene el Stock del ERP para lo mismo loaction - bin
            IList<ProductStock> erpStock = ErpFactory.Documents().GetErpStock(data, detailed);

            if (erpStock == null || erpStock.Count == 0)
                throw new Exception("No ERP Stock to compare.");


            IList<ProductStock> wmsAvailStock = Factory.DaoLabel().GetNodeStock(data,
            new Node { NodeID = NodeType.Stored },
            new Status { StatusID = EntityStatus.Active });

            IList<ProductStock> wmsPickedStock = Factory.DaoLabel().GetNodeStock(data,
            new Node { NodeID = NodeType.Picked },
            new Status { StatusID = EntityStatus.Locked });

            if (wmsAvailStock == null || wmsAvailStock.Count == 0)
                throw new Exception("No WMS Stock to compare.");

            //Adicionando el Picking
            wmsAvailStock = (from avail in wmsAvailStock
                             join pick in wmsPickedStock on avail.Product.ProductID equals pick.Product.ProductID
                             into gj
                             from sub in gj.DefaultIfEmpty()
                             select new ProductStock
                             {
                                 Product = avail.Product,
                                 Stock = avail.Stock,
                                 PackStock = (sub == null) ? 0 : sub.Stock,
                                 Bin = new Bin { Location = data.Bin.Location },
                             }).ToList();


            //Comparando Contra el ERP entragando un solo resultado
            wmsAvailStock = (from erp in erpStock
                             join avail in wmsAvailStock on erp.Product.ProductID equals avail.Product.ProductID
                             into gj
                             from sub in gj.DefaultIfEmpty()
                             select new ProductStock
                             {
                                 Product = erp.Product,
                                 Stock = erp.Stock,  //ERP On Hand
                                 PackStock = (sub == null) ? 0 : sub.Stock,  //WMS Available
                                 MaxStock = (sub == null) ? 0 : sub.PackStock,  //WMS Picking
                                 AuxQty1 = (sub == null) ? 0 : sub.Stock + sub.PackStock,
                                 MinStock = (sub == null) ? -1 * erp.Stock : sub.Stock + sub.PackStock - erp.Stock, //Diference
                                 Bin = new Bin { Location = data.Bin.Location },
                             }).Where(f => f.MinStock != 0).ToList();


            return wmsAvailStock;

        }
        private void LoadSourceLabels() {

            View.Model.LinesToProcess = new List<ProductStock>();

            if (View.Model.SourceLocation.LabelType.DocTypeID == LabelType.BinLocation)
            {

                //Obtener el producto empcadado en cajas
                Label patternLabel = new Label
                {
                    Bin = View.Model.SourceLocation.Bin,
                    //IsLogistic = true,
                    Printed = true,
                    FatherLabel = new Label { LabelID = -1},
                    Status = new Status { StatusID = EntityStatus.Active },
                    Node = new Node { NodeID = NodeType.Stored },
                    LabelType = new DocumentType { DocTypeID = LabelType.ProductLabel }
                };


                View.Model.LabelsToProcess = service.GetLabel(patternLabel)
                    .Where(f => f.StockQty > 0).OrderByDescending(f => f.LabelID).ToList();

            }

            else if (View.Model.SourceLocation.LabelType.DocTypeID == LabelType.ProductLabel) //Cuando tiene Seriales
            {

                //Obtener el producto empcadado en cajas
                Label patternLabel = new Label
                {
                    Status = new Status { StatusID = EntityStatus.Active },
                    Node = new Node { NodeID = NodeType.Stored },
                    FatherLabel = View.Model.SourceLocation
                };

                View.Model.LabelsToProcess = service.GetLabel(patternLabel)
                    .Where(f => f.CurrQty > 0).OrderByDescending(f => f.LabelID).ToList();

            }




            //Muestra El contenido interno del label -- Para moverlo como retail
            if (View.Model.SourceLocation.LabelType.DocTypeID == LabelType.ProductLabel && View.Model.SourceLocation.StockQty > 0 ) //&& View.Model.WithContent
            {
                View.Model.WithContent = true;

               //Si es un label, se muestra a si mismo para poder meoverse completo.
                View.Model.LabelsToProcess.Add(View.Model.SourceLocation);
                View.LvLabelsToMove.Items.Refresh();

                if (View.Model.SourceLocation.CurrQty > 0)
                {

                    ProductStock ps = new ProductStock
                    {
                        Product = View.Model.SourceLocation.Product,
                        Stock = View.Model.SourceLocation.StockQty,
                        Unit = View.Model.SourceLocation.Product.BaseUnit
                    };

                    View.Model.LinesToProcess.Add(ps);
                    View.LvProductToMove.Items.Refresh();
                }
                
                View.StkRetail.Visibility = Visibility.Visible;
                View.StkQtyRetail.Visibility = Visibility.Visible;
                

            }


            if (View.Model.LabelsToProcess != null && View.Model.LabelsToProcess.Count > 0)
            {
                View.StkLabel.Visibility = Visibility.Visible;
                View.BtnMoveLabel.Visibility = Visibility.Visible;
                View.Model.WithContent = true;
            }




        }
Esempio n. 39
0
 public static ProductStock CreateProductStock(long productStockID, decimal cutStock, decimal productStock1, int colorID, long productNameID, long productSizeID)
 {
     ProductStock productStock = new ProductStock();
     productStock.ProductStockID = productStockID;
     productStock.CutStock = cutStock;
     productStock.ProductStock1 = productStock1;
     productStock.ColorID = colorID;
     productStock.ProductNameID = productNameID;
     productStock.ProductSizeID = productSizeID;
     return productStock;
 }
Esempio n. 40
0
        /// <summary>
        /// Retorna una lista de objetos que contienen las ubicaciones de producto en bodega, 
        /// producto,cantidad en unidad base
        /// </summary>
        /// <param name="data"></param>
        /// <param name="records">Numero de registros a devolver</param>
        /// <returns></returns>
        public IList<ProductStock> GetStock(ProductStock data, PickMethod pickMethod, int records)
        {
            //Sale solo product, y del nodo stored
            string initQuery = "select p.ProductID, p.BaseUnitID, b.BinID, SUM(CASE WHEN l.Printed = 0 THEN l.CurrQty*u.BaseAmount ELSE 0 END) AS Stock,"
            + " SUM(CASE WHEN l.Printed = 1 THEN l.CurrQty*u.BaseAmount ELSE 0 END) as PackStock, Max(l.CreationDate) as MaxDate, Min(l.CreationDate) as MinDate " +
                " from Trace.Label l inner join Master.Product p on l.ProductID = p.ProductID " +
                " Inner Join Master.Unit u On l.UnitID = u.UnitID Inner Join Master.Bin b On l.BinID = b.BinID " +
                " where l.CurrQty > 0 AND (l.LabelTypeID = :lt1 OR l.LabelTypeID = :lsn1)  AND l.NodeID = :nd1 AND l.StatusID = :st1 ";

            StringBuilder sql = new StringBuilder(initQuery);
            Parms = new List<Object[]>();

            Parms.Add(new Object[] { "lt1", LabelType.ProductLabel });
            Parms.Add(new Object[] { "lsn1", LabelType.UniqueTrackLabel });
            Parms.Add(new Object[] { "nd1", NodeType.Stored });
            Parms.Add(new Object[] { "st1", EntityStatus.Active });


            if (data.Product != null && data.Product.ProductID != 0)
            {
                sql.Append(" and p.ProductID = :id1 ");
                Parms.Add(new Object[] { "id1", data.Product.ProductID });
            }


            if (data.Bin != null)
            {
                if (data.Bin.BinID != 0)
                {
                    sql.Append(" and b.BinID = :id8 ");
                    Parms.Add(new Object[] { "id8", data.Bin.BinID });
                }

                if (!string.IsNullOrEmpty(data.Bin.BinCode))
                {
                    sql.Append(" and b.BinCode = :idz2 ");
                    Parms.Add(new Object[] { "idz2", data.Bin.BinCode });
                }

                if (data.Bin.Location != null && data.Bin.Location.LocationID != 0)
                {
                    sql.Append(" and b.LocationID = :id10 ");
                    Parms.Add(new Object[] { "id10", data.Bin.Location.LocationID });
                }

            }


            sql = new StringBuilder(sql.ToString());
            sql.Append(" group by  p.ProductID, p.BaseUnitID, b.BinID ");


            //Order By Picking Method

            if (pickMethod == null || pickMethod.MethodID == PickingMethod.FIFO)
                sql.Append(" order by  MinDate");

            else if (pickMethod.MethodID == PickingMethod.LIFO)
                sql.Append(" order by  MaxDate DESC");

            //else if (pickMethod.MethodID == PickingMethod.ZONE)
            //sql.Append(" order by  b.ZoneID, b.Rank");

            //else if (pickMethod == PickingMethod.FEFO)
            //    sql.Append(" order by  ExpirationDate DESC");




            IQuery query = Factory.Session.CreateSQLQuery(sql.ToString());
            SetParameters(query);

            query.SetMaxResults(records);

            IList<ProductStock> ret = GetProductStockObject(query.List<Object[]>(), Factory);

            if (!Factory.IsTransactional)
                Factory.Commit();

            return ret;

        }
        private void MovingReatilProduct(ProductStock record, double qty, bool moveall)
        {


            DocumentLine line = new DocumentLine
            {
                Quantity = qty,
                Product = record.Product,
                Unit = record.Unit,
                CreatedBy = App.curUser.UserName
            };

            try
            {
                line = service.ChangeProductUbication(View.Model.SourceLocation, line, View.Model.DestLocation);

                if (!line.Note.Contains("Change OK!"))
                {
                    Util.ShowError(Util.GetResourceLanguage("TRANSACTION_ERROR") + "\n" + line.Note);
                    return;
                }
            }
            catch (Exception ex)
            {
                Util.ShowError(Util.GetResourceLanguage("TRANSACTION_ERROR") + "\n" + ex.Message);
                ResetToNext();
                return;
            }

            //Add in Moved List
            ProductStock newRecord = new ProductStock { Bin = record.Bin, Product = record.Product, Unit = record.Unit };
            newRecord.Stock = line.Quantity;
            View.Model.LinesMoved.Add(newRecord);

            if (!moveall)
            {
                //Remove from Original List
                View.Model.LinesToProcess.Remove(record);
                record.Stock -= line.Quantity;
                if (record.Stock > 0)
                    View.Model.LinesToProcess.Add(record);
            }




       }
Esempio n. 42
0
 internal IList<ProductStock> GetStockComparation(ProductStock data, bool detailed, 
     Company company)
 {
     try
     {
         SetService();
         return SerClient.GetStockComparation(data, detailed, company);
     }
     finally
     {
         SerClient.Close();
         if (SerClient.State == CommunicationState.Faulted)
             SerClient.Abort();
     }
 }
Esempio n. 43
0
 public IList<ProductStock> GetProductStock(ProductStock productStock, PickMethod pickMethod)
 {
     try
     {
         SetService();
         return SerClient.GetProductStock(productStock, pickMethod);
     }
     finally
     {
         SerClient.Close();
         if (SerClient.State == CommunicationState.Faulted)
             SerClient.Abort();
     }
 }
Esempio n. 44
0
 public IList<ProductStock> GetBinStock(ProductStock data)
 {
     try
     {
         SetService(); return SerClient.GetBinStock(data);
     }
     finally
     {
         SerClient.Close();
         if (SerClient.State == CommunicationState.Faulted)
             SerClient.Abort();
     }
 }
Esempio n. 45
0
 //Abr 8 2009
 public IList<ProductStock> GetReplanishmentList(ProductStock data, Location location, short selector, 
     bool showEmpty, string bin1, string bin2)
 {
     try
     {
         SetService();
         return SerClient.GetReplanishmentList(data, location, selector, showEmpty, bin1, bin2);
     }
     finally
     {
         SerClient.Close();
         if (SerClient.State == CommunicationState.Faulted)
             SerClient.Abort();
     }
 }
Esempio n. 46
0
        public void SetComparer(IUC_IV_ComparerView view)
        {

            this.ViewComp = view;
            ViewComp.Model = this.container.Resolve<UC_IV_Model>();

            ProductStock pstock = new ProductStock{ Bin = new Bin { Location = App.curLocation }};
            ViewComp.Model.RepPackList = service.GetStockComparation(pstock, false, App.curCompany);

        }
Esempio n. 47
0
        public IList<ProductStock> GetReplanishmentList(ProductStock data, Location location, short selector, bool showEmpty, string bin1, string bin2)
        {

            //string initQuery = "SELECT l.ProductID, l.UnitID, l.BinID, l.SingleQuantity + l.PackQuantity AS CurrQty, "+
            //            " 0 as PackStock, l.MaxDate, l.MinDate " +
            //            "FROM         Master.ZoneBinRelation AS zbr INNER JOIN "+
            //            "Master.ZoneEntityRelation AS zer ON zbr.ZoneID = zer.ZoneID INNER JOIN " +
            //            "vwStockSummary AS l ON zer.EntityRowID = l.ProductID AND zbr.BinID = l.BinID AND zer.EntityID = :ip1 Where 1=1 ";

            string initQuery = "";

            if (selector == 1)
            {
                //Obtiene el max Stock o el Min Stock del Bin.
                initQuery = "SELECT zer.EntityRowID, p.BaseUnitID, b.BinID, ISNULL(OutStock.CurrQty,0) AS CurrQty, " +
                            "0 as PackStock, InStock.MaxDate, InStock.MinDate, ISNULL(b.MinBasicUnitcapacity,0) as MinStock,  ISNULL(b.BasicUnitcapacity,0) as MaxStock, InStock.CurrQty  - ISNULL(OutStock.CurrQty,0) " +
                            "FROM    Master.Bin b INNER JOIN Master.ZoneBinRelation AS zbr ON zbr.BinID = b.BinID INNER JOIN " +
                            "Master.ZoneEntityRelation AS zer ON zbr.ZoneID = zer.ZoneID AND zer.EntityID = :ip1 " +
                            "INNER JOIN Master.Product as p on p.ProductID = zer.entityrowid " +

                            //Muestra solo lo que tenga Stock en IN
                            "INNER JOIN (  " +
                            "SELECT l.ProductID, SUM(ISNULL(l.SingleQuantity,0) + ISNULL(l.PackQuantity,0)) AS CurrQty, MAX(l.MaxDate) as MaxDate, MIN(l.MinDate) as MinDate " +
                            "FROM  vwStockSummary AS l INNER JOIN Master.Product as p on p.ProductID = l.ProductID WHERE l.NodeID = :nid And l.StatusID = :sid  and l.LocationID = :id3 " +
                            "GROUP BY l.ProductID HAVING  SUM(ISNULL(l.SingleQuantity,0) + ISNULL(l.PackQuantity,0)) > 0 ) InStock " +
                            "ON InStock.ProductID = zer.EntityRowID " +

                            "LEFT OUTER JOIN  vwStockSummary AS l ON zer.EntityRowID = l.ProductID AND l.LocationID = :id3 " + //
                            //Out Stock
                            "LEFT OUTER JOIN ( SELECT " +
                                "zer.EntityRowID, SUM(ISNULL(l.SingleQuantity,0) + ISNULL(l.PackQuantity,0)) AS CurrQty " +
                                "FROM    Master.Bin b INNER JOIN Master.ZoneBinRelation AS zbr ON zbr.BinID = b.BinID INNER JOIN " +
                                "Master.ZoneEntityRelation AS zer ON zbr.ZoneID = zer.ZoneID AND " +
                                "zer.EntityID = :ip1 INNER JOIN  vwStockSummary AS l ON b.BinId = l.BinID AND zer.EntityRowID = l.ProductID " +
                                "WHERE  l.NodeID = :nid And l.LocationID = :id3 AND l.StatusID = :sid AND ( zbr.BinType = 2 ) GROUP BY  zer.EntityRowID) OutStock " +
                                "ON OutStock.EntityRowID = zer.EntityRowID " +

                            " WHERE l.NodeID = :nid And l.StatusID = :sid ";

                if (!showEmpty)
                {
                    initQuery += " AND ISNULL(b.BasicUnitcapacity,0) - ISNULL(OutStock.CurrQty,0) > 0 " +
                        " AND InStock.CurrQty  - ISNULL(OutStock.CurrQty,0) > 0 ";
                }



            }
            else
            {
                //Query Basado en los datos seteados en el BIN para Cada Producto (Relacion, Zona Producto).
                initQuery = "SELECT zer.EntityRowID, p.BaseUnitID, b.BinID, ISNULL(OutStock.CurrQty,0) AS CurrQty, " +
                            "0 as PackStock, InStock.MaxDate, InStock.MinDate, ISNULL(zbr.MinUnitcapacity,0) as MinStock,  ISNULL(zbr.Unitcapacity,0) as MaxStock, InStock.CurrQty  - ISNULL(OutStock.CurrQty,0) " +
                            "FROM    Master.Bin b INNER JOIN Master.ZoneBinRelation AS zbr ON zbr.BinID = b.BinID INNER JOIN " +
                            "Master.ZoneEntityRelation AS zer ON zbr.ZoneID = zer.ZoneID AND zer.EntityID = :ip1 " +
                            //--"INNER JOIN  vwStockSummary AS l ON zer.EntityRowID = l.ProductID AND l.LocationID = :id3 " + //b.BinId = l.BinID AND
                            "INNER JOIN Master.Product as p on p.ProductID = zer.entityrowid " +

                            //Muestra solo lo que tenga Stock en IN
                            "INNER JOIN (  " +
                            "SELECT l.ProductID, SUM(ISNULL(l.SingleQuantity,0) + ISNULL(l.PackQuantity,0)) AS CurrQty,  MAX(l.MaxDate) as MaxDate, MIN(l.MinDate) as MinDate  " +
                            "FROM  vwStockSummary AS l INNER JOIN Master.Product as p on p.ProductID = l.ProductID WHERE l.NodeID = :nid And l.StatusID = :sid  and l.LocationID = :id3 " +
                            "GROUP BY l.ProductID HAVING  SUM(ISNULL(l.SingleQuantity,0) + ISNULL(l.PackQuantity,0)) > 0 ) InStock " +
                            "ON InStock.ProductID = zer.EntityRowID " +

                            "LEFT OUTER JOIN  vwStockSummary AS l ON zer.EntityRowID = l.ProductID AND l.LocationID = :id3 " + //

                            //Out Stock
                            "LEFT OUTER JOIN ( SELECT " +
                                "zer.EntityRowID, SUM(ISNULL(l.SingleQuantity,0) + ISNULL(l.PackQuantity,0)) AS CurrQty " +
                                "FROM    Master.Bin b INNER JOIN Master.ZoneBinRelation AS zbr ON zbr.BinID = b.BinID INNER JOIN " +
                                "Master.ZoneEntityRelation AS zer ON zbr.ZoneID = zer.ZoneID AND " +
                                "zer.EntityID = :ip1 INNER JOIN  vwStockSummary AS l ON b.BinId = l.BinID AND zer.EntityRowID = l.ProductID " +
                                "WHERE  l.NodeID = :nid And l.LocationID = :id3 And l.StatusID = :sid AND ( zbr.BinType = 2 ) GROUP BY  zer.EntityRowID) OutStock " +
                                "ON OutStock.EntityRowID = zer.EntityRowID " +

                            " WHERE l.NodeID = :nid And l.StatusID = :sid ";

                if (!showEmpty)
                {
                    initQuery += " AND ISNULL(zbr.Unitcapacity,0) - ISNULL(OutStock.CurrQty,0) > 0 " +
                    " AND InStock.CurrQty  - ISNULL(OutStock.CurrQty,0) > 0 ";
                }




            }

            StringBuilder sql = new StringBuilder(initQuery);
            Parms = new List<Object[]>();



            Parms.Add(new Object[] { "ip1", EntityID.Product });
            Parms.Add(new Object[] { "nid", NodeType.Stored });
            Parms.Add(new Object[] { "sid", EntityStatus.Active });



            if (data.Product != null && data.Product.ProductID != 0)
            {
                sql.Append(" and zer.EntityRowID = :id1 ");
                Parms.Add(new Object[] { "id1", data.Product.ProductID });
            }

            if (data.Bin != null && data.Bin.BinID != 0)
            {
                sql.Append(" and b.BinID = :id2 ");
                Parms.Add(new Object[] { "id2", data.Bin.BinID });
            }

            if (location != null && location.LocationID != 0)
            {
                sql.Append(" and b.LocationID = :id3 ");
                Parms.Add(new Object[] { "id3", location.LocationID });
            }

            if (data.BinType != 0)
            {
                sql.Append(" and (zbr.BinType = :id4 )"); //zbr.BinType = 0 Or 
                Parms.Add(new Object[] { "id4", data.BinType });
            }


            //Nov 3 - adicion de rango de Bines
            //############################################################################
            if (data.Product != null && !string.IsNullOrEmpty(data.Product.ProductCode))
            {

                sql.Append(" And (p.ProductCode like :nom1 ");

                if (data.Product.ProductCode.Length >= 3)
                {
                    sql.Append(" Or p.Name like :nom2 ");
                    Parms.Add(new Object[] { "nom2", "%" + data.Product.ProductCode + "%" });
                }

                sql.Append(" ) ");

                Parms.Add(new Object[] { "nom1", data.Product.ProductCode + "%" });

            }


            if (!string.IsNullOrEmpty(bin1))
            {
                sql.Append(" and b.BinCode >= :ib1 ");
                Parms.Add(new Object[] { "ib1", bin1 });
            }


            if (!string.IsNullOrEmpty(bin2))
            {
                sql.Append(" and b.BinCode <= :ib2 ");
                Parms.Add(new Object[] { "ib2", bin2 });
            }
            //############################################################################


            //sql.Append(" order by  b.ZoneID, b.Rank");

            if (selector == 1)
                sql.Append(" GROUP BY zer.EntityRowID, p.BaseUnitID, b.BinID, b.MinBasicUnitcapacity, b.BasicUnitcapacity, InStock.CurrQty, OutStock.CurrQty, InStock.MaxDate, InStock.MinDate ");
            else
                sql.Append(" GROUP BY zer.EntityRowID, p.BaseUnitID, b.BinID, zbr.MinUnitcapacity, zbr.Unitcapacity, InStock.CurrQty, OutStock.CurrQty, InStock.MaxDate, InStock.MinDate ");




            IQuery query = Factory.Session.CreateSQLQuery(sql.ToString());
            SetParameters(query);

            //query.SetMaxResults(WmsSetupValues.);

            IList<ProductStock> ret = GetProductStockObject(query.List<Object[]>(), Factory);

            if (!Factory.IsTransactional)
                Factory.Commit();

            return ret;

        }
        public IList<ProductStock> GetErpStock(ProductStock data, bool detailed)
        {
            IList<ProductStock> result = new List<ProductStock>();

            try
            {
                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);
                Command.Connection.Open();

                string sQuery, table, sWhere="";
                if (detailed)
                {
                    sQuery = "SELECT * FROM IV00112 WHERE (QUANTITY > 0 OR ATYALLOC > 0) ";  //IV00112 Tabla detallada de produto por BIN
                    table = "IV00112";
                }
                else
                {
                    sQuery = "SELECT * FROM IV00102 WHERE RCRDTYPE = 2 AND QTYONHND > 0 ";
                    table = "IV00102";
                }


                if (data.Product != null && data.Product.ProductID != 0)
                    sWhere += " AND ITEMNMBR = '" + data.Product.ProductCode + "'";


                if (data.Bin != null && data.Bin.BinID != 0 && detailed)
                    sWhere += " AND BIN = '" + data.Bin.BinCode + "'";


                if (data.Bin != null && data.Bin.Location != null && data.Bin.Location.LocationID != 0)
                    sWhere += " AND LOCNCODE = '" + data.Bin.Location.ErpCode + "'";

                ds = ReturnDataSet(sQuery + sWhere, "", table, Command.Connection);

                if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0)
                    return null;


                //Creado el Ilist De ProductStock
                ProductStock record;
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    try
                    {


                        record = new ProductStock();
                        record.Product = WType.GetProduct(new Product { Company = CurCompany, ProductCode = dr["ITEMNMBR"].ToString() }); ;

                        if (detailed)
                        {
                            record.Bin = new Bin { BinCode = dr["BIN"].ToString(), Location = data.Bin.Location };
                            record.Stock = double.Parse(dr["QUANTITY"].ToString());
                            record.PackStock = double.Parse(dr["ATYALLOC"].ToString());
                        }
                        else
                        {
                            record.Bin = new Bin { BinCode = DefaultBin.MAIN, Location = data.Bin.Location };
                            record.Stock = double.Parse(dr["QTYONHND"].ToString());
                            record.PackStock = double.Parse(dr["ATYALLOC"].ToString());
                        }

                        result.Add(record);
                    }
                    catch { }
                }




                return result;
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetErpStock", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return null;
            }
        }
Esempio n. 49
0
 public IList<ProductStock> GetReplanishmentList(ProductStock data, Location location, short selector, bool showEmpty, string bin1, string bin2)
 {
     return TranMngr.GetReplanishmentList(data, location, selector, showEmpty, bin1, bin2);
 }
Esempio n. 50
0
        public IList<ProductStock> GetStock(ProductStock data)
        {

            string initQuery = "SELECT l.ProductID, l.UnitID, l.BinID, l.SingleQuantity AS Stock,  l.PackQuantity as PackStock, l.MaxDate, l.MinDate "
             + "FROM vwStockSummary AS l Where (l.SingleQuantity > 0 Or l.PackQuantity > 0)  And l.NodeID = :nid And l.StatusID = :sid ";

            StringBuilder sql = new StringBuilder(initQuery);
            Parms = new List<Object[]>();

            Parms.Add(new Object[] { "nid", NodeType.Stored });
            Parms.Add(new Object[] { "sid", EntityStatus.Active });


            if (data.Product != null && data.Product.ProductID != 0)
            {
                sql.Append(" and l.ProductID = :id1 ");
                Parms.Add(new Object[] { "id1", data.Product.ProductID });
            }


            if (data.Bin != null && data.Bin.BinID != 0)
            {
                sql.Append(" and l.BinID = :id2 ");
                Parms.Add(new Object[] { "id2", data.Bin.BinID });
            }

            if (data.Bin != null && data.Bin.Location != null && data.Bin.Location.LocationID != 0)
            {
                sql.Append(" and l.LocationID = :id3 ");
                Parms.Add(new Object[] { "id3", data.Bin.Location.LocationID });
            }


            IQuery query = Factory.Session.CreateSQLQuery(sql.ToString());
            SetParameters(query);


            IList<ProductStock> ret = GetProductStockObject(query.List<Object[]>(), Factory);

            if (!Factory.IsTransactional)
                Factory.Commit();

            return ret;

        }
Esempio n. 51
0
 public IList<ProductStock> GetStock(ProductStock data, PickMethod pickMethod, int records)
 {
     return Factory.DaoLabel().GetStock(data, pickMethod, records);
 }
Esempio n. 52
0
        public static IList<ProductStock> GetProductStockObject(IList<Object[]> retList, DaoFactory factory)
        {
            if (retList == null || retList.Count == 0)
                return new List<ProductStock>();

            IList<ProductStock> ret = new List<ProductStock>();
            ProductStock curStock;


            foreach (Object[] obj in retList)
            {
                try
                {
                    curStock = new ProductStock();

                    try { curStock.Product = factory.DaoProduct().SelectById(new Product { ProductID = (int)obj[0] }); }
                    catch { }

                    try { curStock.Unit = factory.DaoUnit().SelectById(new Unit { UnitID = (int)obj[1] }); }
                    catch { }

                    try { curStock.Bin = (obj[2] != null && (int)obj[2] != 0) ? factory.DaoBin().SelectById(new Bin { BinID = (int)obj[2] }) : null; }
                    catch { }

                    try { curStock.Stock = Double.Parse(obj[3].ToString()); }
                    catch { }

                    try { curStock.PackStock = Double.Parse(obj[4].ToString()); }
                    catch { }
                    
                    try { curStock.MaxDate = obj[5] != null ? (DateTime?)DateTime.Parse(obj[5].ToString()) : null; }
                    catch { }

                    try { curStock.MinDate = obj[6] != null ? (DateTime?)DateTime.Parse(obj[6].ToString()) : null; }
                    catch { }

                    try { curStock.MinStock = obj[7] != null ? Double.Parse(obj[7].ToString()) : 0; }
                    catch { }

                    try { curStock.MaxStock = obj[8] != null ? Double.Parse(obj[8].ToString()) : 0; }
                    catch { }

                    try { curStock.AuxQty1 = obj[9] != null ? Double.Parse(obj[9].ToString()) : 0; }
                    catch { }

                    ret.Add(curStock);
                }
                catch { }
            }

            return ret;
        }
Esempio n. 53
0
 public IList<ProductStock> GetStockComparation(ProductStock data, bool detailed, Company company)
 {
         return ErpMngr.GetStockComparation(data, company);
 }
Esempio n. 54
0
 public IList<ProductStock> GetProductStock(ProductStock productStock, PickMethod pickMethod)
 { return Factory.DaoLabel().GetStock(productStock, pickMethod, 20); }
Esempio n. 55
0
 public IList<ProductStock> GetBinStock(ProductStock data)
 {
     return Factory.DaoLabel().GetStock(data);
 }
Esempio n. 56
0
        private void imgLook_Click(object sender, RoutedEventArgs e)
        {
            //Search for a Bin
            if (this.Product != null)
            {
                ProductStock ps = new ProductStock { Product = this.Product, Bin = new Bin { Location = App.curLocation } };
                try { BinList = (new WMSServiceClient()).GetBinStock(ps).Select(f=>f.Bin).ToList(); }
                catch { }
            }
            else
                BinList = (new WMSServiceClient()).GetBin(new Bin { Location = App.curLocation });


            if (BinList == null || BinList.Count == 0)
            {
                Util.ShowError("No Bins defined for location: " + App.curLocation.Name);
                return;
            }

            //Cargar la lista de Bins
            this.cboBin.Visibility = Visibility.Visible;
            this.cboBin.IsDropDownOpen = true;

            if (BinList.Count == 1)
            {
                this.cboBin.Visibility = Visibility.Collapsed;
                txtBin.Text = BinList[0].BinCode;
                this.Bin = BinList[0];
                imgLoad.Focus();
                //imgLoad.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, imgLoad));
            }
        }
Esempio n. 57
0
 public String GetStrProductStock(ProductStock productStock, PickMethod pickMethod)
 { return LabelMngr.GetStrProductStock(productStock, pickMethod); }
Esempio n. 58
0
 private WareHouse FindSutiableWareHouse(ProductStock request)
 {
     throw new System.NotImplementedException();
 }
Esempio n. 59
0
        private Task FillDrone(Drone drone, ProductStock request)
        {
            Task task = default(Task);
            task.ProductType = request.ProductType;
            int avaibleCapicaity = drone.Capiciaty;
            int itemWeight = request.ProductType.Weight;

            while(avaibleCapicaity >= itemWeight)
            {
                avaibleCapicaity -= request.ProductType.Weight;
                task.Quanity += 1;
            }
            return task;
        }
Esempio n. 60
0
        private void LoadRepPack(Location location)
        {

            //Load the RepPack
            ProcessWindow pw = new ProcessWindow("Loading Replenishment Records ... ");

            ProductStock productStock = new ProductStock { BinType = BinType.Out_Only };

            if (!string.IsNullOrEmpty(ViewRepPack.CboProduct.Text.ToUpper())) {
                productStock.Product = new Product  { ProductCode = ViewRepPack.CboProduct.Text.ToUpper() };
            }

            //Binrange
            String[] binRange = ViewRepPack.BinRange.Text.Split(':');
            string bin1 = "", bin2 = "";
            try
            {
                if (!string.IsNullOrEmpty(binRange[0]))
                    bin1 = binRange[0].ToUpper();

                if (!string.IsNullOrEmpty(binRange[1]))
                    bin2 = binRange[1].ToUpper();
            }
            catch { }


            IList<ProductStock> repList = service.GetReplanishmentList(productStock, location,
                short.Parse(ReplenishSelector.DataKey), (bool)ViewRepPack.ShowEmpty.IsChecked, bin1, bin2);

            if (repList == null || repList.Count == 0)
            {
                Util.ShowError("No replenishment records.");
                ViewRepPack.Model.RepPackList = null;
                ViewRepPack.Model.BinList = null;
                ViewRepPack.Model.ProductList = null;
                pw.Close();
                return;
            }

            //Le avisa al view     que     fue cargado el replenish.
            ViewRepPack.WasLoaded = true;

            if (ViewRepPack.ShowEmpty.IsChecked == true)
                fullLoaded = true;
            else
                fullLoaded = false;


            //Load the Replanish Value.
            for (int i = 0; i < repList.Count; i++)
            {
                if (repList[i].Stock < repList[i].MinStock)
                {
                    repList[i].PackStock = (repList[i].MaxStock - repList[i].Stock) > 0 ? repList[i].MaxStock - repList[i].Stock : 0;

                    if (repList[i].PackStock > repList[i].AuxQty1)
                        repList[i].PackStock = repList[i].AuxQty1;

                    //Anterior solo marca los que completan el minimo
                    //if (repList[i].MinStock > 0 && (repList[i].Stock + repList[i].PackStock) >= repList[i].MinStock)
                        //repList[i].Mark = true;

                    //nuevo, marca todo lo que sea mayor a cero.
                    if (repList[i].MinStock > 0 && (repList[i].Stock + repList[i].PackStock) > 0 )
                        repList[i].Mark = true;

                }


            }

            repList = repList.OrderBy(f => f.Product.ProductCode).ToList();

            ViewRepPack.Model.OriRepPackList = repList; //OrderByDescending(f => f.PackStock).ToList(); //.Where(f => f.PackStock > 0).ToList();
            ViewRepPack.Model.RepPackList = repList; //.Where(f => f.PackStock > 0).ToList();
            ViewRepPack.Model.ShowProcess = true;


            //Load Filters Bin, Product
            //ViewRepPack.Model.BinList = ViewRepPack.Model.RepPackList.Select(f => f.Bin.BinCode).Distinct().ToList();
            //ViewRepPack.Model.ProductList = ViewRepPack.Model.RepPackList.Select(f => f.Product.ProductCode).Distinct().ToList();
            //ViewRepPack.Model.BinList.Add("Show All");
            //ViewRepPack.Model.ProductList.Add("Show All");

            pw.Close();         


        }