예제 #1
0
 public LiteUser SaveTeamMember(LiteUser teamMember)
 {
     if (teamMember.AccessibleAreaIds == null || teamMember.AccessibleAreaIds.Count() < 1)
     {
         throw new BusinessException(SelectAtLeastOneReportingArea);
     }
     return(_companyRepository.SaveTeamMember(teamMember));
 }
예제 #2
0
 public void InitializeMetrics(LiteUser currentUser)
 {
     if (_metrics == null)
     {
         // Fetch from the database and initialize the map.
         var allMetrics = _metricManager.GetList(new { CompanyId = currentUser.CompanyId });
         _metrics = currentUser.IsCompanyAdmin ? allMetrics : allMetrics.Where(m => m.AreaId.HasValue && currentUser.AccessibleAreaIds.Contains(m.AreaId.Value));
     }
 }
예제 #3
0
 public void InitializeGoals(LiteUser currentUser)
 {
     if (_goals == null)
     {
         // Fetch from the database and initialize the map.
         var allgoals = _goalManager.GetList(new { CompanyId = currentUser.CompanyId });
         _goals = currentUser.IsCompanyAdmin ? allgoals : allgoals.Where(g => g.AreaId.HasValue && currentUser.AccessibleAreaIds.Contains(g.AreaId.Value));
     }
 }
예제 #4
0
        public void AddTeamMember(LiteUser teamMember, string welcomeMessage, string addedByEmail, string registerUrl)
        {
            if (teamMember.AccessibleAreaIds == null || teamMember.AccessibleAreaIds.Count() < 1)
            {
                throw new BusinessException(SelectAtLeastOneReportingArea);
            }
            var status      = _companyRepository.AddTeamMember(teamMember);
            var thisCompany = _companyRepository.Get(teamMember.CompanyId);
            TextReplacements textReplacements;
            string           subject;

            switch (status)
            {
            case 0:
                throw new BusinessException("That email address is already in use by your team");

            case 1:
                // existing user added, notify
                subject = string.Format("{0} - Access Granted", thisCompany.Name);

                textReplacements = new TextReplacements
                {
                    Subject        = subject,
                    CompanyName    = thisCompany.Name,
                    WelcomeMessage = welcomeMessage,
                    OwnerEmail     = addedByEmail,
                    ToEmail        = teamMember.Email,
                    RecipientEmail = teamMember.Email
                };

                _genericEmailManager.SendFromTemplate(teamMember.Email, subject, TextTemplate.TeamGrantAccessEmail, textReplacements);
                break;

            case 2:
                // new user: create invite and send registration link
                var invite       = _companyRepository.AddTeamMemberInvite(teamMember);
                var registerLink = registerUrl.Replace(InviteCode, Uri.EscapeDataString(invite.UniqueId.ToString()));
                registerLink = registerLink.Replace(InviteEmail, Uri.EscapeDataString(teamMember.Email));
                subject      = string.Format("{0} - Invitation", thisCompany.Name);

                textReplacements = new TextReplacements
                {
                    Subject        = subject,
                    CompanyName    = thisCompany.Name,
                    WelcomeMessage = welcomeMessage,
                    OwnerEmail     = addedByEmail,
                    ToEmail        = teamMember.Email,
                    RecipientEmail = teamMember.Email,
                    RegisterLink   = new Uri(new Uri(ConfigUtil.BaseAppUrl), registerLink).AbsoluteUri
                };
                _genericEmailManager.SendFromTemplate(teamMember.Email, subject, TextTemplate.TeamInvitationEmail, textReplacements);
                break;
            }
        }
예제 #5
0
 public void SaveProfile(LiteUser user)
 {
     try
     {
         OpenConnection();
         Connection.Execute("UserProfileUpdate", new { user.Id, user.FirstName, user.LastName }, commandType: CommandType.StoredProcedure);
     }
     finally
     {
         CloseConnection();
     }
 }
