Esempio n. 1
0
        public ActionResult Edit(string playerId, string teamId, string episodeId)
        {
            try
            {
                PlayerEngineDTO player = PlayerEngineService.Instance.GetById(playerId);
                ViewBag.WorkerName = player.Nick;

                List <WorkerTypeMetricDTO> metricsWorkerType = WorkerTypeMetricRepository.Instance.GetAllFromWorkerByPlayerId(playerId);

                List <MetricEngineDTO> metrics = new List <MetricEngineDTO>();

                foreach (WorkerTypeMetricDTO metric in metricsWorkerType)
                {
                    try
                    {
                        MetricEngineDTO m = MetricEngineService.Instance.GetById(metric.MetricExternalId);
                        metrics.Add(m);
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }

                RunEngineDTO run = RunEngineService.Instance.GetRunByPlayerAndTeamId(playerId, teamId);

                List <GoalEngineDTO> goals = new List <GoalEngineDTO>();
                foreach (MetricEngineDTO metric in metrics)
                {
                    try
                    {
                        GoalEngineDTO goal = GoalEngineService.Instance.GetByRunIdAndMetricId(run.Id, metric.Id);
                        goals.Add(goal);
                    }
                    catch (Exception ex)
                    {
                        GoalEngineDTO goal = new GoalEngineDTO
                        {
                            Goal       = 0,
                            MetricId   = metric.Id,
                            RunId      = run.Id,
                            MetricIcon = metric.Icon,
                            MetricName = metric.Name,
                        };
                        goals.Add(goal);
                        Logger.LogException(ex);
                    }
                }


                return(PartialView("_Edit", goals));
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                Error("Ocorreu um erro ao tentar adicionar uma meta.", ex);
            }

            return(Redirect("/admin/metas"));
        }
Esempio n. 2
0
        public ActionResult SearchMetricResults(JQueryDataTableRequest jqueryTableRequest, string metricId, string episodeId, string teamId, string playerId)
        {
            if (jqueryTableRequest != null)
            {
                GetAllDTO all = new GetAllDTO();

                if (playerId != "" && playerId != "empty")
                {
                    RunEngineDTO run = RunEngineService.Instance.GetRunByPlayerAndTeamId(playerId, teamId);
                    all = RunMetricEngineService.Instance.findByRunIdAndMetricId(run.Id, metricId, jqueryTableRequest.Page);
                }
                else if (teamId != "" && teamId != "empty" && teamId != "null")
                {
                    all = TeamEngineService.Instance.resultsByTeamIdAndMetricId(teamId, metricId, jqueryTableRequest.Page);
                }
                else
                {
                    all = EpisodeEngineService.Instance.resultsByEpisodeIdAndMetricId(episodeId, metricId, jqueryTableRequest.Page);
                }

                List <WorkerDTO> workers = all.List == null ? new List <WorkerDTO>() : WorkerRepository.Instance.GetWorkerDTOByListExternalId(all.List.runMetric.Select(i => i.PlayerId).ToList());
                GetAllDTO        itens   = ItemEngineService.Instance.GetByGameId(CurrentFirm.ExternalId, 0, 1000);


                if (all.List != null)
                {
                    foreach (RunMetricEngineDTO rm in all.List.runMetric)
                    {
                        DateTime dat = new DateTime(rm.Date);
                        string   ds  = dat.ToString("dd/MM/yyyy");
                    }
                }
                else
                {
                    all.List           = new GetAllDTO.Embedded();
                    all.List.runMetric = new List <RunMetricEngineDTO>();
                }

                JQueryDataTableResponse response = new JQueryDataTableResponse()
                {
                    Draw            = jqueryTableRequest.Draw,
                    RecordsTotal    = all.PageInfo.totalElements,
                    RecordsFiltered = all.PageInfo.totalElements,
                    Data            = (from runMetric in all.List.runMetric
                                       join worker in workers on runMetric.PlayerId equals worker.ExternalId into runMetricWorker
                                       from rmw in runMetricWorker.DefaultIfEmpty()
                                       select new { Date = new DateTime(runMetric.Date), WorkerName = rmw != null ? rmw.Name : "Jogador excluído", Email = rmw != null ? rmw.Email : "", Result = runMetric.Points, RunMetricId = runMetric.Id, ItemName = itens.List == null ? "" : (itens.List.item.Where(q => q.Id == runMetric.ItemId).Select(x => x.Name)).FirstOrDefault() }).
                                      Select(r => new string[] { r.Date.ToString("dd/MM/yyyy"), r.WorkerName, r.Email, r.ItemName, r.Result.ToString(), r.RunMetricId }).ToArray()
                };

                return(new DataContractResult()
                {
                    Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet
                });
            }

            return(Json(null, JsonRequestBehavior.AllowGet));
        }
Esempio n. 3
0
        public ContentResult LoadBarChart(List <string> metricsIds, string teamId, string workerId, string campaignId)
        {
            if (episodesFilter.Count < 1)
            {
                GetCampaignsModal();
            }

            List <BarDTO> bars = new List <BarDTO>();

            List <string> episodesIds = new List <string>();

            List <MetricEngineDTO> metrics = new List <MetricEngineDTO>();

            foreach (string item in metricsIds)
            {
                metrics.Add(MetricEngineService.Instance.GetById(item));
            }

            List <EpisodeEngineDTO> episodesParam = new List <EpisodeEngineDTO>();

            foreach (EpisodeEngineDTO item in episodesFilter)
            {
                if (item.checkedFlag)
                {
                    episodesParam.Add(item);
                }
            }

            List <RunEngineDTO> runners = new List <RunEngineDTO>();

            if (!string.IsNullOrEmpty(teamId) && !teamId.Equals("empty"))
            {
                if (!string.IsNullOrEmpty(workerId) && !workerId.Equals("empty"))
                {
                    RunEngineDTO run = RunEngineService.Instance.GetByEpisodeIdAndPlayerId(campaignId, workerId);

                    runners.Add(run);
                }
                else
                {
                    runners = RunEngineService.Instance.GetRunsByTeamId(teamId).List.run;
                }
            }

            if (runners.Count > 0)
            {
                bars = CardEngineService.Instance.EpisodesAndMetrics(episodesParam, metrics, runners);
            }
            else
            {
                bars = new List <BarDTO>();
            }

            return(Content(JsonConvert.SerializeObject(bars), "application/json"));
        }
Esempio n. 4
0
        public ActionResult DetailsCheckin(string episodeId, string metricId, string teamId, string playerId)
        {
            List <RunEngineDTO> runners = new List <RunEngineDTO>();

            if (playerId != "empty")
            {
                RunEngineDTO runner = RunEngineService.Instance.GetByEpisodeIdAndPlayerId(episodeId, playerId);

                runners.Add(runner);
            }
            else if (teamId != "empty")
            {
                runners = GetRunsByTeamIdRecursive(teamId);
            }
            else
            {
                GetAllDTO all = TeamEngineService.Instance.FindByEpisodeId(episodeId);

                all.List.team = all.List.team.OrderBy(x => x.Nick).ToList();

                List <string> subTeamsNull = all.List.team.Where(x => x.SubOfTeamId == null).Select(x => x.Id).ToList();

                List <TeamEngineDTO> teams = new List <TeamEngineDTO>();

                foreach (string subTeamNull in subTeamsNull)
                {
                    teams.AddRange(OrganizeHierarchy(all.List.team, subTeamNull));
                }

                foreach (TeamEngineDTO team in teams)
                {
                    runners.AddRange(GetRunsByTeamIdRecursive(team.Id));
                }
            }

            MetricEngineDTO metric = MetricEngineService.Instance.GetById(metricId);

            List <LocationDTO> locations = MetricEngineService.Instance.MapPointsByRunsAndMetric(runners, metric);

            List <LocationViewDTO> locs = new List <LocationViewDTO>();

            foreach (LocationDTO location in locations)
            {
                LocationViewDTO loc = new LocationViewDTO();

                loc.Lat  = location.Latitude;
                loc.Lon  = location.Longitude;
                loc.html = location.Description ?? "Check-in";


                locs.Add(loc);
            }

            ViewBag.EpisodeId = episodeId;
            ViewBag.TeamId    = teamId;
            ViewBag.PlayerId  = playerId;
            ViewBag.Locations = Content(JsonConvert.SerializeObject(locs), "application/json");
            ViewBag.MetricId  = metricId;

            if (playerId != "empty")
            {
                PlayerEngineDTO player = PlayerEngineService.Instance.GetById(playerId);
                ViewBag.Name = player.Nick;
            }
            else if (teamId != "empty")
            {
                TeamEngineDTO team = TeamEngineService.Instance.GetById(teamId);
                ViewBag.Name = team.Nick;
            }
            else
            {
                EpisodeEngineDTO episode = EpisodeEngineService.Instance.GetById(episodeId);
                ViewBag.Name = episode.Name;
            }

            return(View("DetailCheckin"));
        }
Esempio n. 5
0
        public ContentResult GetChartResults(List <string> metricsIds, string campaignId, string teamId, string workerId, string initDate, string endDate)
        {
            List <ChartResultDTO> rtn = new List <ChartResultDTO>();

            EpisodeEngineDTO episodeObj = EpisodeEngineService.Instance.GetById(campaignId);

            List <string> episodesParam = new List <string>();

            episodesParam.Add(campaignId);

            DateTime initDT;

            if (initDate == null || initDate.Length == 0)
            {
                initDT = DateTime.Now.AddDays(-10);
            }
            else
            {
                initDT = DateTime.Parse(initDate);
            }

            DateTime endDT;

            if (endDate == null || endDate.Length == 0)
            {
                endDT = DateTime.Now;
            }
            else
            {
                endDT = DateTime.Parse(endDate);
            }


            initDT = DateTime.Now.AddMonths(-6);
            endDT  = DateTime.Now.AddDays(1);

            List <string> runners = new List <string>();

            if (!string.IsNullOrEmpty(teamId) && !teamId.Equals("empty"))
            {
                if (!string.IsNullOrEmpty(workerId) && !workerId.Equals("empty"))
                {
                    RunEngineDTO run = RunEngineService.Instance.GetByEpisodeIdAndPlayerId(campaignId, workerId);

                    runners.Add(run.Id);
                }
                else
                {
                    List <RunEngineDTO> runnersObj = GetRunsByTeamIdRecursive(teamId);

                    foreach (RunEngineDTO run in runnersObj)
                    {
                        runners.Add(run.Id);
                    }
                }
            }

            List <string> periods = new List <string>();

            foreach (string item in metricsIds)
            {
                ChartResultDTO chartDTO = new ChartResultDTO();

                List <string> metricParam = new List <string>();

                metricParam.Add(item);

                chartDTO = CardEngineService.Instance.GameAndMetricAndPeriod(runners, episodesParam, episodeObj.GameId, metricParam, initDT.Ticks, endDT.Ticks);

                foreach (EpisodeEngineDTO entrie in chartDTO.Entries)
                {
                    if (!periods.Contains(entrie.Name))
                    {
                        periods.Add(entrie.Name);
                    }
                }

                rtn.Add(chartDTO);
            }

            List <LineDTO> linesDTO = new List <LineDTO>();

            foreach (string period in periods)
            {
                LineDTO line = new LineDTO();

                line.Period = period;

                foreach (ChartResultDTO item in rtn)
                {
                    var query = from entrie in item.Entries
                                where entrie.Name.Equals(period)
                                select new LinePointDTO
                    {
                        MetricName = item.Name,
                        Value      = entrie.Value
                    };

                    if (query.ToList().Count <= 0)
                    {
                        LinePointDTO linePoint = new LinePointDTO();
                        linePoint.MetricName = item.Name;
                        linePoint.Value      = 0;

                        line.Points.Add(linePoint);
                    }
                    else
                    {
                        line.Points.Add(query.FirstOrDefault());
                    }
                }

                linesDTO.Add(line);
            }

            foreach (LineDTO aux in linesDTO)
            {
                aux.dateLong = Convert.ToDateTime(aux.Period).Ticks;
            }

            var lineQuery = from line in linesDTO
                            orderby line.dateLong
                            select line;

            linesDTO = lineQuery.ToList();

            return(Content(JsonConvert.SerializeObject(linesDTO), "application/json"));
        }
Esempio n. 6
0
        public ActionResult SearchCheckIn(JQueryDataTableRequest jqueryTableRequest, string episodeId, string metricId, string teamId, string playerId)
        {
            if (jqueryTableRequest != null)
            {
                GetAllDTO all = new GetAllDTO();

                List <RunEngineDTO> runners = new List <RunEngineDTO>();

                if (playerId != "empty")
                {
                    RunEngineDTO runner = RunEngineService.Instance.GetByEpisodeIdAndPlayerId(episodeId, playerId);

                    runners.Add(runner);
                }
                else if (teamId != "empty")
                {
                    runners = GetRunsByTeamIdRecursive(teamId);
                }
                else
                {
                    all = TeamEngineService.Instance.FindByEpisodeId(episodeId);

                    all.List.team = all.List.team.OrderBy(x => x.Nick).ToList();

                    List <string> subTeamsNull = all.List.team.Where(x => x.SubOfTeamId == null).Select(x => x.Id).ToList();

                    List <TeamEngineDTO> teams = new List <TeamEngineDTO>();

                    foreach (string subTeamNull in subTeamsNull)
                    {
                        teams.AddRange(OrganizeHierarchy(all.List.team, subTeamNull));
                    }

                    foreach (TeamEngineDTO team in teams)
                    {
                        runners.AddRange(GetRunsByTeamIdRecursive(team.Id));
                    }
                }

                MetricEngineDTO metric = MetricEngineService.Instance.GetById(metricId);

                List <LocationDTO> locations = MetricEngineService.Instance.MapPointsByRunsAndMetric(runners, metric);

                List <CheckInDTO> checkIns = new List <CheckInDTO>();

                foreach (LocationDTO location in locations)
                {
                    CheckInDTO ci = new CheckInDTO();



                    DateTime date = new DateTime(((location.Date - 10800000) * 10000) + 621355968000000000l);
                    ci.Date = date.ToString("dd'/'MM'/'yyyy HH':'mm':'ss");

                    PlayerEngineDTO player = PlayerEngineService.Instance.GetById(location.PlayerId);
                    ci.PlayerName  = player.Nick;
                    ci.Description = location.Description ?? "Check-in";
                    ci.Place       = location.Place;
                    checkIns.Add(ci);
                }

                JQueryDataTableResponse response = new JQueryDataTableResponse()
                {
                    Draw            = jqueryTableRequest.Draw,
                    RecordsTotal    = locations.Count,
                    RecordsFiltered = locations.Count,
                    Data            = checkIns.OrderByDescending(r => DateTime.Parse(r.Date)).Select(r => new string[] { r.Date, r.PlayerName, r.Description, r.Place }).ToArray()
                };

                return(new DataContractResult()
                {
                    Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet
                });
            }

            return(Json(null, JsonRequestBehavior.AllowGet));
        }
Esempio n. 7
0
        private string CreateEmail(GameEngineDTO game, string episodeId, string teamId, string playerId, WorkerDTO worker)
        {
            PlayerEngineDTO  player  = playerId == null ? null : PlayerEngineService.Instance.GetById(playerId, email);
            TeamEngineDTO    team    = teamId == null ? null : TeamEngineService.Instance.GetById(teamId, email);
            EpisodeEngineDTO episode = episodeId == null ? null : EpisodeEngineService.Instance.GetById(episodeId, email);
            GetAllDTO        runs    = RunEngineService.Instance.GetAllRunScore(teamId, "", email);
            GetAllDTO        teams   = TeamEngineService.Instance.GetAllTeamScoreByEpisodeId(episode.Id, "", email, 0, 10);

            if (runs.List != null)
            {
                List <PlayerEngineDTO> players = new List <PlayerEngineDTO>();

                foreach (RunEngineDTO run in runs.List.run)
                {
                    try
                    {
                        PlayerEngineDTO p = PlayerEngineService.Instance.GetById(run.PlayerId, email);
                        if (p != null)
                        {
                            players.Add(p);
                        }
                    }
                    catch (Exception e)
                    {
                    }
                }

                runs.List.result = (from run in runs.List.run
                                    from p in players
                                    where p.Id == run.PlayerId
                                    select new ResultEngineDTO
                {
                    Id = p.Id,
                    Nick = p.Nick,
                    Score = run.Score,
                    LogoId = p.LogoId
                }).ToList();

                if (player.Id != null && worker.ProfileName == Profiles.JOGADOR && runs.List.result.Find(x => x.Id == player.Id) == null)
                {
                    RunEngineDTO    playerRun = RunEngineService.Instance.GetRunByPlayerAndTeamId(player.Id, team.Id, email);
                    ResultEngineDTO result    = new ResultEngineDTO
                    {
                        Id     = player.Id,
                        Nick   = player.Nick,
                        Score  = playerRun.Score,
                        LogoId = player.LogoId
                    };

                    runs.List.result.Add(result);
                }
            }

            if (teams.List != null)
            {
                teams.List.result = (from t in teams.List.team
                                     select new ResultEngineDTO
                {
                    Id = t.Id,
                    Nick = t.Nick,
                    Score = t.Score,
                    LogoId = t.LogoId
                }).ToList();
            }

            string emailBody = "<!DOCTYPE html><html xmlns = 'http://www.w3.org/1999/xhtml'><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8;'/><style>body{color: #000000; font-family: Roboto, sans-serif;} h1{font-size: 30px;} h2{font-size: 24px;}h3{font-size: 18px;} strong{color: #1cb29b;} a{text-decoration: none; color: #153643; font-weight: 700;} td{text-align: center;} .image-icon{width:48px;height:48px !important;border-radius:100%;margin-right: 10px;} .score{text-align: right !important; padding-left:15px;} .name{text-align:left !important;} .sucess-goal{color: #1cb29b !important; font-weight: bold;} .alert-goal{color: firebrick;font-weight: bold;} .normal-goal{color: orange; font-weight:bold;}</style></head>";

            emailBody += "<body style = 'margin: 0; padding: 0;'><table align = 'center' border = '0' cellpadding = '0' cellspacing = '0' width = '1000'>";
            emailBody += "</td></tr><tr><td style='padding: 0 0 0 0;' align='center'>";
            emailBody += "</td></tr><tr><td>";
            emailBody += "<table border='0' cellpadding='0' cellspacing='0' width='100%'><tr><td width='260' valign='top'>";
            emailBody += "<tr><td align='center'><img src = 'https://s3.amazonaws.com/gamific-prd/images/logos/empresas/logo-1' width = '340' height = '223'/></td></tr>";
            emailBody += "<tr><td><table border='0' cellpadding='0' cellspacing='0' width='100%'><tr><td><h1 align='center'> Olá " + player.Nick + "!<br/> Aqui estão seus resultados diários</h1></td></tr>";
            emailBody += "<tr><td><h2 align='center'> Campanha " + episode.Name + " </h2></td></tr>";
            emailBody += "<tr><td><h2 align='center'>" + team.Nick + " </h2></td></tr>";
            emailBody += "<tr><td><h3 align='center'> Resultados individuais </h3>";
            emailBody += CreateIndividualResultsTable(team, player, game.Id, worker.ProfileName);
            emailBody += "<h3 align='center'>Ranking dos membros da equipe</h3>";
            emailBody += CreateRankingPlayersFromTeamResultsTable(runs.List != null ? runs.List.result : null, playerId);
            emailBody += "<h3 align='center'>Ranking das equipes na campanha</h3>";
            emailBody += CreateRankingTeamsFromCampaignResultsTable(teams.List != null ? teams.List.result : null, teamId);
            emailBody += "</td></tr></table></td></tr>";
            emailBody += "<tr><td><p align='center'>Acesse o site: <a href='http://www.gamific.com.br/'> Gamific </a></p></td></tr>";
            emailBody += "</table></body></html>";

            return(emailBody);
        }
Esempio n. 8
0
        private string CreateIndividualResultsTable(TeamEngineDTO team, PlayerEngineDTO player, string gameId, Profiles perfil)
        {
            RunEngineDTO         run;
            List <GoalEngineDTO> goals = new List <GoalEngineDTO>();
            List <CardEngineDTO> results;

            if (perfil == Profiles.JOGADOR)
            {
                results = CardEngineService.Instance.PlayerWithEmail(gameId, team.Id, player.Id, email);
                run     = RunEngineService.Instance.GetRunByPlayerAndTeamId(player.Id, team.Id, email);
                goals   = GoalEngineService.Instance.GetByRunId(run.Id, email).List.goal;//GoalRepository.Instance.GetByRunId(run.Id);
            }
            else if (perfil == Profiles.LIDER)
            {
                results = CardEngineService.Instance.TeamWithEmail(gameId, team.Id, email);
                GetAllDTO     all    = RunEngineService.Instance.GetRunsByTeamId(team.Id, email);
                List <string> runIds = all.List.run.Select(x => x.Id).ToList();
                foreach (string runId in runIds)
                {
                    goals.AddRange(GoalEngineService.Instance.GetByRunId(runId, email).List.goal); //GoalRepository.Instance.GetByRunId(runIds);
                }
            }
            else
            {
                results = new List <CardEngineDTO>();
                run     = new RunEngineDTO();
                goals   = new List <GoalEngineDTO>();
            }


            results = (from result in results

                       select new CardEngineDTO
            {
                IconMetric = result.IconMetric.Replace("_", "-"),
                MetricId = result.MetricId,
                MetricName = result.MetricName,
                TotalPoints = result.TotalPoints,
                Goal = result.Goal,
                PercentGoal = result.PercentGoal,
                IsAverage = result.IsAverage
            }).ToList();


            string emailBody = "<table align='center' cellpadding = '5px'><tr>";

            emailBody += "<td></td><td>Objetivo</td><td>Alcançado</td><td>Porcentagem</td>";
            emailBody += "</tr>";

            foreach (CardEngineDTO result in results)
            {
                if (result.PercentGoal < 0.3f)
                {
                    emailBody += "<tr class='alert-goal'>";
                }
                else if (result.PercentGoal < 1.0f)
                {
                    emailBody += "<tr class='normal-goal'>";
                }
                else
                {
                    emailBody += "<tr class='sucess-goal'>";
                }

                emailBody += "<td class='name'>" + result.MetricName + "</td>";
                emailBody += "<td>" + result.Goal.ToString("###,###,###,###") + "</td>";
                emailBody += "<td>" + result.TotalPoints.ToString("###,###,###,###") + "</td>";
                emailBody += "<td>" + (result.PercentGoal * 100) + "%</td>";
                emailBody += "</tr>";
            }

            emailBody += "</table>";

            return(emailBody);
        }
Esempio n. 9
0
        /// <summary>
        /// Salva as informações do resultado via arquivo
        /// </summary>
        /// <param name="goalArchive"></param>
        /// <param name="episodeId"></param>
        /// <returns></returns>
        private ActionResult SaveGoalArchiveDefault(HttpPostedFileBase goalArchive, string episodeId)
        {
            string errors          = "Quantidade de erros: {0}<br/>Última linha lida: {1}<br/>";
            int    line            = 1;
            int    countErrors     = 0;
            int    countEmptyLines = 0;

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

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

                var archive = new ExcelQueryFactory(path);

                var rows = from x in archive.WorksheetRange("A1", "D" + rowsCount, "Goals")
                           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;
                    }

                    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].Value.ToString());

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

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

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

                    try
                    {
                        team = TeamEngineService.Instance.GetByEpisodeIdAndNick(episodeId, row[2].Value.ToString());
                    }
                    catch (Exception e)
                    {
                        errors += "Erro na coluna 3 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;
                    }


                    if (!string.IsNullOrWhiteSpace(row[0].ToString()) && !string.IsNullOrWhiteSpace(row[1].ToString()) && !string.IsNullOrWhiteSpace(row[2].ToString()) && !string.IsNullOrWhiteSpace(row[3].ToString()))
                    {
                        GoalEngineDTO goalEngineDTO;


                        try
                        {
                            goalEngineDTO      = GoalEngineService.Instance.GetByRunIdAndMetricId(run.Id, metric.Id);
                            goalEngineDTO.Goal = float.Parse(row[3].Value.ToString());
                        }
                        catch (Exception e)
                        {
                            goalEngineDTO = new GoalEngineDTO
                            {
                                RunId      = run.Id,
                                MetricId   = metric.Id,
                                MetricIcon = metric.Icon,
                                MetricName = metric.Name,
                                Goal       = float.Parse(row[3].Value.ToString()),
                                ItemId     = "",
                                Percentage = 0
                            };
                        }

                        goalEngineDTO.Goal = float.Parse(row[3].Value.ToString());
                        goalEngineDTO      = GoalEngineService.Instance.CreateOrUpdate(goalEngineDTO);
                    }
                }

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

                string emailFrom = ParameterCache.Get("SUPPORT_EMAIL");
                string subject   = countErrors >= 1 ? "Erros ao subir planilha de metas" : "O lançamento de metas 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.DenyGet));
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);

                return(Json(new { Success = false }, JsonRequestBehavior.DenyGet));
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Salva as informações do resultado via arquivo
        /// </summary>
        /// <param name="goalArchive"></param>
        /// <param name="episodeId"></param>
        /// <returns></returns>
        private ActionResult SaveGoalArchiveSyngenta(HttpPostedFileBase goalArchive)
        {
            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;

            int CODIGO_TERRITORIO = 0;
            int RESPONSAVEL       = 1;
            int EMAIL             = 2;
            int REG         = 3;
            int PROMOxISNT  = 4;
            int DIA         = 5;
            int CULTURA     = 6;
            int NOME_PADRAO = 7;
            int TOTAL       = 8;

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

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

                var archive = new ExcelQueryFactory(path);

                var rows = from x in archive.WorksheetRange("A1", "I" + rowsCount, "META")
                           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[TOTAL].ToString().Equals("0"))
                    {
                        continue;
                    }

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



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

                    PlayerEngineDTO player;

                    try
                    {
                        player = PlayerEngineService.Instance.GetByEmail(row[EMAIL].Value.ToString());
                    }
                    catch (Exception e)
                    {
                        errors += "Erro na coluna " + (EMAIL + 1) + " da linha " + line + "<br/>";
                        countErrors++;
                        continue;
                    }

                    EpisodeEngineDTO episode;

                    try
                    {
                        episode = EpisodeEngineService.Instance.FindByGameIdAndName(gameId, row[CULTURA]);
                    }
                    catch (Exception e)
                    {
                        errors += "Erro na coluna 5 da linha " + line + "<br/>";
                        countErrors++;
                        continue;
                    }

                    try
                    {
                        team = TeamEngineService.Instance.GetByEpisodeIdAndNick(episode.Id, row[REG].Value.ToString());
                    }
                    catch (Exception e)
                    {
                        errors += "Erro na coluna 3 da linha " + line + "<br/>";
                        countErrors++;
                        continue;
                    }

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


                    if (!string.IsNullOrWhiteSpace(row[0].ToString()) && !string.IsNullOrWhiteSpace(row[1].ToString()) && !string.IsNullOrWhiteSpace(row[2].ToString()) && !string.IsNullOrWhiteSpace(row[3].ToString()))
                    {
                        GoalEngineDTO goalEngineDTO;


                        try
                        {
                            goalEngineDTO      = GoalEngineService.Instance.GetByRunIdAndMetricId(run.Id, metric.Id);
                            goalEngineDTO.Goal = Int32.Parse(row[TOTAL].Value.ToString());
                        }
                        catch (Exception e)
                        {
                            goalEngineDTO = new GoalEngineDTO
                            {
                                RunId      = run.Id,
                                MetricId   = metric.Id,
                                MetricIcon = metric.Icon,
                                MetricName = metric.Name,
                                Goal       = Int32.Parse(row[TOTAL].Value.ToString()),
                                ItemId     = "",
                                Percentage = 0
                            };
                        }

                        goalEngineDTO = GoalEngineService.Instance.CreateOrUpdate(goalEngineDTO);
                    }
                }

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

                string emailFrom = ParameterCache.Get("SUPPORT_EMAIL");
                string subject   = countErrors >= 1 ? "Erros ao subir planilha de metas" : "O lançamento de metas 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.DenyGet));
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);

                return(Json(new { Success = false }, JsonRequestBehavior.DenyGet));
            }
        }
