示例#1
0
        public Product UpdateProduct(Product product)
        {
            //Add validations here!
            ProductError result = ProductError.None;

            if (string.IsNullOrEmpty(product.Name))
            {
                result |= ProductError.InvalidName;
            }
            if (product.UnitId <= 0)
            {
                result |= ProductError.InvalidUnit;
            }
            if (string.IsNullOrEmpty(product.ScaleCode))
            {
                result |= ProductError.InvalidScaleCode;
            }
            if (product.ProductGroupId <= 0)
            {
                result |= ProductError.InvalidProductGroup;
            }
            if (product.AgriculturalBrandId <= 0)
            {
                result |= ProductError.InvalidAgriculturalBrand;
            }
            if (result != ProductError.None)
            {
                throw new ProductException(result);
            }
            else
            {
                return(productDL.UpdateProduct(product));
            }
        }
示例#2
0
 public void UpdateError(ProductError errProduct)
 {
     if (IsExist(errProduct.ProductId))
     {
         _sqlConnection.Execute(
             "Update Product_Error_Link set CompanyId = @CompanyId, DetailUrl = @DetailUrl, Keyword = @Keyword, Type = @Type, DateLog = @DateLog where ProductId = @ProductId",
             new
         {
             @CompanyId = errProduct.CompanyId,
             @DetailUrl = errProduct.DetailUrl ?? "",
             @Keyword   = errProduct.Keyword ?? "",
             @Type      = errProduct.Type,
             @DateLog   = errProduct.DateLog,
             @ProductId = errProduct.ProductId
         });
     }
     else
     {
         _sqlConnection.Execute(
             "Insert into Product_Error_Link (ProductId, CompanyId, DetailUrl, DateLog, Keyword, Type) values (@ProductId, @CompanyId, @DetailUrl, @DateLog, @Keyword, @Type)",
             new
         {
             @ProductId = errProduct.ProductId,
             @CompanyId = errProduct.CompanyId,
             @DetailUrl = errProduct.DetailUrl ?? "",
             @DateLog   = errProduct.DateLog,
             @Keyword   = errProduct.Keyword ?? "",
             @Type      = errProduct.Type
         });
     }
 }
示例#3
0
        public List <Product> GetProduct(int?id = null)
        {
            //Add validations here!
            ProductError result = ProductError.None;

            if (id != null && id <= 0)
            {
                result |= ProductError.InvalidId;
            }

            if (result != ProductError.None)
            {
                throw new ProductException(result);
            }
            else
            {
                return(productDL.GetProduct(id));
            }
        }
示例#4
0
        public bool DeleteProduct(int id)
        {
            //Add validations here!
            ProductError result = ProductError.None;

            if (id <= 0)
            {
                result |= ProductError.InvalidId;
            }

            if (result != ProductError.None)
            {
                throw new ProductException(result);
            }
            else
            {
                return(productDL.DeleteProduct(id));
            }
        }
