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")); }
public ActionResult Details(string episodeId, string metricId, string teamId, string playerId) { MetricEngineDTO metric = MetricEngineService.Instance.GetById(metricId); metric.Icon = metric.Icon.Replace("_", "-"); ViewBag.EpisodeId = episodeId; ViewBag.TeamId = teamId; ViewBag.PlayerId = playerId; 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("Detail", metric)); }
public ImplantationDTO() { Episode = new EpisodeEngineDTO(); WorkerType = new WorkerTypeEntity(); Worker = new WorkerDTO(); Team = new TeamEngineDTO(); Metric = new MetricEngineDTO(); Goal = new List <GoalEngineDTO>(); }
public ActionResult Index(string metricId) { MetricEngineDTO metric = MetricEngineService.Instance.GetById(metricId); ViewBag.MetricId = metricId; ViewBag.MetricName = metric.Name; ViewBag.Icon = "fa " + metric.Icon.Replace("_", "-"); ViewBag.NumberOfFunctions = WorkerTypeMetricRepository.Instance.GetCountFromMetric(metricId); ViewBag.NumberOfFunctionsToAssociate = WorkerTypeMetricRepository.Instance.GetCountToAssociateFromMetric(metricId, CurrentFirm.ExternalId); return(View()); }
public ActionResult Create() { MetricEngineDTO metric = new MetricEngineDTO(); ViewBag.Icons = Enum.GetValues(typeof(Icons)).Cast <Icons>().Select(i => new SelectListItem { Selected = metric.Icon == i.ToString().Replace("_", "-") ? true : false, Text = i.GetType().GetMember(i.ToString()).First().GetCustomAttribute <DisplayAttribute>().Name, Value = i.ToString().Replace("_", "-") }).ToList(); ViewBag.WorkerTypes = WorkerTypeRepository.Instance.GetAllByGameId(CurrentFirm.ExternalId); return(PartialView("_Edit", metric)); }
public ActionResult Save(List <GoalEngineDTO> goalList) { try { using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required)) { foreach (GoalEngineDTO goal in goalList) { if (goal.Id == null && goal.Goal >= 0) { MetricEngineDTO metric = MetricEngineService.Instance.GetById(goal.MetricId); GoalEngineDTO goalEngine = new GoalEngineDTO { Goal = goal.Goal, MetricIcon = metric.Icon, MetricId = metric.Id, MetricName = metric.Name, RunId = goal.RunId }; GoalEngineService.Instance.CreateOrUpdate(goalEngine); } else if (goal.Goal >= 0) { GoalEngineDTO goalEngine = GoalEngineService.Instance.GetByRunIdAndMetricId(goal.RunId, goal.MetricId); goalEngine.Goal = goal.Goal; GoalEngineService.Instance.CreateOrUpdate(goalEngine); } } Success("Associação feita com sucesso."); scope.Complete(); } } catch (Exception ex) { Logger.LogException(ex); Error("Ocorreu um erro ao tentar adicionar uma meta.", ex); } return(Redirect("/admin/metas")); }
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")); }
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)); }
/// <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)); } }
/// <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)); } }
public MetricEngineDTO CreateOrUpdate(MetricEngineDTO metric) { return(PostDTO <MetricEngineDTO>(ref metric)); }
public List <LocationDTO> MapPointsByRunsAndMetric(List <RunEngineDTO> runners, MetricEngineDTO metric) { using (WebClient client = GetClient()) { try { LocationParamDTO dto = new LocationParamDTO(); dto.Metrics = metric; dto.Runners = runners; string response = client.UploadString(ENGINE_API + "mapPointsByRunsAndMetric", "POST", JsonSerialize(ref dto)); return(JsonDeserialize <List <LocationDTO> >(response)); } catch (Exception e) { throw e; } } }
public ActionResult Save(MetricEngineDTO metric, List <CheckBoxValue> checkBoxes) { try { if (metric.GameId == "" || metric.GameId == null) { metric.GameId = CurrentFirm.ExternalId; } if (ModelState.IsValid) { ValidateModel(metric); MetricEngineDTO newMetric = MetricEngineService.Instance.CreateOrUpdate(metric); List <int> workerTypeMetrics = WorkerTypeMetricRepository.Instance.GetAllWorkerTypesByMetricId(newMetric.Id).Select(x => x.WorkerTypeId).ToList(); foreach (CheckBoxValue checkBox in checkBoxes) { if (checkBox.Checked && !workerTypeMetrics.Contains(checkBox.Value)) { WorkerTypeMetricEntity wtm = WorkerTypeMetricRepository.Instance.CreateWorkerTypeMetric(new WorkerTypeMetricEntity { MetricExternalId = newMetric.Id, Status = GenericStatus.ACTIVE, UpdatedBy = CurrentUserId, WorkerTypeId = checkBox.Value }); } else if (!checkBox.Checked && workerTypeMetrics.Contains(checkBox.Value)) { WorkerTypeMetricEntity toRemove = WorkerTypeMetricRepository.Instance.GetByWorkerTypeIdAndMetricId(checkBox.Value, newMetric.Id); WorkerTypeMetricRepository.Instance.Remove(toRemove); } } if (newMetric == null) { throw new Exception("."); } Success("Metrica atualizada com sucesso."); } else { ViewBag.Icons = Enum.GetValues(typeof(Icons)).Cast <Icons>().Select(i => new SelectListItem { Selected = metric.Icon == i.ToString().Replace("_", "-") ? true : false, Text = i.GetType().GetMember(i.ToString()).First().GetCustomAttribute <DisplayAttribute>().Name, Value = i.ToString().Replace("_", "-") }).ToList(); ViewBag.WorkerTypes = WorkerTypeRepository.Instance.GetAllByGameId(CurrentFirm.ExternalId); ModelState.AddModelError("", "Alguns campos são obrigatórios para salvar a Métrica."); return(PartialView("_Edit", metric)); } } catch (Exception ex) { Logger.LogException(ex); Error("Erro ao atualizar metrica" + ex.Message); } 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)); } }
/// <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)); } }