private void OperatorsContextMenuStripItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e == null)
            {
                return;
            }
            var filter = operatorsContextMenuStrip.Tag as FilterObject;

            if (filter == null)
            {
                return;
            }
            var item = e.ClickedItem;

            if (item == null)
            {
                return;
            }
            filter.Operator = PerformerCriteriaFunction.GetExpressionOperatorByString(item.Text);
            var rowIndex = fastGrid.rows.FindIndex(r => r.ValueObject == filter);

            fastGrid.UpdateRow(rowIndex, filter);
            fastGrid.InvalidateRow(rowIndex);
            UpdateExpression();
        }
Example #2
0
        public void TestPerformerCriteriaFunction()
        {
            PerformerCriteriaFunctionCollection.Instance.ResetCriterias();
            var defaultCrits = PerformerCriteriaFunctionCollection.Instance.criterias;

            Assert.IsNotEmpty(defaultCrits, "Есть критерии по-умолчанию");
            Assert.IsNotEmpty(PerformerCriteriaFunctionCollection.Instance.propertyByVariable,
                              "Заполнен словарь переменная - свойство");

            var critsToStore = defaultCrits.ToList();
            PerformerCriteriaFunction critA, critB, critC, critD;

            critsToStore.Add(critA = new PerformerCriteriaFunction
            {
                Function    = "1-(3+(5-(7+11)))",
                Description = "!"
            });
            critsToStore.Add(critB = new PerformerCriteriaFunction
            {
                Function    = "AYP-(DD^2+ML*2)",
                Description = "Некая сложная формула, в описании\r\nмного строк."
            });
            // эта не должна прочитаться
            critsToStore.Add(critC = new PerformerCriteriaFunction
            {
                Function    = "MVP-sin(DD/5)",
                Description = "Некая весьма сложная формула, в описании\r\nмного строк."
            });
            // эта тоже не должна прочитаться
            critsToStore.Add(critD = new PerformerCriteriaFunction
            {
                Function    = "AYP-)DD^2+ML*2)",
                Description = "!2"
            });
            PerformerCriteriaFunctionCollection.Instance.criterias        = critsToStore;
            PerformerCriteriaFunctionCollection.Instance.SelectedFunction = critA;
            PerformerCriteriaFunctionCollection.Instance.WriteToFile();
            PerformerCriteriaFunctionCollection.Instance.ReadFromFile();

            Assert.AreEqual(defaultCrits.Count + 2, PerformerCriteriaFunctionCollection.Instance.criterias.Count,
                            "Прочитано верное количество формул");
            var countDefault =
                PerformerCriteriaFunctionCollection.Instance.criterias.Count(c => defaultCrits.Any(d => d.AreEqual(c)));

            Assert.AreEqual(defaultCrits.Count, countDefault, "Критерии по-умолчанию прочитаны");

            Assert.AreEqual(1, PerformerCriteriaFunctionCollection.Instance.criterias.Count(c => c.AreEqual(critA)), "Функция А прочитана");
            Assert.AreEqual(1, PerformerCriteriaFunctionCollection.Instance.criterias.Count(c => c.AreEqual(critB)), "Функция B прочитана");
            Assert.IsFalse(PerformerCriteriaFunctionCollection.Instance.criterias.Any(c => c.AreEqual(critC)), "Функция C не прочитана");
            Assert.IsFalse(PerformerCriteriaFunctionCollection.Instance.criterias.Any(c => c.AreEqual(critD)), "Функция D не прочитана");

            Assert.IsTrue(PerformerCriteriaFunctionCollection.Instance.SelectedFunction.AreEqual(critA),
                          "Функция запомнена");
        }