Esempio n. 11
0
 public RunEngineDTO CreateOrUpdate(RunEngineDTO run)
 {
     return(PostDTO <RunEngineDTO>(ref run));
 }
        /// <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));
            }
        }
        /// <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 SaveResultArchiveSyngenta(HttpPostedFileBase resultsArchive)
        {
            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;

            int CODIGO_TERRITORIO = 0;
            int RESPONSAVEL       = 1;
            int EMAIL             = 2;
            int REG         = 3;
            int PROMOxISNT  = 4;
            int DIA         = 5;
            int CULTURA     = 6;
            int NOME_PADRAO = 7;
            int TOTAL       = 8;

            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", "I" + rowsCount, "REALIZADO")
                           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[TOTAL].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(gameId, row[NOME_PADRAO].ToString());
                    }
                    catch (Exception e)
                    {
                        errors += "Erro na coluna " + (NOME_PADRAO + 1) + " da linha " + line + "<br/>";
                        countErrors++;
                        continue;
                    }

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

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

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

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

                    EpisodeEngineDTO episode;

                    try
                    {
                        episode = EpisodeEngineService.Instance.FindByGameIdAndName(gameId, row[CULTURA]);
                    }
                    catch (Exception e)
                    {
                        errors += "Erro na coluna " + (CULTURA + 1) + " da linha " + line + "<br/>";
                        countErrors++;
                        continue;
                    }

                    try
                    {
                        team = TeamEngineService.Instance.GetByEpisodeIdAndNick(episode.Id, row[REG]);
                    }
                    catch (Exception e)
                    {
                        errors += "Erro na coluna " + (REG + 1) + " 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;
                    }

                    float oldResult;

                    try
                    {
                        oldResult = RunMetricEngineService.Instance.findByRunIdAndMetricId(run.Id, metric.Id, 0, 100000).List.runMetric.Sum(x => x.Points);
                    }
                    catch (Exception e)
                    {
                        oldResult = 0;
                    }

                    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[DIA].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[TOTAL].ToString()) - oldResult;
                            result.Score       = 0;
                            result.Xp          = metric.Xp;
                            result.RunId       = run.Id;
                            result.PlayerId    = worker.ExternalId;

                            if (result.Points > 0)
                            {
                                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));
            }
        }