예제 #6
0
        public string ParseReportEmailBody(LiteUser currentUser, Company company, Report report, Recipient recipient,
                                           ReportEmailBuilder reportEmailBuilder)
        {
            // Get the preview banner if required
            var previewBanner = reportEmailBuilder.SendPreview ? _templateManager.GetTemplateText(TextTemplate.ReportEmailPreviewBanner) : String.Empty;

            // Parse the email body defined by the user.
            // Trim line breaks after variables (since we use the <pre> tag.
            var userBody = new StringBuilder(string.Format("{0}{1}", previewBanner, reportEmailBuilder.ReportEmailBody));

            userBody.Replace("[COMPANY_NAME]" + Environment.NewLine, "[COMPANY_NAME]");
            userBody.Replace("[REPORT_TITLE]" + Environment.NewLine, "[REPORT_TITLE]");
            userBody.Replace("[SUMMARY]" + Environment.NewLine, "[SUMMARY]");
            userBody.Replace("[REPORT_BUTTON]" + Environment.NewLine, "[REPORT_BUTTON]");
            userBody.Replace("[REPORT_DISCUSSION]" + Environment.NewLine, "[REPORT_DISCUSSION]");

            // Generate the report link.
            var reportLink = string.Format("{0}reports/{1}", ConfigUtil.BaseAppUrl, report.UniqueId);

            if (reportEmailBuilder.ReportEmailGuid != null)
            {
                reportLink = string.Format("{0}reports/email/{1}/{2}", ConfigUtil.BaseAppUrl, reportEmailBuilder.ReportEmailGuid, reportEmailBuilder.ReportEmailViewKey);
            }

            // Replace the placeholders with the values.
            userBody.Replace("[COMPANY_NAME]", GetReportEmailPart(TextTemplate.ReportEmailCompanyNameSnippet, company.Name));
            userBody.Replace("[REPORT_TITLE]", GetReportEmailPart(TextTemplate.ReportEmailTitleSnippet, company.ReportTitle));
            userBody.Replace("[SUMMARY]", GetReportEmailPart(TextTemplate.ReportEmailSummarySnippet, report.Summary));
            userBody.Replace("[REPORT_BUTTON]", GetReportEmailPart(TextTemplate.ReportEmailButtonSnippet, reportLink));
            userBody.Replace("[MONTH]", report.Date.ToString("MMMM", CultureInfo.InvariantCulture));
            userBody.Replace("[YEAR]", report.Date.Year.ToString(CultureInfo.InvariantCulture));
            userBody.Replace("[FIRSTNAME]", recipient.FirstName);
            userBody.Replace("[LASTNAME]", recipient.LastName);
            userBody.Replace("[SENDER_FIRSTNAME]", currentUser.FirstName);
            userBody.Replace("[SENDER_LASTNAME]", currentUser.LastName);
            string discussionText = string.Empty;

            if (reportEmailBuilder.EnableCommenting && reportEmailBuilder.IsSubscriptionActive)
            {
                discussionText = GetReportEmailPart(TextTemplate.ReportEmailDiscussion, ConfigUtil.BaseAppUrl);
            }
            userBody.Replace("[REPORT_DISCUSSION]", discussionText);

            // Replace the final
            var template = _templateManager.GetTemplateText(TextTemplate.ReportEmail);

            template = template.Replace("[BODY]", userBody.ToString());

            return(template);
        }
예제 #7
0
        public bool IsUserAdminOfCompany(LiteUser currentUser, int companyId)
        {
            if (currentUser == null)
            {
                return(false);
            }

            if (currentUser.CompanyId == companyId)
            {
                return(true);
            }

            return(false);
        }
예제 #8
0
        public int AddTeamMember(LiteUser teamMember)
        {
            try
            {
                var areaData = ConversionUtil.IntArrayToDataTable(teamMember.AccessibleAreaIds);

                OpenConnection();
                return(Connection.Query <int>("CompanyAddTeamMember", new { CompanyId = teamMember.CompanyId, emailAddress = teamMember.Email, accessibleAreaIds = areaData, canViewReports = teamMember.CanViewReports }, commandType: CommandType.StoredProcedure).First());
            }
            finally
            {
                CloseConnection();
            }
        }
