Esempio n. 1
0
        protected void Button6_Click(object sender, EventArgs e)
        {
            Product  prod      = ControllerManager.Product.GetProductInfo("59539502");
            DateTime endDate   = Config.CurrentDate;
            DateTime startDate = Config.CurrentDate.AddDays(-7);

            IList <PartnerNet.Domain.TransactionHistoryWeekly> translist = new List <PartnerNet.Domain.TransactionHistoryWeekly>();

            //aca va un for por cada producto de la lista de productos
            {
                PartnerNet.Domain.TransactionHistoryWeekly transax = new TransactionHistoryWeekly();

                IList <Transactions>  trans = ControllerManager.Transactions.GetTransaction(startDate, endDate, prod);
                IList <PurchaseOrder> pol   = ControllerManager.PurchaseOrder.FilterByWeek(startDate, endDate);

                int purchases      = 0;
                int sales          = 0;
                int purchaseorders = 0;
                int stock          = 0;

                stock = prod.StockQ;

                foreach (Transactions transaction in trans)
                {
                    if (transaction.Quantity > 0)
                    {
                        purchases = purchases + transaction.Quantity;
                    }
                    else if (transaction.Quantity < 0)
                    {
                        sales = sales + (-transaction.Quantity);
                    }
                }
                foreach (PurchaseOrder po in pol)
                {
                    PurchaseOrderItem poi = ControllerManager.PurchaseOrderItem.GetPurchaseOrderInfo(prod, po);
                    if (poi != null)
                    {
                        purchaseorders = purchaseorders + poi.Quantity;
                    }
                }

                transax.ProductID      = PartnerNet.Business.ControllerManager.Product.GetProductInfo(prod.Id);
                transax.Purchase       = purchases;
                transax.Sale           = sales;
                transax.PurchaseOrders = purchaseorders;
                transax.Stock          = stock;
                transax.Year           = Config.CurrentDate.Year;
                transax.Week           = Config.CurrentWeek;
                //borrar esta propiedad!!!
                transax.ProductCode = prod.Id;

                translist.Add(transax);
            }

            GridView1.DataSource = translist;
            GridView1.DataBind();
        }
Esempio n. 2
0
        public override bool Equals(object obj)
        {
            PurchaseOrderItem item = (PurchaseOrderItem)obj;

            return(item.PurchaseOrder.Id == this.PurchaseOrder.Id);
        }
