/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); nbInvalid.Visible = false; var pledgeId = PageParameter("PledgeId").AsInteger(); if (!IsPostBack) { ShowDetail(pledgeId); } // Add any attribute controls. // This must be done here regardless of whether it is a postback so that the attribute values will get saved. var pledge = new FinancialPledgeService(new RockContext()).Get(pledgeId); if (pledge == null) { pledge = new FinancialPledge(); } pledge.LoadAttributes(); phAttributes.Controls.Clear(); Helper.AddEditControls(pledge, phAttributes, true, BlockValidationGroup); }
/// <summary> /// Creates a Linq Expression that can be applied to an IQueryable to filter the result set. /// </summary> /// <param name="entityType">The type of entity in the result set.</param> /// <param name="serviceInstance">A service instance that can be queried to obtain the result set.</param> /// <param name="parameterExpression">The input parameter that will be injected into the filter expression.</param> /// <param name="selection">A formatted string representing the filter settings.</param> /// <returns> /// A Linq Expression that can be used to filter an IQueryable. /// </returns> /// <exception cref="System.Exception">Filter issue(s): + errorMessages.AsDelimited( ; )</exception> public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection) { var settings = new FilterSettings(selection); var context = (RockContext)serviceInstance.Context; // Get the Financial Pledge Data View. var dataView = DataComponentSettingsHelper.GetDataViewForFilterComponent(settings.DataViewGuid, context); // Evaluate the Data View that defines the Person's Financial Pledge. var financialPledgeService = new FinancialPledgeService(context); var financialPledgeQuery = financialPledgeService.Queryable(); if (dataView != null) { financialPledgeQuery = DataComponentSettingsHelper.FilterByDataView(financialPledgeQuery, dataView, financialPledgeService); } var pledgePersonsKey = financialPledgeQuery.Select(a => a.PersonAliasId); // Get all of the Person corresponding to the qualifying Financial Pledges. var qry = new PersonService(context).Queryable() .Where(g => g.Aliases.Any(k => pledgePersonsKey.Contains(k.Id))); // Retrieve the Filter Expression. var extractedFilterExpression = FilterExpressionExtractor.Extract <Model.Person>(qry, parameterExpression, "g"); return(extractedFilterExpression); }
/// <summary> /// Handles the Delete event of the gPledges control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void gPledges_Delete(object sender, RowEventArgs e) { RockTransactionScope.WrapTransaction(() => { var pledgeService = new FinancialPledgeService(); var pledge = pledgeService.Get((int)e.RowKeyValue); string errorMessage; if (pledge == null) { return; } if (!pledgeService.CanDelete(pledge, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } pledgeService.Delete(pledge, CurrentPersonId); pledgeService.Save(pledge, CurrentPersonId); }); BindGrid(); }
public void FinancialPledgeDateKeySavesCorrectly() { var rockContext = new RockContext(); var financialPledgeService = new FinancialPledgeService(rockContext); var financialPledge = BuildFinancialPledge(rockContext, Convert.ToDateTime("3/15/2010"), Convert.ToDateTime("3/16/2010")); financialPledgeService.Add(financialPledge); rockContext.SaveChanges(); var financialPledgeId = financialPledge.Id; // We're bypassing the model because the model doesn't user the FinancialPledgeDateKey from the database, // but it still needs to be correct for inner joins to work correctly. var result = rockContext.Database. SqlQuery <int>($"SELECT StartDateKey FROM FinancialPledge WHERE Id = {financialPledgeId}").First(); Assert.AreEqual(20100315, result); result = rockContext.Database. SqlQuery <int>($"SELECT EndDateKey FROM FinancialPledge WHERE Id = {financialPledgeId}").First(); Assert.AreEqual(20100316, result); }
public void FinancialPledgeDateKeyJoinsCorrectly() { var expectedRecordCount = 15; var year = 2015; var rockContext = new RockContext(); var financialPledgeService = new FinancialPledgeService(rockContext); var minDateValue = TestDataHelper.GetAnalyticsSourceMinDateForYear(rockContext, year); var maxDateValue = TestDataHelper.GetAnalyticsSourceMaxDateForYear(rockContext, year); for (var i = 0; i < 15; i++) { var financialPledge = BuildFinancialPledge(rockContext, TestDataHelper.GetRandomDateInRange(minDateValue, maxDateValue), TestDataHelper.GetRandomDateInRange(minDateValue, maxDateValue)); financialPledgeService.Add(financialPledge); } rockContext.SaveChanges(); var financialPledges = financialPledgeService. Queryable("AnalyticsSourceDate"). Where(i => i.ForeignKey == financialPledgeForeignKey). Where(i => i.StartSourceDate.CalendarYear == year); Assert.AreEqual(expectedRecordCount, financialPledges.Count()); financialPledges = financialPledgeService. Queryable("AnalyticsSourceDate"). Where(i => i.ForeignKey == financialPledgeForeignKey). Where(i => i.EndSourceDate.CalendarYear == year); Assert.AreEqual(expectedRecordCount, financialPledges.Count()); }
/// <summary> /// Handles the Click event of the btnConfirmYes control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnConfirmYes_Click(object sender, EventArgs e) { var pledges = Session["CachedPledges"] as List <FinancialPledge>; if (pledges == null) { return; } var rockContext = new RockContext(); var pledgeService = new FinancialPledgeService(rockContext); foreach (var pledge in pledges) { if (pledge == null || !pledge.IsValid) { continue; } pledgeService.Add(pledge); } rockContext.SaveChanges(); Session.Remove("CachedPledges"); ShowReceipt(pledges.Select(p => p.Id)); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> /// <exception cref="System.NotImplementedException"></exception> protected void btnSave_Click(object sender, EventArgs e) { FinancialPledge pledge; var pledgeService = new FinancialPledgeService(); var pledgeId = int.Parse(hfPledgeId.Value); if (pledgeId == 0) { pledge = new FinancialPledge(); pledgeService.Add(pledge, CurrentPersonId); } else { pledge = pledgeService.Get(pledgeId); } pledge.PersonId = ppPerson.PersonId; pledge.AccountId = int.Parse(fpFund.SelectedValue); pledge.TotalAmount = decimal.Parse(tbAmount.Text); pledge.StartDate = dpDateRange.LowerValue.Value; pledge.EndDate = dpDateRange.UpperValue.Value; pledge.PledgeFrequencyValueId = int.Parse(ddlFrequencyType.SelectedValue); if (!pledge.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => pledgeService.Save(pledge, CurrentPersonId)); NavigateToParentPage(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> /// <exception cref="System.NotImplementedException"></exception> protected void btnSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var pledgeService = new FinancialPledgeService(rockContext); var person = FindPerson(rockContext); var pledges = GetPledges(person).ToList(); // Does this person already have a pledge for these accounts? // If so, give them the option to create a new one? var personPledgeAccountIds = pledgeService.Queryable() .Where(p => p.PersonId == person.Id) .Select(p => p.AccountId) .ToList(); if (Accounts.Any(a => personPledgeAccountIds.Contains(a.Id))) { pnlConfirm.Visible = true; Session.Add("CachedPledges", pledges); return; } foreach (var pledge in pledges) { if (!pledge.IsValid) { continue; } pledgeService.Add(pledge); } rockContext.SaveChanges(); ShowReceipt(pledges.Select(p => p.Id)); }
/// <summary> /// Handles the Click event of the btnConfirmYes control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnConfirmYes_Click(object sender, EventArgs e) { var pledges = Session["CachedPledges"] as List <FinancialPledge>; if (pledges == null) { return; } RockTransactionScope.WrapTransaction(() => { foreach (var pledge in pledges) { if (pledge == null || !pledge.IsValid) { continue; } var pledgeService = new FinancialPledgeService(); pledgeService.Add(pledge, CurrentPersonId); pledgeService.Save(pledge, CurrentPersonId); } Session.Remove("CachedPledges"); ShowReceipt(pledges.Select(p => p.Id)); }); }
/// <summary> /// Event when the user clicks to delete the pledge /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void rptPledges_Delete(object sender, CommandEventArgs e) { var pledgeGuid = e.CommandArgument.ToStringSafe().AsGuid(); var rockContext = new RockContext(); var pledgeService = new FinancialPledgeService(rockContext); var pledge = pledgeService.Get(pledgeGuid); string errorMessage; if (pledge == null) { return; } if (!pledgeService.CanDelete(pledge, out errorMessage)) { mdWarningAlert.Show(errorMessage, ModalAlertType.Information); return; } pledgeService.Delete(pledge); rockContext.SaveChanges(); ShowDetail(); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { pnlUpdateMessage.Visible = false; pnlResults.Visible = true; int?accountId = apAccount.SelectedValue.AsIntegerOrNull(); if (!accountId.HasValue) { return; } var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(drpSlidingDateRange.DelimitedValues); DateTime?start = dateRange.Start ?? (DateTime?)System.Data.SqlTypes.SqlDateTime.MinValue; DateTime?end = dateRange.End ?? ( DateTime? )System.Data.SqlTypes.SqlDateTime.MaxValue; var minPledgeAmount = nrePledgeAmount.LowerValue; var maxPledgeAmount = nrePledgeAmount.UpperValue; var minComplete = nrePercentComplete.LowerValue; var maxComplete = nrePercentComplete.UpperValue; var minGiftAmount = nreAmountGiven.LowerValue; var maxGiftAmount = nreAmountGiven.UpperValue; int includeOption = rblInclude.SelectedValueAsInt() ?? 0; bool includePledges = includeOption != 1; bool includeGifts = includeOption != 0; DataSet ds = FinancialPledgeService.GetPledgeAnalytics(accountId.Value, start, end, minPledgeAmount, maxPledgeAmount, minComplete, maxComplete, minGiftAmount, maxGiftAmount, includePledges, includeGifts); System.Data.DataView dv = ds.Tables[0].DefaultView; if (gList.SortProperty != null) { try { var sortProperties = new List <string>(); foreach (string prop in gList.SortProperty.Property.SplitDelimitedValues(false)) { sortProperties.Add(string.Format("[{0}] {1}", prop, gList.SortProperty.DirectionString)); } dv.Sort = sortProperties.AsDelimited(", "); } catch { dv.Sort = "[LastName] ASC, [NickName] ASC"; } } else { dv.Sort = "[LastName] ASC, [NickName] ASC"; } gList.DataSource = dv; gList.DataBind(); }
/// <summary> /// Gets the pledge data for the given person and year. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="statementYear">The statement year.</param> /// <param name="personAliasIds">The person alias ids.</param> /// <returns></returns> private static List <PledgeSummary> GetPledgeDataForPersonYear(RockContext rockContext, int statementYear, List <int> personAliasIds) { var pledges = new FinancialPledgeService(rockContext).Queryable().AsNoTracking() .Where(p => p.PersonAliasId.HasValue && personAliasIds.Contains(p.PersonAliasId.Value) && p.StartDate.Year <= statementYear && p.EndDate.Year >= statementYear) .GroupBy(p => p.Account) .Select(g => new PledgeSummary { AccountId = g.Key.Id, AccountName = g.Key.Name, PublicName = g.Key.PublicName, AmountPledged = g.Sum(p => p.TotalAmount), PledgeStartDate = g.Min(p => p.StartDate), PledgeEndDate = g.Max(p => p.EndDate) }) .ToList(); // add detailed pledge information foreach (var pledge in pledges) { var adjustedPledgeEndDate = pledge.PledgeEndDate.Value.Date; var statementYearEnd = new DateTime(statementYear + 1, 1, 1); if (adjustedPledgeEndDate != DateTime.MaxValue.Date) { adjustedPledgeEndDate = adjustedPledgeEndDate.AddDays(1); } if (adjustedPledgeEndDate > statementYearEnd) { adjustedPledgeEndDate = statementYearEnd; } if (adjustedPledgeEndDate > RockDateTime.Now) { adjustedPledgeEndDate = RockDateTime.Now; } pledge.AmountGiven = new FinancialTransactionDetailService(rockContext).Queryable() .Where(t => t.AccountId == pledge.AccountId && t.Transaction.AuthorizedPersonAliasId.HasValue && personAliasIds.Contains(t.Transaction.AuthorizedPersonAliasId.Value) && t.Transaction.TransactionDateTime >= pledge.PledgeStartDate && t.Transaction.TransactionDateTime < adjustedPledgeEndDate) .Sum(t => ( decimal? )t.Amount) ?? 0; pledge.AmountRemaining = (pledge.AmountGiven > pledge.AmountPledged) ? 0 : (pledge.AmountPledged - pledge.AmountGiven); if (pledge.AmountPledged > 0) { var test = ( double )pledge.AmountGiven / ( double )pledge.AmountPledged; pledge.PercentComplete = ( int )((pledge.AmountGiven * 100) / pledge.AmountPledged); } } return(pledges); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="pledgeId">The pledge identifier.</param> public void ShowDetail(int pledgeId) { pnlDetails.Visible = true; var frequencyTypeGuid = new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY); ddlFrequencyType.BindToDefinedType(DefinedTypeCache.Read(frequencyTypeGuid), true); FinancialPledge pledge = null; if (pledgeId > 0) { pledge = new FinancialPledgeService(new RockContext()).Get(pledgeId); lActionTitle.Text = ActionTitle.Edit(FinancialPledge.FriendlyTypeName).FormatAsHtmlTitle(); } if (pledge == null) { pledge = new FinancialPledge(); lActionTitle.Text = ActionTitle.Add(FinancialPledge.FriendlyTypeName).FormatAsHtmlTitle(); } var isReadOnly = !IsUserAuthorized(Authorization.EDIT); var isNewPledge = pledge.Id == 0; hfPledgeId.Value = pledge.Id.ToString(); if (pledge.PersonAlias != null) { ppPerson.SetValue(pledge.PersonAlias.Person); } else { ppPerson.SetValue(null); } ppPerson.Enabled = !isReadOnly; apAccount.SetValue(pledge.Account); apAccount.Enabled = !isReadOnly; tbAmount.Text = !isNewPledge?pledge.TotalAmount.ToString() : string.Empty; tbAmount.ReadOnly = isReadOnly; dpDateRange.LowerValue = pledge.StartDate; dpDateRange.UpperValue = pledge.EndDate; dpDateRange.ReadOnly = isReadOnly; ddlFrequencyType.SelectedValue = !isNewPledge?pledge.PledgeFrequencyValueId.ToString() : string.Empty; ddlFrequencyType.Enabled = !isReadOnly; if (isReadOnly) { nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(FinancialPledge.FriendlyTypeName); lActionTitle.Text = ActionTitle.View(BlockType.FriendlyTypeName); btnCancel.Text = "Close"; } btnSave.Visible = !isReadOnly; }
/// <summary> /// Shows the detail. /// </summary> /// <param name="itemKey">The item key.</param> /// <param name="itemKeyValue">The item key value.</param> public void ShowDetail(string itemKey, int itemKeyValue) { pnlDetails.Visible = true; var frequencyTypeGuid = new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY); ddlFrequencyType.BindToDefinedType(DefinedTypeCache.Read(frequencyTypeGuid)); FinancialPledge pledge; if (itemKeyValue > 0) { pledge = new FinancialPledgeService().Get(itemKeyValue); lActionTitle.Text = ActionTitle.Edit(FinancialPledge.FriendlyTypeName); } else { pledge = new FinancialPledge(); lActionTitle.Text = ActionTitle.Add(FinancialPledge.FriendlyTypeName); } var isReadOnly = !IsUserAuthorized("Edit"); var isNewPledge = pledge.Id == 0; hfPledgeId.Value = pledge.Id.ToString(); ppPerson.SetValue(pledge.Person); ppPerson.Enabled = !isReadOnly; fpFund.SetValue(pledge.Account); fpFund.Enabled = !isReadOnly; tbAmount.Text = !isNewPledge?pledge.TotalAmount.ToString() : string.Empty; tbAmount.ReadOnly = isReadOnly; dtpStartDate.Text = !isNewPledge?pledge.StartDate.ToShortDateString() : string.Empty; dtpStartDate.ReadOnly = isReadOnly; dtpEndDate.Text = !isNewPledge?pledge.EndDate.ToShortDateString() : string.Empty; dtpEndDate.ReadOnly = isReadOnly; ddlFrequencyType.SelectedValue = !isNewPledge?pledge.PledgeFrequencyValueId.ToString() : string.Empty; ddlFrequencyType.Enabled = !isReadOnly; if (isReadOnly) { nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(FinancialPledge.FriendlyTypeName); lActionTitle.Text = ActionTitle.View(BlockType.FriendlyTypeName); btnCancel.Text = "Close"; } btnSave.Visible = !isReadOnly; }
/// <summary> /// Event when the user clicks to edit the pledge /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void rptPledges_Edit(object sender, CommandEventArgs e) { var pledgeGuid = e.CommandArgument.ToStringSafe().AsGuid(); var rockContext = new RockContext(); var pledgeService = new FinancialPledgeService(rockContext); var pledge = pledgeService.Get(pledgeGuid); if (pledge != null) { var queryParams = new Dictionary <string, string>(); queryParams.AddOrReplace(PageParameterKey.PledgeId, pledge.Id.ToString()); queryParams.AddOrReplace(PageParameterKey.PersonActionIdentifier, Person.GetPersonActionIdentifier("pledge")); NavigateToLinkedPage(AttributeKey.PledgeDetailPage, queryParams); } }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override System.Linq.Expressions.Expression GetExpression(Type entityType, Data.IService serviceInstance, System.Linq.Expressions.ParameterExpression parameterExpression, string selection) { string[] selectionValues = selection.Split('|'); if (selectionValues.Length >= 1) { var accountGuids = selectionValues[0].Split(',').Select(a => a.AsGuid()).ToList(); var accountIds = new FinancialAccountService((RockContext)serviceInstance.Context).GetByGuids(accountGuids).Select(a => a.Id).ToList(); var qry = new FinancialPledgeService((RockContext)serviceInstance.Context).Queryable() .Where(p => p.AccountId.HasValue && accountIds.Contains(p.AccountId.Value)); Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.FinancialPledge>(qry, parameterExpression, "p"); return(extractedFilterExpression); } return(null); }
private void ShowReceipt(IEnumerable <int> ids) { // Pledges need to be loaded fresh from the database so they can // be attached to a context and be fully hydrated with data. var pledgeService = new FinancialPledgeService(); var pledges = pledgeService.Queryable().Where(p => ids.Contains(p.Id)); var person = pledges.Select(p => p.Person).FirstOrDefault(); rptCompletedPledges.DataSource = pledges.ToList(); rptCompletedPledges.DataBind(); if (person != null) { lPersonFullName.Text = person.FullName; } pnlForm.Visible = false; pnlReceipt.Visible = true; }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> /// <exception cref="System.NotImplementedException"></exception> protected void btnSave_Click(object sender, EventArgs e) { FinancialPledge pledge; var rockContext = new RockContext(); var pledgeService = new FinancialPledgeService(rockContext); var pledgeId = hfPledgeId.Value.AsInteger(); if (pledgeId == 0) { pledge = new FinancialPledge(); pledgeService.Add(pledge); } else { pledge = pledgeService.Get(pledgeId); } pledge.PersonAliasId = ppPerson.PersonAliasId; pledge.GroupId = ddlGroup.SelectedValueAsInt(); pledge.AccountId = apAccount.SelectedValue.AsIntegerOrNull(); pledge.TotalAmount = tbAmount.Text.AsDecimal(); pledge.StartDate = dpDateRange.LowerValue.HasValue ? dpDateRange.LowerValue.Value : DateTime.MinValue; pledge.EndDate = dpDateRange.UpperValue.HasValue ? dpDateRange.UpperValue.Value : DateTime.MaxValue; pledge.PledgeFrequencyValueId = dvpFrequencyType.SelectedValue.AsIntegerOrNull(); pledge.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, pledge); if (!pledge.IsValid) { ShowInvalidResults(pledge.ValidationResults); return; } rockContext.SaveChanges(); pledge.SaveAttributeValues(rockContext); NavigateToParentPage(); }
/// <summary> /// Binds the pledge list. /// </summary> private void BindPledgeList() { var rockContext = new RockContext(); var pledgeService = new FinancialPledgeService(rockContext); var pledgesQry = pledgeService.Queryable(); pledgesQry = pledgesQry.Where(p => p.PersonAlias.Person.GivingId == Person.GivingId); // Filter by configured limit accounts if specified. var accountGuids = GetAttributeValue(AttributeKey.Accounts).SplitDelimitedValues().AsGuidList(); if (accountGuids.Any()) { pledgesQry = pledgesQry.Where(p => accountGuids.Contains(p.Account.Guid)); } var pledges = pledgesQry.ToList(); rptPledges.DataSource = pledges; rptPledges.DataBind(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> /// <exception cref="System.NotImplementedException"></exception> protected void btnSave_Click(object sender, EventArgs e) { FinancialPledge pledge; var rockContext = new RockContext(); var pledgeService = new FinancialPledgeService(rockContext); var pledgeId = hfPledgeId.Value.AsInteger(); if (pledgeId == 0) { pledge = new FinancialPledge(); pledgeService.Add(pledge); } else { pledge = pledgeService.Get(pledgeId); } if (ppPerson.PersonId.HasValue) { pledge.PersonAliasId = ppPerson.PersonAliasId; } pledge.AccountId = apAccount.SelectedValue.AsIntegerOrNull(); pledge.TotalAmount = tbAmount.Text.AsDecimal(); pledge.StartDate = dpDateRange.LowerValue.HasValue ? dpDateRange.LowerValue.Value : DateTime.MinValue; pledge.EndDate = dpDateRange.UpperValue.HasValue ? dpDateRange.UpperValue.Value : DateTime.MaxValue; pledge.PledgeFrequencyValueId = ddlFrequencyType.SelectedValue.AsIntegerOrNull(); if (!pledge.IsValid) { // Controls will render the error messages return; } rockContext.SaveChanges(); NavigateToParentPage(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> /// <exception cref="System.NotImplementedException"></exception> protected void btnSave_Click(object sender, EventArgs e) { using (new UnitOfWorkScope()) { RockTransactionScope.WrapTransaction(() => { var pledgeService = new FinancialPledgeService(); var person = FindPerson(); var pledges = GetPledges(person).ToList(); // Does this person already have a pledge for these accounts? // If so, give them the option to create a new one? var personPledgeAccountIds = pledgeService.Queryable() .Where(p => p.PersonId == person.Id) .Select(p => p.AccountId) .ToList(); if (Accounts.Any(a => personPledgeAccountIds.Contains(a.Id))) { pnlConfirm.Visible = true; Session.Add("CachedPledges", pledges); return; } foreach (var pledge in pledges) { if (!pledge.IsValid) { continue; } pledgeService.Add(pledge, person.Id); pledgeService.Save(pledge, person.Id); } ShowReceipt(pledges.Select(p => p.Id)); }); } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var pledgeService = new FinancialPledgeService(); var sortProperty = gPledges.SortProperty; var pledges = pledgeService.Queryable(); if (ppFilterPerson.PersonId.HasValue) { pledges = pledges.Where(p => p.PersonId == ppFilterPerson.PersonId.Value); } var accountIds = fpFilterAccount.SelectedValuesAsInt().Where(i => i != 0).ToList(); if (accountIds.Any()) { pledges = pledges.Where(p => p.AccountId.HasValue && accountIds.Contains(p.AccountId.Value)); } gPledges.DataSource = sortProperty != null?pledges.Sort(sortProperty).ToList() : pledges.OrderBy(p => p.AccountId).ToList(); gPledges.DataBind(); }
/// <summary> /// Handles the Delete event of the gPledges control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void gPledges_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); var pledgeService = new FinancialPledgeService(rockContext); var pledge = pledgeService.Get(e.RowKeyId); string errorMessage; if (pledge == null) { return; } if (!pledgeService.CanDelete(pledge, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } pledgeService.Delete(pledge); rockContext.SaveChanges(); BindGrid(); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var rockContext = new RockContext(); var pledgeService = new FinancialPledgeService(rockContext); var sortProperty = gPledges.SortProperty; var pledges = pledgeService.Queryable(); Person person = null; if (TargetPerson != null) { person = TargetPerson; } else { int?personId = gfPledges.GetUserPreference("Person").AsIntegerOrNull(); if (personId.HasValue) { person = new PersonService(rockContext).Get(personId.Value); } } if (person != null) { // if a person is specified, get pledges for that person ( and also anybody in their GivingUnit ) pledges = pledges.Where(p => p.PersonAlias.Person.GivingId == person.GivingId); } // get the accounts and make sure they still exist by checking the database var accountIds = gfPledges.GetUserPreference("Accounts").Split(',').AsIntegerList(); accountIds = new FinancialAccountService(rockContext).GetByIds(accountIds).Select(a => a.Id).ToList(); if (accountIds.Any()) { pledges = pledges.Where(p => p.AccountId.HasValue && accountIds.Contains(p.AccountId.Value)); } // Date Range var drp = new DateRangePicker(); drp.DelimitedValues = gfPledges.GetUserPreference("Date Range"); var filterStartDate = drp.LowerValue ?? DateTime.MinValue; var filterEndDate = drp.UpperValue ?? DateTime.MaxValue; /**** * Include any pledges whose Start/EndDates overlap with the Filtered Date Range * * * Pledge1 Range 1/1/2011 - 12/31/2011 * * Pledge2 Range 1/1/0000 - 1/1/9999 * * Pledge3 Range 6/1/2011 - 6/1/2012 * * Filter1 Range 1/1/2010 - 1/1/2013 * * * All Pledges should show * Filter1 Range 1/1/2012 - 1/1/2013 * * * Pledge2 and Pledge3 should show * Filter2 Range 5/1/2012 - 5/2/2012 * * * Pledge2 and Pledge3 should show * Filter3 Range 5/1/2012 - 1/1/9999 * * * Pledge2 and Pledge3 should show * Filter4 Range 5/1/2010 - 5/1/2010 * * * Pledge2 should show ***/ // exclude pledges that start after the filter's end date or end before the filter's start date pledges = pledges.Where(p => !(p.StartDate > filterEndDate) && !(p.EndDate < filterStartDate)); gPledges.DataSource = sortProperty != null?pledges.Sort(sortProperty).ToList() : pledges.OrderBy(p => p.AccountId).ToList(); gPledges.DataBind(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> /// <exception cref="System.NotImplementedException"></exception> protected void btnSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var financialPledgeService = new FinancialPledgeService(rockContext); var financialAccountService = new FinancialAccountService(rockContext); var definedValueService = new DefinedValueService(rockContext); var person = FindPerson(rockContext); FinancialPledge financialPledge = new FinancialPledge(); financialPledge.PersonAliasId = person.PrimaryAliasId; financialPledge.GroupId = ddlGroup.SelectedValueAsInt(); var financialAccount = financialAccountService.Get(GetAttributeValue("Account").AsGuid()); if (financialAccount != null) { financialPledge.AccountId = financialAccount.Id; } financialPledge.TotalAmount = tbTotalAmount.Value ?? 0.0m; var pledgeFrequencySelection = DefinedValueCache.Get(ddlFrequency.SelectedValue.AsInteger()); if (pledgeFrequencySelection != null) { financialPledge.PledgeFrequencyValueId = pledgeFrequencySelection.Id; } financialPledge.StartDate = drpDateRange.LowerValue ?? DateTime.MinValue; financialPledge.EndDate = drpDateRange.UpperValue ?? DateTime.MaxValue; if (sender != btnConfirm) { var duplicatePledges = financialPledgeService.Queryable() .Where(a => a.PersonAlias.PersonId == person.Id) .Where(a => a.AccountId == financialPledge.AccountId) .Where(a => a.StartDate == financialPledge.StartDate) .Where(a => a.EndDate == financialPledge.EndDate).ToList(); if (duplicatePledges.Any()) { pnlAddPledge.Visible = false; pnlConfirm.Visible = true; nbDuplicatePledgeWarning.Text = "The following pledges have already been entered for you:"; nbDuplicatePledgeWarning.Text += "<ul>"; foreach (var pledge in duplicatePledges.OrderBy(a => a.StartDate).ThenBy(a => a.Account.Name)) { nbDuplicatePledgeWarning.Text += string.Format("<li>{0} {1} {2}</li>", pledge.Account, pledge.PledgeFrequencyValue, pledge.TotalAmount); } nbDuplicatePledgeWarning.Text += "</ul>"; return; } } if (financialPledge.IsValid) { financialPledgeService.Add(financialPledge); rockContext.SaveChanges(); // populate account so that Liquid can access it financialPledge.Account = financialAccount; // populate PledgeFrequencyValue so that Liquid can access it financialPledge.PledgeFrequencyValue = definedValueService.Get(financialPledge.PledgeFrequencyValueId ?? 0); var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeFields.Add("Person", person); mergeFields.Add("FinancialPledge", financialPledge); mergeFields.Add("PledgeFrequency", pledgeFrequencySelection); mergeFields.Add("Account", financialAccount); lReceipt.Text = GetAttributeValue("ReceiptText").ResolveMergeFields(mergeFields); // Resolve any dynamic url references string appRoot = ResolveRockUrl("~/"); string themeRoot = ResolveRockUrl("~~/"); lReceipt.Text = lReceipt.Text.Replace("~~/", themeRoot).Replace("~/", appRoot); lReceipt.Visible = true; pnlAddPledge.Visible = false; pnlConfirm.Visible = false; // if a ConfirmationEmailTemplate is configured, send an email var confirmationEmailTemplateGuid = GetAttributeValue("ConfirmationEmailTemplate").AsGuidOrNull(); if (confirmationEmailTemplateGuid.HasValue) { var emailMessage = new RockEmailMessage(confirmationEmailTemplateGuid.Value); emailMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeFields)); emailMessage.AppRoot = ResolveRockUrl("~/"); emailMessage.ThemeRoot = ResolveRockUrl("~~/"); emailMessage.Send(); } } else { ShowInvalidResults(financialPledge.ValidationResults); } }
/// <summary> /// Maps the pledge. /// </summary> /// <param name="tableData">The table data.</param> /// <param name="totalRows">The total rows.</param> /// <exception cref="System.NotImplementedException"></exception> private void MapPledge(IQueryable <Row> tableData, long totalRows = 0) { var lookupContext = new RockContext(); var accountList = new FinancialAccountService(lookupContext).Queryable().AsNoTracking().ToList(); var importedPledges = new FinancialPledgeService(lookupContext).Queryable().AsNoTracking().ToList(); var pledgeFrequencies = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY), lookupContext).DefinedValues; var oneTimePledgeFrequencyId = pledgeFrequencies.FirstOrDefault(f => f.Guid == new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_ONE_TIME)).Id; var newPledges = new List <FinancialPledge>(); if (totalRows == 0) { totalRows = tableData.Count(); } var completedItems = 0; var percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, $"Verifying pledge import ({totalRows:N0} found)."); foreach (var row in tableData.Where(r => r != null)) { var amount = row["Total_Pledge"] as decimal?; var startDate = row["Start_Date"] as DateTime?; var endDate = row["End_Date"] as DateTime?; if (amount.HasValue && startDate.HasValue && endDate.HasValue) { var individualId = row["Individual_ID"] as int?; var householdId = row["Household_ID"] as int?; var personKeys = GetPersonKeys(individualId, householdId, includeVisitors: false); if (personKeys != null && personKeys.PersonAliasId > 0) { var pledge = new FinancialPledge { PersonAliasId = personKeys.PersonAliasId, CreatedByPersonAliasId = ImportPersonAliasId, ModifiedDateTime = ImportDateTime, StartDate = ( DateTime )startDate, EndDate = ( DateTime )endDate, TotalAmount = ( decimal )amount }; var frequency = row["Pledge_Frequency_Name"].ToString(); if (!string.IsNullOrWhiteSpace(frequency)) { if (frequency.Equals("one time", StringComparison.OrdinalIgnoreCase) || frequency.Equals("as can", StringComparison.OrdinalIgnoreCase)) { pledge.PledgeFrequencyValueId = oneTimePledgeFrequencyId; } else { pledge.PledgeFrequencyValueId = pledgeFrequencies .Where(f => f.Value.StartsWith(frequency, StringComparison.OrdinalIgnoreCase) || f.Description.StartsWith(frequency, StringComparison.OrdinalIgnoreCase)) .Select(f => f.Id).FirstOrDefault(); } } var fundName = row["Fund_Name"] as string; var subFund = row["Sub_Fund_Name"] as string; if (!string.IsNullOrWhiteSpace(fundName)) { var parentAccount = accountList.FirstOrDefault(a => !a.CampusId.HasValue && a.Name.Equals(fundName.Truncate(50), StringComparison.OrdinalIgnoreCase)); if (parentAccount == null) { parentAccount = AddFinancialAccount(lookupContext, fundName, $"{fundName} imported {ImportDateTime}", string.Empty, null, null, null, startDate, fundName.RemoveSpecialCharacters()); accountList.Add(parentAccount); } if (!string.IsNullOrWhiteSpace(subFund)) { int?campusFundId = null; // assign a campus if the subfund is a campus fund var campusFund = CampusList.FirstOrDefault(c => subFund.StartsWith(c.Name) || subFund.StartsWith(c.ShortCode)); if (campusFund != null) { // use full campus name as the subfund subFund = campusFund.Name; campusFundId = campusFund.Id; } // add info to easily find/assign this fund in the view subFund = $"{subFund} {fundName}"; var childAccount = accountList.FirstOrDefault(c => c.ParentAccountId == parentAccount.Id && c.Name.Equals(subFund.Truncate(50), StringComparison.OrdinalIgnoreCase)); if (childAccount == null) { // create a child account with a campusId if it was set childAccount = AddFinancialAccount(lookupContext, subFund, $"{subFund} imported {ImportDateTime}", string.Empty, campusFundId, parentAccount.Id, null, startDate, subFund.RemoveSpecialCharacters(), accountTypeValueId: parentAccount.AccountTypeValueId); accountList.Add(childAccount); } pledge.AccountId = childAccount.Id; } else { pledge.AccountId = parentAccount.Id; } } newPledges.Add(pledge); completedItems++; if (completedItems % percentage < 1) { var percentComplete = completedItems / percentage; ReportProgress(percentComplete, $"{completedItems:N0} pledges imported ({percentComplete}% complete)."); } if (completedItems % ReportingNumber < 1) { SavePledges(newPledges); ReportPartialProgress(); newPledges.Clear(); } } } } if (newPledges.Any()) { SavePledges(newPledges); } ReportProgress(100, $"Finished pledge import: {completedItems:N0} pledges imported."); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> /// <exception cref="System.NotImplementedException"></exception> protected void btnSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var financialPledgeService = new FinancialPledgeService(rockContext); var financialAccountService = new FinancialAccountService(rockContext); var definedValueService = new DefinedValueService(rockContext); var person = FindPerson(rockContext); FinancialPledge financialPledge = new FinancialPledge(); financialPledge.PersonAliasId = person.PrimaryAliasId; var financialAccount = financialAccountService.Get(GetAttributeValue("Account").AsGuid()); if (financialAccount != null) { financialPledge.AccountId = financialAccount.Id; } financialPledge.TotalAmount = tbTotalAmount.Text.AsDecimal(); var pledgeFrequencySelection = DefinedValueCache.Read(bddlFrequency.SelectedValue.AsInteger()); if (pledgeFrequencySelection != null) { financialPledge.PledgeFrequencyValueId = pledgeFrequencySelection.Id; } financialPledge.StartDate = drpDateRange.LowerValue ?? DateTime.MinValue; financialPledge.EndDate = drpDateRange.UpperValue ?? DateTime.MaxValue; if (sender != btnConfirm) { var duplicatePledges = financialPledgeService.Queryable() .Where(a => a.PersonAlias.PersonId == person.Id) .Where(a => a.AccountId == financialPledge.AccountId) .Where(a => a.StartDate == financialPledge.StartDate) .Where(a => a.EndDate == financialPledge.EndDate).ToList(); if (duplicatePledges.Any()) { pnlAddPledge.Visible = false; pnlConfirm.Visible = true; nbDuplicatePledgeWarning.Text = "The following pledges have already been entered for you:"; nbDuplicatePledgeWarning.Text += "<ul>"; foreach (var pledge in duplicatePledges.OrderBy(a => a.StartDate).ThenBy(a => a.Account.Name)) { nbDuplicatePledgeWarning.Text += string.Format("<li>{0} {1} {2}</li>", pledge.Account, pledge.PledgeFrequencyValue, pledge.TotalAmount); } nbDuplicatePledgeWarning.Text += "</ul>"; return; } } financialPledgeService.Add(financialPledge); rockContext.SaveChanges(); // populate account so that Liquid can access it financialPledge.Account = financialAccount; // populate PledgeFrequencyValue so that Liquid can access it financialPledge.PledgeFrequencyValue = definedValueService.Get(financialPledge.PledgeFrequencyValueId ?? 0); var mergeObjects = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(this.CurrentPerson); mergeObjects.Add("Person", person); mergeObjects.Add("FinancialPledge", financialPledge); mergeObjects.Add("PledgeFrequency", pledgeFrequencySelection); mergeObjects.Add("Account", financialAccount); lReceipt.Text = GetAttributeValue("ReceiptText").ResolveMergeFields(mergeObjects); // Resolve any dynamic url references string appRoot = ResolveRockUrl("~/"); string themeRoot = ResolveRockUrl("~~/"); lReceipt.Text = lReceipt.Text.Replace("~~/", themeRoot).Replace("~/", appRoot); // show liquid help for debug if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT)) { lReceipt.Text += mergeObjects.lavaDebugInfo(); } lReceipt.Visible = true; pnlAddPledge.Visible = false; pnlConfirm.Visible = false; // if a ConfirmationEmailTemplate is configured, send an email var confirmationEmailTemplateGuid = GetAttributeValue("ConfirmationEmailTemplate").AsGuidOrNull(); if (confirmationEmailTemplateGuid.HasValue) { var recipients = new List <Rock.Communication.RecipientData>(); // add person and the mergeObjects (same mergeobjects as receipt) recipients.Add(new Rock.Communication.RecipientData(person.Email, mergeObjects)); Rock.Communication.Email.Send(confirmationEmailTemplateGuid.Value, recipients, ResolveRockUrl("~/"), ResolveRockUrl("~~/")); } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var rockContext = new RockContext(); var pledgeService = new FinancialPledgeService(rockContext); var sortProperty = gPledges.SortProperty; var pledges = pledgeService.Queryable(); Person person = null; if (TargetPerson != null) { person = TargetPerson; } else { int?personId = gfPledges.GetUserPreference("Person").AsIntegerOrNull(); if (personId.HasValue && ppFilterPerson.Visible) { person = new PersonService(rockContext).Get(personId.Value); } } if (person != null) { // if a person is specified, get pledges for that person ( and also anybody in their GivingUnit ) pledges = pledges.Where(p => p.PersonAlias.Person.GivingId == person.GivingId); } // Filter by configured limit accounts if specified. var accountGuids = GetAttributeValue("Accounts").SplitDelimitedValues().AsGuidList(); if (accountGuids.Any()) { pledges = pledges.Where(p => accountGuids.Contains(p.Account.Guid)); } // get the accounts and make sure they still exist by checking the database var accountIds = gfPledges.GetUserPreference("Accounts").Split(',').AsIntegerList(); accountIds = new FinancialAccountService(rockContext).GetByIds(accountIds).Select(a => a.Id).ToList(); if (accountIds.Any() && apFilterAccount.Visible) { pledges = pledges.Where(p => p.AccountId.HasValue && accountIds.Contains(p.AccountId.Value)); } // Date Range DateRange filterDateRange = DateRangePicker.CalculateDateRangeFromDelimitedValues(gfPledges.GetUserPreference("Date Range")); var filterStartDate = filterDateRange.Start ?? DateTime.MinValue; var filterEndDate = filterDateRange.End ?? DateTime.MaxValue; /**** * Include any pledges whose Start/EndDates overlap with the Filtered Date Range * * * Pledge1 Range 1/1/2011 - 12/31/2011 * * Pledge2 Range 1/1/0000 - 1/1/9999 * * Pledge3 Range 6/1/2011 - 6/1/2012 * * Filter1 Range 1/1/2010 - 1/1/2013 * * * All Pledges should show * Filter1 Range 1/1/2012 - 1/1/2013 * * * Pledge2 and Pledge3 should show * Filter2 Range 5/1/2012 - 5/2/2012 * * * Pledge2 and Pledge3 should show * Filter3 Range 5/1/2012 - 1/1/9999 * * * Pledge2 and Pledge3 should show * Filter4 Range 5/1/2010 - 5/1/2010 * * * Pledge2 should show ***/ // exclude pledges that start after the filter's end date or end before the filter's start date if (drpDates.Visible && (filterDateRange.Start.HasValue || filterDateRange.End.HasValue)) { pledges = pledges.Where(p => !(p.StartDate > filterEndDate) && !(p.EndDate < filterStartDate)); } // Last Modified DateRange filterModifiedDateRange = DateRangePicker.CalculateDateRangeFromDelimitedValues(gfPledges.GetUserPreference("Last Modified")); var filterModifiedStartDate = filterModifiedDateRange.Start ?? DateTime.MinValue; var filterModifiedEndDate = filterModifiedDateRange.End ?? DateTime.MaxValue; if (drpLastModifiedDates.Visible && (filterModifiedDateRange.Start.HasValue || filterModifiedDateRange.End.HasValue)) { pledges = pledges.Where(p => !(p.ModifiedDateTime >= filterModifiedEndDate) && !(p.ModifiedDateTime <= filterModifiedStartDate)); } gPledges.DataSource = sortProperty != null?pledges.Sort(sortProperty).ToList() : pledges.OrderBy(p => p.AccountId).ToList(); gPledges.DataBind(); var showAccountSummary = this.GetAttributeValue("ShowAccountSummary").AsBoolean(); if (showAccountSummary || TargetPerson == null) { pnlSummary.Visible = true; var summaryList = pledges .GroupBy(a => a.AccountId) .Select(a => new AccountSummaryRow { AccountId = a.Key.Value, TotalAmount = a.Sum(x => x.TotalAmount), Name = a.Select(p => p.Account.Name).FirstOrDefault(), Order = a.Select(p => p.Account.Order).FirstOrDefault() }).ToList(); var grandTotalAmount = (summaryList.Count > 0) ? summaryList.Sum(a => a.TotalAmount) : 0; lGrandTotal.Text = grandTotalAmount.FormatAsCurrency(); rptAccountSummary.DataSource = summaryList.Select(a => new { a.Name, TotalAmount = a.TotalAmount.FormatAsCurrency() }).ToList(); rptAccountSummary.DataBind(); } else { pnlSummary.Visible = false; } }
/// <summary> /// Gets the financial pledge query. /// </summary> /// <param name="options">The options.</param> /// <param name="rockContext">The rock context.</param> /// <param name="usePersonFilters">if set to <c>true</c> [use person filters].</param> /// <returns></returns> private IQueryable <FinancialPledge> GetFinancialPledgeQuery(StatementGeneratorOptions options, RockContext rockContext, bool usePersonFilters) { // pledge information var pledgeQry = new FinancialPledgeService(rockContext).Queryable(); // only include pledges that started *before* the enddate of the statement ( we don't want pledges that start AFTER the statement end date ) if (options.EndDate.HasValue) { pledgeQry = pledgeQry.Where(p => p.StartDate <= options.EndDate.Value); } // also only include pledges that ended *after* the statement start date ( we don't want pledges that ended BEFORE the statement start date ) pledgeQry = pledgeQry.Where(p => p.EndDate >= options.StartDate.Value); // Filter to specified AccountIds (if specified) if (options.PledgesAccountIds == null || !options.PledgesAccountIds.Any()) { // if no PledgeAccountIds where specified, don't include any pledges pledgeQry = pledgeQry.Where(a => false); } else { // NOTE: Only get the Pledges that were specifically pledged to the selected accounts // If the PledgesIncludeChildAccounts = true, we'll include transactions to those child accounts as part of the pledge (but only one level deep) var selectedAccountIds = options.PledgesAccountIds; pledgeQry = pledgeQry.Where(a => a.AccountId.HasValue && selectedAccountIds.Contains(a.AccountId.Value)); } if (usePersonFilters) { if (options.PersonId.HasValue) { // If PersonId is specified, then this statement is for a specific person, so don't do any other filtering string personGivingId = new PersonService(rockContext).Queryable().Where(a => a.Id == options.PersonId.Value).Select(a => a.GivingId).FirstOrDefault(); if (personGivingId != null) { pledgeQry = pledgeQry.Where(a => a.PersonAlias.Person.GivingId == personGivingId); } else { // shouldn't happen, but just in case person doesn't exist pledgeQry = pledgeQry.Where(a => false); } } else { // unless we are using a DataView for filtering, filter based on the IncludeBusiness and ExcludeInActiveIndividuals options if (!options.DataViewId.HasValue) { if (!options.IncludeBusinesses) { int recordTypeValueIdPerson = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; pledgeQry = pledgeQry.Where(a => a.PersonAlias.Person.RecordTypeValueId == recordTypeValueIdPerson); } if (options.ExcludeInActiveIndividuals) { int recordStatusValueIdActive = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id; pledgeQry = pledgeQry.Where(a => a.PersonAlias.Person.RecordStatusValueId == recordStatusValueIdActive); } // Only include Non-Deceased People even if we are including inactive individuals pledgeQry = pledgeQry.Where(a => a.PersonAlias.Person.IsDeceased == false); } } } return(pledgeQry); }
private void DisplayResults() { RockContext rockContext = new RockContext(); var statementYear = RockDateTime.Now.Year; if (Request["StatementYear"] != null) { Int32.TryParse(Request["StatementYear"].ToString(), out statementYear); } FinancialTransactionDetailService financialTransactionDetailService = new FinancialTransactionDetailService(rockContext); Person targetPerson = CurrentPerson; List <Guid> excludedCurrencyTypes = new List <Guid>(); if (!string.IsNullOrWhiteSpace(GetAttributeValue("ExcludedCurrencyTypes"))) { excludedCurrencyTypes = GetAttributeValue("ExcludedCurrencyTypes").Split(',').Select(Guid.Parse).ToList(); } if (GetAttributeValue("AllowPersonQuerystring").AsBoolean()) { if (!string.IsNullOrWhiteSpace(Request["PersonGuid"])) { Guid?personGuid = Request["PersonGuid"].AsGuidOrNull(); if (personGuid.HasValue) { var person = new PersonService(rockContext).Get(personGuid.Value); if (person != null) { targetPerson = person; } } } } // fetch all the possible PersonAliasIds that have this GivingID to help optimize the SQL var personAliasIds = new PersonAliasService(rockContext).Queryable().Where(a => a.Person.GivingId == targetPerson.GivingId).Select(a => a.Id).ToList(); // get the transactions for the person or all the members in the person's giving group (Family) var qry = financialTransactionDetailService.Queryable().AsNoTracking() .Where(t => t.Transaction.AuthorizedPersonAliasId.HasValue && personAliasIds.Contains(t.Transaction.AuthorizedPersonAliasId.Value)); qry = qry.Where(t => t.Transaction.TransactionDateTime.Value.Year == statementYear); if (string.IsNullOrWhiteSpace(GetAttributeValue("Accounts"))) { qry = qry.Where(t => t.Account.IsTaxDeductible); } else { var accountGuids = GetAttributeValue("Accounts").Split(',').Select(Guid.Parse).ToList(); qry = qry.Where(t => accountGuids.Contains(t.Account.Guid)); } if (excludedCurrencyTypes.Count > 0) { qry = qry.Where(t => !excludedCurrencyTypes.Contains(t.Transaction.FinancialPaymentDetail.CurrencyTypeValue.Guid)); } qry = qry.OrderByDescending(t => t.Transaction.TransactionDateTime); var mergeFields = new Dictionary <string, object>(); mergeFields.Add("StatementStartDate", "1/1/" + statementYear.ToString()); if (statementYear == RockDateTime.Now.Year) { mergeFields.Add("StatementEndDate", RockDateTime.Now); } else { mergeFields.Add("StatementEndDate", "12/31/" + statementYear.ToString()); } var familyGroupTypeId = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY).Id; var groupMemberQry = new GroupMemberService(rockContext).Queryable().Where(m => m.Group.GroupTypeId == familyGroupTypeId); // get giving group members in order by family role (adult -> child) and then gender (male -> female) var givingGroup = new PersonService(rockContext).Queryable().AsNoTracking() .Where(p => p.GivingId == targetPerson.GivingId) .GroupJoin( groupMemberQry, p => p.Id, m => m.PersonId, (p, m) => new { p, m }) .SelectMany(x => x.m.DefaultIfEmpty(), (y, z) => new { Person = y.p, GroupMember = z }) .Select(p => new { FirstName = p.Person.NickName, LastName = p.Person.LastName, FamilyRoleOrder = p.GroupMember.GroupRole.Order, Gender = p.Person.Gender, PersonId = p.Person.Id }) .DistinctBy(p => p.PersonId) .OrderBy(p => p.FamilyRoleOrder).ThenBy(p => p.Gender) .ToList(); string salutation = string.Empty; if (givingGroup.GroupBy(g => g.LastName).Count() == 1) { salutation = string.Join(", ", givingGroup.Select(g => g.FirstName)) + " " + givingGroup.FirstOrDefault().LastName; if (salutation.Contains(",")) { salutation = salutation.ReplaceLastOccurrence(",", " &"); } } else { salutation = string.Join(", ", givingGroup.Select(g => g.FirstName + " " + g.LastName)); if (salutation.Contains(",")) { salutation = salutation.ReplaceLastOccurrence(",", " &"); } } mergeFields.Add("Salutation", salutation); var homeAddress = targetPerson.GetHomeLocation(); if (homeAddress != null) { mergeFields.Add("StreetAddress1", homeAddress.Street1); mergeFields.Add("StreetAddress2", homeAddress.Street2); mergeFields.Add("City", homeAddress.City); mergeFields.Add("State", homeAddress.State); mergeFields.Add("PostalCode", homeAddress.PostalCode); mergeFields.Add("Country", homeAddress.Country); } else { mergeFields.Add("StreetAddress1", string.Empty); mergeFields.Add("StreetAddress2", string.Empty); mergeFields.Add("City", string.Empty); mergeFields.Add("State", string.Empty); mergeFields.Add("PostalCode", string.Empty); mergeFields.Add("Country", string.Empty); } mergeFields.Add("TransactionDetails", qry.ToList()); mergeFields.Add("AccountSummary", qry.GroupBy(t => t.Account.Name).Select(s => new AccountSummary { AccountName = s.Key, Total = s.Sum(a => a.Amount), Order = s.Max(a => a.Account.Order) }).OrderBy(s => s.Order)); // pledge information var pledges = new FinancialPledgeService(rockContext).Queryable().AsNoTracking() .Where(p => p.PersonAliasId.HasValue && personAliasIds.Contains(p.PersonAliasId.Value)) .GroupBy(p => p.Account) .Select(g => new PledgeSummary { AccountId = g.Key.Id, AccountName = g.Key.Name, AmountPledged = g.Sum(p => p.TotalAmount), PledgeStartDate = g.Min(p => p.StartDate), PledgeEndDate = g.Max(p => p.EndDate) }) .ToList(); // add detailed pledge information foreach (var pledge in pledges) { var adjustedPedgeEndDate = pledge.PledgeEndDate.Value.Date.AddDays(1); pledge.AmountGiven = new FinancialTransactionDetailService(rockContext).Queryable() .Where(t => t.AccountId == pledge.AccountId && t.Transaction.AuthorizedPersonAliasId.HasValue && personAliasIds.Contains(t.Transaction.AuthorizedPersonAliasId.Value) && t.Transaction.TransactionDateTime >= pledge.PledgeStartDate && t.Transaction.TransactionDateTime < adjustedPedgeEndDate) .Sum(t => ( decimal? )t.Amount) ?? 0; pledge.AmountRemaining = (pledge.AmountGiven > pledge.AmountPledged) ? 0 : (pledge.AmountPledged - pledge.AmountGiven); if (pledge.AmountPledged > 0) { var test = (double)pledge.AmountGiven / (double)pledge.AmountPledged; pledge.PercentComplete = (int)((pledge.AmountGiven * 100) / pledge.AmountPledged); } } mergeFields.Add("Pledges", pledges); var template = GetAttributeValue("LavaTemplate"); lResults.Text = template.ResolveMergeFields(mergeFields); // show debug info if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT)) { lDebug.Visible = true; lDebug.Text = mergeFields.lavaDebugInfo(); } }