示例#1
0
        public ActionResult ContributionStatements(bool?pdf, DateTime?fromDate, DateTime?endDate, string startswith)
        {
            if (!fromDate.HasValue || !endDate.HasValue)
            {
                return(Content("<h3>Must have a Startdate and Enddate</h3>"));
            }
            var runningtotals = new ContributionsRun
            {
                Started   = DateTime.Now,
                Count     = 0,
                Processed = 0
            };

            if (!startswith.HasValue())
            {
                startswith = null;
            }
            DbUtil.Db.ContributionsRuns.InsertOnSubmit(runningtotals);
            DbUtil.Db.SubmitChanges();
            var cul    = DbUtil.Db.Setting("Culture", "en-US");
            var host   = Util.Host;
            var output = Output(pdf);

            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                Thread.CurrentThread.Priority         = ThreadPriority.Lowest;
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(cul);
                Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(cul);
                var m = new ContributionStatementsExtract(host, fromDate.Value, endDate.Value, pdf ?? false, output, startswith);
                m.DoWork();
            });
            return(Redirect("/Statements/Progress"));
        }
示例#2
0
        public ActionResult ContributionStatements(DateTime?fromDate, DateTime?endDate, string startswith, string sort, int?tagid, bool excludeelectronic, string customstatement = null, bool exportcontributors = false)
        {
            if (!fromDate.HasValue || !endDate.HasValue)
            {
                return(Content("<h3>Must have a Startdate and Enddate</h3>"));
            }
            var runningtotals = new ContributionsRun
            {
                Started   = DateTime.Now,
                Count     = 0,
                Processed = 0
            };
            var cs = Models.Report.ContributionStatements.GetStatementSpecification(customstatement);

            if (!startswith.HasValue())
            {
                startswith = null;
            }
            if (exportcontributors)
            {
                var        db          = DbUtil.Db;
                var        noaddressok = !db.Setting("RequireAddressOnStatement", true);
                const bool useMinAmt   = true;
                if (tagid == 0)
                {
                    tagid = null;
                }
                var qc = APIContribution.Contributors(db, fromDate.Value, endDate.Value, 0, 0, 0, cs.Funds, noaddressok, useMinAmt, startswith, sort, tagid: tagid, excludeelectronic: excludeelectronic);
                return(ExcelExportModel.ToDataTable(qc.ToList()).ToExcel("Contributors.xlsx"));
            }
            DbUtil.Db.ContributionsRuns.InsertOnSubmit(runningtotals);
            DbUtil.Db.SubmitChanges();
            var cul  = DbUtil.Db.Setting("Culture", "en-US");
            var host = Util.Host;

            var output = Output();

            if (tagid == 0)
            {
                tagid = null;
            }

            HostingEnvironment.QueueBackgroundWorkItem(ct =>
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(cul);
                Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(cul);
                var m = new ContributionStatementsExtract(host, fromDate.Value, endDate.Value, output, startswith, sort, tagid, excludeelectronic);
                m.DoWork(cs);
            });
            return(Redirect("/Statements/Progress"));
        }
示例#3
0
        public ActionResult ContributionStatements(DateTime?fromDate, DateTime?endDate, string startswith, string sort, int?tagid, bool excludeelectronic)
        {
            if (!fromDate.HasValue || !endDate.HasValue)
            {
                return(Content("<h3>Must have a Startdate and Enddate</h3>"));
            }
            var runningtotals = new ContributionsRun
            {
                Started   = DateTime.Now,
                Count     = 0,
                Processed = 0
            };

            if (!startswith.HasValue())
            {
                startswith = null;
            }
            DbUtil.Db.ContributionsRuns.InsertOnSubmit(runningtotals);
            DbUtil.Db.SubmitChanges();
            var cul  = DbUtil.Db.Setting("Culture", "en-US");
            var host = Util.Host;

            var output = Output();

            if (tagid == 0)
            {
                tagid = null;
            }

            HostingEnvironment.QueueBackgroundWorkItem(ct =>
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(cul);
                Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(cul);
                var m = new ContributionStatementsExtract(host, fromDate.Value, endDate.Value, output, startswith, sort, tagid, excludeelectronic);
                m.DoWork();
            });
            return(Redirect("/Statements/Progress"));
        }