Esempio n. 3
0
        public bool Execute(out string errors)
        {
            errors = "";

            try
            {
                #region Check if needs to be executed

                if (Config.CurrentDate.DayOfWeek ==
                    (DayOfWeek)Convert.ToInt32(ConfigurationManager.AppSettings["ExecuteDayOfWeek"]) &&
                    DateTime.Now.Hour >= Convert.ToInt32(ConfigurationManager.AppSettings["ExecuteHour"]))
                {
                    //Review if the forecast is executing in the log
                    //If not start the process, otherwise returns true with no errors.
                    if (ControllerManager.Log.IsExecuting(Name, ExecutionStatus.Start))
                    {
                        return(true);
                    }
                    else
                    {
                        ControllerManager.Log.Add(Name, ExecutionStatus.Start, string.Empty);
                    }
                }
                else
                {
                    return(true);
                }

                #endregion



                DateTime endDate   = Config.CurrentDate;
                DateTime startDate = endDate.AddDays(-7);

                #region Provider Refresh
                IList <Grundfos.ScalaConnector.Provider> proveedoresScala = Grundfos.ScalaConnector.ControllerManager.Provider.GetProviderList();
                List <PartnerNet.Domain.Provider>        proveedores      = ControllerManager.Provider.GetFullProviderList();
                try
                {
                    foreach (Grundfos.ScalaConnector.Provider provider in proveedoresScala)
                    {
                        bool updated = false;
                        PartnerNet.Domain.Provider prov = null;
                        prov = proveedores.Find(delegate(PartnerNet.Domain.Provider record)
                        {
                            if (record.ProviderCode != provider.Id)
                            {
                                return(false);
                            }
                            return(true);
                        });

                        if (prov != null)
                        {
                            prov.Name        = provider.Name;
                            prov.CountryCode = provider.CountryCode;
                            updated          = true;
                        }

                        if (updated == false)
                        {
                            PartnerNet.Domain.Provider nuevo = new PartnerNet.Domain.Provider();
                            nuevo.Name         = provider.Name;
                            nuevo.ProviderCode = provider.Id;
                            //cambiar y resubir
                            nuevo.CountryCode = provider.CountryCode;
                            ControllerManager.Provider.SaveOrUpdate(nuevo);
                            updated = true;
                        }
                    }
                    ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Provider refresh successfully");
                }
                catch (Exception ex)
                {
                    errors = ex.ToString();

                    try
                    {
                        string process = "Provider Refresh";
                        ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                        SendErrorEmail(process, errors);
                    }
                    catch
                    {
                    }

                    return(false);
                }
                #endregion

                #region Product Refresh
                IList <Grundfos.ScalaConnector.Product> productosScala = Grundfos.ScalaConnector.ControllerManager.Product.GetProductList();
                List <PartnerNet.Domain.Product>        productos      = ControllerManager.Product.GetFullProductList();
                try
                {
                    foreach (Grundfos.ScalaConnector.Product product in productosScala)
                    {
                        PartnerNet.Domain.Product producto = productos.Find(delegate(PartnerNet.Domain.Product record)
                        {
                            if (record.ProductCode != product.Id)
                            {
                                return(false);
                            }
                            return(true);
                        });

                        if (producto == null)
                        {
                            producto             = new PartnerNet.Domain.Product();
                            producto.ProductCode = product.Id;
                            producto.Safety      = 6;
                        }

                        producto.Description = product.Description;
                        producto.Group       = product.Group;
                        producto.LeadTime    = product.Detail[0].Leadtime;
                        producto.CountryCode = product.CountryCode;
                        if (producto.RepositionLevel != product.Detail[0].RepPoint)
                        {
                            producto.RepositionLevel = product.Detail[0].RepPoint;
                            //ProductRepositionLevelHistory prlh = new ProductRepositionLevelHistory();
                            //prlh.Product = producto;
                            //prlh.RepositionLevel = producto.RepositionLevel;
                            //ControllerManager.Product.GenericSave(prlh);
                        }
                        producto.RepositionPoint    = product.Detail[0].PurchaseMod;
                        producto.AlternativeProduct = product.AlternativeProduct;
                        producto.AlternativeDate    = product.AlternativeDate;
                        PartnerNet.Domain.Provider provtemp = proveedores.Find(delegate(PartnerNet.Domain.Provider record)
                        {
                            if (record.ProviderCode != product.Provider.Id)
                            {
                                return(false);
                            }
                            return(true);
                        });
                        if (provtemp != null)
                        {
                            producto.Provider = provtemp;
                        }
                        else if (provtemp == null)
                        {
                            producto.Provider = proveedores.Find(delegate(PartnerNet.Domain.Provider record)
                            {
                                if (record.ProviderCode != "999999")
                                {
                                    return(false);
                                }
                                return(true);
                            });
                        }
                        foreach (ProductDetail productDetail in product.Detail)
                        {
                            if (productDetail.RepPoint == 0)
                            {
                                producto.ScalaRep0 = true;
                            }
                        }

                        ControllerManager.Product.Save(producto);
                    }
                    ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Product refresh successfully");
                }
                catch (Exception ex)
                {
                    errors = ex.ToString();

                    try
                    {
                        string process = "Product Refresh";
                        ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                        SendErrorEmail(process, errors);
                    }
                    catch
                    {
                    }

                    return(false);
                }
                #endregion

                #region Generate History

                #region Limpieza de datos procesador de esta semana (si los hubiera)

                ControllerManager.TransactionHistoryWeekly.CleanData(Config.CurrentWeek, Config.CurrentDate.Year);

                #endregion

                IList <Product> prodlist = Grundfos.ScalaConnector.ControllerManager.Product.GetProductList();
                List <PartnerNet.Domain.Product> productlist = ControllerManager.Product.GetProductListAlt();
                try
                {
                    List <Transactions>      transcomp = Grundfos.ScalaConnector.ControllerManager.Transactions.GetTransaction(startDate, endDate, 0);
                    List <Transactions>      transvent = Grundfos.ScalaConnector.ControllerManager.Transactions.GetTransaction(startDate, endDate, 1);
                    List <PurchaseOrderItem> poil      = Grundfos.ScalaConnector.ControllerManager.PurchaseOrderItem.GetWeeklyTransaction(startDate, endDate);

                    foreach (Product prod in prodlist)
                    {
                        PartnerNet.Domain.Product producto = null;
                        producto = productlist.Find(delegate(PartnerNet.Domain.Product record)
                        {
                            if (record.ProductCode != prod.Id)
                            {
                                return(false);
                            }
                            return(true);
                        });

                        if (producto != null)
                        {
                            #region Generate TransactionHistoryWeekly

                            TransactionHistoryWeekly transax = new TransactionHistoryWeekly();

                            int stock          = 0;
                            int purchases      = 0;
                            int sales          = 0;
                            int purchaseorders = 0;

                            stock = prod.StockQ;

                            Transactions subList = null;

                            subList = transcomp.Find(delegate(Transactions record)
                            {
                                if (record.Product != prod)
                                {
                                    return(false);
                                }
                                return(true);
                            });

                            if (subList != null)
                            {
                                purchases = subList.Quantity;
                            }

                            subList = transvent.Find(delegate(Transactions record)
                            {
                                if (record.Product != prod)
                                {
                                    return(false);
                                }
                                return(true);
                            });
                            if (subList != null)
                            {
                                sales = -subList.Quantity;
                            }

                            PurchaseOrderItem subList2 = null;
                            subList2 = poil.Find(delegate(PurchaseOrderItem record)
                            {
                                if (record.Product != prod)
                                {
                                    return(false);
                                }
                                return(true);
                            });

                            if (subList2 != null)
                            {
                                purchaseorders = subList2.QuantityOrdered;
                            }


                            transax.ProductID      = producto;
                            transax.Purchase       = purchases;
                            transax.Sale           = sales;
                            transax.PurchaseOrders = purchaseorders;
                            transax.Stock          = stock;
                            transax.Year           = endDate.Year;
                            transax.Week           =
                                Thread.CurrentThread.CurrentCulture.Calendar.GetWeekOfYear(endDate,
                                                                                           CalendarWeekRule.
                                                                                           FirstFourDayWeek,
                                                                                           DayOfWeek.Sunday);
                            transax.ProductCode = prod.Id;

                            ControllerManager.TransactionHistoryWeekly.Save(transax);

                            #endregion
                        }
                    }

                    ControllerManager.TransactionHistoryWeekly.Copy();

                    ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Weekly history created successfully");
                }
                catch (Exception ex)
                {
                    errors = ex.ToString();

                    try
                    {
                        string process = "Weekly History";
                        ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                        SendErrorEmail(process, errors);
                    }
                    catch
                    {
                    }

                    return(false);
                }
                #endregion

                #region Generate Weekly Statitics
                try
                {
                    ControllerManager.TransactionHistoryWeekly.CalculateFullStatistic(Config.CurrentWeek,
                                                                                      Config.CurrentDate.Year);

                    ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Weekly statistics created successfully");
                }
                catch (Exception ex)
                {
                    errors = ex.ToString();

                    try
                    {
                        string process = "Weekly Statistics";
                        ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                        SendErrorEmail(process, errors);
                    }
                    catch
                    {
                    }

                    return(false);
                }
                #endregion

                if (Config.CurrentDate.Day <= 7)
                {
                    #region Limpieza de datos procesador de este mes (si los hubiera)

                    ControllerManager.TransactionHistoryMonthly.CleanData(Config.CurrentDate.Month, Config.CurrentDate.Year);

                    #endregion

                    #region Generate Monthly History
                    try
                    {
                        DateTime endDateM   = GetLastDayOfMonth(Config.CurrentDate.AddMonths(-1));
                        DateTime startDateM = GetFirstDayOfMonth(Config.CurrentDate.AddMonths(-1));

                        List <Transactions>      transcompm = Grundfos.ScalaConnector.ControllerManager.Transactions.GetTransaction(startDateM, endDateM, 0);
                        List <Transactions>      transventm = Grundfos.ScalaConnector.ControllerManager.Transactions.GetTransaction(startDateM, endDateM, 1);
                        List <PurchaseOrderItem> poilm      = Grundfos.ScalaConnector.ControllerManager.PurchaseOrderItem.GetWeeklyTransaction(startDateM, endDateM);

                        foreach (Product prod in prodlist)
                        {
                            PartnerNet.Domain.Product producto = null;
                            producto = productlist.Find(delegate(PartnerNet.Domain.Product record)
                            {
                                if (record.ProductCode != prod.Id)
                                {
                                    return(false);
                                }
                                return(true);
                            });

                            if (producto != null)
                            {
                                #region Generate TransactionHistoryMonthly

                                TransactionHistoryMonthly transax = new TransactionHistoryMonthly();

                                int stock          = 0;
                                int purchases      = 0;
                                int sales          = 0;
                                int purchaseorders = 0;

                                stock = prod.StockQ;

                                Transactions subList = null;

                                subList = transcompm.Find(delegate(Transactions record)
                                {
                                    if (record.Product != prod)
                                    {
                                        return(false);
                                    }
                                    return(true);
                                });

                                if (subList != null)
                                {
                                    purchases = subList.Quantity;
                                }

                                subList = transventm.Find(delegate(Transactions record)
                                {
                                    if (record.Product != prod)
                                    {
                                        return(false);
                                    }
                                    return(true);
                                });
                                if (subList != null)
                                {
                                    sales = -subList.Quantity;
                                }

                                PurchaseOrderItem subList2 = null;
                                subList2 = poilm.Find(delegate(PurchaseOrderItem record)
                                {
                                    if (record.Product != prod)
                                    {
                                        return(false);
                                    }
                                    return(true);
                                });

                                if (subList2 != null)
                                {
                                    purchaseorders = subList2.QuantityOrdered;
                                }


                                transax.ProductID      = producto;
                                transax.Purchase       = purchases;
                                transax.Sale           = sales;
                                transax.PurchaseOrders = purchaseorders;
                                transax.Stock          = stock;
                                transax.Year           = endDateM.Year;
                                transax.Month          =
                                    Thread.CurrentThread.CurrentCulture.Calendar.GetMonth(endDateM);
                                transax.ProductCode = prod.Id;

                                ControllerManager.TransactionHistoryMonthly.Save(transax);

                                #endregion
                            }
                        }

                        ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Montly history created successfully");
                    }
                    catch (Exception ex)
                    {
                        errors = ex.ToString();

                        try
                        {
                            string process = "Monthly History";
                            ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                            SendErrorEmail(process, errors);
                        }
                        catch
                        {
                        }

                        return(false);
                    }

                    #endregion

                    #region Generate Monthly Statitics

                    //try
                    //{
                    //    ControllerManager.TransactionHistoryMonthly.CalculateFullStatistic(Config.CurrentDate.Month - 1, Config.CurrentDate.Year);

                    //    ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Monthly statistics created successfully");
                    //}
                    //catch (Exception ex)
                    //{
                    //    errors = ex.ToString();

                    //    try
                    //    {
                    //        string process = "Monthly Statistics";
                    //        ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                    //        SendErrorEmail(process, errors);
                    //    }
                    //    catch
                    //    {
                    //    }

                    //    return false;
                    //}

                    #endregion
                }


                #region Generate Forecast

                try
                {
                    IList <PartnerNet.Domain.Product> tempprodlist = new List <PartnerNet.Domain.Product>();
                    ControllerManager.Forecast.CalculateFullForecast(Config.CurrentWeek, Config.CurrentDate.Year, tempprodlist, true);

                    ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Forecast created successfully");
                }
                catch (Exception ex)
                {
                    errors = ex.ToString();

                    try
                    {
                        string process = "Forecast";
                        ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                        SendErrorEmail(process, errors);
                    }
                    catch
                    {
                    }

                    return(false);
                }
                #endregion

                #region Generate Purchase Orders

                #region Limpieza de datos procesador de esta semana (si los hubiera)

                ControllerManager.PurchaseOrder.CleanData(Config.CurrentDate);

                #endregion

                try
                {
                    ControllerManager.PurchaseOrder.GenerateFullPO(Config.CurrentWeek, Config.CurrentDate.Year, PurchaseOrderType.Forecast);

                    ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Purchase orders created successfully");
                }
                catch (Exception ex)
                {
                    errors = ex.ToString();

                    try
                    {
                        string process = "Purchase Orders";
                        ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                        SendErrorEmail(process, errors);
                    }
                    catch
                    {
                    }

                    return(false);
                }
                #endregion

                #region Proceso de Forecast a Productos Faltantes
                //List<string> prodlistfalt = PartnerNet.Business.ControllerManager.Product.GetLeftProductList();
                //List<PartnerNet.Domain.Product> prodlisttemp = PartnerNet.Business.ControllerManager.Product.GetFullProductList();
                //List<string> leftproducts = new List<string>();

                //foreach (PartnerNet.Domain.Product product in prodlisttemp)
                //{
                //    string temp = prodlistfalt.Find(delegate(string record)
                //                                                          {
                //                                                              if (record == product.ProductCode)
                //                                                              {
                //                                                                  return true;
                //                                                              }
                //                                                              return false;
                //                                                          });

                //    if (temp == null)
                //    {
                //        leftproducts.Add(product.ProductCode);
                //    }
                //}



                //foreach (string product in leftproducts)
                //{
                //    PartnerNet.Domain.Product producto = PartnerNet.Business.ControllerManager.Product.GetProductInfo(product);
                //    PartnerNet.Business.ControllerManager.Forecast.CalculateIndividualForecast(Config.CurrentWeek, Config.CurrentDate.Year, producto);
                //}
                #endregion

                ControllerManager.Log.Add(Name, ExecutionStatus.Finished, "Process finished successfully");
            }
            catch (Exception ex)
            {
                errors = ex.ToString();

                try
                {
                    string process = "Proceso de Forecast";
                    ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                    SendErrorEmail(process, errors);
                }
                catch
                {
                }

                return(false);
            }

            return(true);
        }