예제 #9
0
        private void NotifyReportingAreaUpdated(LiteUser currentUser, ReportArea reportArea, IEnumerable <Webhook> webhooks, string url)
        {
            var payload = new WebhookPayload {
                Text = string.Format("{0} updated a Reporting Area", currentUser.DisplayName)
            };

            payload.Attachments.Add(new WebhookPayloadAttachment
            {
                Title = string.Format("{0}, {1}", reportArea.AreaName, reportArea.ReportDate.ToString("MMMM \\'yy")),
                Text  = string.Format("{0}\n<{1}{2}|Go to Report>", reportArea.Summary, ConfigUtil.BaseAppUrl, url)
            });

            PostMessages(webhooks, payload);
        }
예제 #10
0
        public LiteUser SaveTeamMember(LiteUser teamMember)
        {
            try
            {
                //only need to update area permissions
                var areaData = ConversionUtil.IntArrayToDataTable(teamMember.AccessibleAreaIds);
                OpenConnection();
                Connection.Execute("CompanyTeamMemberPermissionsUpdate", new { companyId = teamMember.CompanyId, userGuid = teamMember.UniqueId, accessibleAreaIds = areaData, canViewReports = teamMember.CanViewReports }, commandType: CommandType.StoredProcedure);

                return(teamMember);
            }
            finally
            {
                CloseConnection();
            }
        }
예제 #11
0
        public IEnumerable <Report> GetReportSummaryList(int companyId, LiteUser currentUser, int totalMetrics)
        {
            const string dateFormat        = "yyyy MMMM";
            var          reportSummaryList = _reportRepository.GetReportSummaryList(companyId).ToList();

            // Remove areas this user can't access
            if (!currentUser.IsCompanyAdmin)
            {
                foreach (var report in reportSummaryList)
                {
                    report.AreaList   = report.AreaList.Where(a => currentUser.AccessibleAreaIds.Contains(a.AreaId)).ToList();
                    report.MetricList = report.MetricList.Where(a => a.AreaId.HasValue && currentUser.AccessibleAreaIds.Contains(a.AreaId.Value)).ToList();
                    report.GoalList   = report.GoalList.Where(a => a.AreaId.HasValue && currentUser.AccessibleAreaIds.Contains(a.AreaId.Value)).ToList();

                    if (report.Status == ReportStatus.InProgress)
                    {
                        // Override status and set it to complete if user has done all of their areas
                        if (report.AreasCompleted == currentUser.AccessibleAreaIds.Count() && report.MetricCount == totalMetrics)
                        {
                            report.Status = ReportStatus.Completed;
                        }
                    }
                }
            }

            // Add missing months.
            var company          = _companyRepository.Get(companyId);
            var companyStartDate = company.StartMonth ?? DateTime.Now;
            var currentDate      = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

            // Setting report date for the months which are in the range of company start date to current date.
            while (companyStartDate <= currentDate)
            {
                if (reportSummaryList.All(r => r.Date.ToString(dateFormat) != companyStartDate.ToString(dateFormat)))
                {
                    // If report for this month not exist, building dummy report
                    reportSummaryList.Add(new Report {
                        CompanyId = company.Id, Date = companyStartDate
                    });
                }

                companyStartDate = companyStartDate.AddMonths(1);
            }


            return(reportSummaryList);
        }
        protected void InitializeMasterLists(LiteUser currentUser)
        {
            ListHelper.InitializeAreas(currentUser);
            ListHelper.InitializeGoals(currentUser);
            ListHelper.InitializeMetrics(currentUser);

            MasterAreas   = ListHelper.GetAreas().ToList();
            MasterGoals   = ListHelper.GetGoals().ToList();
            MasterMetrics = ListHelper.GetMetrics().ToList();

            CompanyMetadata = new CompanyMetadata
            {
                AreaCount   = MasterAreas.Count,
                GoalCount   = MasterGoals.Count,
                MetricCount = MasterMetrics.Count
            };
        }
