public void DoWork() { Db = DbUtil.Create(Host); Db.CommandTimeout = 1200; var noaddressok = Db.Setting("RequireAddressOnStatement", "true") == "false"; showCheckNo = Db.Setting("RequireCheckNoOnStatement", "false").ToLower() == "true"; showNotes = Db.Setting("RequireNotesOnStatement", "false").ToLower() == "true"; const bool UseMinAmt = true; var qc = APIContribution.contributors(Db, fd, td, 0, 0, 0, noaddressok, UseMinAmt, StartsWith, Sort, tagid: TagId, excludeelectronic: ExcludeElectronic); var runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).First(); runningtotals.Count = qc.Count(); Db.SubmitChanges(); if (showCheckNo || showNotes) { var c = new ContributionStatementsExtra { FromDate = fd, ToDate = td, typ = 3, ShowCheckNo = showCheckNo, ShowNotes = showNotes }; using (var stream = new FileStream(OutputFile, FileMode.Create)) c.Run(stream, Db, qc); LastSet = c.LastSet(); var sets = c.Sets(); foreach (var set in sets) using (var stream = new FileStream(Output(OutputFile, set), FileMode.Create)) c.Run(stream, Db, qc, set); runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).First(); runningtotals.LastSet = LastSet; runningtotals.Sets = string.Join(",", sets); runningtotals.Completed = DateTime.Now; Db.SubmitChanges(); } else { var c = new ContributionStatements { FromDate = fd, ToDate = td, typ = 3 }; using (var stream = new FileStream(OutputFile, FileMode.Create)) c.Run(stream, Db, qc); LastSet = c.LastSet(); var sets = c.Sets(); foreach (var set in sets) using (var stream = new FileStream(Output(OutputFile, set), FileMode.Create)) c.Run(stream, Db, qc, set); runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).First(); runningtotals.LastSet = LastSet; runningtotals.Sets = string.Join(",", sets); runningtotals.Completed = DateTime.Now; Db.SubmitChanges(); } }
public static int DoAllGiving(CMSDataContext Db) { var gateway = Db.Setting("TransactionGateway", ""); int count = 0; if (gateway.HasValue()) { var q = from rg in Db.ManagedGivings where rg.NextDate < Util.Now.Date //where rg.PeopleId == 819918 select rg; foreach (var rg in q) rg.NextDate = rg.FindNextDate(Util.Now.Date); var rgq = from rg in Db.ManagedGivings where rg.NextDate == Util.Now.Date select new { rg, rg.Person, rg.Person.RecurringAmounts, }; foreach (var i in rgq) count += i.rg.DoGiving(Db); } return count; }
public UploadAddressesModel(CMSDataContext db, int peopleId) { this.db = db; userpeopleid = peopleId; var spec = db.Setting("NcoaColumns", "PeopleId=1,Addr1=4,Addr2=5,City=6,State=7,Zip=8,MoveDate=10"); NcoaCols = spec.Split(',').Select(vv => vv.Split('=')).ToDictionary(vv => vv[0], vv => vv[1].ToInt()-1); }
public SagePayments(CMSDataContext Db, bool testing) { #if DEBUG2 testing = true; #endif this.Db = Db; if (testing) { login = "******"; key = "S4S3N4D2W1D9"; } else { login = Db.Setting("M_id", ""); key = Db.Setting("M_key", ""); } this.testing = testing; }
public ActionResult Index(int id) { var mm = DbUtil.Db.Meetings.SingleOrDefault(m => m.MeetingId == id); if (mm == null) return Content("error: no meeting"); DbUtil.LogActivity("Delete meeting for {0}".Fmt(Session["ActiveOrganization"])); var runningtotals = new DeleteMeetingRun { Started = DateTime.Now, Count = mm.Attends.Count(a => a.EffAttendFlag == true || a.AttendanceFlag == true), Processed = 0, Meetingid = id }; DbUtil.Db.DeleteMeetingRuns.InsertOnSubmit(runningtotals); DbUtil.Db.SubmitChanges(); var host = Util.Host; System.Threading.Tasks.Task.Factory.StartNew(() => { Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; var Db = new CMSDataContext(Util.GetConnectionString(host)); var cul = Db.Setting("Culture", "en-US"); Thread.CurrentThread.CurrentUICulture = new CultureInfo(cul); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cul); var meeting = Db.Meetings.SingleOrDefault(m => m.MeetingId == id); var q = from a in Db.Attends where a.MeetingId == id where a.AttendanceFlag == true || a.EffAttendFlag == true select a.PeopleId; var list = q.ToList(); foreach (var pid in list) { Db.Dispose(); Db = new CMSDataContext(Util.GetConnectionString(host)); Attend.RecordAttendance(Db, pid, id, false); var r = Db.DeleteMeetingRuns.Where(m => m.Meetingid == id).OrderByDescending(m => m.Id).First(); r.Processed++; Db.SubmitChanges(); } var rr = Db.DeleteMeetingRuns.Where(m => m.Meetingid == id).OrderByDescending(m => m.Id).First(); rr.Processed--; Db.SubmitChanges(); Db.ExecuteCommand( "delete dbo.SubRequest WHERE EXISTS(SELECT NULL FROM Attend a WHERE a.AttendId = AttendId AND a.MeetingId = {0})", id); Db.ExecuteCommand("DELETE dbo.VolRequest where MeetingId = {0}", id); Db.ExecuteCommand("delete attend where MeetingId = {0}", id); Db.ExecuteCommand("delete MeetingExtra where MeetingId = {0}", id); Db.ExecuteCommand("delete meetings where MeetingId = {0}", id); rr.Processed++; rr.Completed = DateTime.Now; Db.SubmitChanges(); }); return Redirect("/DeleteMeeting/Progress/" + id); }
public AuthorizeNet(CMSDataContext Db, bool testing) { #if DEBUG testing = true; #endif this.Db = Db; if (testing) { login = "******"; key = "9j33v58nuZB865WR"; url = testurl; } else { login = Db.Setting("x_login", ""); key = Db.Setting("x_tran_key", ""); url = produrl; } }
public bool CanVoid(CMSDataContext db) { if (!Util.IsSage.HasValue) Util.IsSage = db.Setting("TransactionGateway", "").ToLower() == "sage"; return Approved == true && !CanCredit(db) && Util.IsSage.Value && Voided != true && Credited != true && (Coupon ?? false) == false && TransactionId.HasValue() && Amt > 0; }
public ActionResult Start(int tag, int orgid, bool pending = false, bool prospect = false) { var runningtotals = new AddToOrgFromTagRun { Started = DateTime.Now, Count = 0, Processed = 0, Orgid = orgid }; DbUtil.Db.AddToOrgFromTagRuns.InsertOnSubmit(runningtotals); DbUtil.Db.SubmitChanges(); var host = Util.Host; var qid = DbUtil.Db.FetchLastQuery().Id; System.Threading.Tasks.Task.Factory.StartNew(() => { Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; var Db = new CMSDataContext(Util.GetConnectionString(host)); var cul = Db.Setting("Culture", "en-US"); Thread.CurrentThread.CurrentUICulture = new CultureInfo(cul); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cul); IEnumerable<int> q = null; if (tag == -1) // (last query) q = Db.PeopleQuery(qid).Select(pp => pp.PeopleId); else q = from t in Db.TagPeople where t.Id == tag select t.PeopleId; var pids = q.ToList(); foreach (var pid in pids) { Db.Dispose(); Db = new CMSDataContext(Util.GetConnectionString(host)); OrganizationMember.InsertOrgMembers(Db, orgid, pid, prospect ? MemberTypeCode.Prospect : MemberTypeCode.Member, DateTime.Now, null, pending); var r = Db.AddToOrgFromTagRuns.Where(mm => mm.Orgid == orgid).OrderByDescending(mm => mm.Id).First(); r.Processed++; r.Count = pids.Count; Db.SubmitChanges(); } var rr = Db.AddToOrgFromTagRuns.Where(mm => mm.Orgid == orgid).OrderByDescending(mm => mm.Id).First(); rr.Completed = DateTime.Now; Db.SubmitChanges(); Db.UpdateMainFellowship(orgid); }); return Redirect("/AddToOrgFromTag/Progress/" + orgid); }
public string MemberProfileAutomation(CMSDataContext Db) { if (Db.Setting("UseMemberProfileAutomation", "true") != "true") return "ok"; var script = Db.Content("MemberProfileAutomation"); if (script == null) return "ok"; var path = HttpContext.Current.Server.MapPath("/Content/"); #if DEBUG2 var options = new Dictionary<string, object>(); options["Debug"] = true; var engine = Python.CreateEngine(options); var paths = engine.GetSearchPaths(); paths.Add(path); engine.SetSearchPaths(paths); var sc = engine.CreateScriptSourceFromFile(HttpContext.Current.Server.MapPath("/Content/MembershipAutomation2.py")); #else var engine = Python.CreateEngine(); var paths = engine.GetSearchPaths(); paths.Add(path); engine.SetSearchPaths(paths); var sc = engine.CreateScriptSourceFromString(script.Body); #endif try { var code = sc.Compile(); var scope = engine.CreateScope(); code.Execute(scope); dynamic MembershipAutomation = scope.GetVariable("MembershipAutomation"); dynamic m = MembershipAutomation(); var ret = m.Run(Db, this); //var m = scope.GetVariable("MembershipAutomation"); //dynamic instance = engine.Operations.CreateInstance(m); //var value = instance.Run(Db, this); return errorReturn; } catch (Exception ex) { return "MemberProfileAutomation script error: " + ex.Message; } }
public static void AddNewPerson(CMSDataContext Db, int newpersonid) { var newPeopleManagerId = Db.NewPeopleManagerId; if (Db.Setting("NoNewPersonTasks") || newPeopleManagerId == 0) return; var task = new Task { ListId = GetRequiredTaskList(Db, "InBox", newPeopleManagerId).Id, OwnerId = newPeopleManagerId, Description = "New Person Data Entry", WhoId = newpersonid, StatusId = TaskStatusCode.Active, }; if (Util.UserPeopleId.HasValue && Util.UserPeopleId.Value != newPeopleManagerId) { task.CoOwnerId = Util.UserPeopleId.Value; task.CoListId = GetRequiredTaskList(Db, "InBox", Util.UserPeopleId.Value).Id; } Db.Tasks.InsertOnSubmit(task); Db.SubmitChanges(); }
public void SetTagString(CMSDataContext db, string value) { if (!value.HasValue()) { db.DivOrgs.DeleteAllOnSubmit(DivOrgs); return; } var a = value.Split(','); var qdelete = from d in DivOrgs where !a.Contains(d.Division.Name) select d; db.DivOrgs.DeleteAllOnSubmit(qdelete); var q = from s in a join d2 in DivOrgs on s equals d2.Division.Name into g from d in g.DefaultIfEmpty() where d == null select s; foreach (var s in q) { var div = db.Divisions.FirstOrDefault(d => d.Name == s); if (div == null) { div = new Division { Name = s }; string misctags = db.Setting("MiscTagsString", "Misc Tags"); var prog = db.Programs.SingleOrDefault(p => p.Name == misctags); if (prog == null) { prog = new Program { Name = misctags }; db.Programs.InsertOnSubmit(prog); } div.Program = prog; } DivOrgs.Add(new DivOrg { Division = div }); } tagString = value; }
public void Run(Stream stream, CMSDataContext Db, IEnumerable<ContributorInfo> q, int set = 0) { pageEvents.set = set; IEnumerable<ContributorInfo> contributors = q; var toDate = ToDate.Date.AddHours(24).AddSeconds(-1); PdfContentByte dc; var font = FontFactory.GetFont(FontFactory.HELVETICA, 11); var boldfont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 11); var doc = new Document(PageSize.LETTER); doc.SetMargins(36f, 30f, 24f, 36f); var w = PdfWriter.GetInstance(doc, stream); w.PageEvent = pageEvents; doc.Open(); dc = w.DirectContent; int prevfid = 0; var runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).FirstOrDefault(); runningtotals.Processed = 0; Db.SubmitChanges(); var count = 0; foreach (var ci in contributors) { if (set > 0 && pageEvents.FamilySet[ci.PeopleId] != set) continue; doc.NewPage(); if (prevfid != ci.FamilyId) { prevfid = ci.FamilyId; pageEvents.EndPageSet(); } if (set == 0) pageEvents.FamilySet[ci.PeopleId] = 0; count++; var css = @" <style> h1 { font-size: 24px; font-weight:normal; margin-bottom:0; } h2 { font-size: 11px; font-weight:normal; margin-top: 0; } p { font-size: 11px; } </style> "; //----Church Name var t1 = new PdfPTable(1); t1.TotalWidth = 72f * 5f; t1.DefaultCell.Border = Rectangle.NO_BORDER; string html1 = Db.ContentHtml("StatementHeader", Resource1.ContributionStatementHeader); string html2 = Db.ContentHtml("StatementNotice", Resource1.ContributionStatementNotice); var mh = new MyHandler(); using (var sr = new StringReader(css + html1)) XMLWorkerHelper.GetInstance().ParseXHtml(mh, sr); var cell = new PdfPCell(t1.DefaultCell); foreach (var e in mh.elements) if (e.Chunks.Count > 0) cell.AddElement(e); //cell.FixedHeight = 72f * 1.25f; t1.AddCell(cell); t1.AddCell("\n"); var t1a = new PdfPTable(1); t1a.TotalWidth = 72f * 5f; t1a.DefaultCell.Border = Rectangle.NO_BORDER; var ae = new PdfPTable(1); ae.DefaultCell.Border = Rectangle.NO_BORDER; ae.WidthPercentage = 100; var a = new PdfPTable(1); a.DefaultCell.Indent = 25f; a.DefaultCell.Border = Rectangle.NO_BORDER; a.AddCell(new Phrase(ci.Name, font)); a.AddCell(new Phrase(ci.Address1, font)); if (ci.Address2.HasValue()) a.AddCell(new Phrase(ci.Address2, font)); a.AddCell(new Phrase(ci.CityStateZip, font)); cell = new PdfPCell(a) { Border = Rectangle.NO_BORDER }; //cell.FixedHeight = 72f * 1.0625f; ae.AddCell(cell); cell = new PdfPCell(t1a.DefaultCell); cell.AddElement(ae); t1a.AddCell(ae); //-----Notice var t2 = new PdfPTable(1); t2.TotalWidth = 72f * 3f; t2.DefaultCell.Border = Rectangle.NO_BORDER; t2.AddCell(new Phrase("\nPrint Date: {0:d} (id:{1} {2})".Fmt(DateTime.Now, ci.PeopleId, ci.CampusId), font)); t2.AddCell(""); var mh2 = new MyHandler(); using (var sr = new StringReader(css + html2)) XMLWorkerHelper.GetInstance().ParseXHtml(mh2, sr); cell = new PdfPCell(t1.DefaultCell); foreach (var e in mh2.elements) if (e.Chunks.Count > 0) cell.AddElement(e); t2.AddCell(cell); // POSITIONING OF ADDRESSES //----Header var yp = doc.BottomMargin + Db.Setting("StatementRetAddrPos", "10.125").ToFloat() * 72f; t1.WriteSelectedRows(0, -1, doc.LeftMargin - 0.1875f * 72f, yp, dc); yp = doc.BottomMargin + Db.Setting("StatementAddrPos", "8.3375").ToFloat() * 72f; t1a.WriteSelectedRows(0, -1, doc.LeftMargin, yp, dc); yp = doc.BottomMargin + 10.125f * 72f; t2.WriteSelectedRows(0, -1, doc.LeftMargin + 72f * 4.4f, yp, dc); //----Contributions doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ") { SpacingBefore = 72f * 2.125f }); doc.Add(new Phrase("\n Period: {0:d} - {1:d}".Fmt(FromDate, toDate), boldfont)); var pos = w.GetVerticalPosition(true); var ct = new ColumnText(dc); float gutter = 20f; float colwidth = (doc.Right - doc.Left - gutter) / 2; var t = new PdfPTable(new float[] { 10f, 24f, 10f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase("Contributions\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Date", boldfont)); t.AddCell(new Phrase("Description", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Amount", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; var total = 0m; foreach (var c in APIContribution.contributions(Db, ci, FromDate, toDate)) { t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font)); t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font); t.AddCell(cell); total += (c.ContributionAmount); } t.DefaultCell.Border = Rectangle.TOP_BORDER; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 2; cell.Phrase = new Phrase("Total Contributions for period", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(total.ToString("N2"), font); t.AddCell(cell); ct.AddElement(t); //------Pledges var pledges = APIContribution.pledges(Db, ci, toDate).ToList(); if (pledges.Count > 0) { t = new PdfPTable(new float[] { 16f, 12f, 12f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase("\n\nPledges\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Fund", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Pledge", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Given", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var c in pledges) { t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.PledgeAmount.ToString2("N2"), font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString2("N2"), font); t.AddCell(cell); } ct.AddElement(t); } //------Gifts In Kind var giftsinkind = APIContribution.GiftsInKind(Db, ci, FromDate, toDate).ToList(); if (giftsinkind.Count > 0) { t = new PdfPTable(new float[] { 12f, 18f, 20f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase("\n\nGifts in Kind\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Date", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase("Fund", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase("Description", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var c in giftsinkind) { t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font)); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase(c.Fund, font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase(c.Description, font); t.AddCell(cell); } ct.AddElement(t); } //-----Summary t = new PdfPTable(new float[] { 29f, 9f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 2; cell.Phrase = new Phrase("\n\nPeriod Summary\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Fund", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Amount", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var c in APIContribution.quarterlySummary(Db, ci, FromDate, toDate)) { t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font); t.AddCell(cell); } t.DefaultCell.Border = Rectangle.TOP_BORDER; t.AddCell(new Phrase("Total contributions for period", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(total.ToString("N2"), font); t.AddCell(cell); ct.AddElement(t); var col = 0; var status = 0; while (ColumnText.HasMoreText(status)) { if (col == 0) ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, pos); else if (col == 1) ct.SetSimpleColumn(doc.Right - colwidth, doc.Bottom, doc.Right, pos); status = ct.Go(); ++col; if (col > 1) { col = 0; pos = doc.Top; doc.NewPage(); } } runningtotals.Processed += 1; runningtotals.CurrSet = set; Db.SubmitChanges(); } if (count == 0) { doc.NewPage(); doc.Add(new Phrase("no data")); } doc.Close(); if (set == LastSet()) runningtotals.Completed = DateTime.Now; Db.SubmitChanges(); }
public void LogPictureUpload(CMSDataContext db, int UserPeopleId) { var c = new ChangeLog { UserPeopleId = UserPeopleId, PeopleId = PeopleId, Field = "Basic Info", Created = Util.Now }; db.ChangeLogs.InsertOnSubmit(c); c.ChangeDetails.Add(new ChangeDetail("Picture", null, "(new upload)")); var np = db.GetNewPeopleManagers(); if (np != null) db.EmailRedacted(db.Setting("AdminMail", "*****@*****.**"), np, "Picture Uploaded on " + Util.Host, $"{Util.UserName} Uploaded a picture for <a href=\"{db.ServerLink($"/Person2/{PeopleId}")}\">{Name}</a><br />\n"); }
public static Person Add(CMSDataContext Db, bool SendNotices, Family fam, int position, Tag tag, string firstname, string nickname, string lastname, string dob, int MarriedCode, int gender, int originId, int? EntryPointId, bool testing = false) { var p = new Person(); p.CreatedDate = Util.Now; p.CreatedBy = Util.UserId; Db.People.InsertOnSubmit(p); p.PositionInFamilyId = position; p.AddressTypeId = 10; if (Util.HasValue(firstname)) p.FirstName = firstname.Trim().ToProper().Truncate(25); else p.FirstName = ""; if (Util.HasValue(nickname)) p.NickName = nickname.Trim().ToProper().Truncate(15); if (Util.HasValue(lastname)) p.LastName = lastname.Trim().ToProper().Truncate(30); else p.LastName = "?"; p.GenderId = gender; if (p.GenderId == 99) p.GenderId = 0; p.MaritalStatusId = MarriedCode; DateTime dt; if (Util.BirthDateValid(dob, out dt)) { if (dt.Year == Util.SignalNoYear) { p.BirthDay = dt.Day; p.BirthMonth = dt.Month; p.BirthYear = null; } else { while (dt.Year < 1900) dt = dt.AddYears(100); if (dt > Util.Now) dt = dt.AddYears(-100); p.BirthDay = dt.Day; p.BirthMonth = dt.Month; p.BirthYear = dt.Year; } if (p.GetAge() < 18 && MarriedCode == 0) p.MaritalStatusId = MaritalStatusCode.Single; } // I think this else statement is no longer necessary else if (DateTime.TryParse(dob, out dt)) { p.BirthDay = dt.Day; p.BirthMonth = dt.Month; if (Regex.IsMatch(dob, @"\d+[-/]\d+[-/]\d+")) { p.BirthYear = dt.Year; while (p.BirthYear < 1900) p.BirthYear += 100; if (p.GetAge() < 18 && MarriedCode == 0) p.MaritalStatusId = MaritalStatusCode.Single; } } p.MemberStatusId = MemberStatusCode.JustAdded; if (fam == null) { fam = new Family(); Db.Families.InsertOnSubmit(fam); p.Family = fam; } else fam.People.Add(p); if (tag != null) tag.PersonTags.Add(new TagPerson { Person = p }); p.OriginId = originId; p.EntryPointId = EntryPointId; p.FixTitle(); if(Db.Setting("ElectronicStatementDefault", "false").Equal("true")) p.ElectronicStatement = true; if (!testing) Db.SubmitChanges(); if (SendNotices) { if (Util.UserPeopleId.HasValue && Util.UserPeopleId.Value != Db.NewPeopleManagerId && HttpContext.Current.User.IsInRole("Access") && !HttpContext.Current.User.IsInRole("OrgMembersOnly") && !HttpContext.Current.User.IsInRole("OrgLeadersOnly")) Task.AddNewPerson(Db, p.PeopleId); else { var np = Db.GetNewPeopleManagers(); if (np != null) Db.Email(Util.SysFromEmail, np, $"Just Added Person on {Db.Host}", $"<a href='{Db.ServerLink("/Person2/" + p.PeopleId)}'>{p.Name}</a>"); } } return p; }
public Contribution PostUnattendedContribution(CMSDataContext Db, decimal Amt, int? Fund, string Description, bool pledge = false, int? typecode = null, int? tranid = null) { if (!typecode.HasValue) { typecode = BundleTypeCode.Online; if (pledge) typecode = BundleTypeCode.OnlinePledge; } var now = Util.Now; var d = now.Date; BundleHeader bundle = null; var spec = Db.Setting("OnlineContributionBundleDayTime", ""); if (Util.HasValue(spec)) { var a = spec.SplitStr(" ", 2); try { var next = DateTime.Parse(now.ToShortDateString() + " " + a[1]); var dow = Enum.Parse(typeof(DayOfWeek), a[0], ignoreCase: true); next = next.Sunday().Add(next.TimeOfDay).AddDays(dow.ToInt()); if(now > next) next = next.AddDays(7); var prev = next.AddDays(-7); var bid = BundleTypeCode.MissionTrip == typecode ? Db.GetCurrentMissionTripBundle(next, prev) : Db.GetCurrentOnlineBundle(next, prev); bundle = Db.BundleHeaders.SingleOrDefault(bb => bb.BundleHeaderId == bid); } catch (Exception) { spec = ""; } } if(!Util.HasValue(spec)) { var nextd = d.AddDays(1); var bid = BundleTypeCode.MissionTrip == typecode ? Db.GetCurrentMissionTripBundle(nextd, d) : Db.GetCurrentOnlineBundle(nextd, d); bundle = Db.BundleHeaders.SingleOrDefault(bb => bb.BundleHeaderId == bid); } if (bundle == null) { bundle = new BundleHeader { BundleHeaderTypeId = typecode.Value, BundleStatusId = BundleStatusCode.Open, CreatedBy = Util.UserId1, ContributionDate = d, CreatedDate = now, FundId = Db.Setting("DefaultFundId", "1").ToInt(), RecordStatus = false, TotalCash = 0, TotalChecks = 0, TotalEnvelopes = 0, BundleTotal = 0 }; Db.BundleHeaders.InsertOnSubmit(bundle); } if (!Fund.HasValue) Fund = Db.Setting("DefaultFundId", "1").ToInt(); var fundtouse = (from f in Db.ContributionFunds where f.FundId == Fund select f).SingleOrDefault(); //failsafe if fund is not found if(fundtouse == null) Fund = (from f in Db.ContributionFunds where f.FundStatusId == 1 orderby f.FundId select f.FundId).First(); var FinanceManagerId = Db.Setting("FinanceManagerId", "").ToInt2(); if (!FinanceManagerId.HasValue) { var qu = from u in Db.Users where u.UserRoles.Any(ur => ur.Role.RoleName == "Finance") orderby u.Person.LastName select u.UserId; FinanceManagerId = qu.FirstOrDefault(); if (!FinanceManagerId.HasValue) FinanceManagerId = 1; } var bd = new BundleDetail { BundleHeaderId = bundle.BundleHeaderId, CreatedBy = FinanceManagerId.Value, CreatedDate = now, }; var typid = ContributionTypeCode.CheckCash; if (pledge) typid = ContributionTypeCode.Pledge; bd.Contribution = new Contribution { CreatedBy = FinanceManagerId.Value, CreatedDate = bd.CreatedDate, FundId = Fund.Value, PeopleId = PeopleId, ContributionDate = bd.CreatedDate, ContributionAmount = Amt, ContributionStatusId = 0, ContributionTypeId = typid, ContributionDesc = Description, TranId = tranid, Source = Util2.FromMobile.HasValue() ? 1 : (int?)null }; bundle.BundleDetails.Add(bd); Db.SubmitChanges(); if(fundtouse == null) Db.LogActivity($"FundNotFound Used fund #{Fund} on contribution #{bd.ContributionId}"); return bd.Contribution; }
public int DoGiving(CMSDataContext db) { var total = (from a in db.RecurringAmounts where a.PeopleId == PeopleId where a.ContributionFund.FundStatusId == 1 where a.ContributionFund.OnlineSort != null select a.Amt).Sum(); if (!total.HasValue || total == 0) { return(0); } var paymentInfo = db.PaymentInfos.Single(x => x.PeopleId == PeopleId); var preferredType = paymentInfo.PreferredGivingType; var gw = GetGateway(db, paymentInfo); var t = new Transaction { TransactionDate = DateTime.Now, TransactionId = "started", First = Person.FirstName, MiddleInitial = Person.MiddleName.Truncate(1) ?? "", Last = Person.LastName, Suffix = Person.SuffixCode, Amt = total, Description = "Recurring Giving", Testing = false, TransactionGateway = gw.GatewayType, Financeonly = true, PaymentType = preferredType, LastFourCC = preferredType == PaymentType.CreditCard ? paymentInfo.MaskedCard.Last(4) : null, LastFourACH = preferredType == PaymentType.Ach ? paymentInfo.MaskedAccount.Last(4) : null }; db.Transactions.InsertOnSubmit(t); db.SubmitChanges(); var ret = gw.PayWithVault(PeopleId, total ?? 0, "Recurring Giving", t.Id, preferredType); t.Message = ret.Message; t.AuthCode = ret.AuthCode; t.Approved = ret.Approved; t.TransactionId = ret.TransactionId; var systemEmail = db.Setting("SystemEmailAddress", "*****@*****.**"); var contributionemail = (from ex in Person.PeopleExtras where ex.Field == "ContributionEmail" select ex.Data).SingleOrDefault(); if (contributionemail.HasValue()) { contributionemail = contributionemail.Trim(); } if (!Util.ValidEmail(contributionemail)) { contributionemail = Person.FromEmail; } var gift = db.Setting("NameForPayment", "gift"); var church = db.Setting("NameOfChurch", db.CmsHost); var q = from a in db.RecurringAmounts where a.PeopleId == PeopleId select a; var tot = q.Where(aa => aa.ContributionFund.FundStatusId == 1).Sum(aa => aa.Amt); t.TransactionPeople.Add(new TransactionPerson { PeopleId = Person.PeopleId, Amt = tot, }); if (ret.Approved) { foreach (var a in q) { if (a.ContributionFund.FundStatusId == 1 && a.ContributionFund.OnlineSort != null && a.Amt > 0) { Person.PostUnattendedContribution(db, a.Amt ?? 0, a.FundId, "Recurring Giving", tranid: t.Id); } } NextDate = FindNextDate(Util.Now.Date.AddDays(1)); db.SubmitChanges(); if (tot > 0) { var msg = db.Content("RecurringGiftNotice") ?? new Content { Title = $"Recurring {gift} for {{church}}", Body = "Your payment of {total} was processed this morning." }; var subject = msg.Title.Replace("{church}", church); var body = msg.Body.Replace("{total}", $"${tot:N2}"); var from = Util.TryGetMailAddress(contributionemail); var m = new EmailReplacements(db, body, from); body = m.DoReplacements(db, Person); Util.SendMsg(systemEmail, db.CmsHost, from, subject, body, Util.ToMailAddressList(contributionemail), 0, Person.PeopleId); } } else { db.SubmitChanges(); var msg = db.Content("RecurringGiftFailedNotice") ?? new Content { Title = $"Recurring {gift} for {{church}} did not succeed", Body = @"Your payment of {total} failed to process this morning.<br> The message was '{message}'. Please contact the Finance office at the church." }; var subject = msg.Title.Replace("{church}", church); var body = msg.Body.Replace("{total}", $"${tot:N2}") .Replace("{message}", ret.Message); var from = Util.TryGetMailAddress(contributionemail); var m = new EmailReplacements(db, body, from); body = m.DoReplacements(db, Person); var adminEmail = db.Setting("AdminMail", systemEmail); Util.SendMsg(systemEmail, db.CmsHost, from, subject, body, Util.ToMailAddressList(contributionemail), 0, Person.PeopleId); foreach (var p in db.RecurringGivingNotifyPersons()) { Util.SendMsg(systemEmail, db.CmsHost, Util.TryGetMailAddress(adminEmail), "Recurring Giving Failed on " + db.CmsHost, $"<a href='{db.CmsHost}/Transactions/{t.Id}'>message: {ret.Message}, tranid:{t.Id}</a>", Util.ToMailAddressList(p.EmailAddress), 0, Person.PeopleId); } } return(1); }
public ActionResult QueueEmails(MassEmailer m) { if (!m.Subject.HasValue() || !m.Body.HasValue()) return Json(new { id = 0, content = "<h2>Both Subject and Body need some text</h2>" }); if (!User.IsInRole("Admin") && m.Body.Contains("{createaccount}")) return Json(new { id = 0, content = "<h2>Only Admin can use {createaccount}</h2>" }); if (Util.SessionTimedOut()) { Session["massemailer"] = m; return Content("timeout"); } DbUtil.LogActivity("Emailing people"); if (m.EmailFroms().Count(ef => ef.Value == m.FromAddress) == 0) return Json(new { id = 0, content = "No email address to send from" }); m.FromName = m.EmailFroms().First(ef => ef.Value == m.FromAddress).Text; int id; try { id = m.CreateQueue(); if (id == 0) throw new Exception("No Emails to send (tag does not exist)"); if (m.Schedule.HasValue) return Json(new { id = 0, content = "<h2>Emails Queued</h2>" }); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); return Json(new { id = 0, content = "<h2>Error</h2><p>{0}</p>".Fmt(ex.Message) }); } string host = Util.Host; // save these from HttpContext to set again inside thread local storage var useremail = Util.UserEmail; var isinroleemailtest = User.IsInRole("EmailTest"); System.Threading.Tasks.Task.Factory.StartNew(() => { Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; try { var Db = new CMSDataContext(Util.GetConnectionString(host)); Db.Host = host; var cul = Db.Setting("Culture", "en-US"); Thread.CurrentThread.CurrentUICulture = new CultureInfo(cul); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cul); // set these again inside thread local storage Util.UserEmail = useremail; Util.IsInRoleEmailTest = isinroleemailtest; Db.SendPeopleEmail(id); } catch (Exception ex) { var ex2 = new Exception("Emailing error for queueid " + id, ex); ErrorLog errorLog = ErrorLog.GetDefault(null); errorLog.Log(new Error(ex2)); var Db = new CMSDataContext(Util.GetConnectionString(host)); Db.Host = host; var equeue = Db.EmailQueues.Single(ee => ee.Id == id); equeue.Error = ex.Message.Truncate(200); Db.SubmitChanges(); } }); string keepdraft = Request["keepdraft"]; int saveid = Request["saveid"].ToInt(); System.Diagnostics.Debug.Print("Keep: " + keepdraft + " - Save ID: " + saveid); if (keepdraft != "on" && saveid > 0) DbUtil.ContentDeleteFromID(saveid); return Json(new { id = id }); }
public ActionResult SendNow(int id) { string host = Util.Host; // save these from HttpContext to set again inside thread local storage var useremail = Util.UserEmail; var isinroleemailtest = User.IsInRole("EmailTest"); System.Threading.Tasks.Task.Factory.StartNew(() => { Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; try { var Db = new CMSDataContext(Util.GetConnectionString(host)); Db.Host = host; var cul = Db.Setting("Culture", "en-US"); Thread.CurrentThread.CurrentUICulture = new CultureInfo(cul); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cul); // set these again inside thread local storage Util.UserEmail = useremail; Util.IsInRoleEmailTest = isinroleemailtest; Db.SendPeopleEmail(id); } catch (Exception ex) { var ex2 = new Exception("Emailing error for queueid " + id, ex); ErrorLog errorLog = ErrorLog.GetDefault(null); errorLog.Log(new Error(ex2)); var Db = new CMSDataContext(Util.GetConnectionString(host)); Db.Host = host; var equeue = Db.EmailQueues.Single(ee => ee.Id == id); equeue.Error = ex.Message.Truncate(200); Db.SubmitChanges(); } }); return Redirect("/Manage/Emails/Details/" + id); }
public int DoGiving(CMSDataContext Db) { var gateway = Db.Setting("TransactionGateway", ""); AuthorizeNet anet = null; SagePayments sage = null; if (gateway == "AuthorizeNet") { anet = new AuthorizeNet(Db, testing: false); } else if (gateway == "Sage") { sage = new SagePayments(Db, testing: false); } else { return(0); } TransactionResponse ret = null; var total = (from a in Db.RecurringAmounts where a.PeopleId == PeopleId where a.ContributionFund.FundStatusId == 1 select a.Amt).Sum(); if (!total.HasValue || total == 0) { return(0); } var preferredtype = (from pi in Db.PaymentInfos where pi.PeopleId == PeopleId select pi.PreferredGivingType).Single(); var t = new Transaction { TransactionDate = DateTime.Now, TransactionId = "started", First = Person.FirstName, MiddleInitial = Person.MiddleName.Truncate(1) ?? "", Last = Person.LastName, Suffix = Person.SuffixCode, Amt = total, Description = "Recurring Giving", Testing = false, TransactionGateway = gateway, Financeonly = true }; Db.Transactions.InsertOnSubmit(t); Db.SubmitChanges(); if (gateway == "AuthorizeNet") { ret = anet.createCustomerProfileTransactionRequest(PeopleId, total ?? 0, "Recurring Giving", t.Id); } else { ret = sage.createVaultTransactionRequest(PeopleId, total ?? 0, "Recurring Giving", t.Id, preferredtype); } t.Message = ret.Message; t.AuthCode = ret.AuthCode; t.Approved = ret.Approved; t.TransactionId = ret.TransactionId; var systemEmail = Db.Setting("SystemEmailAddress", "*****@*****.**"); var contributionemail = (from ex in Person.PeopleExtras where ex.Field == "ContributionEmail" select ex.Data).SingleOrDefault(); if (contributionemail.HasValue()) { contributionemail = contributionemail.Trim(); } if (!Util.ValidEmail(contributionemail)) { contributionemail = Person.FromEmail; } var gift = Db.Setting("NameForPayment", "gift"); var church = Db.Setting("NameOfChurch", Db.CmsHost); if (ret.Approved) { var q = from a in Db.RecurringAmounts where a.PeopleId == PeopleId select a; foreach (var a in q) { if (a.ContributionFund.FundStatusId == 1 && a.Amt > 0) { Person.PostUnattendedContribution(Db, a.Amt ?? 0, a.FundId, "Recurring Giving", tranid: t.Id); } } var tot = q.Where(aa => aa.ContributionFund.FundStatusId == 1).Sum(aa => aa.Amt); t.TransactionPeople.Add(new TransactionPerson { PeopleId = Person.PeopleId, Amt = tot, }); NextDate = FindNextDate(Util.Now.Date.AddDays(1)); Db.SubmitChanges(); if (tot > 0) { Util.SendMsg(systemEmail, Db.CmsHost, Util.TryGetMailAddress(contributionemail), "Recurring {0} for {1}".Fmt(gift, church), "Your payment of ${0:N2} was processed this morning.".Fmt(tot), Util.ToMailAddressList(contributionemail), 0, null); } } else { Db.SubmitChanges(); var failedGivingMessage = Db.ContentHtml("FailedGivingMessage", Resources.ManagedGiving_FailedGivingMessage); var adminEmail = Db.Setting("AdminMail", systemEmail); Util.SendMsg(systemEmail, Db.CmsHost, Util.TryGetMailAddress(contributionemail), "Recurring {0} failed for {1}".Fmt(gift, church), failedGivingMessage.Replace("{first}", Person.PreferredName), Util.ToMailAddressList(contributionemail), 0, null); foreach (var p in Db.FinancePeople()) { Util.SendMsg(systemEmail, Db.CmsHost, Util.TryGetMailAddress(adminEmail), "Recurring Giving Failed on " + Db.CmsHost, "<a href='{0}Transactions/{2}'>message: {1}, tranid:{2}</a>".Fmt(Db.CmsHost, ret.Message, t.Id), Util.ToMailAddressList(p.EmailAddress), 0, null); } } return(1); }
private IGateway GetGateway(CMSDataContext db, PaymentInfo pi) { var tempgateway = db.Setting("TemporaryGateway", ""); if (!tempgateway.HasValue()) return db.Gateway(); var gateway = db.Setting("TransactionGateway", ""); switch (gateway.ToLower()) // Check to see if standard gateway is set up { case "sage": if ((pi.PreferredGivingType == "B" && pi.SageBankGuid.HasValue) || (pi.PreferredGivingType == "C" && pi.SageCardGuid.HasValue)) return db.Gateway(); break; case "transnational": if ((pi.PreferredGivingType == "B" && pi.TbnBankVaultId.HasValue) || (pi.PreferredGivingType == "C" && pi.TbnCardVaultId.HasValue)) return db.Gateway(); break; } // fall back to temporary gateway because the user hasn't migrated their payments off of the temporary gateway yet return db.Gateway(usegateway: tempgateway); }
internal static Expression VisitNumber( ParameterExpression parm, CMSDataContext Db, string number, CompareType op, DateTime? dt) { int n = number.ToInt2() ?? 1; var cdt = Db.Setting("DbConvertedDate", "1/1/1900").ToDate(); Expression<Func<Person, bool>> pred = null; switch (op) { case CompareType.Greater: pred = p => p.CreatedDate > cdt && p.Attends.Any(aa => aa.SeqNo == n && aa.MeetingDate > dt); break; case CompareType.Less: pred = p => p.CreatedDate > cdt && p.Attends.Any(aa => aa.SeqNo == n && aa.MeetingDate < dt); break; case CompareType.GreaterEqual: pred = p => p.CreatedDate > cdt && p.Attends.Any(aa => aa.SeqNo == n && aa.MeetingDate >= dt); break; case CompareType.LessEqual: pred = p => p.CreatedDate > cdt && p.Attends.Any(aa => aa.SeqNo == n && aa.MeetingDate <= dt); break; case CompareType.Equal: pred = p => p.CreatedDate > cdt && p.Attends.Any(aa => aa.SeqNo == n && aa.MeetingDate.Date == dt); break; case CompareType.NotEqual: case CompareType.IsNull: pred = p => p.CreatedDate > cdt && !p.Attends.Any(aa => aa.SeqNo == n && aa.MeetingDate.Date == dt); break; case CompareType.IsNotNull: pred = p => p.CreatedDate > cdt && p.Attends.Any(aa => aa.SeqNo == n); break; } Expression expr = Expression.Invoke(pred, parm); return expr; }
internal static Expression RecentVisitNumber( ParameterExpression parm, CMSDataContext Db, string number, int days, CompareType op, bool tf) { int n = number.ToInt2() ?? 1; var dt = DateTime.Now.AddDays(-days); var cdt = Db.Setting("DbConvertedDate", "1/1/1900").ToDate(); Expression<Func<Person, bool>> pred = p => p.CreatedDate > cdt && p.Attends.Any(aa => aa.SeqNo == n && aa.MeetingDate > dt); Expression expr = Expression.Invoke(pred, parm); if (!(op == CompareType.Equal && tf)) expr = Expression.Not(expr); return expr; }
public Contribution PostUnattendedContribution(CMSDataContext Db, decimal Amt, int? Fund, string Description, bool pledge = false, int? typecode = null) { if (!typecode.HasValue) { typecode = BundleTypeCode.Online; if (pledge) typecode = BundleTypeCode.OnlinePledge; } var now = DateTime.Now; var d = Util.Now.Date; var q = from b in Db.BundleHeaders where b.BundleHeaderTypeId == typecode where b.BundleStatusId == BundleStatusCode.Open where b.ContributionDate >= d where b.ContributionDate < now where b.ContributionDate.Year == now.Year where b.ContributionDate.Month == now.Month orderby b.ContributionDate descending select b; var bundle = q.FirstOrDefault(); if (bundle == null) { bundle = new BundleHeader { BundleHeaderTypeId = typecode.Value, BundleStatusId = BundleStatusCode.Open, CreatedBy = Util.UserId1, ContributionDate = d, CreatedDate = now, FundId = Db.Setting("DefaultFundId", "1").ToInt(), RecordStatus = false, TotalCash = 0, TotalChecks = 0, TotalEnvelopes = 0, BundleTotal = 0 }; Db.BundleHeaders.InsertOnSubmit(bundle); } if (!Fund.HasValue) Fund = (from f in Db.ContributionFunds where f.FundStatusId == 1 orderby f.FundId select f.FundId).First(); var FinanceManagerId = Db.Setting("FinanceManagerId", "").ToInt2(); if (!FinanceManagerId.HasValue) { var qu = from u in Db.Users where u.UserRoles.Any(ur => ur.Role.RoleName == "Finance") orderby u.Person.LastName select u.UserId; FinanceManagerId = qu.FirstOrDefault(); if (!FinanceManagerId.HasValue) FinanceManagerId = 1; } var bd = new CmsData.BundleDetail { BundleHeaderId = bundle.BundleHeaderId, CreatedBy = FinanceManagerId.Value, CreatedDate = now, }; var typid = ContributionTypeCode.CheckCash; if (pledge) typid = ContributionTypeCode.Pledge; bd.Contribution = new Contribution { CreatedBy = FinanceManagerId.Value, CreatedDate = bd.CreatedDate, FundId = Fund.Value, PeopleId = PeopleId, ContributionDate = bd.CreatedDate, ContributionAmount = Amt, ContributionStatusId = 0, ContributionTypeId = typid, ContributionDesc = Description, }; bundle.BundleDetails.Add(bd); Db.SubmitChanges(); return bd.Contribution; }
public void Run(Stream stream, CMSDataContext Db, IEnumerable<ContributorInfo> q, int set = 0) { pageEvents.set = set; pageEvents.PeopleId = 0; var contributors = q; PdfContentByte dc; var font = FontFactory.GetFont(FontFactory.HELVETICA, 11); var boldfont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 11); var doc = new Document(PageSize.LETTER); doc.SetMargins(36f, 30f, 24f, 36f); var w = PdfWriter.GetInstance(doc, stream); w.PageEvent = pageEvents; doc.Open(); dc = w.DirectContent; var prevfid = 0; var runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).FirstOrDefault(); runningtotals.Processed = 0; Db.SubmitChanges(); var count = 0; foreach (var ci in contributors) { if (set > 0 && pageEvents.FamilySet[ci.PeopleId] != set) continue; var contributions = APIContribution.contributions(Db, ci, FromDate, ToDate).ToList(); var pledges = APIContribution.pledges(Db, ci, ToDate).ToList(); var giftsinkind = APIContribution.GiftsInKind(Db, ci, FromDate, ToDate).ToList(); var nontaxitems = Db.Setting("DisplayNonTaxOnStatement", "false").ToBool() ? APIContribution.NonTaxItems(Db, ci, FromDate, ToDate).ToList() : new List<ContributionInfo>(); if ((contributions.Count + pledges.Count + giftsinkind.Count + nontaxitems.Count) == 0) { runningtotals.Processed += 1; runningtotals.CurrSet = set; Db.SubmitChanges(); if (set == 0) pageEvents.FamilySet[ci.PeopleId] = 0; continue; } pageEvents.NextPeopleId = ci.PeopleId; doc.NewPage(); if (prevfid != ci.FamilyId) { prevfid = ci.FamilyId; pageEvents.EndPageSet(); pageEvents.PeopleId = ci.PeopleId; } if (set == 0) pageEvents.FamilySet[ci.PeopleId] = 0; count++; var css = @" <style> h1 { font-size: 24px; font-weight:normal; margin-bottom:0; } h2 { font-size: 11px; font-weight:normal; margin-top: 0; } p { font-size: 11px; } </style> "; //----Church Name var t1 = new PdfPTable(1); t1.TotalWidth = 72f*5f; t1.DefaultCell.Border = Rectangle.NO_BORDER; var html1 = Db.ContentHtml("StatementHeader", Resource1.ContributionStatementHeader); var html2 = Db.ContentHtml("StatementNotice", Resource1.ContributionStatementNotice); var mh = new MyHandler(); using (var sr = new StringReader(css + html1)) XMLWorkerHelper.GetInstance().ParseXHtml(mh, sr); var cell = new PdfPCell(t1.DefaultCell); foreach (var e in mh.elements) if (e.Chunks.Count > 0) cell.AddElement(e); //cell.FixedHeight = 72f * 1.25f; t1.AddCell(cell); t1.AddCell("\n"); var t1a = new PdfPTable(1); t1a.TotalWidth = 72f*5f; t1a.DefaultCell.Border = Rectangle.NO_BORDER; var ae = new PdfPTable(1); ae.DefaultCell.Border = Rectangle.NO_BORDER; ae.WidthPercentage = 100; var a = new PdfPTable(1); a.DefaultCell.Indent = 25f; a.DefaultCell.Border = Rectangle.NO_BORDER; a.AddCell(new Phrase(ci.Name, font)); foreach (var line in ci.MailingAddress.SplitLines()) a.AddCell(new Phrase(line, font)); cell = new PdfPCell(a) {Border = Rectangle.NO_BORDER}; //cell.FixedHeight = 72f * 1.0625f; ae.AddCell(cell); cell = new PdfPCell(t1a.DefaultCell); cell.AddElement(ae); t1a.AddCell(ae); //-----Notice var t2 = new PdfPTable(1); t2.TotalWidth = 72f*3f; t2.DefaultCell.Border = Rectangle.NO_BORDER; var envno = ""; if (Db.Setting("PrintEnvelopeNumberOnStatement")) { var ev = Person.GetExtraValue(Db, ci.PeopleId, "EnvelopeNumber"); var s = Util.PickFirst(ev.Data, ev.IntValue.ToString(), ev.StrValue); if(s.HasValue()) envno = $" env: {Util.PickFirst(ev.Data, ev.IntValue.ToString(), ev.StrValue)}"; } t2.AddCell(Db.Setting("NoPrintDateOnStatement") ? new Phrase($"\nid:{ci.PeopleId}{envno} {ci.CampusId}", font) : new Phrase($"\nprinted: {DateTime.Now:d} id:{ci.PeopleId}{envno} {ci.CampusId}", font)); t2.AddCell(""); var mh2 = new MyHandler(); using (var sr = new StringReader(css + html2)) XMLWorkerHelper.GetInstance().ParseXHtml(mh2, sr); cell = new PdfPCell(t1.DefaultCell); foreach (var e in mh2.elements) if (e.Chunks.Count > 0) cell.AddElement(e); t2.AddCell(cell); // POSITIONING OF ADDRESSES //----Header var yp = doc.BottomMargin + Db.Setting("StatementRetAddrPos", "10.125").ToFloat()*72f; t1.WriteSelectedRows(0, -1, doc.LeftMargin - 0.1875f*72f, yp, dc); yp = doc.BottomMargin + Db.Setting("StatementAddrPos", "8.3375").ToFloat()*72f; t1a.WriteSelectedRows(0, -1, doc.LeftMargin, yp, dc); yp = doc.BottomMargin + 10.125f*72f; t2.WriteSelectedRows(0, -1, doc.LeftMargin + 72f*4.4f, yp, dc); //----Contributions doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ") {SpacingBefore = 72f*2.125f}); doc.Add(new Phrase($"\n Period: {FromDate:d} - {ToDate:d}", boldfont)); var pos = w.GetVerticalPosition(true); var ct = new ColumnText(dc); var colwidth = (doc.Right - doc.Left); var t = new PdfPTable(new[] {15f, 25f, 15f, 15f, 30f}); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 5; cell.Phrase = new Phrase("Contributions\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Date", boldfont)); t.AddCell(new Phrase("Description", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Amount", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_CENTER; if (ShowCheckNo) cell.Phrase = new Phrase("Check No", boldfont); else cell.Phrase = new Phrase("", boldfont); t.AddCell(cell); if (ShowNotes) t.AddCell(new Phrase("Notes", boldfont)); else t.AddCell(new Phrase("", boldfont)); t.DefaultCell.Border = Rectangle.NO_BORDER; var total = 0m; foreach (var c in contributions) { t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font)); t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_CENTER; if (ShowCheckNo) cell.Phrase = new Phrase(c.CheckNo, font); else cell.Phrase = new Phrase("", font); t.AddCell(cell); if (ShowNotes) t.AddCell(new Phrase(c.Description.trim(), font)); else t.AddCell(new Phrase("", font)); total += (c.ContributionAmount); } t.DefaultCell.Border = Rectangle.TOP_BORDER; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 2; cell.Phrase = new Phrase("Total Contributions for period", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(total.ToString("N2"), font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Colspan = 2; cell.Phrase = new Phrase(""); t.AddCell(cell); ct.AddElement(t); //------Pledges if (pledges.Count > 0) { t = new PdfPTable(new[] {25f, 15f, 15f, 15f, 30f}); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 5; cell.Phrase = new Phrase("\n\nPledges\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Fund", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Pledge", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Given", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); foreach (var c in pledges) { t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.PledgeAmount.ToString2("N2"), font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString2("N2"), font); t.AddCell(cell); t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); } ct.AddElement(t); } //------Gifts In Kind if (giftsinkind.Count > 0) { t = new PdfPTable(new[] {15f, 25f, 15f, 15f, 30f}); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; // Headers cell = new PdfPCell(t.DefaultCell); cell.Colspan = 5; cell.Phrase = new Phrase("\n\nGifts in Kind\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Date", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase("Fund", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase("Description", boldfont); t.AddCell(cell); t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); t.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var c in giftsinkind) { t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font)); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase(c.Fund, font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase(c.Description, font); t.AddCell(cell); } ct.AddElement(t); } //-----Summary t = new PdfPTable(new[] {40f, 15f, 45f}); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase("\n\nPeriod Summary\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Fund", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Amount", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; t.AddCell(new Phrase("", boldfont)); foreach (var c in APIContribution.quarterlySummary(Db, ci, FromDate, ToDate)) { t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font); t.AddCell(cell); t.AddCell(new Phrase("", boldfont)); } t.DefaultCell.Border = Rectangle.NO_BORDER; cell = new PdfPCell(t.DefaultCell); cell.Border = Rectangle.TOP_BORDER; cell.Colspan = 1; cell.Phrase = new Phrase("Total Contributions for period", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Border = Rectangle.TOP_BORDER; cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(total.ToString("N2"), font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase(""); t.AddCell(cell); ct.AddElement(t); //------NonTax if (nontaxitems.Count > 0) { t = new PdfPTable(new[] {15f, 25f, 15f, 15f, 30f}); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 5; cell.Phrase = new Phrase("\n\nNon Tax-Deductible Items\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Date", boldfont)); t.AddCell(new Phrase("Description", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Amount", boldfont); t.AddCell(cell); t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); t.DefaultCell.Border = Rectangle.NO_BORDER; var ntotal = 0m; foreach (var c in nontaxitems) { t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font)); t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font); t.AddCell(cell); t.AddCell(new Phrase("", boldfont)); if (ShowNotes) t.AddCell(new Phrase(c.Description, font)); else t.AddCell(new Phrase("", font)); ntotal += (c.ContributionAmount); } t.DefaultCell.Border = Rectangle.TOP_BORDER; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 2; cell.Phrase = new Phrase("Total Non Tax-Deductible Items for period", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(ntotal.ToString("N2"), font); t.AddCell(cell); t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); ct.AddElement(t); } var status = 0; while (ColumnText.HasMoreText(status)) { ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, pos); status = ct.Go(); pos = doc.Top; doc.NewPage(); } runningtotals.Processed += 1; runningtotals.CurrSet = set; Db.SubmitChanges(); } if (count == 0) { doc.NewPage(); doc.Add(new Phrase("no data")); } doc.Close(); if (set == LastSet()) runningtotals.Completed = DateTime.Now; Db.SubmitChanges(); }
public int DoGiving(CMSDataContext db) { var q = (from a in db.RecurringAmounts where a.PeopleId == PeopleId where a.ContributionFund.FundStatusId == 1 where a.ContributionFund.OnlineSort != null where a.Amt > 0 select new GivingConfirmation.FundItem() { Amt = a.Amt.Value, Desc = a.ContributionFund.FundName, Fundid = a.FundId }).ToList(); var total = q.Sum(vv => vv.Amt); if (total == 0) { return(0); } var paymentInfo = db.PaymentInfos.Single(x => x.PeopleId == PeopleId); var preferredType = paymentInfo.PreferredGivingType; var gw = GetGateway(db, paymentInfo); var orgid = (from o in db.Organizations where o.RegistrationTypeId == RegistrationTypeCode.ManageGiving select o.OrganizationId).FirstOrDefault(); var t = new Transaction { TransactionDate = DateTime.Now, TransactionId = "started", First = Person.FirstName, MiddleInitial = Person.MiddleName.Truncate(1) ?? "", Last = Person.LastName, Suffix = Person.SuffixCode, Amt = total, Description = "Recurring Giving", Testing = false, TransactionGateway = gw.GatewayType, Financeonly = true, PaymentType = preferredType, LastFourCC = preferredType == PaymentType.CreditCard ? paymentInfo.MaskedCard.Last(4) : null, LastFourACH = preferredType == PaymentType.Ach ? paymentInfo.MaskedAccount.Last(4) : null, OrgId = orgid, LoginPeopleId = Person.PeopleId, }; var vaultid = gw.VaultId(PeopleId); if (!vaultid.HasValue()) { t.Message = "Missing VaultId"; t.Approved = false; } db.Transactions.InsertOnSubmit(t); db.SubmitChanges(); if (!vaultid.HasValue()) { return(0); } var ret = gw.PayWithVault(PeopleId, total, "Recurring Giving", t.Id, preferredType); t.Message = ret.Message; t.AuthCode = ret.AuthCode; t.Approved = ret.Approved; t.TransactionId = ret.TransactionId; var gift = db.Setting("NameForPayment", "gift"); var church = db.Setting("NameOfChurch", db.CmsHost); var notify = db.RecurringGivingNotifyPersons(); var staff = notify[0]; var from = Util.TryGetMailAddress(staff.EmailAddress); if (ret.Approved) { NextDate = FindNextDate(Util.Now.Date.AddDays(1)); db.SubmitChanges(); var msg = db.Content("RecurringGiftNotice") ?? new Content { Title = $"Recurring {gift} for {{church}}", Body = $"Your gift of {total:C} was processed this morning." }; var body = GivingConfirmation.PostAndBuild(db, staff, Person, msg.Body, orgid, q, t, "Recurring Giving"); var subject = msg.Title.Replace("{church}", church); var m = new EmailReplacements(db, body, from); body = m.DoReplacements(db, Person); db.EmailFinanceInformation(from, Person, null, subject, body); } else { db.SubmitChanges(); var msg = db.Content("RecurringGiftFailedNotice") ?? new Content { Title = $"Recurring {gift} for {{church}} did not succeed", Body = @"Your payment of {total} failed to process this morning.<br> The message was '{message}'. Please contact the Finance office at the church." }; var subject = msg.Title.Replace("{church}", church); var body = msg.Body.Replace("{total}", $"${total:N2}") .Replace("{message}", ret.Message); var m = new EmailReplacements(db, body, from); body = m.DoReplacements(db, Person); db.Email(from, Person, null, subject, body, false); foreach (var p in db.RecurringGivingNotifyPersons()) { db.EmailFinanceInformation(from, p, null, $"Recurring Giving Failed on {db.CmsHost}", $"<a href='{db.CmsHost}/Transactions/{t.Id}'>message: {ret.Message}, tranid:{t.Id}</a>"); } } return(1); }
public int DoGiving(CMSDataContext Db) { var gateway = Db.Setting("TransactionGateway", ""); AuthorizeNet anet = null; SagePayments sage = null; if (gateway == "AuthorizeNet") anet = new AuthorizeNet(Db, testing: false); else if (gateway == "Sage") sage = new SagePayments(Db, testing: false); else return 0; TransactionResponse ret = null; var total = (from a in Db.RecurringAmounts where a.PeopleId == PeopleId where a.ContributionFund.FundStatusId == 1 select a.Amt).Sum(); if (!total.HasValue || total == 0) return 0; var preferredtype = (from pi in Db.PaymentInfos where pi.PeopleId == PeopleId select pi.PreferredGivingType).Single(); var t = new Transaction { TransactionDate = DateTime.Now, TransactionId = "started", First = Person.FirstName, MiddleInitial = Person.MiddleName.Truncate(1) ?? "", Last = Person.LastName, Suffix = Person.SuffixCode, Amt = total, Description = "Recurring Giving", Testing = false, TransactionGateway = gateway, Financeonly = true }; Db.Transactions.InsertOnSubmit(t); Db.SubmitChanges(); if (gateway == "AuthorizeNet") ret = anet.createCustomerProfileTransactionRequest(PeopleId, total ?? 0, "Recurring Giving", t.Id); else ret = sage.createVaultTransactionRequest(PeopleId, total ?? 0, "Recurring Giving", t.Id, preferredtype); t.TransactionPeople.Add(new TransactionPerson { PeopleId = PeopleId, Amt = total }); t.Message = ret.Message; t.AuthCode = ret.AuthCode; t.Approved = ret.Approved; t.TransactionId = ret.TransactionId; var systemEmail = Db.Setting("SystemEmailAddress", "*****@*****.**"); var contributionemail = (from ex in Person.PeopleExtras where ex.Field == "ContributionEmail" select ex.Data).SingleOrDefault(); if (contributionemail.HasValue()) contributionemail = contributionemail.Trim(); if (!Util.ValidEmail(contributionemail)) contributionemail = Person.FromEmail; var gift = Db.Setting("NameForPayment", "gift"); var church = Db.Setting("NameOfChurch", Db.CmsHost); if (ret.Approved) { var q = from a in Db.RecurringAmounts where a.PeopleId == PeopleId select a; foreach (var a in q) { if (a.ContributionFund.FundStatusId == 1 && a.Amt > 0) Person.PostUnattendedContribution(Db, a.Amt ?? 0, a.FundId, "Recurring Giving", pledge: false); } var tot = q.Where(aa => aa.ContributionFund.FundStatusId == 1).Sum(aa => aa.Amt); NextDate = FindNextDate(DateTime.Today.AddDays(1)); Db.SubmitChanges(); if (tot > 0) { Util.SendMsg(systemEmail, Db.CmsHost, Util.TryGetMailAddress(contributionemail), "Recurring {0} for {1}".Fmt(gift, church), "Your payment of ${0:N2} was processed this morning.".Fmt(tot), Util.ToMailAddressList(contributionemail), 0, null); } } else { Db.SubmitChanges(); var failedGivingMessage = Db.ContentHtml("FailedGivingMessage", Resources.ManagedGiving_FailedGivingMessage); var adminEmail = Db.Setting("AdminMail", systemEmail); Util.SendMsg(systemEmail, Db.CmsHost, Util.TryGetMailAddress(contributionemail), "Recurring {0} failed for {1}".Fmt(gift, church), failedGivingMessage.Replace("{first}", Person.PreferredName), Util.ToMailAddressList(contributionemail), 0, null); foreach (var p in Db.FinancePeople()) Util.SendMsg(systemEmail, Db.CmsHost, Util.TryGetMailAddress(adminEmail), "Recurring Giving Failed on " + Db.CmsHost, "<a href='{0}Transactions/{2}'>message: {1}, tranid:{2}</a>".Fmt(Db.CmsHost, ret.Message, t.Id), Util.ToMailAddressList(p.EmailAddress), 0, null); } return 1; }
public int DoGiving(CMSDataContext db) { var total = (from a in db.RecurringAmounts where a.PeopleId == PeopleId where a.ContributionFund.FundStatusId == 1 where a.ContributionFund.OnlineSort != null select a.Amt).Sum(); if (!total.HasValue || total == 0) return 0; var paymentInfo = db.PaymentInfos.Single(x => x.PeopleId == PeopleId); var preferredType = paymentInfo.PreferredGivingType; var gw = GetGateway(db, paymentInfo); var orgid = (from o in db.Organizations where o.RegistrationTypeId == RegistrationTypeCode.ManageGiving select o.OrganizationId).FirstOrDefault(); var t = new Transaction { TransactionDate = DateTime.Now, TransactionId = "started", First = Person.FirstName, MiddleInitial = Person.MiddleName.Truncate(1) ?? "", Last = Person.LastName, Suffix = Person.SuffixCode, Amt = total, Description = "Recurring Giving", Testing = false, TransactionGateway = gw.GatewayType, Financeonly = true, PaymentType = preferredType, LastFourCC = preferredType == PaymentType.CreditCard ? paymentInfo.MaskedCard.Last(4) : null, LastFourACH = preferredType == PaymentType.Ach ? paymentInfo.MaskedAccount.Last(4) : null, OrgId = orgid, }; db.Transactions.InsertOnSubmit(t); db.SubmitChanges(); var ret = gw.PayWithVault(PeopleId, total ?? 0, "Recurring Giving", t.Id, preferredType); t.Message = ret.Message; t.AuthCode = ret.AuthCode; t.Approved = ret.Approved; t.TransactionId = ret.TransactionId; var gift = db.Setting("NameForPayment", "gift"); var church = db.Setting("NameOfChurch", db.CmsHost); var q = from a in db.RecurringAmounts where a.PeopleId == PeopleId select a; var tot = q.Where(aa => aa.ContributionFund.FundStatusId == 1).Sum(aa => aa.Amt); t.TransactionPeople.Add(new TransactionPerson { PeopleId = Person.PeopleId, Amt = tot, }); var notify = db.RecurringGivingNotifyPersons(); var from = Util.TryGetMailAddress(notify[0].EmailAddress); if (ret.Approved) { foreach (var a in q) { if (a.ContributionFund.FundStatusId == 1 && a.ContributionFund.OnlineSort != null && a.Amt > 0) Person.PostUnattendedContribution(db, a.Amt ?? 0, a.FundId, "Recurring Giving", tranid: t.Id); } NextDate = FindNextDate(Util.Now.Date.AddDays(1)); db.SubmitChanges(); if (tot > 0) { var msg = db.Content("RecurringGiftNotice") ?? new Content { Title = $"Recurring {gift} for {{church}}", Body = "Your gift of {total} was processed this morning." }; var subject = msg.Title.Replace("{church}", church); var body = msg.Body.Replace("{total}", $"${tot:N2}"); var m = new EmailReplacements(db, body, from); body = m.DoReplacements(db, Person); db.EmailFinanceInformation(from, Person, null, subject, body); } } else { db.SubmitChanges(); var msg = db.Content("RecurringGiftFailedNotice") ?? new Content { Title = $"Recurring {gift} for {{church}} did not succeed", Body = @"Your payment of {total} failed to process this morning.<br> The message was '{message}'. Please contact the Finance office at the church." }; var subject = msg.Title.Replace("{church}", church); var body = msg.Body.Replace("{total}", $"${tot:N2}") .Replace("{message}", ret.Message); var m = new EmailReplacements(db, body, from); body = m.DoReplacements(db, Person); db.Email(from, Person, null, subject, body, false); foreach (var p in db.RecurringGivingNotifyPersons()) db.EmailFinanceInformation(from, p, null, $"Recurring Giving Failed on {db.CmsHost}", $"<a href='{db.CmsHost}/Transactions/{t.Id}'>message: {ret.Message}, tranid:{t.Id}</a>"); } return 1; }
public void DoWork() { Db = new CMSDataContext(Util.GetConnectionString(Host)); Db.Host = Host; Db.CommandTimeout = 1200; var noaddressok = Db.Setting("RequireAddressOnStatement", "true") == "false"; showCheckNo = Db.Setting("RequireCheckNoOnStatement", "false").ToLower() == "true"; showNotes = Db.Setting("RequireNotesOnStatement", "false").ToLower() == "true"; var qc = APIContribution.contributors(Db, fd, td, 0, 0, 0, noaddressok, useMinAmt: true, startswith: StartsWith, sort: Sort); var runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).First(); runningtotals.Count = qc.Count(); Db.SubmitChanges(); if (PDF) { if (showCheckNo || showNotes) { var c = new ContributionStatementsExtra { FromDate = fd, ToDate = td, typ = 3, ShowCheckNo = showCheckNo, ShowNotes = showNotes }; using (var stream = new FileStream(OutputFile, FileMode.Create)) c.Run(stream, Db, qc); LastSet = c.LastSet(); var sets = c.Sets(); foreach (var set in sets) using (var stream = new FileStream(Output(OutputFile, set), FileMode.Create)) c.Run(stream, Db, qc, set); runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).First(); runningtotals.LastSet = LastSet; runningtotals.Sets = string.Join(",", sets); runningtotals.Completed = DateTime.Now; Db.SubmitChanges(); } else { var c = new ContributionStatements { FromDate = fd, ToDate = td, typ = 3 }; using (var stream = new FileStream(OutputFile, FileMode.Create)) c.Run(stream, Db, qc); LastSet = c.LastSet(); var sets = c.Sets(); foreach (var set in sets) using (var stream = new FileStream(Output(OutputFile, set), FileMode.Create)) c.Run(stream, Db, qc, set); runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).First(); runningtotals.LastSet = LastSet; runningtotals.Sets = string.Join(",", sets); runningtotals.Completed = DateTime.Now; Db.SubmitChanges(); } } else { textStream = new StreamWriter(OutputFile); foreach (var c in qc) { pageStatement = 1; writeHeader(c); writeContributions(c); string hdrGift = " Date Fund Name Description of Gift-in-Kind Given as of {0:d}\n\n".Fmt(td); rWrite(hdrGift); writeSummary(c); runningtotals.Processed += 1; Db.SubmitChanges(); } textStream.Close(); runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).First(); runningtotals.Completed = DateTime.Now; Db.SubmitChanges(); } }