Example #3
0
        public void TestPerformerCriteriaFunction()
        {
            PerformerCriteriaFunctionCollection.Instance.ResetCriterias();
            var defaultCrits = PerformerCriteriaFunctionCollection.Instance.criterias;
            Assert.IsNotEmpty(defaultCrits, "Есть критерии по-умолчанию");
            Assert.IsNotEmpty(PerformerCriteriaFunctionCollection.Instance.propertyByVariable,
                              "Заполнен словарь переменная - свойство");

            var critsToStore = defaultCrits.ToList();
            PerformerCriteriaFunction critA, critB, critC, critD;
            critsToStore.Add(critA = new PerformerCriteriaFunction
            {
                Function = "1-(3+(5-(7+11)))",
                Description = "!"
            });
            critsToStore.Add(critB = new PerformerCriteriaFunction
                {
                    Function = "AYP-(DD^2+ML*2)",
                    Description = "Некая сложная формула, в описании\r\nмного строк."
                });
            // эта не должна прочитаться
            critsToStore.Add(critC = new PerformerCriteriaFunction
            {
                Function = "MVP-sin(DD/5)",
                Description = "Некая весьма сложная формула, в описании\r\nмного строк."
            });
            // эта тоже не должна прочитаться
            critsToStore.Add(critD = new PerformerCriteriaFunction
            {
                Function = "AYP-)DD^2+ML*2)",
                Description = "!2"
            });
            PerformerCriteriaFunctionCollection.Instance.criterias = critsToStore;
            PerformerCriteriaFunctionCollection.Instance.SelectedFunction = critA;
            PerformerCriteriaFunctionCollection.Instance.WriteToFile();
            PerformerCriteriaFunctionCollection.Instance.ReadFromFile();

            Assert.AreEqual(defaultCrits.Count + 2, PerformerCriteriaFunctionCollection.Instance.criterias.Count,
                "Прочитано верное количество формул");
            var countDefault =
                PerformerCriteriaFunctionCollection.Instance.criterias.Count(c => defaultCrits.Any(d => d.AreEqual(c)));
            Assert.AreEqual(defaultCrits.Count, countDefault, "Критерии по-умолчанию прочитаны");

            Assert.AreEqual(1, PerformerCriteriaFunctionCollection.Instance.criterias.Count(c => c.AreEqual(critA)), "Функция А прочитана");
            Assert.AreEqual(1, PerformerCriteriaFunctionCollection.Instance.criterias.Count(c => c.AreEqual(critB)), "Функция B прочитана");
            Assert.IsFalse(PerformerCriteriaFunctionCollection.Instance.criterias.Any(c => c.AreEqual(critC)), "Функция C не прочитана");
            Assert.IsFalse(PerformerCriteriaFunctionCollection.Instance.criterias.Any(c => c.AreEqual(critD)), "Функция D не прочитана");

            Assert.IsTrue(PerformerCriteriaFunctionCollection.Instance.SelectedFunction.AreEqual(critA),
                "Функция запомнена");
        }
        // "save" button
        private void BtnAcceptClick(object sender, EventArgs e)
        {
            // добавить новый критерий или удалить существующий
            var formula = (cbFunction.Text ?? "").Trim();
            if (lastSelectedItem == null && string.IsNullOrEmpty(formula)) return;

            // удалить?
            if (string.IsNullOrEmpty(formula))
            {
                if (MessageBox.Show("Удалить формулу \"" + lastSelectedItem.Function + "\"?", "Подтверждение",
                                    MessageBoxButtons.YesNo) == DialogResult.No) return;
                PerformerCriteriaFunctionCollection.Instance.criterias.Remove(lastSelectedItem);
                PerformerCriteriaFunctionCollection.Instance.WriteToFile();
                FillFormulas();
                return;
            }

            // проверить значение
            string error;
            if (!ExpressionResolver.CheckFunction(formula, out error,
                PerformerCriteriaFunctionCollection.Instance.enabledParametersNames))
            {
                MessageBox.Show("Формула \"" + formula + "\" не распознана: " + error);
                return;
            }

            // переписать комментарий
            var existItem = PerformerCriteriaFunctionCollection.Instance.criterias.FirstOrDefault(
                c => c.FormulasEqual(formula));
            if (existItem != null)
            {
                existItem.MarginValue = cbMargin.Checked ? tbMarginValue.Text.ToFloatUniformSafe() : null;
                existItem.Description = tbComment.Text;
                PerformerCriteriaFunctionCollection.Instance.WriteToFile();
                return;
            }

            // добавить новое значение
            var newFunc = new PerformerCriteriaFunction
                {
                    Function = formula,
                    Description = tbComment.Text,
                    PreferredSortOrder = cbSortOrder.SelectedIndex == 0 ? SortOrder.Descending : SortOrder.Ascending,
                    MarginValue =
                        cbMargin.Checked ? tbMarginValue.Text.Trim().Replace(",", ".").ToFloatUniformSafe() : null
                };
            PerformerCriteriaFunctionCollection.Instance.criterias.Add(newFunc);
            PerformerCriteriaFunctionCollection.Instance.SelectedFunction = newFunc;
            PerformerCriteriaFunctionCollection.Instance.WriteToFile();
            FillFormulas();
        }
        private void CbFunctionSelectedIndexChanged(object sender, EventArgs e)
        {
            var item = cbFunction.SelectedItem;

            if (item == null)
            {
                return;
            }
            var crit = (PerformerCriteriaFunction)item;

            lastSelectedItem      = crit;
            tbComment.Text        = crit.Description;
            cbMargin.Checked      = crit.MarginValue.HasValue;
            tbMarginValue.Enabled = crit.MarginValue.HasValue;
            tbMarginValue.Text    = crit.MarginValue.HasValue ? crit.MarginValue.Value.ToString("f2") : "0.00";
        }
        private void FastGridUserHitCell(object sender, MouseEventArgs mouseEventArgs, int rowIndex, FastColumn col)
        {
            var filterObject = (FilterObject)fastGrid.rows[rowIndex].ValueObject;

            if (col.PropertyName == filterObject.Property(p => p.Selected))
            {
                filterObject.Selected = !filterObject.Selected;
                fastGrid.UpdateRow(rowIndex, filterObject);
                fastGrid.InvalidateRow(rowIndex);
                UpdateExpression();
            }
            if (col.PropertyName == filterObject.Property(p => p.Operator))
            {
                operatorsContextMenuStrip.Tag = filterObject;
                foreach (ToolStripMenuItem item in operatorsContextMenuStrip.Items)
                {
                    item.Checked = PerformerCriteriaFunction.GetExpressionOperatorString(filterObject.Operator) == item.Text;
                }
                operatorsContextMenuStrip.Show(fastGrid, fastGrid.GetCellCoords(col, rowIndex));
            }
        }
        private void SaveButtonClick(object sender, EventArgs e)
        {
            var dialog = new SimpleDialog(Localizer.GetString("TitleExpressionCreation"),
                                          Localizer.GetString("MessageEnterFormulaComment"), true, SelectedFunction.Description);

            if (dialog.ShowDialog(this) == DialogResult.Cancel)
            {
                return;
            }
            var newF = new PerformerCriteriaFunction(SelectedFunction)
            {
                Description = dialog.InputValue
            };

            PerformerCriteriaFunctionCollection.Instance.criterias.Add(newF);
            PerformerCriteriaFunctionCollection.Instance.SelectedFunction = newF;
            PerformerCriteriaFunctionCollection.Instance.WriteToFile();
            if (PerformerCriteriaFunctionCollectionChanged != null)
            {
                PerformerCriteriaFunctionCollectionChanged(this, new EventArgs());
            }
        }
        private void UpdateExpression()
        {
            // если что-то изменили в таблице, то формула обновляется;
            // если таблица в предыдущей итерации не смогла представить ее, то старая формула стирается,
            // и новая начинает формироваться по таблице
            var expression = "";

            foreach (var fiterObject in filterObjects)
            {
                if (!fiterObject.Selected)
                {
                    continue;
                }
                expression = fiterObject.UpdateExpression(expression);
            }
            // избегаем ошибки парсинга в PerformerStatField.ParseSimpleFormula, задавая поле для сортировки
            if (SortField == null)
            {
                var blank = new PerformerStat();
                SortField = PerformerStatField.fields.FirstOrDefault(f => f.PropertyName == blank.Property(p => p.Profit));
                if (SortField == null)
                {
                    return;
                }
            }
            expression       = (!string.IsNullOrEmpty(expression) ? "(" + expression + ")*" : "") + SortField.ExpressionParamName;
            SelectedFunction = new PerformerCriteriaFunction
            {
                Function           = expression,
                PreferredSortOrder = SortOrder,
                MarginValue        = 0
            };
            expressionLabel.Text = SelectedFunction.Function;
            if (PerformerCriteriaFunctionChanged != null)
            {
                PerformerCriteriaFunctionChanged(this, new EventArgs());
            }
        }
        private void RecalcUserScore(IEnumerable <PerformerStatEx> performerStats)
        {
            var crit = PerformerCriteriaFunctionCollection.Instance.SelectedFunction;
            ExpressionResolver resv;

            try
            {
                resv = new ExpressionResolver(crit.Function);
            }
            catch
            {
                resv = null;
            }

            foreach (var performerStat in performerStats)
            {
                // посчитать критерий
                if (resv != null)
                {
                    performerStat.UserScore = (float)PerformerCriteriaFunction.Calculate(resv, performerStat);
                }
            }
        }
        // "save" button
        private void BtnAcceptClick(object sender, EventArgs e)
        {
            // добавить новый критерий или удалить существующий
            var formula = (cbFunction.Text ?? "").Trim();

            if (lastSelectedItem == null && string.IsNullOrEmpty(formula))
            {
                return;
            }

            // удалить?
            if (string.IsNullOrEmpty(formula))
            {
                if (MessageBox.Show("Удалить формулу \"" + lastSelectedItem.Function + "\"?", "Подтверждение",
                                    MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }
                PerformerCriteriaFunctionCollection.Instance.criterias.Remove(lastSelectedItem);
                PerformerCriteriaFunctionCollection.Instance.WriteToFile();
                FillFormulas();
                return;
            }

            // проверить значение
            string error;

            if (!ExpressionResolver.CheckFunction(formula, out error,
                                                  PerformerCriteriaFunctionCollection.Instance.enabledParametersNames))
            {
                MessageBox.Show("Формула \"" + formula + "\" не распознана: " + error);
                return;
            }

            // переписать комментарий
            var existItem = PerformerCriteriaFunctionCollection.Instance.criterias.FirstOrDefault(
                c => c.FormulasEqual(formula));

            if (existItem != null)
            {
                existItem.MarginValue = cbMargin.Checked ? tbMarginValue.Text.ToFloatUniformSafe() : null;
                existItem.Description = tbComment.Text;
                PerformerCriteriaFunctionCollection.Instance.WriteToFile();
                return;
            }

            // добавить новое значение
            var newFunc = new PerformerCriteriaFunction
            {
                Function           = formula,
                Description        = tbComment.Text,
                PreferredSortOrder = cbSortOrder.SelectedIndex == 0 ? SortOrder.Descending : SortOrder.Ascending,
                MarginValue        =
                    cbMargin.Checked ? tbMarginValue.Text.Trim().Replace(",", ".").ToFloatUniformSafe() : null
            };

            PerformerCriteriaFunctionCollection.Instance.criterias.Add(newFunc);
            PerformerCriteriaFunctionCollection.Instance.SelectedFunction = newFunc;
            PerformerCriteriaFunctionCollection.Instance.WriteToFile();
            FillFormulas();
        }
Example #11
0
        public List <PerformerStat> GetAllPerformersWithCriteria(bool managersOnly, string criteria, int count, bool ascending,
                                                                 float?marginScore, int serviceTypeMask)
        {
            // данные не готовы к работе
            if (!cacheUpdated)
            {
                Logger.Info("GetAllPerformersWithCriteria - данные не готовы");
                return(new List <PerformerStat>());
            }

            ExpressionResolver resv;

            try
            {
                resv = new ExpressionResolver(criteria);
            }
            catch
            {
                resv = null;
            }

            var result    = new List <PerformerStat>();
            var startTime = DateTime.Now;

            foreach (var performer in dicPerformers.ReceiveAllData())
            {
                if (managersOnly && performer.Value.Statistics.Service == 0)
                {
                    continue;
                }
                var performerStat = performer.Value.Statistics;
                if (resv != null)
                {
                    performerStat.UserScore = (float)PerformerCriteriaFunction.Calculate(resv, performerStat);
                }
                else
                {
                    performerStat.UserScore = performerStat.Profit;
                }
                // отсеять тех, кто не удовлетворяет условию
                if (marginScore.HasValue)
                {
                    //if (performerStat.UserScore.AreSame(marginScore.Value, 0.0001f)) continue;
                    if ((performerStat.UserScore <= marginScore.Value && !ascending) ||
                        (performerStat.UserScore >= marginScore.Value && ascending))
                    {
                        continue;
                    }
                }
                if (serviceTypeMask != 0)
                {
                    if ((serviceTypeMask & 1) != 0)
                    {
                        if (performerStat.ServiceType != (int)PaidServiceType.Signals)
                        {
                            continue;
                        }
                    }
                    if ((serviceTypeMask & 2) != 0)
                    {
                        if (performerStat.ServiceType != (int)PaidServiceType.PAMM)
                        {
                            continue;
                        }
                    }
                }
                result.Add(performerStat);
            }

            // отсортировать и отобрать count результатов
            var total = result.Count;

            result.Sort(ComparePerformerStats);
            if (!ascending)
            {
                result.Reverse();
            }
            if (result.Count > count)
            {
                result = result.GetRange(0, count);
            }

            Logger.InfoFormat("GetAllPerformersWithCriteria (managersOnly={0}, criteria={1}, count={2}, margin={3})" +
                              " - записей: {4}, время вычислений: {5} мс",
                              managersOnly,
                              criteria + (ascending ? "[asc]" : "[desc]"),
                              count,
                              marginScore,
                              total,
                              DateTime.Now.Subtract(startTime).TotalMilliseconds);

            return(result.ToList());
        }
 // конкатенация выражения этого объекта с существующим выражением;
 // используется для представления формулы из FilterObject-ов в виде строки
 public string UpdateExpression(string expression)
 {
     return(expression + (!string.IsNullOrEmpty(expression) ? "&" : "") + "(" + Name +
            PerformerCriteriaFunction.GetExpressionOperatorString(Operator) + Value + ")");
 }
 public void SetExpression(PerformerCriteriaFunction function)
 {
     SortOrder = function.PreferredSortOrder;
     SetExpression(function.Function);
 }
 private void CbFunctionSelectedIndexChanged(object sender, EventArgs e)
 {
     var item = cbFunction.SelectedItem;
     if (item == null) return;
     var crit = (PerformerCriteriaFunction) item;
     lastSelectedItem = crit;
     tbComment.Text = crit.Description;
     cbMargin.Checked = crit.MarginValue.HasValue;
     tbMarginValue.Enabled = crit.MarginValue.HasValue;
     tbMarginValue.Text = crit.MarginValue.HasValue ? crit.MarginValue.Value.ToString("f2") : "0.00";
 }