Exemplo n.º 1
0
        public ActionResult Create()
        {
            ItemEngineDTO items = new ItemEngineDTO();

            ViewBag.Icons = Enum.GetValues(typeof(Icons)).Cast <Icons>().Select(i => new SelectListItem
            {
                Text  = i.ToString(),
                Value = i.ToString()
            }).ToList();

            return(PartialView("_Edit", items));
        }
Exemplo n.º 2
0
        public ActionResult Edit(string itemId)
        {
            ItemEngineDTO item = ItemEngineService.Instance.GetById(itemId);


            item.GameId = CurrentFirm.ExternalId;

            ViewBag.Icons = Enum.GetValues(typeof(Icons)).Cast <Icons>().Select(i => new SelectListItem
            {
                Text  = i.ToString(),
                Value = i.ToString()
            }).ToList();


            return(PartialView("_edit", item));
        }
Exemplo n.º 3
0
        public ActionResult Save(ItemEngineDTO items)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (items.Name == null || items.Name == "")
                    {
                        Error("O item deve possuir um nome.");
                    }
                    else
                    {
                        items.GameId = CurrentFirm.ExternalId;

                        ValidateModel(items);

                        ItemEngineDTO newItems = ItemEngineService.Instance.CreateOrUpdate(items);

                        if (newItems == null)
                        {
                            throw new Exception(".");
                        }

                        Success("Item atualizado com sucesso.");
                    }
                }
                else
                {
                    ViewBag.Icons = Enum.GetValues(typeof(Icons)).Cast <Icons>().Select(i => new SelectListItem
                    {
                        Text  = i.ToString(),
                        Value = i.ToString()
                    }).ToList();
                    ModelState.AddModelError("", "Alguns campos são obrigatórios para salvar o Produto.");
                    return(PartialView("_Edit", items));
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);

                Error("Erro ao atualizar Item" + ex.Message);
                return(PartialView("_Edit"));
            }

            return(new EmptyResult());
        }
        /// <summary>
        /// Salva as informações do resultado via arquivo
        /// </summary>
        /// <param name="resultsArchive"></param>
        /// <returns></returns>
        //[Route("salvarResultadoArquivo")]
        //[HttpPost]
        //[CustomAuthorize(Roles = "WORKER,ADMINISTRADOR,SUPERVISOR DE CAMPANHA,SUPERVISOR DE EQUIPE")]
        private ActionResult SaveResultArchiveStandard(HttpPostedFileBase resultsArchive, string episodeId)
        {
            string errors          = "Quantidade de erros: {0}<br/>Última linha lida: {1}<br/>";
            int    line            = 1;
            int    countErrors     = 0;
            int    countEmptyLines = 0;

            string gameId = CurrentFirm.ExternalId;

            try
            {
                resultsArchive.SaveAs(Path.Combine(Server.MapPath("~/App_Data"), resultsArchive.FileName));

                string path = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(resultsArchive.FileName));

                var archive = new ExcelQueryFactory(path);

                var rows = from x in archive.WorksheetRange("A1", "F" + rowsCount, "Results")
                           select x;

                foreach (var row in rows)
                {
                    line++;

                    if (countEmptyLines >= 3)
                    {
                        break;
                    }

                    if (row[0] == null || row[0].ToString().Equals("") || row[1] == null || row[1].ToString().Equals(""))
                    {
                        countEmptyLines++;
                        continue;
                    }

                    countEmptyLines = 0;

                    if (row[3].ToString().Equals("0"))
                    {
                        continue;
                    }

                    RunMetricEngineDTO result = new RunMetricEngineDTO();
                    MetricEngineDTO    metric = new MetricEngineDTO();
                    TeamEngineDTO      team   = new TeamEngineDTO();
                    RunEngineDTO       run    = new RunEngineDTO();

                    try
                    {
                        metric = MetricEngineService.Instance.GetDTOByGameAndName(CurrentFirm.ExternalId, row[1].ToString());
                    }
                    catch (Exception e)
                    {
                        errors += "Erro na coluna 2 da linha " + line + "<br/>";
                        countErrors++;
                        continue;
                    }

                    UserProfileEntity user = UserProfileRepository.Instance.GetByEmail(row[0].ToString());

                    if (user == null)
                    {
                        errors += "Erro na coluna 1 da linha " + line + "<br/>";
                        countErrors++;
                        continue;
                    }

                    WorkerEntity worker = WorkerRepository.Instance.GetByUserId((int)user.Id);

                    if (worker == null)
                    {
                        errors += "Erro na coluna 1 da linha " + line + "<br/>";
                        countErrors++;
                        continue;
                    }

                    try
                    {
                        team = TeamEngineService.Instance.GetByEpisodeIdAndNick(episodeId, row[4]);
                    }
                    catch (Exception e)
                    {
                        errors += "Erro na coluna 5 da linha " + line + "<br/>";
                        countErrors++;
                        continue;
                    }

                    try
                    {
                        run = RunEngineService.Instance.GetRunByPlayerAndTeamId(worker.ExternalId, team.Id);
                    }
                    catch (Exception e)
                    {
                        errors += "Jogador " + user.Name + " não está cadastrado no time " + team.Nick + ". Linha: " + line + "<br/>";
                        countErrors++;
                        continue;
                    }

                    ItemEngineDTO item = new ItemEngineDTO
                    {
                        GameId = gameId,
                        Name   = Regex.Replace(row[5].ToString().Trim(), "[^0-9a-zA-Z]+", " ")
                    };

                    try
                    {
                        item = ItemEngineService.Instance.FindByNameAndGameId(item.Name, item.GameId);
                    }
                    catch (Exception e)
                    {
                        if (item.Name != "")
                        {
                            item = ItemEngineService.Instance.CreateOrUpdate(item);
                        }
                    }


                    if (!string.IsNullOrWhiteSpace(row[0].ToString()) && !string.IsNullOrWhiteSpace(row[1].ToString()) && !string.IsNullOrWhiteSpace(row[2].ToString()) && !string.IsNullOrWhiteSpace(row[3].ToString()))
                    {
                        try
                        {
                            result.Ceiling     = metric.Ceiling;
                            result.Date        = Convert.ToDateTime(row[2].ToString()).Ticks;
                            result.Description = metric.Description;
                            result.Floor       = metric.Floor;
                            result.MetricId    = metric.Id;
                            result.Multiplier  = metric.Multiplier;
                            result.Name        = metric.Name;
                            result.Points      = float.Parse(row[3].ToString());
                            result.Score       = 0;
                            result.Xp          = metric.Xp;
                            result.RunId       = run.Id;
                            result.PlayerId    = worker.ExternalId;
                            result.ItemId      = item.Id;
                            result.ItemName    = item.Name;

                            RunMetricEngineService.Instance.CreateOrUpdate(result);
                        }
                        catch (Exception e)
                        {
                            errors += "O formato das colunas 'Periodo' ou 'Resultado' estão errados. Linha: " + line + "<br/>";
                            countErrors++;
                            continue;
                        }
                    }
                }

                errors = string.Format(errors, countErrors, line);

                string emailFrom = ParameterCache.Get("SUPPORT_EMAIL");
                string subject   = countErrors >= 1 ? "Erros ao subir planilha de resultados" : "O lançamento de resultados foi um sucesso.";
                subject = CurrentFirm.FirmName + ": " + subject;
                bool r = EmailDispatcher.SendEmail(emailFrom, subject, new List <string>()
                {
                    emailFrom, CurrentUserProfile.Email
                }, errors);

                return(Json(new { Success = true }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);

                //ModelState.AddModelError("", "Ocorreu um erro ao tentar salvar os resultados.");

                return(Json(new { Success = false, Exception = ex.Message }, JsonRequestBehavior.DenyGet));
            }
        }
        //Sol bebidas
        /// <summary>
        /// Salva as informações do resultado via arquivo
        /// </summary>
        /// <param name="resultsArchive"></param>
        /// <param name="episodeId"></param>
        /// <returns></returns>
        //[Route("salvarResultadoArquivo")]
        //[HttpPost]
        //[CustomAuthorize(Roles = "WORKER,ADMINISTRADOR,SUPERVISOR DE CAMPANHA,SUPERVISOR DE EQUIPE")]
        public ActionResult SaveResultArchiveSolBebidas(HttpPostedFileBase resultsArchive, string episodeId)
        {
            int ANO                = 0;
            int MES                = 1;
            int REPRESENTANTE      = 2;
            int EMAIL              = 3;
            int CLIENTE            = 4;
            int COD_PRODUTO        = 5;
            int PRODUTO            = 6;
            int QTDE_OBJ           = 7;
            int QTDE_REAL          = 8;
            int PERCENT_QTDE       = 9;
            int VLR_OBJ            = 10;
            int VLR_BRUTO_REAL     = 11;
            int PERCENT_VALOR      = 12;
            int VLR_MEDIO_OBJETIVO = 13;
            int VLR_MEDIO_REAL     = 14;
            int TIPO_PRODUTO       = 15;

            EpisodeEngineDTO episode = EpisodeEngineService.Instance.GetById(episodeId);
            string           gameId  = CurrentFirm.ExternalId;

            string errors = "Erros: {0}<br/>";

            List <GoalEngineDTO> goalsTotalFat = new List <GoalEngineDTO>();
            List <GoalEngineDTO> goalsTotalVol = new List <GoalEngineDTO>();

            MetricEngineDTO metricFat;
            MetricEngineDTO metricVol;

            int line        = 1;
            int errorsCount = 0;

            string productType = resultsArchive.FileName.Split(' ')[0];

            try
            {
                metricFat = MetricEngineService.Instance.GetDTOByGameAndName(gameId, productType + " FATURAMENTO");
            }
            catch (Exception e)
            {
                errors += "Metrica (Faturamento) não encontrado.<br/>";
                errorsCount++;
                metricFat = new MetricEngineDTO();
                Debug.Print("Error metric: " + e.Message);
            }

            try
            {
                metricVol = MetricEngineService.Instance.GetDTOByGameAndName(gameId, productType + " VOLUME");
            }
            catch (Exception e)
            {
                errors += "Metrica (Volume) não encontrado.<br/>";
                errorsCount++;
                metricVol = new MetricEngineDTO();
                Debug.Print("Error metric: " + e.Message);
            }

            try
            {
                //EpisodeEngineService.Instance.DeleteAllScoreByEpisodeId(episodeId);

                resultsArchive.SaveAs(Path.Combine(Server.MapPath("~/App_Data"), resultsArchive.FileName));

                var archive = new ExcelQueryFactory(Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(resultsArchive.FileName)));

                var rows = from x in archive.WorksheetRange("A1", "O" + rowsCount, "Plan1") select x;

                float points;

                foreach (var row in rows)
                {
                    line++;

                    PlayerEngineDTO player;
                    RunEngineDTO    run;

                    if (row[PRODUTO].ToString().ToLower().Contains("uvinha"))
                    {
                        continue;
                    }

                    try
                    {
                        player = PlayerEngineService.Instance.GetByEmail(row[EMAIL].ToString().Trim().ToLower());
                    }
                    catch (Exception e)
                    {
                        Debug.Print("Error player: " + e.Message);
                        errors += "(Linha -> " + line + "°, Coluna -> 'Representante') " + "Jogador: " + row[EMAIL].ToString().Trim() + " não encontrado.<br/>";
                        errorsCount++;
                        continue;
                    }

                    try
                    {
                        run = RunEngineService.Instance.GetByEpisodeIdAndPlayerId(episodeId, player.Id);
                    }
                    catch (Exception e)
                    {
                        Debug.Print("Error run: " + e.Message);
                        errors += "(Linha -> " + line + "°, Coluna -> 'Email') " + "Jogador: " + row[EMAIL].ToString().Trim() + " não participa desta campanha.<br/>";
                        errorsCount++;
                        continue;
                    }

                    float.TryParse(row[VLR_OBJ].ToString(), out points);
                    if (goalsTotalFat.Find(x => x.RunId == run.Id) != null)
                    {
                        goalsTotalFat.Find(x => x.RunId == run.Id).Goal += points;
                    }
                    else
                    {
                        GoalEngineDTO goalFat;
                        try
                        {
                            goalFat      = GoalEngineService.Instance.GetByRunIdAndMetricId(run.Id, metricFat.Id);
                            goalFat.Goal = points;
                        }
                        catch (Exception e)
                        {
                            goalFat = new GoalEngineDTO
                            {
                                Goal       = points,
                                MetricIcon = metricFat.Icon,
                                MetricId   = metricFat.Id,
                                MetricName = metricFat.Name,
                                Percentage = 0,
                                RunId      = run.Id
                            };

                            Debug.Print("Goal faturamento: " + e.Message);
                        }

                        goalsTotalFat.Add(goalFat);
                    }

                    float.TryParse(row[QTDE_OBJ].ToString(), out points);
                    if (goalsTotalVol.Find(x => x.RunId == run.Id) != null)
                    {
                        goalsTotalVol.Find(x => x.RunId == run.Id).Goal += points;
                    }
                    else
                    {
                        GoalEngineDTO goalVol;
                        try
                        {
                            goalVol      = GoalEngineService.Instance.GetByRunIdAndMetricId(run.Id, metricVol.Id);
                            goalVol.Goal = points;
                        }
                        catch (Exception e)
                        {
                            goalVol = new GoalEngineDTO
                            {
                                Goal       = points,
                                MetricIcon = metricVol.Icon,
                                MetricId   = metricVol.Id,
                                MetricName = metricVol.Name,
                                Percentage = 0,
                                RunId      = run.Id
                            };

                            Debug.Print("Goal volume: " + e.Message);
                        }

                        goalsTotalVol.Add(goalVol);
                    }

                    ItemEngineDTO item = new ItemEngineDTO
                    {
                        GameId = gameId,
                        Name   = row[PRODUTO].ToString().Trim()
                    };

                    try
                    {
                        item = ItemEngineService.Instance.FindByNameAndGameId(item.Name, item.GameId);
                    }
                    catch (Exception e)
                    {
                        item = ItemEngineService.Instance.CreateOrUpdate(item);
                        Debug.Print("Error metric: " + e.Message);
                    }

                    float.TryParse(row[VLR_BRUTO_REAL].ToString(), out points);
                    RunMetricEngineDTO resultFaturamento = new RunMetricEngineDTO
                    {
                        Ceiling     = metricFat.Ceiling,
                        Description = metricFat.Description,
                        Floor       = metricFat.Floor,
                        MetricId    = metricFat.Id,
                        Multiplier  = metricFat.Multiplier,
                        Name        = metricFat.Name,
                        Xp          = 0,
                        Score       = 0,
                        Points      = (int)points,
                        Date        = DateTime.Now.Ticks,
                        PlayerId    = player.Id,
                        ItemId      = item.Id,
                        ItemName    = item.Name,
                        RunId       = run.Id
                    };

                    float.TryParse(row[QTDE_REAL].ToString(), out points);
                    RunMetricEngineDTO resultVolume = new RunMetricEngineDTO
                    {
                        Ceiling     = metricVol.Ceiling,
                        Description = metricVol.Description,
                        Floor       = metricVol.Floor,
                        MetricId    = metricVol.Id,
                        Multiplier  = metricVol.Multiplier,
                        Name        = metricVol.Name,
                        Xp          = 0,
                        Score       = 0,
                        Points      = (int)points,
                        Date        = DateTime.Now.Ticks,
                        PlayerId    = player.Id,
                        ItemId      = item.Id,
                        ItemName    = item.Name,
                        RunId       = run.Id
                    };

                    RunMetricEngineService.Instance.CreateOrUpdate(resultFaturamento);
                    RunMetricEngineService.Instance.CreateOrUpdate(resultVolume);
                }

                foreach (GoalEngineDTO goal in goalsTotalVol)
                {
                    GoalEngineService.Instance.CreateOrUpdate(goal);
                }

                foreach (GoalEngineDTO goal in goalsTotalFat)
                {
                    GoalEngineService.Instance.CreateOrUpdate(goal);
                }

                errors = string.Format(errors, errorsCount);
                string emailFrom = ParameterCache.Get("SUPPORT_EMAIL");
                string subject   = errorsCount >= 1 ? "Erros ao subir planilha de resultados" : "O lançamento de resultados foi um sucesso.";
                subject = CurrentFirm.FirmName + ": " + subject;
                bool r = EmailDispatcher.SendEmail(emailFrom, subject, new List <string>()
                {
                    emailFrom, CurrentUserProfile.Email
                }, errors);

                return(Json(new { Success = true }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception e)
            {
                Debug.Print("Geral Error: " + e.Message);

                return(Json(new { Success = false, Exception = e.Message }, JsonRequestBehavior.DenyGet));
            }
        }
        public ActionResult Save(List <RunMetricEngineDTO> resultList, string runId, string date, string itemId)
        {
            DateTime      dateTime   = Convert.ToDateTime(date);
            long          time       = dateTime.Ticks;
            ItemEngineDTO itemEngine = null;

            try {
                itemEngine = ItemEngineService.Instance.GetById(itemId);
            } catch (Exception e)
            {
                itemEngine = null;
            }

            float valorVendas = 0f;

            string gameId = CurrentFirm.ExternalId;

            if (gameId == "5880a1743a87783b4f0ba709") //pelegrini
            {
                valorVendas = resultList.Where(x => x.Name == "VENDAS").Select(y => y.Points).FirstOrDefault();
            }

            bool flag = false;

            foreach (RunMetricEngineDTO result in resultList)
            {
                if (result.Points > 0)
                {
                    flag         = true;
                    result.Score = 0;
                    result.RunId = runId;
                    result.Date  = time;
                    if (itemEngine != null)
                    {
                        result.ItemId   = itemEngine.Id;
                        result.ItemName = itemEngine.Name;
                    }
                    result.ArithmeticMultiplier = valorVendas > 0 ? valorVendas : 1;
                    RunMetricEngineService.Instance.CreateOrUpdate(result);
                }
            }

            if (gameId == "58e623fe3a877804f5b6bf22" && flag == true) //duplov
            {
                List <AccountDevicesDTO> devices = AccountDevicesRepository.Instance.FindAllByGameId(gameId);

                PlayerEngineDTO player  = PlayerEngineService.Instance.GetById(resultList.First().PlayerId);
                string          message = player.Nick + " está acelerando, veja seus novos resultados!";

                foreach (AccountDevicesDTO device in devices)
                {
                    NotificationPushDTO notification = new NotificationPushDTO
                    {
                        Token    = device.Notification_Token,
                        PlayerId = device.External_User_Id,
                        Message  = message,
                        Title    = "Gamific - Novos Resultados"
                    };

                    NotificationPushService.Instance.SendPush(notification);
                }
            }

            return(Json(new { Success = true }, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 7
0
 public ItemEngineDTO CreateOrUpdate(ItemEngineDTO item)
 {
     return(PostDTO <ItemEngineDTO>(ref item));
 }