示例#5
0
        public async Task <JsonResult> UploadFiles(IFormFile Zip, IFormFile ProductsExcelFile)
        {
            var    webRoot  = _env.WebRootPath;
            string TempPath = Path.Combine(webRoot, "Uploads/Product/");

            // upload zip file
            #region upload zip file

            string ZipFileName = TempPath + Zip.FileName;
            var    photos      = new Dictionary <string, PhotoStruct>();
            if (Path.GetExtension(ZipFileName).Equals(".zip"))
            {
                try
                {
                    using (var s = new ZipInputStream(Zip.OpenReadStream()))
                    {
                        ZipEntry theEntry;
                        while ((theEntry = s.GetNextEntry()) != null)
                        {
                            string fileName = Path.GetFileName(theEntry.Name);

                            // create directory
                            if (fileName != String.Empty)
                            {
                                if (fileName.IndexOfAny(@"!@#$%^*/~\".ToCharArray()) > 0)
                                {
                                    continue;
                                }
                                var size      = theEntry.Size;
                                var binary    = new byte[size];
                                int readBytes = 0;
                                while (readBytes < size)
                                {
                                    var read = s.Read(binary, readBytes, Convert.ToInt32(size));
                                    readBytes += read;
                                }
                                var ext      = Path.GetExtension(fileName);
                                var guidName = Guid.NewGuid().ToString() + ext;
                                photos.Add(fileName, new PhotoStruct(ref binary, guidName));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    return(Json(new { Ok = false, message = "Empty File" }));
                }
            }
            else
            {
                // ViewBag.noticZipFileUpload = "Empty File";
                return(Json(new { Ok = false, message = "Empty File" }));
            }

            #endregion

            // upload Sheet
            #region upload sheet

            if (ProductsExcelFile.Length > 0 && photos.Count > 0)
            {
                // extract only the filename
                var    fileName = Path.GetFileName(ProductsExcelFile.FileName);
                string ext      = Path.GetExtension(ProductsExcelFile.FileName);

                string NewFileName = "Products_" + DateTime.Now.ToShortDateString().Replace("/", "-") + "-" + DateTime.Now.ToShortTimeString().Replace(":", "-").Replace(" ", "-") + ext;

                fileName = NewFileName;

                var path = Path.Combine(TempPath, fileName);


                using (var wb = new XLWorkbook(ProductsExcelFile.OpenReadStream()))
                {
                    IXLWorksheet sheet;
                    try
                    {
                        wb.SaveAs(path);
                        wb.TryGetWorksheet("Sheet1", out sheet);
                        if (sheet != null)
                        {
                            // get last row
                            string lastrow = sheet.LastRowUsed().RangeAddress.FirstAddress.ToString();
                            lastrow = lastrow.Remove(0, 1);
                            var rowCount = int.Parse(lastrow);
                            // 2 beacuse header
                            var rowRange  = sheet.Rows(2, rowCount).ToList();
                            var rowsCount = rowRange.Count();
                            // to get first row
                            var firstrowRange = sheet.Rows(1, 2).ToList();
                            var FirstRowcols  = firstrowRange[0].Cells().ToList();


                            if (
                                FirstRowcols[0].Value.ToString() == "Product Name" &&
                                FirstRowcols[1].Value.ToString() == "Code" &&
                                FirstRowcols[2].Value.ToString() == "Image Name" &&
                                FirstRowcols[3].Value.ToString() == "Department" &&
                                FirstRowcols[4].Value.ToString() == "Amount")
                            {
                                if (rowsCount < 1000)
                                {
                                    List <Product>      productList = new List <Product>();
                                    List <ProductError> lstErr      = new List <ProductError>()
                                    {
                                    };


                                    var AllProduct = UnitOfWork.ProductBL.GetAllProductList()
                                                     .Where(p => p.IsActive == true)
                                                     .ToList();


                                    for (int i = 0; i < rowsCount; i++)

                                    {
                                        Product      product = new Product();
                                        ProductError err     = new ProductError();
                                        string       reason  = string.Empty;

                                        var cols = rowRange.ElementAt(i).Cells().ToList();
                                        if (
                                            !string.IsNullOrEmpty(cols[0].Value.ToString()) &&
                                            !string.IsNullOrEmpty(cols[1].Value.ToString()) &&
                                            !string.IsNullOrEmpty(cols[2].Value.ToString()) &&
                                            !string.IsNullOrEmpty(cols[3].Value.ToString()) &&
                                            !string.IsNullOrEmpty(cols[4].Value.ToString())

                                            )
                                        {
                                            product.InventoryQnty = Convert.ToDecimal(cols[4].Value);
                                            product.IsActive      = true;
                                            product.CreatedDate   = DateTime.Now;
                                            product.CreatedBy     = LoggedUserId;

                                            // Department
                                            var department = AllProduct.Where(p => p.Department.Name.ToLower() == (string)cols[3].Value.ToString().ToLower())
                                                             .FirstOrDefault();
                                            if (department != null)
                                            {
                                                product.DepartmentId = department.DepartmentId;
                                            }
                                            else
                                            {
                                                reason += "Department not exist, ";
                                            }


                                            // end
                                            if (department != null)
                                            {
                                                // check unique name
                                                if (AllProduct.Where(p => p.DepartmentId == department.DepartmentId && p.Name == cols.ElementAt(0).Value.ToString()).FirstOrDefault() == null)
                                                {
                                                    product.Name = cols[0].Value.ToString();
                                                }
                                                else
                                                {
                                                    reason += "Name already exist, ";
                                                }
                                                //Code
                                                if (AllProduct.Where(p => p.DepartmentId == department.DepartmentId && p.Code == cols[1].Value.ToString()).FirstOrDefault() == null)
                                                {
                                                    product.Code = cols[1].Value.ToString();
                                                }
                                                else
                                                {
                                                    reason += "Code already exist, ";
                                                }
                                            }


                                            //End


                                            // image
                                            string imageName = cols[2].Value.ToString();
                                            if (photos.ContainsKey(imageName))
                                            {
                                                var photoStruct = photos[imageName];
                                                var imagePath   = Path.Combine("Uploads", "Product", photoStruct.GuidName);
                                                var fullpath    = Path.Combine(webRoot, imagePath);
                                                try
                                                {
                                                    if (!System.IO.File.Exists(fullpath))
                                                    {
                                                        await System.IO.File.WriteAllBytesAsync(fullpath, photoStruct.Binary);
                                                    }
                                                    product.Image = @"\" + imagePath;
                                                }
                                                catch (Exception ex)
                                                {
                                                    reason += "Failed to save image, ";
                                                }
                                            }
                                            else
                                            {
                                                reason += "Image doesn't exist in zip file, ";
                                            }
                                            // end
                                        }
                                        else if (string.IsNullOrEmpty(cols[0].ToString()) || string.IsNullOrEmpty(cols[1].ToString()) || string.IsNullOrEmpty(cols[2].ToString()) || string.IsNullOrEmpty(cols[3].ToString()))
                                        {
                                            reason += "Empty Field, ";
                                        }

                                        if (string.IsNullOrEmpty(reason))
                                        {
                                            if (!string.IsNullOrEmpty(product.Name) && !string.IsNullOrEmpty(product.Code))
                                            {
                                                productList.Add(product);
                                            }
                                        }
                                        else
                                        {
                                            err.Name   = cols[0].Value.ToString();
                                            err.Code   = cols[1].Value.ToString();
                                            err.Image  = cols[3].Value.ToString();
                                            err.Reason = reason;
                                            lstErr.Add(err);
                                        }
                                    }

                                    UnitOfWork.ProductBL.AddRange(productList);
                                    if (UnitOfWork.Complete(LoggedUserId) > 0)
                                    {
                                        return(Json(new { Ok = true, Message = ApplicationMessages.SaveSuccess, err = lstErr }));
                                    }
                                    else
                                    {
                                        return(Json(new { Ok = false, Message = "Failed to import products", err = lstErr }));
                                    }
                                }
                            }
                            else
                            {
                                return(Json(new { Ok = false, Message = "Please download Tempelte", temp = true }));
                            }
                        }
                    }

                    catch (Exception ex)
                    {
                        return(Json(new { Ok = false, Message = ApplicationMessages.ErrorOccure }));
                    }
                }
            }
            return(Json(new { Ok = true }));

            #endregion
        }
示例#6
0
 public ProductException(ProductError error, string message) : base(message)
 {
     Error = error;
 }
示例#7
0
 public ProductException(ProductError error)
 {
     Error = error;
 }