예제 #13
0
        public Report GetReport(int companyId, DateTime reportDate, LiteUser currentUser = null)
        {
            var report = _reportRepository.GetReport(companyId, reportDate);

            if (report != null && string.IsNullOrWhiteSpace(report.Title))
            {
                report.Title = DefaultReportTitle;
            }

            if (report != null && currentUser != null && !currentUser.IsCompanyAdmin)
            {
                report.MetricList = report.MetricList.Where(m => m.AreaId.HasValue && currentUser.AccessibleAreaIds.Contains(m.AreaId.Value)).ToList();
                report.GoalList   = report.GoalList.Where(g => g.AreaId.HasValue && currentUser.AccessibleAreaIds.Contains(g.AreaId.Value)).ToList();
                report.AreaList   = report.AreaList.Where(g => currentUser.AccessibleAreaIds.Contains(g.AreaId)).ToList();
            }

            return(report);
        }
예제 #14
0
        public CompanyTeamMemberInvite AddTeamMemberInvite(LiteUser teamMember)
        {
            try
            {
                var areaData = ConversionUtil.IntArrayToDataTable(teamMember.AccessibleAreaIds);
                OpenConnection();

                var invite = Connection.Query <CompanyTeamMemberInvite>("CompanyInviteUser", param: new { EmailAddress = teamMember.Email, CompanyId = teamMember.CompanyId, accessibleAreaIds = areaData, canViewReports = teamMember.CanViewReports }, commandType: CommandType.StoredProcedure).First();
                if (invite == null)
                {
                    throw new BusinessException("That email address is already registered");
                }

                return(invite);
            }
            finally
            {
                CloseConnection();
            }
        }
예제 #15
0
        public void SendReports(LiteUser currentUser, Company company, Report report, ReportEmailBuilder reportEmailBuilder)
        {
            var subject = ParseReportEmailSubject(company, report, reportEmailBuilder.ReportEmailSubject);

            reportEmailBuilder.ReportEmailBody = reportEmailBuilder.ReportEmailBody.Replace(Environment.NewLine, "<br>");

            if (reportEmailBuilder.SendPreview)
            {
                var previewRecipient = new Recipient
                {
                    FirstName = reportEmailBuilder.PreviewFirstName,
                    LastName  = reportEmailBuilder.PreviewLastName,
                    Email     = reportEmailBuilder.PreviewAddress
                };
                var body = ParseReportEmailBody(currentUser, company, report, previewRecipient, reportEmailBuilder);

                QueueEmail(company, previewRecipient, subject, body);
            }
            else
            {
                var recipients = reportEmailBuilder.RecipientList.Where(s => s.IsSelected).ToList();
                foreach (var recipient in recipients)
                {
                    // log the email
                    var reportEmail = Create(new ReportEmail
                    {
                        RecipientId = recipient.Id,
                        ReportId    = report.Id,
                        CompanyId   = company.Id,
                        Status      = EmailStatus.Sent
                    });
                    reportEmailBuilder.ReportEmailGuid    = reportEmail.UniqueId;
                    reportEmailBuilder.ReportEmailViewKey = reportEmail.ViewKey;

                    var body = ParseReportEmailBody(currentUser, company, report, recipient, reportEmailBuilder);

                    QueueEmail(company, recipient, subject, body);
                }
            }
        }
