/// <summary>
        /// Generates the and save weekly report.
        /// </summary>
        /// <param name="enddate">The enddate.</param>
        /// <param name="buildDate">The build date.</param>
        public void GenerateAndSaveWeeklyReport(DateTime enddate, DateTime buildDate)
        {
            var result = new WeeklyReportModel
            {
                VisitSentimentTrend =
                    this.weeklyReportRepository.GetSentiments(
                        this.currentClientUser.UserFilter,
                        enddate)
            };

            var dbRowDataList = this.weeklyReportRepository.GetWeeklyReportCountByHour(
                this.currentClientUser.UserFilter,
                enddate);

            // Generate Daily ReportCountTrend from 24*7 data
            result.ReportCountTrend = new List <TimeCount>();
            var dayHourCounts = dbRowDataList as IList <DayHourCount> ?? dbRowDataList.ToList();

            for (var daySequence = 6; daySequence >= 0; daySequence--)
            {
                var datetime      = new DateTime(enddate.Year, enddate.Month, enddate.Day, 0, 0, 0).AddDays(-daySequence);
                var dayTotalCount = 0;
                foreach (var dbItem in dayHourCounts)
                {
                    if (dbItem.date == datetime)
                    {
                        dayTotalCount += dbItem.Count;
                    }
                }
                result.ReportCountTrend.Add(new TimeCount(datetime.Month + "/" + datetime.Day, dayTotalCount));
            }

            result.VisitCountTrend = new List <TimeCount>();
            try
            {
                result.VisitCountTrend =
                    this.weeklyReportRepository.GetVisitCountTrend(this.currentClientUser.UserFilter, enddate);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }

            try
            {
                result.TopNewsSource = this.weeklyReportRepository.GetTop5NewsSource(
                    this.currentClientUser.UserFilter,
                    enddate);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }

            try
            {
                var ageGenderForSort =
                    this.weeklyReportRepository.GetVisitAgeGenderCount(this.currentClientUser.UserFilter, enddate);

                var list = new List <AgeGenderCount>();
                foreach (var dbItem in ageGenderForSort)
                {
                    var AgeGroup = dbItem.AgeGroup;
                    AgeGroup = AgeGroup.Replace("[", "");
                    AgeGroup = AgeGroup.Replace(")", "");
                    AgeGroup = AgeGroup.Replace(",", "-");

                    list.Add(new AgeGenderCount {
                        AgeGroup = AgeGroup, Gender = dbItem.Gender, Count = dbItem.Count
                    });
                }
                var Comparer = new AgeGenderGroupComparer();
                list.Sort(Comparer);
                result.AgeGenderCount = list;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }

            var data = AnalysisDataConvert.ToCAData(DataType.WEEKLYREPORT, buildDate, result);

            this.caDataManager.SaveCaData(data);
        }
Exemplo n.º 2
0
        public bool ProcessWeeklyReport()
        {
            StringBuilder sb         = new StringBuilder();
            bool          hadErrors  = false;
            Stopwatch     sw         = new Stopwatch();
            Stopwatch     swInternal = new Stopwatch();

            sw.Start();
            try
            {
                List <Mail.Message> messages = new List <Mail.Message>();

                using (var context = ApplicationDbContext.Create())
                {
                    var representatives = context.Representatives
                                          .Where(x => x.UserRepresentativeQuestions.Any(y => y.AnswerToken != null && y.AnswerToken.Processed && y.AnswerToken.Answer == null))
                                          .ToList();

                    foreach (var rep in representatives)
                    {
                        try
                        {
                            swInternal = new Stopwatch();
                            swInternal.Start();
                            var questions = context.UserRepresentativeQuestions
                                            .Where(x => x.RepresentativeID == rep.RepresentativeID)
                                            .Where(x => x.Question.Verified)
                                            .Where(x => x.AnswerToken != null)
                                            .Where(x => x.AnswerToken.Answer == null)
                                            .Include(x => x.Question.Law)
                                            .Include(x => x.Question.Likes)
                                            .Include(x => x.AnswerToken)
                                            .ToList();

                            var questionCounts = questions
                                                 .GroupBy(x => x.QuestionID)
                                                 .Select(x => new { QuestionID = x.Key, Count = x.Count() })
                                                 .ToDictionary(k => k.QuestionID, v => v.Count);

                            var laws = questions
                                       .Select(x => x.Question)
                                       .ToList()
                                       .Select(x => x.Law)
                                       .Where(x => x != null)
                                       .Distinct();

                            var model = new WeeklyReportModel
                            {
                                BaseUrl          = GetBaseUrl(),
                                FirstName        = rep.FirstName,
                                LastName         = rep.LastName,
                                RepresentativeId = rep.RepresentativeID,
                                Laws             = laws.Select(x => new LawModel
                                {
                                    LawID     = x.LawID,
                                    Title     = x.Title,
                                    Questions = questions
                                                .Select(y => new { Question = y.Question, Token = y.AnswerToken })
                                                .Where(y => y.Question.LawID != null && y.Question.LawID == x.LawID)
                                                .Select(y => new QuestionModel
                                    {
                                        QuestionId   = y.Question.QuestionID,
                                        AskedOn      = y.Question.CreateTimeUtc,
                                        QuestionText = y.Question.Text,
                                        AnswerToken  = y.Token.Token,
                                        VotesUp      = y.Question.Likes.Count(z => z.Vote),
                                        VotesDown    = y.Question.Likes.Count(z => !z.Vote),
                                        AskedCount   = questionCounts[y.Question.QuestionID]
                                    })
                                                .ToList()
                                }).ToList(),
                                Questions = questions
                                            .Where(x => x.Question.Law == null)
                                            .Select(x => new QuestionModel
                                {
                                    QuestionId   = x.QuestionID,
                                    QuestionText = x.Question.Text,
                                    AskedOn      = x.Question.CreateTimeUtc,
                                    AnswerToken  = x.AnswerToken.Token,
                                    VotesUp      = x.Question.Likes.Count(z => z.Vote),
                                    VotesDown    = x.Question.Likes.Count(z => !z.Vote),
                                    AskedCount   = questionCounts[x.Question.QuestionID]
                                })
                                            .ToList()
                            };

                            messages.Add(new Mail.Message
                            {
                                To      = GetRepEmail(rep.Email),
                                Bcc     = GetBccDeliveryList(),
                                Subject = ApplyMacros(GetWeeklyEmailSubject(), model),
                                Body    = ApplyMacros(GetWeeklyEmailBody(), model)
                            });

                            swInternal.Stop();
                            sb.AppendLine(string.Format("Weekly email sent to {0}  in {1}ms", rep.DisplayName, swInternal.ElapsedMilliseconds));
                        }
                        catch (Exception ex)
                        {
                            sb.AppendLine(string.Format("Failed to send weekly email to {0} with exception: {1}{2} ", rep.DisplayName, Environment.NewLine, ex));
                            hadErrors = true;
                        }
                    }
                }


                Mail.EmailSender.SendEmails(messages);
            }
            catch (Exception ex)
            {
                sb.AppendLine("Failed to send weekly emails = " + ex.ToString());
            }


            sw.Stop();
            sb.AppendLine(string.Format("Processing completed in {0}ms", sw.ElapsedMilliseconds));

            if (hadErrors)
            {
                sb.AppendLine("Errors Found !!!");
                logger.Error(sb.ToString());
            }
            else
            {
                sb.AppendLine("No Errors Found.");
                logger.Warn(sb.ToString());
            }


            return(hadErrors);
        }