示例#4
0
        private void HtmlToPdfMethod(Stream stream, CMSDataContext db, IEnumerable <ContributorInfo> q, StatementSpecification cs, int set)
        {
            IConverter       converter     = GetConverter();
            string           nameOfChurch  = db.Setting("NameOfChurch", "Name of Church");
            string           startAddress  = db.Setting("StartAddress", "Start Address");
            string           churchPhone   = db.Setting("ChurchPhone", "(000) 000-0000");
            string           html          = cs.Template ?? db.Content("StatementTemplate", Resource1.ContributionStatementTemplate, ContentTypeCode.TypeText).Body;
            string           bodyHtml      = cs.TemplateBody ?? db.Content("StatementTemplateBody", Resource1.ContributionStatementTemplateBody, ContentTypeCode.TypeText).Body;
            string           header        = cs.Header ?? db.Content("StatementHeader", string.Format(Resource1.ContributionStatementHeader, nameOfChurch, startAddress, churchPhone), ContentTypeCode.TypeHtml).Body;
            string           notice        = cs.Notice ?? db.Content("StatementNotice", string.Format(Resource1.ContributionStatementNotice, nameOfChurch), ContentTypeCode.TypeHtml).Body;
            string           footer        = cs.Footer ?? db.Content("StatementTemplateFooter", "", ContentTypeCode.TypeText).Body;
            ContributionsRun runningtotals = db.ContributionsRuns.Where(mm => mm.UUId == UUId).SingleOrDefault();
            StatementOptions options;

            if (!GetStatementOptions(bodyHtml, out options))
            {
                GetStatementOptions(html, out options);
            }

            var toDate = ToDate.Date.AddHours(24).AddSeconds(-1);

            var document = new HtmlToPdfDocument
            {
                GlobalSettings =
                {
                    DocumentTitle  = (cs.Description ?? "Contribution Statement {date}").Replace("{date}", $"{toDate:d}"),
                    Margins        = options.Margins.Settings,
                    PaperSize      = options.PaperSize,
                    ProduceOutline = false,
                }
            };

            var familiesInSet = pageEvents.FamilySet.Where(k => k.Value == set).Select(k => k.Key);
            var contributors  = q.Where(c => set == 0 || familiesInSet.Contains(c.FamilyId));
            var count         = contributors.Count();

            if (count == 0)
            {
                document.Objects.Add(new ObjectSettings {
                    HtmlText = @"<p>no data</p>
                    <a href=""https://docs.touchpointsoftware.com/Finance/ContributionStatements.html#troubleshooting"">
                    See this help document docs.touchpointsoftware.com/Finance/ContributionStatements.html
                    </a>"
                });
                var bytes = converter.Convert(document);
                stream.Write(bytes, 0, bytes.Length);
                return;
            }

            if (runningtotals != null)
            {
                runningtotals.Processed = 0;
            }
            db.SubmitChanges();

            Document combinedPDF     = new Document();
            var      combinedPDFName = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.pdf");

            using (FileStream combinedStream = new FileStream(combinedPDFName, FileMode.Create))
            {
                using (PdfCopy writer = new PdfCopy(combinedPDF, combinedStream))
                {
                    combinedPDF.Open();

                    var lastFamilyId = 0;
                    foreach (var contributor in contributors)
                    {
                        if (runningtotals != null)
                        {
                            runningtotals.Processed += 1;
                            runningtotals.CurrSet    = set;
                            db.SubmitChanges();
                        }

                        if (lastFamilyId != contributor.FamilyId)
                        {
                            lastFamilyId = contributor.FamilyId;

                            if (set == 0)
                            {
                                pageEvents.FamilySet[contributor.FamilyId] = 0;
                            }
                        }

                        var contributions = APIContribution.Contributions(db, contributor, FromDate, toDate, cs.Funds).ToList();
                        var pledges       = APIContribution.Pledges(db, contributor, toDate, cs.Funds).ToList();
                        var giftsinkind   = APIContribution.GiftsInKind(db, contributor, FromDate, toDate, cs.Funds).ToList();
                        var nontaxitems   = APIContribution.NonTaxItems(db, contributor, FromDate, toDate, cs.Funds).ToList();

                        if ((contributions.Count + pledges.Count + giftsinkind.Count + nontaxitems.Count) > 0)
                        {
                            contributor.MailingAddress = string.Join("<br/>", contributor.MailingAddress.SplitLines());
                            var taxSummary    = SumByFund(contributions);
                            var nontaxSummary = SumByFund(nontaxitems.Select(i => new NormalContribution(i)).ToList());
                            if (options.CombinedTaxSummary)
                            {
                                taxSummary.Combine(SumByFund(giftsinkind.Select(i => new NormalContribution(i)).ToList()));
                            }

                            var data = new StatementContext
                            {
                                fromDate       = FromDate,
                                toDate         = toDate,
                                header         = "",
                                notice         = "",
                                now            = DateTime.Now,
                                body           = "",
                                footer         = "",
                                contributor    = contributor,
                                envelopeNumber = Convert.ToString(Person.GetExtraValue(db, contributor.PeopleId, "EnvelopeNumber")?.IntValue),
                                contributions  = new ListOfNormalContributions(contributions),
                                pledges        = pledges,
                                giftsinkind    = giftsinkind,
                                nontaxitems    = nontaxitems,
                                taxSummary     = taxSummary,
                                nontaxSummary  = nontaxSummary,
                                totalGiven     = taxSummary.Total + nontaxSummary.Total
                            };
                            data.header = db.RenderTemplate(header, data);
                            data.notice = db.RenderTemplate(notice, data);
                            data.body   = db.RenderTemplate(bodyHtml, data);
                            data.footer = db.RenderTemplate(footer, data);
                            var htmlDocument = db.RenderTemplate(html, data);
                            document.Objects.Clear();
                            document.Objects.Add(new ObjectSettings
                            {
                                CountPages     = true,
                                FooterSettings = options.Footer.Settings,
                                HeaderSettings = options.Header.Settings,
                                HtmlText       = htmlDocument,
                                WebSettings    = new WebSettings
                                {
                                    EnableJavascript = false,
                                    PrintBackground  = true
                                },
                                LoadSettings = new LoadSettings {
                                    BlockLocalFileAccess = true
                                }
                            });
                        }
                        else
                        {
                            continue;
                        }

                        var bytes     = converter.Convert(document);
                        var pageCount = 0;
                        using (PdfReader reader = new PdfReader(bytes))
                        {
                            pageCount = reader.NumberOfPages;
                            for (int p = 0; p < pageCount; p++)
                            {
                                var page = writer.GetImportedPage(reader, p + 1);
                                writer.AddPage(page);
                            }
                        }

                        if (set == 0)
                        {
                            pageEvents.FamilySet[contributor.FamilyId] += pageCount;
                        }
                    }
                }
            }
            using (var combined = File.OpenRead(combinedPDFName))
            {
                combined.CopyTo(stream);
            }
        }
        public ActionResult ContributionStatements(DateTime?fromDate, DateTime?endDate, string startswith, string sort, int?tagid, bool excludeelectronic, string customstatement = null, bool exportcontributors = false)
        {
            if (!fromDate.HasValue || !endDate.HasValue)
            {
                return(Content("<h3>Must have a Startdate and Enddate</h3>"));
            }

            if (fromDate.Value > endDate.Value)
            {
                return(Content("<h3>The Startdate must be earlier than the Enddate</h3>"));
            }

            var spec = ContributionStatementsExtract.GetStatementSpecification(CurrentDatabase, customstatement);

            if (!startswith.HasValue())
            {
                startswith = null;
            }
            var        noaddressok = !CurrentDatabase.Setting("RequireAddressOnStatement", true);
            const bool useMinAmt   = true;

            if (tagid == 0)
            {
                tagid = null;
            }
            var qc           = APIContribution.Contributors(CurrentDatabase, fromDate.Value, endDate.Value, 0, 0, 0, spec.Funds, noaddressok, useMinAmt, startswith, sort, tagid: tagid, excludeelectronic: excludeelectronic);
            var contributors = qc.ToList();

            if (exportcontributors)
            {
                return(ExcelExportModel.ToDataTable(contributors).ToExcel("Contributors.xlsx"));
            }
            var statementsRun = new ContributionsRun
            {
                Started   = DateTime.Now,
                Count     = contributors.Count,
                Processed = 0,
                UUId      = Guid.NewGuid(),
                UserId    = CurrentDatabase.UserId,
            };

            CurrentDatabase.ContributionsRuns.InsertOnSubmit(statementsRun);
            CurrentDatabase.SubmitChanges();
            var cul  = CurrentDatabase.Setting("Culture", "en-US");
            var host = CurrentDatabase.Host;
            var id   = $"{statementsRun.UUId:n}";

            var output = Output(host, id);

            if (tagid == 0)
            {
                tagid = null;
            }

            var showCheckNo = CurrentDatabase.Setting("RequireCheckNoOnStatement");
            var showNotes   = CurrentDatabase.Setting("RequireNotesOnStatement");
            var statements  = new ContributionStatements
            {
                UUId     = Guid.Parse(id),
                FromDate = fromDate.Value,
                ToDate   = endDate.Value,
                typ      = 3,
                //TODO: once we switch to entirely html-based statement templates we won't need to check for these options
                NumberOfColumns = showCheckNo || showNotes ? 1 : 2,
                ShowCheckNo     = showCheckNo,
                ShowNotes       = showNotes,
            };

            if (CurrentDatabase.Setting("UseNewStatementsFormat"))
            {
                // Must do this before entering the background worker because it relies on the Application context
                statements.GetConverter();
            }

            var elmah = Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current);

            HostingEnvironment.QueueBackgroundWorkItem(ct =>
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(cul);
                Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(cul);
                try
                {
                    var m = new ContributionStatementsExtract(host, fromDate.Value, endDate.Value, output, startswith, sort, tagid, excludeelectronic)
                    {
                        id = id
                    };
                    m.DoWork(statements, spec, contributors);
                }
                catch (Exception e)
                {
                    elmah.Log(new Elmah.Error(e));
                    var db        = CMSDataContext.Create(host);
                    var run       = db.ContributionsRuns.Single(c => c.UUId == Guid.Parse(id));
                    run.Error     = e.Message;
                    run.Completed = DateTime.Now;
                    db.SubmitChanges();
                }
            });
            return(Redirect($"/Statements/Progress/{id}"));
        }