예제 #16
0
        public void InitializeAreas(LiteUser currentUser)
        {
            if (_areaMap == null)
            {
                _areaMap = new Dictionary <int, string>();

                if (AllowUnassignedGoalsAndMetrics(currentUser))
                {
                    // add default element
                    _areaMap.Add(-1, "-none-");
                }

                // Fetch from the database and initialize the map.
                var allAreas = _areaManager.GetList(new { CompanyId = currentUser.CompanyId }).OrderBy(x => x.DisplayOrder).ThenBy(i => i.Id);

                _areas = allAreas.Where(a => currentUser.AccessibleAreaIds.Contains(a.Id));

                foreach (var area in _areas)
                {
                    _areaMap.Add(area.Id, area.Name);
                }
            }
        }
예제 #17
0
        public IEnumerable <ReportGoalView> GetReportGoals(int companyId, DateTime reportDate, LiteUser currentUser = null)
        {
            var results = _reportGoalRepository.GetReportGoals(companyId, reportDate);

            if (results != null && currentUser != null && !currentUser.IsCompanyAdmin)
            {
                results = results.Where(m => m.AreaId.HasValue && currentUser.AccessibleAreaIds.Contains(m.AreaId.Value)).ToList();
            }
            return(results);
        }
예제 #18
0
        public void ReportingAreaUpdated(int companyId, LiteUser currentUser, ReportArea reportArea, string reportUrl)
        {
            var webhooks = _webhookRepository.GetList(new { CompanyId = companyId, EventReportingAreaUpdated = true });

            Task.Run(() => NotifyReportingAreaUpdated(currentUser, reportArea, webhooks, reportUrl));
        }
예제 #19
0
 private bool AllowUnassignedGoalsAndMetrics(LiteUser currentUser)
 {
     return(currentUser.IsCompanyAdmin);
 }
예제 #20
0
        private void NotifyParticipantsOfNewComment(Discussion discussion, Comment newComment, LiteUser owner)
        {
            // Check if there are authors in this discussion part from the owner and the author of this new comment.
            if (discussion.Comments.Count(c => c.AuthorEmail != owner.Email && c.AuthorEmail != newComment.AuthorEmail) == 0)
            {
                //there's no one to notify
                return;
            }

            var subject = string.Format("{0} replied to your comment", newComment.AuthorName);

            var textReplacements = new TextReplacements
            {
                Subject                  = subject,
                FullName                 = newComment.AuthorName,
                Text                     = subject,
                DiscussionTitle          = discussion.Title,
                ReportPeriodName         = discussion.ReportDate.ToString("MMMM \\'yy", CultureInfo.InvariantCulture),
                Comment                  = newComment.Text,
                GravatarUrl              = GravatarHelper.GravatarHelper.CreateGravatarUrl(newComment.AuthorEmail, 96, ConfigUtil.DefaultGravatarImage, null, null, null),
                ExcludePasswordResetLink = true,
                ReportLink               = string.Format("{0}reports/{1}?discuss={2}&requireLogin=true", ConfigUtil.BaseAppUrl, discussion.ReportGuId, discussion.DiscussionName),
            };

            var participants = discussion.Comments.Where(c => c.AuthorEmail != owner.Email && c.AuthorEmail != newComment.AuthorEmail).Select(c => c.AuthorEmail).Distinct();

            foreach (var email in participants)
            {
                var reportEmail = _reportEmailManager.GetByEmailAddress(discussion.CompanyId, discussion.ReportId, email);
                if (reportEmail != null)
                {
                    textReplacements.ReportLink = string.Format("{0}reports/email/{1}/{2}?discuss={3}", ConfigUtil.BaseAppUrl, reportEmail.UniqueId, reportEmail.ViewKey, discussion.DiscussionName);
                }

                _genericEmailManager.SendFromTemplate(email, subject, TextTemplate.ReportCommentNotificationEmail, textReplacements);
            }
        }