Esempio n. 4
0
        public bool Execute(out string errors)
        {
            errors = "";

            try
            {
                #region Check if needs to be executed

                if (DateTime.Now.Hour >= Convert.ToInt32(ConfigurationManager.AppSettings["ExecuteHourAlerts"]))
                {
                    // Review if the forecast is executing in the log
                    // If not start the process, otherwise returns true with no errors.
                    if (ControllerManager.Log.IsExecuting(Name, ExecutionStatus.Start))
                    {
                        return(true);
                    }
                    else
                    {
                        ControllerManager.Log.Add(Name, ExecutionStatus.Start, string.Empty);
                    }
                }
                else
                {
                    return(true);
                }

                #endregion

                //------------------------------------------------------------------------------------------------------------------
                List <PartnerNet.Domain.Product> products = ControllerManager.Product.GetAll() as List <PartnerNet.Domain.Product>;
                List <PurchaseOrderItem>         purchaseOrderItemList = Grundfos.ScalaConnector.ControllerManager.PurchaseOrderItem.GetAlerts();

                # region Alerta de Ordenes de Compras Confirmadas y no Despachadas
                try
                {
                    List <StockMovementPending> stockMovementPendings = Grundfos.ScalaConnector.ControllerManager.StockMovementPending.GetPurchaseOrders() as List <StockMovementPending>;
                    List <PurchaseOrder>        purchaseOrderList     = Grundfos.ScalaConnector.ControllerManager.PurchaseOrder.GetAll() as List <PurchaseOrder>;

                    ControllerManager.AlertPurchaseOrder.CleanAlertPurchaseOrder();

                    foreach (StockMovementPending item in stockMovementPendings)
                    {
                        PurchaseOrder po = purchaseOrderList.Find(delegate(PurchaseOrder record)
                        {
                            if (record.Id == item.OrderNumber)
                            {
                                return(true);
                            }
                            return(false);
                        });
                        PurchaseOrderItem poi = purchaseOrderItemList.Find(delegate(PurchaseOrderItem record)
                        {
                            if ((record.Product.Id == item.ProductCode) && (record.PurchaseOrder.Id == item.OrderNumber))
                            {
                                return(true);
                            }
                            return(false);
                        });
                        AlertPurchaseOrder alert = new AlertPurchaseOrder();

                        alert.Destination       = AlertPurchaseOrderDestination.Stock;
                        alert.PurchaseOrderCode = item.OrderNumber;
                        alert.Product           = products.Find(delegate(PartnerNet.Domain.Product record)
                        {
                            if (record.ProductCode == item.ProductCode)
                            {
                                return(true);
                            }
                            return(false);
                        });
                        alert.Quantity = item.Quantity;
                        alert.Type     = AlertPurchaseOrderType.NoConfirmada;
                        if (poi.Confirmed == "1")
                        {
                            alert.Type = AlertPurchaseOrderType.Confirmada;
                        }
                        alert.GAP           = (item.DeliveryCommitt - po.Date).Days;
                        alert.WayOfDelivery = (WayOfDelivery)po.WayOfDelivery;
                        alert.ArrivalDate   = item.DeliveryCommitt;
                        if (item.CustSupCode == null)
                        {
                            alert.PurchaseOrderProviderCode = ControllerManager.Provider.GetProvider("999999").ProviderCode;
                        }
                        else if (!string.IsNullOrEmpty(item.CustSupCode.Trim()))
                        {
                            alert.PurchaseOrderProviderCode = item.CustSupCode;
                        }
                        else
                        {
                            alert.PurchaseOrderProviderCode = string.Empty;
                        }

                        alert.PurchaseOrderDate = po.Date;

                        if (item.CustSupName.EndsWith("#"))
                        {
                            alert.Type = AlertPurchaseOrderType.Transito;
                        }

                        if (alert.Product == null)
                        {
                            continue;
                        }

                        AlertOCGapAverage += alert.GAP;
                        AlertOCGapCount++;

                        ControllerManager.AlertPurchaseOrder.Save(alert);
                    }
                    ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Alerta de Ordenes de Compras Confirmadas y no Despachadas: Completadas");
                }
                catch (Exception ex)
                {
                    errors = ex.ToString();

                    try
                    {
                        string process = "Alerta de Ordenes de Compras Confirmadas y no Despachadas";
                        ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                        SendErrorEmail(process, errors);
                    }
                    catch
                    {
                    }

                    return(false);
                }

                #endregion

                #region Alerta de Ordenes de Compras No Confirmadas
                //Se reemplazo y unio todo con la alerta 1

                #endregion

                #region Alerta de Stock Negativos
                try
                {
                    List <ProductDetail> productDetails = Grundfos.ScalaConnector.ControllerManager.ProductDetail.GetAlert3();

                    ControllerManager.AlertProduct.CleanAlertProduct();

                    foreach (ProductDetail productDetail in productDetails)
                    {
                        AlertProduct alert = new AlertProduct();
                        alert.StandardCost = productDetail.Product.StandardCost;
                        alert.SubTotal     = productDetail.Product.StandardCost * Convert.ToDouble(productDetail.Stock);
                        alert.Quantity     = productDetail.Stock;
                        alert.Type         = 1;
                        alert.NegativeDate = DateTime.Today;
                        alert.Location     = productDetail.Location;
                        alert.Product      = products.Find(delegate(PartnerNet.Domain.Product record)
                        {
                            if (record.ProductCode == productDetail.Product.Id)
                            {
                                return(true);
                            }
                            return(false);
                        });

                        ControllerManager.AlertProduct.Save(alert);
                    }

                    ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Alertas de Stock Negativo: Completadas");
                }
                catch (Exception ex)
                {
                    errors = ex.ToString();

                    try
                    {
                        string process = "Alertas de Stock Negativo";
                        ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                        SendErrorEmail(process, errors);
                    }
                    catch
                    {
                    }
                    return(false);
                }

                #endregion

                #region Alerta de Ventas no Cumplimentadas
                try
                {
                    List <SaleOrderItem> saleorderitems = Grundfos.ScalaConnector.ControllerManager.SaleOrderItem.PendingSaleOrder(Config.CurrentDate.AddDays(-44));

                    List <PurchaseOrderItem> POListAlert3 = purchaseOrderItemList.FindAll(delegate(PurchaseOrderItem record)
                    {
                        if ((record.Confirmed == "1") &&
                            (record.PurchaseOrder.Location ==
                             "01") &&
                            (record.PurchaseOrder.Id.
                             StartsWith("00000")))
                        {
                            return(true);
                        }
                        return(false);
                    });

                    ControllerManager.AlertSaleOrder.CleanAlertSaleOrder();

                    List <Product> scalaProducts = new List <Product>();
                    foreach (SaleOrderItem saleOrderItem in saleorderitems)
                    {
                        CreateAlert(products, saleOrderItem, POListAlert3, scalaProducts);
                    }
                    ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Alertas de Ventas no Cumplimentadas: Completadas");
                }
                catch (Exception ex)
                {
                    errors = ex.ToString();

                    try
                    {
                        string process = "Alertas de Ventas no Cumplimentadas";
                        ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                        SendErrorEmail(process, errors);
                    }
                    catch
                    {
                    }

                    return(false);
                }

                #endregion

                #region Alerta de Stock Futuro Menor al Safety
                //PENDIENTE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                //try
                //{
                //    List<PartnerNet.Domain.Product> ProdList = ControllerManager.Product.GetAlertNegativeFutureStock();
                //    PartnerNet.Domain.Product prodtemp = null;

                //    foreach (PartnerNet.Domain.Product product in ProdList)
                //    {
                //        if (prodtemp != product)
                //        {
                //            AlertProduct alert = new AlertProduct();
                //            alert.StandardCost = 0;
                //            alert.SubTotal = 0;
                //            alert.Quantity = product.Forecasts[0].FinalStock;
                //            DateTime fechatemp = Convert.ToDateTime("01/01/" + Config.CurrentDate.Year.ToString());
                //            fechatemp = Thread.CurrentThread.CurrentCulture.Calendar.AddWeeks(fechatemp, product.Forecasts[0].Week);
                //            alert.NegativeDate = fechatemp.AddDays(-7 + (int)fechatemp.DayOfWeek);
                //            alert.Type = 2;
                //            alert.Product = product;

                //            ControllerManager.AlertProduct.Save(alert);

                //            prodtemp = product;
                //        }
                //    }
                //    ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Stock Futuro Menor al Safety: Completadas");
                //}
                //catch (Exception ex)
                //{
                //    errors = ex.ToString();

                //    try
                //    {
                //        string process = "Stock Futuro Menor al Safety";
                //        ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                //        SendErrorEmail(process, errors);
                //    }
                //    catch
                //    {
                //    }

                //    return false;
                //}

                //PENDIENTE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                #endregion

                #region Alerta de Nivel de Reposición
                try
                {
                    List <AlertReposition> lstrepotmp = ControllerManager.TransactionHistoryWeekly.GetAlert6(Config.CurrentWeek, Config.CurrentDate.Year) as List <AlertReposition>;
                    ControllerManager.AlertReposition.CleanAlertReposition();

                    List <AlertReposition> aRLst = lstrepotmp.FindAll(delegate(AlertReposition record)
                    {
                        if (record.Product.AlternativeProduct == " " &&
                            record.Product.AlternativeDate == new DateTime(9999, 12, 31)

                            )
                        {
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    });

                    List <AlertReposition> aRLst2 = lstrepotmp.FindAll(delegate(AlertReposition record)
                    {
                        if (record.Product.AlternativeProduct != " " &&
                            record.Product.AlternativeDate != new DateTime(9999, 12, 31)
                            )
                        {
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    });

                    List <string> alternativeProducts = new List <string>();
                    foreach (AlertReposition alertReposition in aRLst2)
                    {
                        alternativeProducts.Add(alertReposition.Product.AlternativeProduct);
                    }

                    List <AlertReposition> lstprodalt = ControllerManager.TransactionHistoryWeekly.GetAlert6(Config.CurrentWeek, Config.CurrentDate.Year, alternativeProducts) as List <AlertReposition>;

                    List <AlertReposition> aRLst3 = lstprodalt.FindAll(delegate(AlertReposition record)
                    {
                        if (record.Product.AlternativeProduct == " " &&
                            record.Product.AlternativeDate == new DateTime(9999, 12, 31)

                            )
                        {
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    });

                    List <SaleOrderItem> soFullLst = Grundfos.ScalaConnector.ControllerManager.SaleOrderItem.SaleOrdersByProduct();
                    foreach (AlertReposition ar in aRLst)
                    {
                        List <SaleOrderItem> soLst = soFullLst.FindAll(delegate(SaleOrderItem record)
                        {
                            if (record.Product.Id == ar.Product.ProductCode)
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        });

                        double maximumQuantity  = 0;
                        double total            = 0;
                        bool   haveParts        = false;
                        string maximumOrderCode = "Sin Orden";
                        foreach (SaleOrderItem sOI in soLst)
                        {
                            if (sOI.Quantity > maximumQuantity)
                            {
                                maximumQuantity  = sOI.Quantity;
                                maximumOrderCode = sOI.SaleOrderId;
                            }
                            total = total + sOI.Quantity;

                            if (sOI.Product.Parts.Count > 0 && sOI.Product.Parts[0].Type == "B")
                            {
                                haveParts = true;
                                break;
                            }
                        }
                        if (!haveParts)
                        {
                            if (((maximumQuantity * total) / 100) > 40)
                            {
                                ar.IsConflicted = true;
                            }
                            else
                            {
                                ar.IsConflicted = false;
                            }

                            ar.OrderInfo = soLst.Count + "/" + ((maximumQuantity * total) / 100) + "/" + maximumOrderCode;

                            GetAlertRepositionResult(ar, null);

                            if (!aRLst3.Exists(delegate(AlertReposition record)
                            {
                                if (record.ProductCode == ar.ProductCode)
                                {
                                    return(true);
                                }
                                else
                                {
                                    return(false);
                                }
                            }))
                            {
                                ControllerManager.AlertReposition.Save(ar);
                            }
                        }
                    }

                    foreach (AlertReposition ar in aRLst3)
                    {
                        AlertReposition pastproduct = aRLst2.Find(delegate(AlertReposition record)
                        {
                            if (record.Product.AlternativeProduct == ar.Product.ProductCode)
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        });

                        List <SaleOrderItem> soLst = soFullLst.FindAll(delegate(SaleOrderItem record)
                        {
                            if (record.Product.Id == ar.Product.ProductCode)
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        });


                        List <SaleOrderItem> soLstAlt = soFullLst.FindAll(delegate(SaleOrderItem record)
                        {
                            if (record.Product.Id == pastproduct.Product.ProductCode)
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        });

                        ar.Sales += pastproduct.Sales;

                        GetAlertRepositionResult(ar, pastproduct);

                        double maximumQuantity  = 0;
                        double total            = 0;
                        bool   haveParts        = false;
                        string maximumOrderCode = "Sin Orden";
                        foreach (SaleOrderItem sOI in soLst)
                        {
                            if (sOI.Quantity > maximumQuantity)
                            {
                                maximumQuantity  = sOI.Quantity;
                                maximumOrderCode = sOI.SaleOrderId;
                            }
                            total = total + sOI.Quantity;

                            if (sOI.Product.Parts.Count > 0 && sOI.Product.Parts[0].Type == "B")
                            {
                                haveParts = true;
                                break;
                            }
                        }
                        foreach (SaleOrderItem sOI in soLstAlt)
                        {
                            if (sOI.Quantity > maximumQuantity)
                            {
                                maximumQuantity  = sOI.Quantity;
                                maximumOrderCode = sOI.SaleOrderId;
                            }
                            total = total + sOI.Quantity;

                            if (sOI.Product.Parts.Count > 0 && sOI.Product.Parts[0].Type == "B")
                            {
                                haveParts = true;
                                break;
                            }
                        }
                        if (!haveParts)
                        {
                            if (((maximumQuantity * total) / 100) > 40)
                            {
                                ar.IsConflicted = true;
                            }
                            else
                            {
                                ar.IsConflicted = false;
                            }

                            ar.OrderInfo = soLst.Count + "/" + ((maximumQuantity * total) / 100) + "/" + maximumOrderCode;

                            ControllerManager.AlertReposition.Save(ar);
                        }
                    }
                    ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Alertas de Nivel de Reposición: Completadas");
                }
                catch (Exception ex)
                {
                    errors = ex.ToString();

                    try
                    {
                        string process = "Alertas de Nivel de Reposición";
                        ControllerManager.Log.Add(Name, ExecutionStatus.Running, process + ": " + errors);
                        SendErrorEmail(process, errors);
                    }
                    catch
                    {
                    }

                    return(false);
                }

                #endregion

                #region Obtener Totales

                AlertTotal alerttotal;

                for (int i = 1; i <= 6; i++)
                {
                    alerttotal = ControllerManager.AlertTotal.GetAlertTotal(i);

                    switch (i)
                    {
                    case 1:
                        alerttotal.Total = AlertOCGapAverage / AlertOCGapCount;
                        if (alerttotal.Total < 0)
                        {
                            alerttotal.Total = -alerttotal.Total;
                        }
                        break;

                    case 2:
                        alerttotal.Total = AlertOCGapAverage / AlertOCGapCount;
                        if (alerttotal.Total < 0)
                        {
                            alerttotal.Total = -alerttotal.Total;
                        }
                        break;

                    case 3:
                        alerttotal.Total = ControllerManager.TransactionHistoryWeekly.GetActiveProducts(Config.CurrentWeek, Config.CurrentDate.Year);
                        break;

                    case 4:
                        alerttotal.Total = AlertOVGapAverage / AlertOVGapCount;
                        if (alerttotal.Total < 0)
                        {
                            alerttotal.Total = -alerttotal.Total;
                        }
                        break;

                    case 5:
                        alerttotal.Total = ControllerManager.TransactionHistoryWeekly.GetActiveProducts(Config.CurrentWeek, Config.CurrentDate.Year);
                        break;

                    case 6:
                        alerttotal.Total = ControllerManager.TransactionHistoryWeekly.GetActiveProducts(Config.CurrentWeek, Config.CurrentDate.Year);
                        break;
                    }
                }
                ControllerManager.Log.Add(Name, ExecutionStatus.Running, "Totales obtenidos para las alertas.");
                #endregion

                ControllerManager.Log.Add(Name, ExecutionStatus.Finished, "Alert process finished successfully");
            }