Example #1
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            IDictionary <String, IList <CsvRow> > uniqueCollections = new Dictionary <String, IList <CsvRow> >();

            String folder = txtFolder.Text;

            if (String.IsNullOrWhiteSpace(UserDefinedTags) == true)
            {
                UserDefinedTags = textBoxTags.Text;
            }

            Task.Run(

                () => {
                #region Delete the previously generated files

                String[] filePaths = Directory.GetFiles(@"Use");
                foreach (string filePath in filePaths)
                {
                    try {
                        File.Delete(filePath);
                    } catch (Exception) {}
                }
                #endregion

                #region Save the inclusive and exclusive filters
                IList <String> inclusiveFilters = new List <String>();

                foreach (String filter in listBoxInclusiveFilters.Items)
                {
                    inclusiveFilters.Add(filter);
                }


                IList <String> exclusiveFilters = new List <String>();

                foreach (String filter in listBoxExclusiveFilters.Items)
                {
                    exclusiveFilters.Add(filter);
                }

                #endregion

                #region Load the Prodcts.csv file

                String file0 = $"{folder}\\products.csv";
                GreenDropShipProductFile greenDropShipAllProductFile = new GreenDropShipProductFile();
                if (File.Exists(file0))
                {
                    IList <CsvColumn> extraColumns = new List <CsvColumn>()
                    {
                        new CsvColumn("collection", ""),
                        new CsvColumn("tags", ""),
                        new CsvColumn("Variant Grams", ""),
                        new CsvColumn("Variant Price", ""),
                        new CsvColumn("Cost Per Item", ""),
                        new CsvColumn("Option1 Value", "Default Title"),
                        new CsvColumn("Option1 Name", "Title"),
                        new CsvColumn("Published", "TRUE"),
                        new CsvColumn("Vendor", "Groton Valley Traders"),
                        new CsvColumn("Handle", ""),
                        new CsvColumn("Compare at Price", ""),
                        new CsvColumn("Variant Inventory Tracker", "shopify"),
                        new CsvColumn("Variant Inventory Policy", "deny"),
                        new CsvColumn("Variant Fulfillment Service", "manual"),
                        new CsvColumn("Map", ""),
                        new CsvColumn("Google Shopping / MPN", "")
                    };
                    if (ProcessImages == true)
                    {
                        extraColumns.Add(new CsvColumn("image src", ""));
                    }
                    greenDropShipAllProductFile.Load(file0, @"^\w{4}\d{8}", extraColumns);
                }
                #endregion

                #region Create unique list of categories
                foreach (CsvRow row in greenDropShipAllProductFile.Rows)
                {
                    if (row.ExcludeMe == true)
                    {
                        continue;
                    }

                    if (FilterOnKeyWords == true && (inclusiveFilters.Count > 0 || exclusiveFilters.Count > 0))
                    {
                        IFilterValue descriptionColumn = row.GetColumn("description");
                        IFilterValue categoriesColumn  = row.GetColumn("categories");
                        IFilterValue storageColumn     = row.GetColumn("storage");
                        IFilterValue handleColumn      = row.GetColumn("Handle");
                        IFilterValue brandColumn       = row.GetColumn("brand");
                        IFilterValue nameColumn        = row.GetColumn("name");
                        IFilterValue skuColumn         = row.GetColumn("sku");
                        Dispatcher.Invoke(() =>
                        {
                            if (String.IsNullOrEmpty(skuColumn?.Value) == false)
                            {
                                if (inclusiveFilters.Count > 0)
                                {
                                    var found = inclusiveFilters.Where(f =>
                                                                       descriptionColumn.Value.ContainsWord(f) ||
                                                                       categoriesColumn.Value.ContainsWord(f) ||
                                                                       storageColumn.Value.ContainsWord(f) ||
                                                                       handleColumn.Value.ContainsWord(f) ||
                                                                       brandColumn.Value.ContainsWord(f) ||
                                                                       nameColumn.Value.ContainsWord(f) ||
                                                                       skuColumn.Value.ContainsWord(f)
                                                                       );

                                    if (!found.Any())
                                    {
                                        row.ExcludeMe = true;
                                        return;
                                    }
                                }
                                if (exclusiveFilters.Count > 0)
                                {
                                    var found = exclusiveFilters.Where(f =>
                                                                       descriptionColumn.Value.ContainsWord(f) ||
                                                                       categoriesColumn.Value.ContainsWord(f) ||
                                                                       storageColumn.Value.ContainsWord(f) ||
                                                                       handleColumn.Value.ContainsWord(f) ||
                                                                       brandColumn.Value.ContainsWord(f) ||
                                                                       nameColumn.Value.ContainsWord(f) ||
                                                                       skuColumn.Value.ContainsWord(f)
                                                                       );

                                    if (found.Any())
                                    {
                                        row.ExcludeMe = true;
                                        return;
                                    }
                                }
                            }
                        });
                    }
                }
                #endregion

                #region purge excluded rows

                int rowId = 0;
                do
                {
                    CsvRow row = greenDropShipAllProductFile.Rows[rowId];
                    if (row.ExcludeMe == false)
                    {
                        IFilterValue storage = row.GetColumn("storage");
                        row.ExcludeMe        = string.IsNullOrWhiteSpace(storage.Value) == true;
                    }

                    if (row.ExcludeMe == true)
                    {
                        greenDropShipAllProductFile.Rows.RemoveAt(rowId);
                    }
                    else
                    {
                        rowId++;
                    }
                } while (rowId < greenDropShipAllProductFile.Rows.Count);

                #endregion

                #region Update the Handle field with the value from the Name field

                IDictionary <String, String> skuHandleMap = new Dictionary <string, string>(30000);
                String file1 = $"{folder}\\products_shopify_inventory.csv";
                GreenDropShipProductFile greenDropShipInventoryFile = new GreenDropShipProductFile();
                if (File.Exists(file1))
                {
                    greenDropShipInventoryFile.Load(file1, @"^\w{4}\d{8}", null);
                    foreach (CsvRow row in greenDropShipInventoryFile.Rows)
                    {
                        IFilterValue handle = row.GetColumn("Handle");
                        IFilterValue sku    = row.GetColumn("SKU");

                        skuHandleMap.Add(sku.Value, handle.Value.Replace("-", ""));
                    }
                }

                foreach (CsvRow row in greenDropShipAllProductFile.Rows)
                {
                    IFilterValue skuValue = row.GetColumn("sku");
                    if (skuHandleMap.ContainsKey(skuValue.Value))
                    {
                        row.SetColumn("Handle", $"{skuHandleMap[skuValue.Value]}");
                    }
                }

                #endregion

                #region Adjust the Product Price Based on Shipping and Price and Profit

                AdjustPricingFilter pricingAdjustmentFilter = new AdjustPricingFilter(true, AddShippingToPrice, ProfitMargin, ProfitMarginThreshold, ShippingSurcharge);
                IList <IFilter> hasAdjustedPriceFilter      = new List <IFilter>()
                {
                    pricingAdjustmentFilter
                };
                foreach (CsvRow row in greenDropShipAllProductFile.Rows)
                {
                    if (row.ExcludeMe)
                    {
                        continue;
                    }
                    row.IncludeMeWhenTrue(hasAdjustedPriceFilter);
                }
                #endregion

                #region Adjust the Product Weight

                AdjustWeightFilter weightAdjustmentFilter = new AdjustWeightFilter(false);
                IList <IFilter> hasAdjustedWeightFilter   = new List <IFilter>()
                {
                    weightAdjustmentFilter
                };
                foreach (CsvRow row in greenDropShipAllProductFile.Rows)
                {
                    if (row.ExcludeMe)
                    {
                        continue;
                    }
                    row.IncludeMeWhenTrue(hasAdjustedWeightFilter);
                }
                #endregion

                #region Filter Products based on whether they can have free shipping
                FreeShippingFilter freeShippingFilter = new FreeShippingFilter(FilterOnFreeShipping, FreeShippingProfitMargin);
                IList <IFilter> hasFreeShippingFilter = new List <IFilter>()
                {
                    freeShippingFilter
                };
                foreach (CsvRow row in greenDropShipAllProductFile.Rows)
                {
                    if (row.ExcludeMe)
                    {
                        continue;
                    }
                    row.IncludeMeWhenTrue(hasFreeShippingFilter);
                }
                #endregion

                #region Filter Products based on the cubic volume < 0.23
                Under023CubicVolumeFilter under023CubicVolumeFilter = new Under023CubicVolumeFilter(FilterOnUnder023CubicVolume);
                IList <IFilter> hasUnder023CubicVolumeFilter        = new List <IFilter>()
                {
                    under023CubicVolumeFilter
                };
                foreach (CsvRow row in greenDropShipAllProductFile.Rows)
                {
                    if (row.ExcludeMe)
                    {
                        continue;
                    }
                    row.IncludeMeWhenTrue(hasUnder023CubicVolumeFilter);
                }
                #endregion

                #region Filter Products based on the inventory threshold
                IdProductsWithInventoryFilter inventoryFilter = new IdProductsWithInventoryFilter(FilterOnInventory, MinimumInventoryThreshold, MaximumInventoryThreshold);
                IList <IFilter> inventoryThresholdFilter      = new List <IFilter>()
                {
                    inventoryFilter
                };
                foreach (CsvRow row in greenDropShipAllProductFile.Rows)
                {
                    if (row.ExcludeMe)
                    {
                        continue;
                    }
                    row.IncludeMeWhenTrue(inventoryThresholdFilter);
                }
                #endregion

                #region Filter Products based on the item weighs one pound or under

                UnderOnePoundWeightFilter underOnePoundFilter = new UnderOnePoundWeightFilter(FilterOnUnderOnePound);
                IList <IFilter> hasUnderOnePoundFilter        = new List <IFilter>()
                {
                    underOnePoundFilter
                };
                foreach (CsvRow row in greenDropShipAllProductFile.Rows)
                {
                    if (row.ExcludeMe)
                    {
                        continue;
                    }
                    row.IncludeMeWhenTrue(hasUnderOnePoundFilter);
                }

                #endregion

                #region Process Images

                if (ProcessImages)
                {
                    foreach (CsvRow row in greenDropShipAllProductFile.Rows)
                    {
                        if (row.ExcludeMe)
                        {
                            continue;
                        }

                        IFilterValue image = row?.GetColumn("images_1");
                        if (String.IsNullOrWhiteSpace(image?.Value) == true)
                        {
                            continue;
                        }

                        row?.SetColumn("image src", image.Value);

                        for (int i = 2; i < 5; i++)
                        {
                            image = row?.GetColumn("images_" + i);
                            if (String.IsNullOrWhiteSpace(image?.Value) == true)
                            {
                                continue;
                            }

                            CsvRow?newRow = row?.CloneMe(new HashSet <string>()
                            {
                                "image src", "Handle"
                            }, false);
                            newRow?.SetColumn("image src", image?.Value);
                            row.AddChild(newRow);
                        }
                    }
                }

                #endregion

                #region Create unique list of categories
                foreach (CsvRow row in greenDropShipAllProductFile.Rows)
                {
                    IList <String> updatedCategories = CsvRow.UpdateCategories(row.Collection);
                    String updatedCollection         = CsvRow.GetUpdatedCollection(updatedCategories);
                    row.UpdateCollection(updatedCollection);

                    if (uniqueCollections.ContainsKey(row.Collection) == false)
                    {
                        uniqueCollections.Add(row.Collection, new List <CsvRow>()
                        {
                            row
                        });
                    }
                    else
                    {
                        uniqueCollections[row.Collection].Add(row);
                    }
                }
                #endregion

                #region Create the category / menu layout

                IDictionary <String, Category> categoryTree = new Dictionary <String, Category>();

                foreach (String collection in uniqueCollections.Keys)
                {
                    String[] categories      = collection.Split('>');
                    Category?currentCategory = null;
                    foreach (String category in categories)
                    {
                        if (currentCategory != null)
                        {
                            currentCategory = currentCategory.AddChild(category);
                        }
                        else
                        {
                            if (categoryTree.ContainsKey(category.Trim()) == false)
                            {
                                currentCategory = new Category(category.Trim());
                                categoryTree.Add(currentCategory.Name, currentCategory);
                            }
                            else
                            {
                                currentCategory = categoryTree[category.Trim()];
                            }
                        }
                    }
                }

                using (StreamWriter sw = new StreamWriter("Use\\MenuLayout.txt"))
                {
                    StringBuilder menu = new StringBuilder();

                    foreach (String key in categoryTree.Keys)
                    {
                        Category c = categoryTree[key];

                        c.Print(menu, 0);
                    }
                    sw.Write(menu);
                }
                #endregion

                #region Create list of row updaters
                IList <IRowUpdater> rowUpdaters =
                    new List <IRowUpdater>()
                {
                    new CreateTags(UserDefinedTags),
                    new ProductTitleRowUpdater(),
                    new GTINRowUpdater(),
                    pricingAdjustmentFilter,
                    weightAdjustmentFilter
                };
                #endregion

                #region Save the files by category using the category name

                foreach (String collection in uniqueCollections.Keys)
                {
                    IList <CsvRow> rows = uniqueCollections[collection];
                    if (rows.Count > 0)
                    {
                        var invalidChars           = System.IO.Path.GetInvalidFileNameChars();
                        string invalidCharsRemoved = new string(collection
                                                                .Where(x => !invalidChars.Contains(x))
                                                                .ToArray());

                        CsvFile.Save(greenDropShipAllProductFile.ColumnHeaders, rows, "Use\\" + invalidCharsRemoved + ".csv", new List <IFilter>()
                        {
                            inventoryFilter, freeShippingFilter
                        }, rowUpdaters);
                    }
                }

                #endregion

                #region Save the rows in one file rather than multiple ones split by category

                List <CsvRow> allRows = new List <CsvRow>();
                foreach (String collection in uniqueCollections.Keys)
                {
                    allRows.AddRange(uniqueCollections[collection]);
                }
                CsvFile.Save(greenDropShipAllProductFile.ColumnHeaders, allRows, "Use\\allrecords.csv", new List <IFilter>()
                {
                    inventoryFilter, freeShippingFilter
                }, rowUpdaters);

                #endregion

                #region Save the rows to a file that contain errors. ie. we couldn't successfully parse them.

                GreenDropShipProductFile.Save(greenDropShipAllProductFile.ColumnHeaders, greenDropShipAllProductFile.Rows.Where(r => r.InvalidRow == true).ToList(), "InvalidRows.csv");

                #endregion

                #region Save the folder to the configuration file
                ConfigurationHelper.SetAppSetting("Folder", folder);
                #endregion

                MessageBox.Show("The files were created successfully!");
            }
                );
        }