예제 #21
0
        private void NotifyOwnerOfNewComment(Discussion discussion, Comment newComment, LiteUser owner, bool hasWebhooks)
        {
            var subject = string.Format("{0} commented on your report", newComment.AuthorName);

            var textReplacements = new TextReplacements
            {
                Subject          = subject,
                FullName         = newComment.AuthorName,
                Text             = subject,
                DiscussionTitle  = discussion.Title,
                ReportPeriodName = discussion.ReportDate.ToString("MMMM \\'yy", CultureInfo.InvariantCulture),
                Comment          = newComment.Text,
                GravatarUrl      = GravatarHelper.GravatarHelper.CreateGravatarUrl(newComment.AuthorEmail, 96, ConfigUtil.DefaultGravatarImage, null, null, null),
                ReportLink       = string.Format("{0}reports/{1}?discuss={2}&requireLogin=true", ConfigUtil.BaseAppUrl, discussion.ReportGuId, discussion.DiscussionName),
                PromoteSlack     = !hasWebhooks
            };

            _genericEmailManager.SendFromTemplate(owner.Email, subject, TextTemplate.ReportCommentNotificationEmail, textReplacements);
        }
예제 #22
0
        public void SaveProfile(IOwinContext context, LiteUser user)
        {
            var userStore = new AppUserStore <AppUser>(context.Get <IdentityDatabaseContext <AppUser, IdentityRole> >());

            userStore.SaveProfile(user);
        }
        public bool InitializeContext()
        {
            if (_companyId > 0)
            {
                // Already initialised.
                return(true);
            }

            // Get the user id from the identity and get the user attributes from the database.
            var userId = User.Identity.GetUserId <int>();

            CurrentUser = UserManager.GetUserAttributes(HttpContext.GetOwinContext(), userId);

            // Exit if the user is not found.
            if (CurrentUser == null)
            {
                return(false);
            }

            // Initialize the fields.
            _companyId             = CurrentUser.CompanyId;
            CompanyName            = CurrentUser.Company;
            LogoPath               = string.IsNullOrEmpty(CurrentUser.LogoPath) ? ConfigUtil.DefaultLogoUrl : CurrentUser.LogoPath;
            IsCompanyAdmin         = CurrentUser.IsCompanyAdmin;
            IsUserAdmin            = CurrentUser.IsAdmin;
            SubscriptionStatus     = CurrentUser.SubscriptionStatus;
            SubscriptionExpiryDate = CurrentUser.SubscriptionExpiryDate;
            IsSubscriptionActive   = ConfigUtil.FreeAccessToPremiumFeatures || CurrentUser.SubscriptionExpiryDate >= DateTime.UtcNow.Date;
            HasValidSubscription   = CurrentUser.HasValidSubscription;
            OtherCompanies         = CurrentUser.OtherCompanies;

            // Show trial banners if trial/cancelled and has no subscription set up
            UnconvertedTrial = ConfigUtil.FreeAccessToPremiumFeatures ? false :
                               ((SubscriptionStatus == SubscriptionStatus.Trialing || SubscriptionStatus == SubscriptionStatus.Cancelled) &&
                                !HasValidSubscription && // No Stripe subscription Id
                                IsSubscriptionActive); // Expiry date not yet reached


            // Throw a 404 if admin access is required and user is not an admin.
            if (_adminAccessOnly && !IsUserAdmin)
            {
                throw new HttpException(404, "Invalid URL!");
            }

            // Throw a 403 if owner access is required and user is not an owner.
            if (_ownerAccessOnly && !IsCompanyAdmin)
            {
                throw new HttpException(403, "Forbidden");
            }

            ViewBag.CompanyName          = CompanyName;
            ViewBag.CompanyId            = _companyId;
            ViewBag.LogoPath             = LogoPath;
            ViewBag.IsCompanyAdmin       = IsCompanyAdmin;
            ViewBag.IsAdmin              = IsUserAdmin;
            ViewBag.OtherCompanies       = OtherCompanies;
            ViewBag.IsSubscriptionActive = IsSubscriptionActive;
            ViewBag.HasValidSubscription = HasValidSubscription;
            ViewBag.UnconvertedTrial     = UnconvertedTrial;
            ViewBag.AcceptedLatestTerms  = CurrentUser.AcceptedLatestTerms;

            return(true);
        }