Esempio n. 1
0
        public ActionResult ConfirmVolunteerSlots(VolunteerModel m)
        {
            m.UpdateCommitments();
            if (m.SendEmail || !m.IsLeader)
            {
                List <Person> Staff = null;
                Staff = CurrentDatabase.StaffPeopleForOrg(m.OrgId);
                var staff = Staff[0];

                var summary = m.Summary(this);
                var text    = Util.PickFirst(m.Setting.Body, "confirmation email body not found");
                text = text.Replace("{church}", CurrentDatabase.Setting("NameOfChurch", "church"), true);
                text = text.Replace("{name}", m.Person.Name, true);
                text = text.Replace("{date}", DateTime.Now.ToString("d"), true);
                text = text.Replace("{email}", m.Person.EmailAddress, true);
                text = text.Replace("{phone}", m.Person.HomePhone.FmtFone(), true);
                text = text.Replace("{contact}", staff.Name, true);
                text = text.Replace("{contactemail}", staff.EmailAddress, true);
                text = text.Replace("{contactphone}", m.Org.PhoneNumber.FmtFone(), true);
                text = text.Replace("{details}", summary, true);
                CurrentDatabase.Email(staff.FromEmail, m.Person, m.Setting.Subject, text);

                CurrentDatabase.Email(m.Person.FromEmail, Staff, "Volunteer Commitments managed", $@"{m.Person.Name} managed volunteer commitments to {m.Org.OrganizationName}<br/>
The following Commitments:<br/>
{summary}");
            }
            ViewData["Organization"] = m.Org.OrganizationName;
            SetHeaders(m.OrgId);
            if (m.IsLeader)
            {
                TempData[Fromcalendar] = true;
                return(View("ManageVolunteer/PickSlots", m));
            }
            return(View("ManageVolunteer/ConfirmVolunteerSlots", m));
        }
Esempio n. 2
0
        public User CreateAccount()
        {
            //var Db = Db;
            if (!person.EmailAddress.HasValue())
            {
                CannotCreateAccount = true;
            }
            else if (person.Users.Any()) // already have account
            {
                if (org == null || org.IsMissionTrip == true)
                {
                    return(null);
                }

                SawExistingAccount = true;
                var user = person.Users.OrderByDescending(uu => uu.LastActivityDate).First();

                var message = CurrentDatabase.ContentHtml("ExistingUserConfirmation", Resource1.CreateAccount_ExistingUser);
                message = message
                          .Replace("{name}", person.Name)
                          .Replace("{host}", CurrentDatabase.CmsHost);
                Log("AlreadyHaveAccount");
                CurrentDatabase.Email(DbUtil.AdminMail, person, "Account information for " + CurrentDatabase.Host, message);
            }
            else
            {
                CreatedAccount = true;
                var user = MembershipService.CreateUser(CurrentDatabase, person.PeopleId);
                Log("SendNewUserEmail");
                AccountModel.SendNewUserEmail(CurrentDatabase, user.Username);
                return(user);
            }
            return(null);
        }
Esempio n. 3
0
        private string DoDonationModifyMessage(string message)
        {
            var p = List[donor ?? 0];

            Transaction.Fund = p.setting.DonationFund();
            var desc = $"{p.person.Name}; {p.person.PrimaryAddress}; {p.person.PrimaryCity}, {p.person.PrimaryState} {p.person.PrimaryZip}";

            if (!Transaction.TransactionId.StartsWith("Coupon") && Transaction.Donate.HasValue)
            {
                p.person.PostUnattendedContribution(CurrentDatabase, Transaction.Donate.Value, p.setting.DonationFundId, desc,
                                                    tranid: Transaction.Id);
                Log("ExtraDonation");
            }
            var subject = GetSubject(p);
            var ma      = donationtext.Match(message);

            if (ma.Success)
            {
                var v = ma.Groups["text"].Value;
                message = donationtext.Replace(message, v);
            }
            message = message.Replace("{donation}", Transaction.Donate.ToString2("N2"));
            // send donation confirmations
            var notifyIds = GetNotifyIds(p);
            var notice    = $"${Transaction.Donate:N2} donation received from {Transaction.FullName(Transaction)} on behalf of {p.person.Name}";

            CurrentDatabase.Email(notifyIds[0].FromEmail, notifyIds, subject + "-donation", notice);
            return(message);
        }
Esempio n. 4
0
        public void ProcessReply(string ans)
        {
            var dt = new DateTime(ticks);
            var i  = (from rr in CurrentDatabase.SubRequests
                      where rr.AttendId == attend.AttendId
                      where rr.RequestorId == person.PeopleId
                      where rr.Requested == dt
                      where rr.SubstituteId == sid
                      select rr).Single();

            if (attend.Commitment == AttendCommitmentCode.SubFound || attend.SubRequests.Any(ss => ss.CanSub == true))
            {
                DisplayMessage = "This substitute request has already been covered. Thank you so much for responding.";
                Log("Covered", i.Requested, i.SubstituteId);
                return;
            }
            i.Responded = DateTime.Now;
            if (ans != "yes")
            {
                DisplayMessage = "Thank you for responding";
                i.CanSub       = false;
                Log("Regrets", i.Requested, i.SubstituteId);
                CurrentDatabase.SubmitChanges();
                return;
            }
            i.CanSub = true;
            Attend.MarkRegistered(CurrentDatabase, i.Substitute.PeopleId, attend.MeetingId, AttendCommitmentCode.Substitute);
            attend.Commitment = AttendCommitmentCode.SubFound;
            Log("Claimed", i.Requested, i.SubstituteId);
            CurrentDatabase.SubmitChanges();

            message = CurrentDatabase.ContentHtml("VolunteerSubConfirm", Resource1.VolSubModel_VolunteerSubConfirm);

            var body = message
                       .Replace("{substitute}", i.Substitute.Name)
                       .Replace("{requestor}", i.Requestor.Name)
                       .Replace("{org}", org.OrganizationName)
                       .Replace("{meetingdate}", $"{attend.MeetingDate:MMM d, yyyy}")
                       .Replace("{meetingtime}", $"{attend.MeetingDate:h:mm tt}");

            // on screen message
            DisplayMessage = $"<p>You have been sent the following email at {Util.ObscureEmail(i.Substitute.EmailAddress)}.</p>\n" + body;

            // email confirmation
            CurrentDatabase.Email(i.Requestor.FromEmail, i.Substitute,
                                  "Volunteer Substitute Commitment for " + org.OrganizationName, body);

            // notify requestor and org notifyids
            var list = CurrentDatabase.PeopleFromPidString(org.NotifyIds).ToList();

            list.Insert(0, i.Requestor);
            CurrentDatabase.Email(i.Substitute.FromEmail, list,
                                  "Volunteer Substitute Commitment for " + org.OrganizationName,
                                  $@"
<p>The following email was sent to {i.Substitute.Name}.</p>
<blockquote>
{body}
</blockquote>");
        }
Esempio n. 5
0
        public void SendNotices()
        {
            var leaders = NoticesToSend();

            foreach (var leader in leaders)
            {
                CurrentDatabase.Email(CurrentDatabase.CurrentUser.Person.FromEmail, leader.Key, null,
                                      CurrentDatabase.Setting("SubjectAttendanceNotices", "Attendance reports are ready for viewing"), leader.Value, false);
            }
            CurrentDatabase.Email(CurrentDatabase.CurrentUser.Person.FromEmail, CurrentDatabase.CurrentUser.Person, null,
                                  "Attendance emails sent", noticelist, false);
        }
Esempio n. 6
0
        public void FinishLaterNotice()
        {
            var registerLink = EmailReplacements.CreateRegisterLink(masterorgid ?? Orgid,
                                                                    $"Resume registration for {Header}");
            var msg = "<p>Hi {first},</p>\n<p>Here is the link to continue your registration:</p>\n" + registerLink;

            Debug.Assert((masterorgid ?? Orgid) != null, "m.Orgid != null");
            var notifyids = CurrentDatabase.NotifyIds((masterorg ?? org).NotifyIds);
            var p         = UserPeopleId.HasValue ? CurrentDatabase.LoadPersonById(UserPeopleId.Value) : List[0].person;

            CurrentDatabase.Email(notifyids[0].FromEmail, p, $"Continue your registration for {Header}", msg);
        }
Esempio n. 7
0
        private void SendSingleConfirmationForOrg(OnlineRegPersonModel p)
        {
            var ts = TransactionSummary();

            CurrentDatabase.SetCurrentOrgId(p.orgid);
            var emailSubject = GetSubject(p);
            var message      = p.GetMessage();
            var details      = "";

            if (message.Contains("{details}"))
            {
                details = p.PrepareSummaryText(CurrentDatabase);
                message = message.Replace("{details}", details);
            }
            var notifyIds = CurrentDatabase.StaffPeopleForOrg(p.org.OrganizationId);
            var notify    = notifyIds[0];

            var location = p.org.Location;

            if (!location.HasValue())
            {
                location = masterorg.Location;
            }

            message = APIOrganization.MessageReplacements(CurrentDatabase, p.person,
                                                          masterorg.OrganizationName, p.org.OrganizationId, p.org.OrganizationName, location, message);

            if (Transaction.Donate > 0 && p == List[donor ?? 0])
            {
                message = DoDonationModifyMessage(message);
            }
            else
            {
                message = donationtext.Replace(message, "");
            }

            // send confirmations
            if (emailSubject != "DO NOT SEND")
            {
                CurrentDatabase.Email(notify.FromEmail, p.person, Util.EmailAddressListFromString(p.fromemail),
                                      emailSubject, message, false);
                Log("SentConfirmation");
            }
            // notify the staff
            CurrentDatabase.Email(Util.PickFirst(p.person.FromEmail, notify.FromEmail),
                                  notifyIds, Header,
                                  $@"{p.person.Name} has registered for {Header}<br/>
Fee paid for this registrant: {p.AmountToPay():C}<br/>
Others in this registration session: {p.GetOthersInTransaction(Transaction)}<br/>
Total Fee paid for this registration session: {ts?.TotPaid:C}<br/>
<pre>{details}</pre>");
        }
        public ActionResult PMMResults()
        {
            string req = Request["request"];

            int iBillingReference = 0;
            int iReportID         = 0;

            string sReportLink = "";
            string sOrderID    = "";

            bool bHasAlerts = false;

            XDocument xd = XDocument.Parse(req, LoadOptions.None);

            iReportID         = Int32.Parse(xd.Root.Element("ReportID").Value);
            iBillingReference = Int32.Parse(xd.Root.Element("Order").Element("BillingReferenceCode").Value);

            if (xd.Root.Element("Order").Element("Alerts") != null)
            {
                bHasAlerts = true;
            }

            sReportLink = xd.Root.Element("Order").Element("ReportLink").Value;
            sOrderID    = xd.Root.Element("Order").Element("OrderDetail").Attribute("OrderId").Value;

            var check = (from e in CurrentDatabase.BackgroundChecks
                         where e.Id == iBillingReference
                         select e).Single();

            if (check != null)
            {
                check.Updated    = DateTime.Now;
                check.ReportID   = iReportID;
                check.ReportLink = sReportLink;
                check.StatusID   = 3;
                if (bHasAlerts)
                {
                    check.IssueCount = 1;
                }

                CurrentDatabase.SubmitChanges();

                CurrentDatabase.Email(DbUtil.AdminMail, check.User, "TouchPoint Notification: Background Check Complete", "A scheduled background check has been completed for " + check.Person.Name);
            }

            //System.IO.File.WriteAllText(@"C:\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt", req);

            return(Content("<?xml version=\"1.0\" encoding=\"utf-8\"?><OrderXML><Success>TRUE</Success></OrderXML>"));
        }
Esempio n. 9
0
        private string SendAnEmail()
        {
            if (person == null)
            {
                return(GetNoPersonMessage());
            }
            row.Args = $"{{ \"EmailId\": \"{action.EmailId}\"}}";
            if (action.EmailId == null)
            {
                return(GetError($"Email Draft not found for id {action.EmailId}"));
            }
            var email = CurrentDatabase.ContentFromID(action.EmailId.Value);

            CurrentDatabase.Email(DbUtil.AdminMail, person, email.Title, email.Body);
            return(GetActionReplyMessage());
        }
        public ActionResult PMMResults()
        {
            string req = Request["request"];

            int reportID = 0;

            string reportLink       = "";
            string orderID          = "";
            string billingReference = "";

            bool hasAlerts = false;

            XDocument xmldoc = XDocument.Parse(req, LoadOptions.None);

            reportID         = int.Parse(xmldoc.Root.Element("ReportID").Value);
            billingReference = xmldoc.Root.Element("Order").Element("BillingReferenceCode").Value;

            if (xmldoc.Root.Element("Order").Element("Alerts") != null)
            {
                hasAlerts = true;
            }

            reportLink = xmldoc.Root.Element("Order").Element("ReportLink").Value;
            orderID    = xmldoc.Root.Element("Order").Element("OrderDetail").Attribute("OrderId").Value;

            var check = (from e in CurrentDatabase.BackgroundChecks
                         where e.ReportID == reportID
                         select e).SingleOrDefault();

            if (check != null)
            {
                check.Updated    = DateTime.Now;
                check.ReportID   = reportID;
                check.ReportLink = reportLink;
                check.StatusID   = 3;
                if (hasAlerts)
                {
                    check.IssueCount = 1;
                }

                CurrentDatabase.SubmitChanges();

                CurrentDatabase.Email(DbUtil.AdminMail, check.User, "TouchPoint Notification: Background Check Complete", "A scheduled background check has been completed for " + check.Person.Name);
            }

            return(Content("<?xml version=\"1.0\" encoding=\"utf-8\"?><OrderXML><Success>TRUE</Success></OrderXML>"));
        }
Esempio n. 11
0
        private void SendAllConfirmations(string message)
        {
            CurrentDatabase.SetCurrentOrgId(org.OrganizationId);
            var subject = GetSubject();
            var amtpaid = Transaction.Amt ?? 0;

            var firstPerson = List[0].person;

            if (user != null)
            {
                firstPerson = user;
            }

            var notifyIds = GetNotifyIds();

            if (subject != "DO NOT SEND")
            {
                CurrentDatabase.Email(notifyIds[0].FromEmail, firstPerson, listMailAddress, subject, message, false);
                Log("SentConfirmations");
            }

            CurrentDatabase.SubmitChanges();
            // notify the staff
            foreach (var p in List)
            {
                var messageNotice = UsedAdminsForNotify
                    ? @"<span style='color:red'>THERE ARE NO NOTIFY IDS ON THIS REGISTRATION!!</span><br/>
<a href='https://docs.touchpointsoftware.com/OnlineRegistration/MessagesSettings.html'>see documentation</a><br/><br/>"
                    : "";

                var detailSection = GetDetailsSection();
                if (ValidateEmailRecipientRegistrant(p.person.Name, detailSection))
                {
                    CurrentDatabase.Email(Util.PickFirst(p.person.FromEmail, notifyIds[0].FromEmail), notifyIds, Header,
                                          $@"{messageNotice}{p.person.Name} has registered for {Header}<br/>{detailSection}<hr>");
                    Log("SentConfirmationsToStaff");
                }
                else
                {
                    CurrentDatabase.LogActivity($"Person ({p.person.Name}) is different from the registrant in the email body. " +
                                                $"The email was not sent.");
                }
            }
        }
Esempio n. 12
0
        public void SendNotices()
        {
            var q = from gm in CurrentDatabase.SMSGroupMembers
                    where gm.GroupID == model.GroupIdInt
                    where gm.ReceiveNotifications == true
                    select gm.User.Person;
            var subject = $"Received Text from {From}";
            var body    = $@"
SMS Group: {groupName}<br>
Received: {row.DateReceived}<br>
From: {person?.Name ?? "name unknown"}<br>
Message: {Body} <a href='{CurrentDatabase.CmsHost}/SmsMessages#{row.Id}'>(view)</a><br>
Auto Reply: {row.ActionResponse}<br><br>";

            foreach (var p in q)
            {
                CurrentDatabase.Email(Util.AdminMail, p, null, subject, body, false);
            }
        }
Esempio n. 13
0
        public ActionResult ConfirmSubscriptions(ManageSubsModel m)
        {
            m.UpdateSubscriptions();

            var Staff = CurrentDatabase.StaffPeopleForOrg(m.masterorgid);

            var msg     = CurrentDatabase.ContentHtml("ConfirmSubscriptions", Resource1.ConfirmSubscriptions);
            var orgname = m.Description();

            msg = msg.Replace("{org}", orgname).Replace("{details}", m.Summary);
            CurrentDatabase.Email(Staff.First().FromEmail, m.person, "Subscription Confirmation", msg);

            CurrentDatabase.Email(m.person.FromEmail, Staff, "Subscriptions managed",
                                  $@"{m.person.Name} managed subscriptions to {m.Description()}<br/>{m.Summary}");

            SetHeaders(m.masterorgid);
            m.Log("Confirm");
            return(View("ManageSubscriptions/Confirm", m));
        }
Esempio n. 14
0
        public ActionResult Resend(int id)
        {
            var email = (from e in CurrentDatabase.EmailQueues
                         where e.Id == id
                         select e).Single();
            var et = email.EmailQueueTos.First();
            var p  = CurrentDatabase.LoadPersonById(et.PeopleId);

            if (email.FinanceOnly == true)
            {
                CurrentDatabase.EmailFinanceInformation(email.FromAddr, p, email.Subject, email.Body);
            }
            else
            {
                CurrentDatabase.Email(email.FromAddr, p, email.Subject, email.Body);
            }

            Util.TempSuccessMessage = "Mail Resent";
            return(RedirectToAction("Details", new { id }));
        }
Esempio n. 15
0
        public ActionResult SaveProgress(OnlineRegModel m)
        {
            m.HistoryAdd("saveprogress");
            if (m.UserPeopleId == null)
            {
                m.UserPeopleId = Util.UserPeopleId;
            }
            m.UpdateDatum();
            var p = m.UserPeopleId.HasValue ? CurrentDatabase.LoadPersonById(m.UserPeopleId.Value) : m.List[0].person;

            if (p == null)
            {
                return(Content("We have not found your record yet, cannot save progress, sorry"));
            }
            if (m.masterorgid == null && m.Orgid == null)
            {
                return(Content("Registration is not far enough along to save, sorry."));
            }

            var msg          = CurrentDatabase.ContentHtml("ContinueRegistrationLink", @"
<p>Hi {first},</p>
<p>Here is the link to continue your registration:</p>
Resume [registration for {orgname}]
").Replace("{orgname}", m.Header);
            var linktext     = Regex.Match(msg, @"(\[(.*)\])", RegexOptions.Singleline).Groups[2].Value;
            var registerlink = EmailReplacements.CreateRegisterLink(m.masterorgid ?? m.Orgid, linktext);

            msg = Regex.Replace(msg, @"(\[.*\])", registerlink, RegexOptions.Singleline);

            var notifyids = CurrentDatabase.NotifyIds((m.masterorg ?? m.org).NotifyIds);

            CurrentDatabase.Email(notifyids[0].FromEmail, p, $"Continue your registration for {m.Header}", msg);

            /* We use Content as an ActionResult instead of Message because we want plain text sent back
             * This is an HttpPost ajax call and will have a SiteLayout wrapping this.
             */
            return(Content(@"
We have saved your progress. An email with a link to finish this registration will come to you shortly.
<input type='hidden' id='SavedProgress' value='true'/>
"));
        }
Esempio n. 16
0
        public ActionResult TestEmail(MassEmailer m)
        {
            m.Body = GetBody(m.Body);
            if (UsesGrammarly(m))
            {
                return Json(new { error = GrammarlyNotAllowed });
            }

            if (TooLarge(m))
            {
                return Json(new { error = TooLargeError });
            }

            if (Util.SessionTimedOut())
            {
                Session["massemailer"] = m;
                return Content("timeout");
            }

            if (m.EmailFroms().Count(ef => ef.Value == m.FromAddress) == 0)
            {
                return Json(new { error = "No email address to send from." });
            }

            m.FromName = m.EmailFroms().First(ef => ef.Value == m.FromAddress).Text;
            var from = Util.FirstAddress(m.FromAddress, m.FromName);
            var p = CurrentDatabase.LoadPersonById(Util.UserPeopleId ?? 0);

            try
            {
                ValidateEmailReplacementCodes(CurrentDatabase, m.Body, from);

                CurrentDatabase.CopySession();
                CurrentDatabase.Email(from, p, null, m.Subject, m.Body, false);
            }
            catch (Exception ex)
            {
                return Json(new { error = ex.Message });
            }
            return Content("Test email sent.");
        }
Esempio n. 17
0
        public void SendOneTimeLink(string from, string url, string subject, string body, string appendQueryString = "")
        {
            var ot = new OneTimeLink
            {
                Id          = Guid.NewGuid(),
                Querystring = $"{divid ?? orgid ?? masterorgid},{PeopleId}"
            };

            //var Db = Db;
            CurrentDatabase.OneTimeLinks.InsertOnSubmit(ot);
            CurrentDatabase.SubmitChanges();

            url = $"{url}{ot.Id.ToCode()}{(!string.IsNullOrWhiteSpace(appendQueryString) ? $"?{appendQueryString}" : string.Empty)}";

            var message = body.Replace("{url}", url, ignoreCase: true);

            message = message.Replace(WebUtility.UrlEncode("{url}"), url, ignoreCase: true);
            message = message.Replace("{name}", person.Name, ignoreCase: true);
            message = message.Replace("{first}", person.PreferredName, ignoreCase: true);

            CurrentDatabase.Email(from, person, subject, message);
        }
Esempio n. 18
0
        public ActionResult SendLink(string id, FormCollection formCollection)
        {
            var li = new LinkInfo(sendlinkSTR, landingSTR, id);

            if (li.error.HasValue())
            {
                return(Message(li.error));
            }

            try
            {
                if (!li.pid.HasValue)
                {
                    throw new Exception("missing peopleid");
                }

                if (!li.oid.HasValue)
                {
                    throw new Exception("missing orgid");
                }

                var queueid  = li.a[2].ToInt();
                var linktype = li.a[3]; // for supportlink, this will also have the goerid
                var q        = (from pp in CurrentDatabase.People
                                where pp.PeopleId == li.pid
                                let org = CurrentDatabase.LoadOrganizationById(li.oid)
                                          select new { p = pp, org }).Single();

                if (q.org == null && CurrentDatabase.Host == "trialdb")
                {
                    var oid = li.oid + Util.TrialDbOffset;
                    q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.LoadOrganizationById(oid)
                                   select new { p = pp, org }).Single();
                }

                if (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive)
                {
                    throw new Exception("sorry, registration has been closed");
                }

                if (q.org.RegistrationTypeId == RegistrationTypeCode.None)
                {
                    throw new Exception("sorry, registration is no longer available");
                }

                DbUtil.LogActivity($"{sendlinkSTR}{confirmSTR}", li.oid, li.pid);

                var    expires = DateTime.Now.AddMinutes(CurrentDatabase.Setting("SendlinkExpireMinutes", "30").ToInt());
                string action  = (linktype.Contains("supportlink") ? "support" : "register for");
                string minutes = CurrentDatabase.Setting("SendLinkExpireMinutes", "30");
                var    c       = DbUtil.Content("SendLinkMessage");
                if (c == null)
                {
                    c = new Content
                    {
                        Name  = "SendLinkMessage",
                        Title = "Your Link for {org}",
                        Body  = @"
<p>Here is your temporary <a href='{url}'>LINK</a> to {action} {org}.</p>

<p>This link will expire at {time} ({minutes} minutes).
You may request another link by clicking the link in the original email you received.</p>

<p>Note: If you did not request this link, please ignore this email,
or contact the church if you need help.</p>
"
                    };
                    CurrentDatabase.Contents.InsertOnSubmit(c);
                    CurrentDatabase.SubmitChanges();
                }
                var url = EmailReplacements.RegisterLinkUrl(CurrentDatabase,
                                                            li.oid.Value, li.pid.Value, queueid, linktype, expires);
                var subject = c.Title.Replace("{org}", q.org.OrganizationName);
                var msg     = c.Body.Replace("{org}", q.org.OrganizationName)
                              .Replace("{time}", expires.ToString("f"))
                              .Replace("{url}", url)
                              .Replace("{action}", action)
                              .Replace("{minutes}", minutes)
                              .Replace("%7Burl%7D", url);

                var NotifyIds = CurrentDatabase.StaffPeopleForOrg(q.org.OrganizationId);
                CurrentDatabase.Email(NotifyIds[0].FromEmail, q.p, subject, msg); // send confirmation

                return(Message($"Thank you, {q.p.PreferredName}, we just sent an email to {Util.ObscureEmail(q.p.EmailAddress)} with your link..."));
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{sendlinkSTR}{confirmSTR}Error: {ex.Message}", li.oid, li.pid);
                return(Message(ex.Message));
            }
        }
Esempio n. 19
0
        public void SendEmails()
        {
            var tag = CurrentDatabase.FetchOrCreateTag(Util.SessionId, Util.UserPeopleId, CurrentDatabase.NextTagId);

            CurrentDatabase.ExecuteCommand("delete TagPerson where Id = {0}", tag.Id);
            CurrentDatabase.TagAll(pids, tag);
            var dt = new DateTime(ticks);

            foreach (var id in pids)
            {
                var vr = new SubRequest
                {
                    AttendId     = attend.AttendId,
                    RequestorId  = person.PeopleId,
                    Requested    = dt,
                    SubstituteId = id,
                };
                attend.SubRequests.Add(vr);
            }
            CurrentDatabase.SubmitChanges();

            var qb = CurrentDatabase.ScratchPadCondition();

            qb.Reset();
            qb.AddNewClause(QueryType.HasMyTag, CompareType.Equal, $"{tag.Id},temp");
            attend.Commitment = CmsData.Codes.AttendCommitmentCode.FindSub;
            qb.Save(CurrentDatabase);

            var rurl       = CurrentDatabase.ServerLink($"/OnlineReg/VolSubReport/{attend.AttendId}/{person.PeopleId}/{dt.Ticks}");
            var reportlink = $@"<a href=""{rurl}"">Substitute Status Report</a>";
            var list       = CurrentDatabase.PeopleFromPidString(org.NotifyIds).ToList();

            //list.Insert(0, person);
            CurrentDatabase.Email(person.FromEmail, list,
                                  "Volunteer Substitute Commitment for " + org.OrganizationName,
                                  $@"
<p>{person.Name} has requested a substitute on {attend.MeetingDate:MMM d} at {attend.MeetingDate:h:mm tt}.</p>
<blockquote>
{reportlink}
</blockquote>");

            // Email subs
            var m = new MassEmailer(qb.Id);

            m.Subject = subject;
            m.Body    = message;

            m.FromName    = person.Name;
            m.FromAddress = person.FromEmail;

            var    eqid = m.CreateQueue(transactional: true).Id;
            string host = CurrentDatabase.Host;
            // save these from HttpContext to set again inside thread local storage
            var useremail         = Util.UserEmail;
            var isinroleemailtest = HttpContextFactory.Current.User.IsInRole("EmailTest");

            Log("Send Emails");

            HostingEnvironment.QueueBackgroundWorkItem(ct =>
            {
                try
                {
                    var db = CMSDataContext.Create(host);
                    // set these again inside thread local storage
                    Util.UserEmail         = useremail;
                    Util.IsInRoleEmailTest = isinroleemailtest;
                    db.SendPeopleEmail(eqid);
                }
                catch (Exception ex)
                {
                    Log("Email Error");
                    var ex2           = new Exception("Emailing error for queueid " + eqid, ex);
                    ErrorLog errorLog = ErrorLog.GetDefault(null);
                    errorLog.Log(new Error(ex2));

                    var db = CMSDataContext.Create(host);
                    // set these again inside thread local storage
                    Util.UserEmail         = useremail;
                    Util.IsInRoleEmailTest = isinroleemailtest;
                    var equeue             = db.EmailQueues.Single(ee => ee.Id == eqid);
                    equeue.Error           = ex.Message.Truncate(200);
                    db.SubmitChanges();
                }
            });
        }
Esempio n. 20
0
        public ActionResult RsvpLinkSg(string id, string message, bool?confirm, FormCollection formCollection, bool regrets = false)
        {
            var li = new LinkInfo(rsvplinkSTR, landingSTR, id, false);

            if (li.error.HasValue())
            {
                return(Message(li.error));
            }

            try
            {
                if (!li.pid.HasValue)
                {
                    throw new Exception("missing peopleid");
                }

                var meetingid  = li.a[0].ToInt();
                var emailid    = li.a[2].ToInt();
                var smallgroup = li.a[3];
                if (meetingid == 0 && li.a[0].EndsWith(".next"))
                {
                    var orgid    = li.a[0].Split('.')[0].ToInt();
                    var nextmeet = (from mm in CurrentDatabase.Meetings
                                    where mm.OrganizationId == orgid
                                    where mm.MeetingDate > DateTime.Now
                                    orderby mm.MeetingDate
                                    select mm).FirstOrDefault();
                    if (nextmeet == null)
                    {
                        return(Message("no meeting"));
                    }

                    meetingid = nextmeet.MeetingId;
                }
                var q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let meeting = CurrentDatabase.Meetings.SingleOrDefault(mm => mm.MeetingId == meetingid)
                                       let org = meeting.Organization
                                                 select new { p = pp, org, meeting }).Single();

                if (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive)
                {
                    throw new Exception("sorry, registration has been closed");
                }

                if (q.org.RegistrationTypeId == RegistrationTypeCode.None)
                {
                    throw new Exception("rsvp is no longer available");
                }

                if (q.org.Limit <= q.meeting.Attends.Count(aa => aa.Commitment == 1))
                {
                    throw new Exception("sorry, maximum limit has been reached");
                }

                var omb = OrganizationMember.Load(CurrentDatabase, li.pid.Value, q.meeting.OrganizationId) ??
                          OrganizationMember.InsertOrgMembers(CurrentDatabase,
                                                              q.meeting.OrganizationId, li.pid.Value, MemberTypeCode.Member, DateTime.Now, null, false);
                if (smallgroup.HasValue())
                {
                    omb.AddToGroup(CurrentDatabase, smallgroup);
                }

                li.ot.Used = true;
                CurrentDatabase.SubmitChanges();
                Attend.MarkRegistered(CurrentDatabase, li.pid.Value, meetingid, regrets ? AttendCommitmentCode.Regrets : AttendCommitmentCode.Attending);
                DbUtil.LogActivity($"{rsvplinkSTR}{confirmSTR}: {regrets}", q.org.OrganizationId, li.pid);
                var setting = CurrentDatabase.CreateRegistrationSettings(q.meeting.OrganizationId);

                if (confirm == true)
                {
                    var subject = Util.PickFirst(setting.Subject, "no subject");
                    var msg     = Util.PickFirst(setting.Body, "no message");
                    msg = APIOrganization.MessageReplacements(CurrentDatabase, q.p, q.org.DivisionName, q.org.OrganizationId, q.org.OrganizationName, q.org.Location, msg);
                    msg = msg.Replace("{details}", q.meeting.MeetingDate.ToString2("f"));
                    var NotifyIds = CurrentDatabase.StaffPeopleForOrg(q.org.OrganizationId);

                    CurrentDatabase.Email(NotifyIds[0].FromEmail, q.p, subject, msg); // send confirmation
                    CurrentDatabase.Email(q.p.FromEmail, NotifyIds,
                                          q.org.OrganizationName,
                                          $"{q.p.Name} has registered for {q.org.OrganizationName}<br>{q.meeting.MeetingDate.ToString2("f")}");
                }
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{rsvplinkSTR}{confirmSTR}Error: {regrets}", peopleid: li.pid);
                return(Message(ex.Message));
            }
            return(Message(message));
        }
Esempio n. 21
0
        private bool DoMissionTripSupporter()
        {
            var notifyIds = GetNotifyIds();
            var p         = List[0];

            Transaction.Fund = p.setting.DonationFund();
            var goerid = p.Parent.GoerId > 0
                ? p.Parent.GoerId
                : p.MissionTripGoerId;
            var forgoer    = "";
            var forgeneral = "";

            if (p.MissionTripSupportGoer > 0 && p.orgid.HasValue && p.PeopleId.HasValue)
            {
                var gsa = new GoerSenderAmount
                {
                    Amount         = p.MissionTripSupportGoer ?? 0,
                    Created        = DateTime.Now,
                    OrgId          = p.orgid.Value,
                    SupporterId    = p.PeopleId.Value,
                    NoNoticeToGoer = p.MissionTripNoNoticeToGoer
                };
                if (goerid > 0)
                {
                    gsa.GoerId = goerid;
                }

                CurrentDatabase.GoerSenderAmounts.InsertOnSubmit(gsa);
                if (p.Parent.GoerSupporterId.HasValue)
                {
                    var gs = CurrentDatabase.GoerSupporters.Single(gg => gg.Id == p.Parent.GoerSupporterId);
                    if (!gs.SupporterId.HasValue)
                    {
                        gs.SupporterId = p.PeopleId;
                    }
                }
                if (!Transaction.TransactionId.StartsWith("Coupon"))
                {
                    p.person.PostUnattendedContribution(CurrentDatabase,
                                                        p.MissionTripSupportGoer ?? 0, p.setting.DonationFundId,
                                                        $"SupportMissionTrip: org={p.orgid}; goer={goerid}", tranid: Transaction.Id);
                    Log("GoerSupport");
                    // send notices
                    if (goerid > 0 && !p.MissionTripNoNoticeToGoer)
                    {
                        var goer = CurrentDatabase.LoadPersonById(goerid.Value);
                        forgoer = $", {p.MissionTripSupportGoer:c} for {goer.Name}";
                        CurrentDatabase.Email(notifyIds[0].FromEmail, goer, org.OrganizationName + "-donation",
                                              $"{p.MissionTripSupportGoer ?? 0:C} donation received from {Transaction.FullName(Transaction)}{forgoer}");
                    }
                }
            }
            if (p.MissionTripSupportGeneral > 0 && p.orgid.HasValue && p.PeopleId.HasValue)
            {
                CurrentDatabase.GoerSenderAmounts.InsertOnSubmit(
                    new GoerSenderAmount
                {
                    Amount      = p.MissionTripSupportGeneral ?? 0,
                    Created     = DateTime.Now,
                    OrgId       = p.orgid.Value,
                    SupporterId = p.PeopleId.Value
                });
                forgeneral = $", ({p.MissionTripSupportGeneral ?? 0:c}) for trip";
                if (!Transaction.TransactionId.StartsWith("Coupon"))
                {
                    p.person.PostUnattendedContribution(CurrentDatabase,
                                                        p.MissionTripSupportGeneral ?? 0, p.setting.DonationFundId,
                                                        "SupportMissionTrip: org=" + p.orgid, tranid: Transaction.Id);
                    Log("TripSupport");
                }
            }
            var notifyids = CurrentDatabase.NotifyIds(org.GiftNotifyIds);

            CurrentDatabase.Email(notifyIds[0].FromEmail, notifyids, org.OrganizationName + "-donation",
                                  $"${Transaction.Amt:N2} donation received from {Transaction.FullName(Transaction)}{forgoer}{forgeneral}");

            var orgsettings   = settings[org.OrganizationId];
            var senderSubject = orgsettings.SenderSubject ?? "NO SUBJECT SET";
            var senderBody    = orgsettings.SenderBody ?? "NO SENDEREMAIL MESSAGE HAS BEEN SET";

            senderBody = APIOrganization.MessageReplacements(CurrentDatabase, p.person,
                                                             org.DivisionName, org.OrganizationId, org.OrganizationName, org.Location, senderBody);
            senderBody = senderBody.Replace("{phone}", org.PhoneNumber.FmtFone7());
            senderBody = senderBody.Replace("{paid}", Transaction.Amt.ToString2("c"));

            //Transaction.Description = "Mission Trip Giving";
            CurrentDatabase.Email(notifyids[0].FromEmail, p.person, listMailAddress, senderSubject, senderBody, false);
            CurrentDatabase.SubmitChanges();
            return(true);
        }
Esempio n. 22
0
        public void SendMovedNotices()
        {
            var q = from om in CurrentDatabase.OrganizationMembers
                    where om.Organization.DivOrgs.Any(di => di.DivId == SourceDivId)
                    where om.Moved == true || EmailAllNotices
                    select new
            {
                om,
                om.Person,
                om.Person.FromEmail,
                om.Person.EmailAddress,
                om.RegisterEmail,
                om.Person.Name,
                om.PeopleId,
                om.Organization.OrganizationName,
                om.Organization.Location,
                om.Organization.LeaderName,
                om.Organization.PhoneNumber
            };
            var content = CurrentDatabase.ContentOfTypeHtml("OrgMembersModel_SendMovedNotices");

            if (content == null)
            {
                content = new Content()
                {
                    Name  = "OrgMembersModel_SendMovedNotices",
                    Body  = Resource1.OrgMembersModel_SendMovedNotices,
                    Title = "Room Assignment for {name} in {org}"
                };
                CurrentDatabase.Contents.InsertOnSubmit(content);
                CurrentDatabase.SubmitChanges();
            }
            if (content.Title == "SendMovedNotices")                   // replace old Title with new, improved version
            {
                content.Title = "Room Assignment for {name} in {org}"; // this will be the subject
            }

            var sb = new StringBuilder("Org Assignment Notices sent to:\r\n<pre>\r\n");

            foreach (var i in q)
            {
                var msg = content.Body.Replace("{name}", i.Name)
                          .Replace("{org}", i.OrganizationName)
                          .Replace("{room}", i.Location)
                          .Replace("{leader}", i.LeaderName)
                          .Replace("{phone}", CurrentDatabase.Setting("ChurchPhone", "ChurchPhone"))
                          .Replace("{church}", CurrentDatabase.Setting("NameOfChurch", "NameOfChurch"));

                var subj = content.Title // the title of the content is the subject
                           .Replace("{name}", i.Name)
                           .Replace("{org}", i.OrganizationName)
                           .Replace("{room}", i.Location);

                if (i.om.Moved == true || EmailAllNotices)
                {
                    if (i.RegisterEmail.HasValue())
                    {
                        CurrentDatabase.Email(CurrentDatabase.CurrentUser.Person.FromEmail,
                                              i.om.Person, Util.ToMailAddressList(i.RegisterEmail),
                                              subj, msg, false);
                        sb.Append($"\"{i.Name}\" [{i.FromEmail}]R ({i.PeopleId}): {i.Location}\r\n");
                        i.om.Moved = false;
                    }

                    var flist = (from fm in i.om.Person.Family.People
                                 where (fm.EmailAddress ?? "") != ""
                                 where fm.EmailAddress != i.RegisterEmail
                                 where fm.PositionInFamilyId == PositionInFamily.PrimaryAdult
                                 select fm).ToList();
                    CurrentDatabase.Email(CurrentDatabase.CurrentUser.Person.FromEmail, flist, subj, msg);
                    foreach (var m in flist)
                    {
                        sb.Append($"{m}P ({i.PeopleId}): {i.Location}\r\n");
                        i.om.Moved = false;
                    }
                }
            }
            sb.Append("</pre>\n");

            var q0 = from o in CurrentDatabase.Organizations
                     where o.DivOrgs.Any(di => di.DivId == SourceDivId)
                     where o.NotifyIds.Length > 0
                     where o.RegistrationTypeId > 0
                     select o;
            var onlineorg = q0.FirstOrDefault();

            if (onlineorg == null)
            {
                CurrentDatabase.Email(CurrentDatabase.CurrentUser.Person.FromEmail,
                                      CurrentDatabase.CurrentUserPerson,
                                      "Org Assignment notices sent to:", sb.ToString());
            }
            else
            {
                CurrentDatabase.Email(CurrentDatabase.CurrentUser.Person.FromEmail,
                                      CurrentDatabase.PeopleFromPidString(onlineorg.NotifyIds),
                                      "Org Assignment notices sent to:", sb.ToString());
            }

            CurrentDatabase.SubmitChanges();
        }
Esempio n. 23
0
        public ActionResult VoteLinkSg(string id, string message, bool?confirm, FormCollection formCollection)
        {
            var li = new LinkInfo(votelinkSTR, confirmSTR, id);

            if (li.error.HasValue())
            {
                return(Message(li.error));
            }

            try
            {
                var smallgroup = li.a[4];

                if (!li.oid.HasValue)
                {
                    throw new Exception("orgid missing");
                }

                if (!li.pid.HasValue)
                {
                    throw new Exception("peopleid missing");
                }

                var q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.Organizations.SingleOrDefault(oo => oo.OrganizationId == li.oid)
                                   let om = CurrentDatabase.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == li.oid && oo.PeopleId == li.pid)
                                            select new { p = pp, org, om }).Single();

                if (q.org == null && CurrentDatabase.Host == "trialdb")
                {
                    var oid = li.oid + Util.TrialDbOffset;
                    q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.Organizations.SingleOrDefault(oo => oo.OrganizationId == oid)
                                   let om = CurrentDatabase.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == oid && oo.PeopleId == li.pid)
                                            select new { p = pp, org, om }).Single();
                }

                if (q.org == null)
                {
                    throw new Exception("org missing, bad link");
                }
                if ((q.org.RegistrationTypeId ?? RegistrationTypeCode.None) == RegistrationTypeCode.None)
                {
                    throw new Exception("votelink is no longer active");
                }

                if (q.om == null && q.org.Limit <= q.org.RegLimitCount(CurrentDatabase))
                {
                    throw new Exception("sorry, maximum limit has been reached");
                }

                if (q.om == null &&
                    (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive))
                {
                    throw new Exception("sorry, registration has been closed");
                }

                var setting = CurrentDatabase.CreateRegistrationSettings(li.oid.Value);
                if (IsSmallGroupFilled(setting, li.oid.Value, smallgroup))
                {
                    throw new Exception("sorry, maximum limit has been reached for " + smallgroup);
                }

                var omb = OrganizationMember.Load(CurrentDatabase, li.pid.Value, li.oid.Value) ??
                          OrganizationMember.InsertOrgMembers(CurrentDatabase,
                                                              li.oid.Value, li.pid.Value, MemberTypeCode.Member, Util.Now, null, false);

                if (q.org.AddToSmallGroupScript.HasValue())
                {
                    var script = CurrentDatabase.Content(q.org.AddToSmallGroupScript);
                    if (script != null && script.Body.HasValue())
                    {
                        try
                        {
                            var pe = new PythonModel(Util.Host, "RegisterEvent", script.Body);
                            pe.instance.AddToSmallGroup(smallgroup, omb);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                omb.AddToGroup(CurrentDatabase, smallgroup);
                li.ot.Used = true;
                CurrentDatabase.SubmitChanges();

                DbUtil.LogActivity($"{votelinkSTR}{confirmSTR}: {smallgroup}", li.oid, li.pid);

                if (confirm == true)
                {
                    var subject = Util.PickFirst(setting.Subject, "no subject");
                    var msg     = Util.PickFirst(setting.Body, "no message");
                    msg = APIOrganization.MessageReplacements(CurrentDatabase, q.p, q.org.DivisionName, q.org.OrganizationId, q.org.OrganizationName, q.org.Location, msg);
                    msg = msg.Replace("{details}", smallgroup);
                    var NotifyIds = CurrentDatabase.StaffPeopleForOrg(q.org.OrganizationId);

                    try
                    {
                        CurrentDatabase.Email(NotifyIds[0].FromEmail, q.p, subject, msg); // send confirmation
                    }
                    catch (Exception ex)
                    {
                        CurrentDatabase.Email(q.p.FromEmail, NotifyIds,
                                              q.org.OrganizationName,
                                              "There was a problem sending confirmation from org: " + ex.Message);
                    }
                    CurrentDatabase.Email(q.p.FromEmail, NotifyIds,
                                          q.org.OrganizationName,
                                          $"{q.p.Name} has registered for {q.org.OrganizationName}<br>{smallgroup}<br>(from votelink)");
                }
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{votelinkSTR}{confirmSTR}Error: {ex.Message}", li.oid, li.pid);
                return(Message(ex.Message));
            }

            return(Message(message));
        }