Esempio n. 1
0
        /// <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);
        }
Esempio n. 2
0
        /// <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();
        }
Esempio n. 3
0
        /// <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>
        /// 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;
        }
Esempio n. 5
0
        /// <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;
        }
Esempio n. 7
0
        /// <summary>
        /// Exports the financial pledges.
        /// </summary>
        public static void ExportFinancialPledges()
        {
            try
            {
                _request = new RestRequest(API_PLEDGE_CAMPAIGNS, Method.GET);
                _request.AddQueryParameter("session_id", SessionId);
                var response = _client.Execute(_request);
                ApiCounter++;

                dynamic data = JsonConvert.DeserializeObject(response.Content);

                JArray records = data.data;

                if (records.Count > 0)
                {
                    foreach (var pledge in records)
                    {
                        string pledgeId = pledge.Value <string>("campaignId");

                        _request = new RestRequest(API_PLEDGE_PEOPLE + pledgeId.ToString(), Method.GET);
                        _request.AddQueryParameter("session_id", SessionId);
                        response = _client.Execute(_request);
                        ApiCounter++;

                        data = JsonConvert.DeserializeObject(response.Content);

                        JArray personPledgeRecords = data.data;

                        if (personPledgeRecords != null)
                        {
                            foreach (var personPledge in personPledgeRecords)
                            {
                                FinancialPledge importPledge = ElexioCommunityFinancialPledge.Translate(personPledge);
                                if (importPledge != null)
                                {
                                    ImportPackage.WriteToPackage(importPledge);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Binds the attributes
        /// </summary>
        private void BindAttributes()
        {
            // Parse the attribute filters
            AvailableAttributes = new List <AttributeCache>();

            int entityTypeId = new FinancialPledge().TypeId;

            foreach (var attributeModel in new AttributeService(new RockContext()).Queryable()
                     .Where(a =>
                            a.EntityTypeId == entityTypeId &&
                            a.IsGridColumn)
                     .OrderBy(a => a.Order)
                     .ThenBy(a => a.Name))
            {
                AvailableAttributes.Add(AttributeCache.Get(attributeModel));
            }
        }
        public static FinancialPledge Translate(DataRow row)
        {
            var financialPledge = new FinancialPledge();

            financialPledge.Id          = row.Field <int>("PledgeId");
            financialPledge.PersonId    = row.Field <int>("IndividualId");
            financialPledge.AccountId   = row.Field <Int16>("FundNumber");
            financialPledge.StartDate   = row.Field <DateTime?>("StartDate");
            financialPledge.EndDate     = row.Field <DateTime?>("StopDate");
            financialPledge.TotalAmount = row.Field <decimal>("TotalPled");

            var frequency = row.Field <string>("Freq");

            switch (frequency)
            {
            case "Bi-Weekly":
                financialPledge.PledgeFrequency = PledgeFrequency.BiWeekly;
                break;

            case "Monthly":
                financialPledge.PledgeFrequency = PledgeFrequency.Monthly;
                break;

            case "One Time":
                financialPledge.PledgeFrequency = PledgeFrequency.OneTime;
                break;

            case "Semi-Monthly":
                financialPledge.PledgeFrequency = PledgeFrequency.TwiceAMonth;
                break;

            case "Weekly":
                financialPledge.PledgeFrequency = PledgeFrequency.Weekly;
                break;

            case "Yearly":
                financialPledge.PledgeFrequency = PledgeFrequency.Yearly;
                break;

            default:
                financialPledge.PledgeFrequency = PledgeFrequency.OneTime;     // not sure if this is the best option
                break;
            }

            return(financialPledge);
        }
Esempio n. 10
0
        /// <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>
        /// 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();
        }
Esempio n. 12
0
        public static FinancialPledge Translate(dynamic importFinancialPledge)
        {
            var pledge = new FinancialPledge();

            pledge.Id          = importFinancialPledge.pledgeId;
            pledge.PersonId    = importFinancialPledge.uid;
            pledge.AccountId   = importFinancialPledge.categoryId;
            pledge.StartDate   = importFinancialPledge.startDate;
            pledge.EndDate     = importFinancialPledge.endDate;
            pledge.TotalAmount = importFinancialPledge.totalAmount;

            string pledgeFreq = importFinancialPledge.frequency;

            if (pledgeFreq == "yearly")
            {
                pledge.PledgeFrequency = PledgeFrequency.Yearly;
            }
            else if (pledgeFreq == "quarterly")
            {
                pledge.PledgeFrequency = PledgeFrequency.Quarterly;
            }
            else if (pledgeFreq == "monthly")
            {
                pledge.PledgeFrequency = PledgeFrequency.Monthly;
            }
            else if (pledgeFreq == "weekly")
            {
                pledge.PledgeFrequency = PledgeFrequency.Weekly;
            }
            else
            {
                pledge.PledgeFrequency = PledgeFrequency.OneTime;
            }


            return(pledge);
        }
Esempio n. 13
0
        public static FinancialPledge Translate(XElement inputPledge)
        {
            var pledge = new FinancialPledge();

            pledge.Id = inputPledge.Attribute("id").Value.AsInteger();

            // Creating variable to hold fund element
            var fundElement = inputPledge.Element("fund");

            // Checking if there is a subfund
            if (string.IsNullOrEmpty(fundElement.Element("subFund")?.Attribute("id").Value))
            {
                pledge.AccountId = fundElement.Attribute("id").Value.AsInteger();
            }
            else
            {
                pledge.AccountId = fundElement.Element("subFund").Attribute("id").Value.AsInteger();
            }

            pledge.StartDate = inputPledge.Element("startDate")?.Value.AsDateTime();
            pledge.EndDate   = inputPledge.Element("endDate")?.Value.AsDateTime();

            pledge.CreatedDateTime  = inputPledge.Element("createdDate")?.Value.AsDateTime();
            pledge.ModifiedDateTime = inputPledge.Element("lastUpdatedDate")?.Value.AsDateTime();

            // F1 doesn't store a pledge frequency
            pledge.PledgeFrequency = PledgeFrequency.OneTime; // not sure if this is the best default

            var goal = inputPledge.Element("goal").Value.AsDecimalOrNull();

            if (goal.HasValue && goal.Value > 0)
            {
                pledge.TotalAmount = inputPledge.Element("goal").Value.AsDecimal();
            }

            return(pledge);
        }
Esempio n. 14
0
        /// <summary>
        /// Adds columns for any Pledge attributes marked as Show In Grid
        /// </summary>
        protected void AddAttributeColumns()
        {
            // Remove attribute columns
            foreach (var column in gPledges.Columns.OfType <AttributeField>().ToList())
            {
                gPledges.Columns.Remove(column);
            }

            int entityTypeId = new FinancialPledge().TypeId;

            foreach (var attribute in new AttributeService(new RockContext()).Queryable()
                     .Where(a =>
                            a.EntityTypeId == entityTypeId &&
                            a.IsGridColumn
                            )
                     .OrderBy(a => a.Order)
                     .ThenBy(a => a.Name))
            {
                string dataFieldExpression = attribute.Key;
                bool   columnExists        = gPledges.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                if (!columnExists)
                {
                    AttributeField boundField = new AttributeField();
                    boundField.DataField   = dataFieldExpression;
                    boundField.AttributeId = attribute.Id;
                    boundField.HeaderText  = attribute.Name;

                    var attributeCache = Rock.Web.Cache.AttributeCache.Get(attribute.Id);
                    if (attributeCache != null)
                    {
                        boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                    }

                    gPledges.Columns.Add(boundField);
                }
            }
        }
Esempio n. 15
0
        public static FinancialPledge Translate(DataRow row, Dictionary <int, HeadOfHousehold> headOfHouseHolds)
        {
            var pledge = new FinancialPledge();

            pledge.Id = row.Field <int>("Pledge_id");
            var householdId  = row.Field <int?>("household_id");
            var individualId = row.Field <int?>("individual_id");

            if (individualId.HasValue)
            {
                pledge.PersonId = individualId.Value;
            }
            else if (householdId.HasValue && headOfHouseHolds.TryGetValue(householdId.Value, out var headOfHousehold))
            {
                pledge.PersonId = headOfHousehold?.IndividualId ?? 0;
            }

            pledge.TotalAmount = row.Field <decimal>("total_pledge");
            pledge.StartDate   = row.Field <DateTime?>("start_date");
            pledge.EndDate     = row.Field <DateTime?>("end_date");

            switch (row.Field <string>("pledge_frequency_name"))
            {
            case "One Time":
                pledge.PledgeFrequency = PledgeFrequency.OneTime;
                break;

            case "Monthly":
                pledge.PledgeFrequency = PledgeFrequency.Monthly;
                break;

            case "Yearly":
                pledge.PledgeFrequency = PledgeFrequency.Yearly;
                break;

            case "Quarterly":
                pledge.PledgeFrequency = PledgeFrequency.Quarterly;
                break;

            case "Twice a Month":
                pledge.PledgeFrequency = PledgeFrequency.BiWeekly;
                break;

            case "Weekly":
                pledge.PledgeFrequency = PledgeFrequency.Weekly;
                break;

            default:
                pledge.PledgeFrequency = PledgeFrequency.OneTime;
                break;
            }

            //Set Account Id
            if (string.IsNullOrWhiteSpace(row.Field <string>("sub_fund_name")))
            {
                //Use Hash to create Account ID
                MD5    md5Hasher   = MD5.Create();
                string valueToHash = row.Field <string>("fund_name");
                var    hashed      = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(valueToHash));
                var    accountId   = Math.Abs(BitConverter.ToInt32(hashed, 0)); // used abs to ensure positive number
                if (accountId > 0)
                {
                    pledge.AccountId = accountId;
                }
            }
            else
            {
                //Use Hash to create Account ID
                MD5    md5Hasher   = MD5.Create();
                string valueToHash = row.Field <string>("fund_name") + row.Field <string>("sub_fund_name");
                var    hashed      = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(valueToHash));
                var    accountId   = Math.Abs(BitConverter.ToInt32(hashed, 0)); // used abs to ensure positive number
                if (accountId > 0)
                {
                    pledge.AccountId = accountId;
                }
            }

            return(pledge);
        }
Esempio n. 16
0
        /// <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 );

            using ( var rockContext = new RockContext() )
            {
                FinancialPledge pledge = null;

                if ( pledgeId > 0 )
                {
                    pledge = new FinancialPledgeService( rockContext ).Get( pledgeId );
                    lActionTitle.Text = ActionTitle.Edit( FinancialPledge.FriendlyTypeName ).FormatAsHtmlTitle();
                    pdAuditDetails.SetEntity( pledge, ResolveRockUrl( "~" ) );
                }

                if ( pledge == null )
                {
                    pledge = new FinancialPledge();
                    lActionTitle.Text = ActionTitle.Add( FinancialPledge.FriendlyTypeName ).FormatAsHtmlTitle();
                    // hide the panel drawer that show created and last modified dates
                    pdAuditDetails.Visible = false;
                }

                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;

                GroupType groupType = null;
                Guid? groupTypeGuid = GetAttributeValue( "SelectGroupType" ).AsGuidOrNull();
                if ( groupTypeGuid.HasValue )
                {
                    groupType = new GroupTypeService( rockContext ).Get( groupTypeGuid.Value );
                }

                if ( groupType != null )
                {
                    ddlGroup.Label = groupType.Name;
                    ddlGroup.Visible = true;
                    LoadGroups( pledge.GroupId );
                    ddlGroup.Enabled = !isReadOnly;
                }
                else
                {
                    ddlGroup.Visible = false;
                }

                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;
            }
        }
Esempio n. 17
0
        /// <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();
        }
Esempio n. 18
0
        /// <summary>
        /// Maps the pledge.
        /// </summary>
        /// <param name="queryable">The queryable.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        private void MapPledge(IQueryable <Row> tableData)
        {
            var lookupContext   = new RockContext();
            var accountList     = new FinancialAccountService(lookupContext).Queryable().AsNoTracking().ToList();
            var importedPledges = new FinancialPledgeService(lookupContext).Queryable().AsNoTracking().ToList();

            var pledgeFrequencies        = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY), lookupContext).DefinedValues;
            int oneTimePledgeFrequencyId = pledgeFrequencies.FirstOrDefault(f => f.Guid == new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_ONE_TIME)).Id;

            var newPledges = new List <FinancialPledge>();

            int completed  = 0;
            int totalRows  = tableData.Count();
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying pledge import ({0:N0} found).", totalRows));

            foreach (var row in tableData.Where(r => r != null))
            {
                decimal? amount    = row["Total_Pledge"] as decimal?;
                DateTime?startDate = row["Start_Date"] as DateTime?;
                DateTime?endDate   = row["End_Date"] as DateTime?;
                if (amount != null && startDate != null && endDate != null)
                {
                    int?individualId = row["Individual_ID"] as int?;
                    int?householdId  = row["Household_ID"] as int?;

                    var personKeys = GetPersonKeys(individualId, householdId, includeVisitors: false);
                    if (personKeys != null && personKeys.PersonAliasId > 0)
                    {
                        var pledge = new FinancialPledge();
                        pledge.PersonAliasId          = personKeys.PersonAliasId;
                        pledge.CreatedByPersonAliasId = ImportPersonAliasId;
                        pledge.ModifiedDateTime       = ImportDateTime;
                        pledge.StartDate   = (DateTime)startDate;
                        pledge.EndDate     = (DateTime)endDate;
                        pledge.TotalAmount = (decimal)amount;

                        string frequency = row["Pledge_Frequency_Name"].ToString().ToLower();
                        if (frequency != null)
                        {
                            frequency = frequency.ToLower();
                            if (frequency.Equals("one time") || frequency.Equals("as can"))
                            {
                                pledge.PledgeFrequencyValueId = oneTimePledgeFrequencyId;
                            }
                            else
                            {
                                pledge.PledgeFrequencyValueId = pledgeFrequencies
                                                                .Where(f => f.Value.ToLower().StartsWith(frequency) || f.Description.ToLower().StartsWith(frequency))
                                                                .Select(f => f.Id).FirstOrDefault();
                            }
                        }

                        string fundName = row["Fund_Name"] as string;
                        string subFund  = row["Sub_Fund_Name"] as string;
                        if (fundName != null)
                        {
                            var parentAccount = accountList.FirstOrDefault(a => a.Name.Equals(fundName) && a.CampusId == null);
                            if (parentAccount == null)
                            {
                                parentAccount = AddAccount(lookupContext, fundName, string.Empty, null, null, null);
                                accountList.Add(parentAccount);
                            }

                            if (subFund != null)
                            {
                                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 = string.Format("{0} {1}", subFund, fundName);

                                var childAccount = accountList.FirstOrDefault(c => c.Name.Equals(subFund) && c.ParentAccountId == parentAccount.Id);
                                if (childAccount == null)
                                {
                                    // create a child account with a campusId if it was set
                                    childAccount = AddAccount(lookupContext, subFund, string.Empty, campusFundId, parentAccount.Id, null);
                                    accountList.Add(childAccount);
                                }

                                pledge.AccountId = childAccount.Id;
                            }
                            else
                            {
                                pledge.AccountId = parentAccount.Id;
                            }
                        }

                        newPledges.Add(pledge);
                        completed++;
                        if (completed % percentage < 1)
                        {
                            int percentComplete = completed / percentage;
                            ReportProgress(percentComplete, string.Format("{0:N0} pledges imported ({1}% complete).", completed, percentComplete));
                        }
                        else if (completed % ReportingNumber < 1)
                        {
                            SavePledges(newPledges);
                            ReportPartialProgress();
                            newPledges.Clear();
                        }
                    }
                }
            }

            if (newPledges.Any())
            {
                SavePledges(newPledges);
            }

            ReportProgress(100, string.Format("Finished pledge import: {0:N0} pledges imported.", completed));
        }
Esempio n. 19
0
        /// <summary>
        /// Maps the pledge.
        /// </summary>
        /// <param name="queryable">The queryable.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        private void MapPledge( IQueryable<Row> tableData )
        {
            var accountService = new FinancialAccountService();

            List<FinancialAccount> importedAccounts = accountService.Queryable().ToList();

            List<DefinedValue> pledgeFrequencies = new DefinedValueService().GetByDefinedTypeGuid( new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY ) ).ToList();

            List<FinancialPledge> importedPledges = new FinancialPledgeService().Queryable().ToList();

            var newPledges = new List<FinancialPledge>();

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Checking pledge import ({0:N0} found).", totalRows ) );

            foreach ( var row in tableData )
            {
                decimal? amount = row["Total_Pledge"] as decimal?;
                DateTime? startDate = row["Start_Date"] as DateTime?;
                DateTime? endDate = row["End_Date"] as DateTime?;
                if ( amount != null && startDate != null && endDate != null )
                {
                    int? individualId = row["Individual_ID"] as int?;
                    int? householdId = row["Household_ID"] as int?;
                    int? personId = GetPersonId( individualId, householdId );
                    if ( personId != null && !importedPledges.Any( p => p.PersonId == personId && p.TotalAmount == amount && p.StartDate.Equals( startDate ) ) )
                    {
                        var pledge = new FinancialPledge();
                        pledge.CreatedByPersonAliasId = ImportPersonAlias.Id;
                        pledge.StartDate = (DateTime)startDate;
                        pledge.EndDate = (DateTime)endDate;
                        pledge.TotalAmount = (decimal)amount;

                        string frequency = row["Pledge_Frequency_Name"] as string;
                        if ( frequency != null )
                        {
                            if ( frequency == "One Time" || frequency == "As Can" )
                            {
                                pledge.PledgeFrequencyValueId = pledgeFrequencies.FirstOrDefault( f => f.Guid == new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_ONE_TIME ) ).Id;
                            }
                            else
                            {
                                pledge.PledgeFrequencyValueId = pledgeFrequencies
                                    .Where( f => f.Name.StartsWith( frequency ) || f.Description.StartsWith( frequency ) )
                                    .Select( f => f.Id ).FirstOrDefault();
                            }
                        }

                        string fundName = row["Fund_Name"] as string;
                        string subFund = row["Sub_Fund_Name"] as string;
                        if ( fundName != null )
                        {
                            FinancialAccount matchingAccount = null;
                            int? fundCampusId = null;
                            if ( subFund != null )
                            {
                                // match by campus if the subfund appears to be a campus
                                fundCampusId = CampusList.Where( c => c.Name.StartsWith( subFund ) || c.ShortCode == subFund )
                                    .Select( c => (int?)c.Id ).FirstOrDefault();

                                if ( fundCampusId != null )
                                {
                                    matchingAccount = importedAccounts.FirstOrDefault( a => a.Name.StartsWith( fundName ) && a.CampusId != null && a.CampusId.Equals( fundCampusId ) );
                                }
                                else
                                {
                                    matchingAccount = importedAccounts.FirstOrDefault( a => a.Name.StartsWith( fundName ) && a.Name.StartsWith( subFund ) );
                                }
                            }
                            else
                            {
                                matchingAccount = importedAccounts.FirstOrDefault( a => a.Name.StartsWith( fundName ) );
                            }

                            if ( matchingAccount == null )
                            {
                                matchingAccount = new FinancialAccount();
                                matchingAccount.Name = fundName;
                                matchingAccount.PublicName = fundName;
                                matchingAccount.IsTaxDeductible = true;
                                matchingAccount.IsActive = true;
                                matchingAccount.CampusId = fundCampusId;
                                matchingAccount.CreatedByPersonAliasId = ImportPersonAlias.Id;

                                accountService.Add( matchingAccount );
                                accountService.Save( matchingAccount );
                                importedAccounts.Add( matchingAccount );
                                pledge.AccountId = matchingAccount.Id;
                            }
                        }

                        // Attributes to add?
                        // Pledge_Drive_Name

                        newPledges.Add( pledge );
                        completed++;
                        if ( completed % percentage < 1 )
                        {
                            int percentComplete = completed / percentage;
                            ReportProgress( percentComplete, string.Format( "{0:N0} pledges imported ({1}% complete).", completed, percentComplete ) );
                        }
                        else if ( completed % ReportingNumber < 1 )
                        {
                            RockTransactionScope.WrapTransaction( () =>
                            {
                                var pledgeService = new FinancialPledgeService();
                                pledgeService.RockContext.FinancialPledges.AddRange( newPledges );
                                pledgeService.RockContext.SaveChanges();
                            } );

                            ReportPartialProgress();
                        }
                    }
                }
            }

            if ( newPledges.Any() )
            {
                RockTransactionScope.WrapTransaction( () =>
                {
                    var pledgeService = new FinancialPledgeService();
                    pledgeService.RockContext.FinancialPledges.AddRange( newPledges );
                    pledgeService.RockContext.SaveChanges();
                } );
            }

            ReportProgress( 100, string.Format( "Finished pledge import: {0:N0} pledges imported.", completed ) );
        }
Esempio n. 20
0
        /// <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 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 );

            // show liquid help for debug
            if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
            {
                lReceipt.Text += mergeFields.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, mergeFields ) );

                Rock.Communication.Email.Send( confirmationEmailTemplateGuid.Value, recipients, ResolveRockUrl( "~/" ), ResolveRockUrl( "~~/" ) );
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Maps the pledge.
        /// </summary>
        /// <param name="queryable">The queryable.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        private int MapPledge(CSVInstance csvData)
        {
            var lookupContext   = new RockContext();
            var accountList     = new FinancialAccountService(lookupContext).Queryable().AsNoTracking().ToList();
            var importedPledges = new FinancialPledgeService(lookupContext).Queryable().AsNoTracking().ToList();

            var pledgeFrequencies        = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY), lookupContext).DefinedValues;
            int oneTimePledgeFrequencyId = pledgeFrequencies.FirstOrDefault(f => f.Guid == new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_ONE_TIME)).Id;

            var newPledges = new List <FinancialPledge>();

            int completed = 0;

            ReportProgress(0, string.Format("Verifying pledge import ({0:N0} already exist).", importedPledges.Count));

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                string   amountKey    = row[TotalPledge];
                decimal? amount       = amountKey.AsType <decimal?>();
                string   startDateKey = row[StartDate];
                DateTime?startDate    = startDateKey.AsType <DateTime?>();
                string   endDateKey   = row[EndDate];
                DateTime?endDate      = endDateKey.AsType <DateTime?>();
                if (amount != null && startDate != null && endDate != null)
                {
                    string individualIdKey = row[IndividualID];
                    int?   individualId    = individualIdKey.AsType <int?>();

                    var personKeys = GetPersonKeys(individualId);
                    if (personKeys != null && personKeys.PersonAliasId > 0)
                    {
                        var pledge = new FinancialPledge();
                        pledge.PersonAliasId          = personKeys.PersonAliasId;
                        pledge.CreatedByPersonAliasId = ImportPersonAliasId;
                        pledge.StartDate   = (DateTime)startDate;
                        pledge.EndDate     = (DateTime)endDate;
                        pledge.TotalAmount = (decimal)amount;

                        string frequency = row[PledgeFrequencyName].ToString().ToLower();
                        if (frequency != null)
                        {
                            frequency = frequency.ToLower();
                            if (frequency.Equals("one time") || frequency.Equals("as can"))
                            {
                                pledge.PledgeFrequencyValueId = oneTimePledgeFrequencyId;
                            }
                            else
                            {
                                pledge.PledgeFrequencyValueId = pledgeFrequencies
                                                                .Where(f => f.Value.ToLower().StartsWith(frequency) || f.Description.ToLower().StartsWith(frequency))
                                                                .Select(f => f.Id).FirstOrDefault();
                            }
                        }

                        string  fundName         = row[FundName] as string;
                        string  subFund          = row[SubFundName] as string;
                        string  fundGLAccount    = row[FundGLAccount] as string;
                        string  subFundGLAccount = row[SubFundGLAccount] as string;
                        string  isFundActiveKey  = row[FundIsActive];
                        Boolean?isFundActive     = isFundActiveKey.AsType <Boolean?>();

                        if (fundName != null)
                        {
                            var parentAccount = accountList.FirstOrDefault(a => a.Name.Equals(fundName) && a.CampusId == null);
                            if (parentAccount == null)
                            {
                                parentAccount = AddAccount(lookupContext, fundName, string.Empty, null, null, isFundActive);
                                accountList.Add(parentAccount);
                            }

                            if (subFund != null)
                            {
                                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 = string.Format("{0} {1}", subFund, fundName);

                                var childAccount = accountList.FirstOrDefault(c => c.Name.Equals(subFund) && c.ParentAccountId == parentAccount.Id);
                                if (childAccount == null)
                                {
                                    // create a child account with a campusId if it was set
                                    childAccount = AddAccount(lookupContext, subFund, string.Empty, campusFundId, parentAccount.Id, isFundActive);
                                    accountList.Add(childAccount);
                                }

                                pledge.AccountId = childAccount.Id;
                            }
                            else
                            {
                                pledge.AccountId = parentAccount.Id;
                            }
                        }

                        newPledges.Add(pledge);
                        completed++;
                        if (completed % (ReportingNumber * 10) < 1)
                        {
                            ReportProgress(0, string.Format("{0:N0} pledges imported.", completed));
                        }
                        else if (completed % ReportingNumber < 1)
                        {
                            SavePledges(newPledges);
                            ReportPartialProgress();
                            newPledges.Clear();
                        }
                    }
                }
            }

            if (newPledges.Any())
            {
                SavePledges(newPledges);
            }

            ReportProgress(100, string.Format("Finished pledge import: {0:N0} pledges imported.", completed));
            return(completed);
        }
Esempio n. 22
0
        /// <summary>
        /// Maps the pledge.
        /// </summary>
        /// <param name="queryable">The queryable.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        private void MapPledge(IQueryable <Row> tableData)
        {
            var lookupContext = new RockContext();
            List <FinancialAccount> accountList     = new FinancialAccountService(lookupContext).Queryable().ToList();
            List <FinancialPledge>  importedPledges = new FinancialPledgeService(lookupContext).Queryable().ToList();

            var pledgeFrequencies = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY), lookupContext).DefinedValues;

            var newPledges = new List <FinancialPledge>();

            int completed  = 0;
            int totalRows  = tableData.Count();
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying pledge import ({0:N0} found).", totalRows));

            foreach (var row in tableData)
            {
                decimal? amount    = row["Total_Pledge"] as decimal?;
                DateTime?startDate = row["Start_Date"] as DateTime?;
                DateTime?endDate   = row["End_Date"] as DateTime?;
                if (amount != null && startDate != null && endDate != null)
                {
                    int?individualId = row["Individual_ID"] as int?;
                    int?householdId  = row["Household_ID"] as int?;
                    int?personId     = GetPersonAliasId(individualId, householdId);
                    if (personId != null && !importedPledges.Any(p => p.PersonAliasId == personId && p.TotalAmount == amount && p.StartDate.Equals(startDate)))
                    {
                        var pledge = new FinancialPledge();
                        pledge.CreatedByPersonAliasId = ImportPersonAlias.Id;
                        pledge.StartDate   = (DateTime)startDate;
                        pledge.EndDate     = (DateTime)endDate;
                        pledge.TotalAmount = (decimal)amount;

                        string frequency = row["Pledge_Frequency_Name"].ToString().ToLower();
                        if (frequency != null)
                        {
                            if (frequency == "one time" || frequency == "as can")
                            {
                                pledge.PledgeFrequencyValueId = pledgeFrequencies.FirstOrDefault(f => f.Guid == new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_ONE_TIME)).Id;
                            }
                            else
                            {
                                pledge.PledgeFrequencyValueId = pledgeFrequencies
                                                                .Where(f => f.Value.ToLower().StartsWith(frequency) || f.Description.ToLower().StartsWith(frequency))
                                                                .Select(f => f.Id).FirstOrDefault();
                            }
                        }

                        string fundName = row["Fund_Name"] as string;
                        string subFund  = row["Sub_Fund_Name"] as string;
                        if (fundName != null)
                        {
                            FinancialAccount matchingAccount = null;
                            int?fundCampusId = null;
                            if (subFund != null)
                            {
                                // match by campus if the subfund appears to be a campus
                                fundCampusId = CampusList.Where(c => c.Name.StartsWith(subFund) || c.ShortCode == subFund)
                                               .Select(c => (int?)c.Id).FirstOrDefault();

                                if (fundCampusId != null)
                                {
                                    matchingAccount = accountList.FirstOrDefault(a => a.Name.StartsWith(fundName) && a.CampusId != null && a.CampusId.Equals(fundCampusId));
                                }
                                else
                                {
                                    matchingAccount = accountList.FirstOrDefault(a => a.Name.StartsWith(fundName) && a.Name.StartsWith(subFund));
                                }
                            }
                            else
                            {
                                matchingAccount = accountList.FirstOrDefault(a => a.Name.StartsWith(fundName));
                            }

                            if (matchingAccount == null)
                            {
                                matchingAccount = AddAccount(lookupContext, fundName, fundCampusId);
                                accountList.Add(matchingAccount);
                            }

                            pledge.AccountId = matchingAccount.Id;
                        }

                        // Attributes to add?
                        // Pledge_Drive_Name

                        newPledges.Add(pledge);
                        completed++;
                        if (completed % percentage < 1)
                        {
                            int percentComplete = completed / percentage;
                            ReportProgress(percentComplete, string.Format("{0:N0} pledges imported ({1}% complete).", completed, percentComplete));
                        }
                        else if (completed % ReportingNumber < 1)
                        {
                            SavePledges(newPledges);
                            ReportPartialProgress();
                        }
                    }
                }
            }

            if (newPledges.Any())
            {
                SavePledges(newPledges);
            }

            ReportProgress(100, string.Format("Finished pledge import: {0:N0} pledges imported.", completed));
        }
Esempio n. 23
0
        /// <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);

            dvpFrequencyType.DefinedTypeId = DefinedTypeCache.Get(frequencyTypeGuid).Id;

            using (var rockContext = new RockContext())
            {
                FinancialPledge pledge = null;

                if (pledgeId > 0)
                {
                    pledge            = new FinancialPledgeService(rockContext).Get(pledgeId);
                    lActionTitle.Text = ActionTitle.Edit(FinancialPledge.FriendlyTypeName).FormatAsHtmlTitle();
                    pdAuditDetails.SetEntity(pledge, ResolveRockUrl("~"));
                }

                if (pledge == null)
                {
                    pledge            = new FinancialPledge();
                    lActionTitle.Text = ActionTitle.Add(FinancialPledge.FriendlyTypeName).FormatAsHtmlTitle();
                    // hide the panel drawer that show created and last modified dates
                    pdAuditDetails.Visible = false;
                }

                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;

                GroupType groupType     = null;
                Guid?     groupTypeGuid = GetAttributeValue("SelectGroupType").AsGuidOrNull();
                if (groupTypeGuid.HasValue)
                {
                    groupType = new GroupTypeService(rockContext).Get(groupTypeGuid.Value);
                }

                if (groupType != null)
                {
                    ddlGroup.Label   = groupType.Name;
                    ddlGroup.Visible = true;
                    LoadGroups(pledge.GroupId);
                    ddlGroup.Enabled = !isReadOnly;
                }
                else
                {
                    ddlGroup.Visible = false;
                }

                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;

                dvpFrequencyType.SelectedValue = !isNewPledge?pledge.PledgeFrequencyValueId.ToString() : string.Empty;

                dvpFrequencyType.Enabled = !isReadOnly;

                if (isReadOnly)
                {
                    nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(FinancialPledge.FriendlyTypeName);
                    lActionTitle.Text      = ActionTitle.View(BlockType.FriendlyTypeName);
                    btnCancel.Text         = "Close";
                }

                btnSave.Visible = !isReadOnly;
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Maps the pledge.
        /// </summary>
        /// <param name="csvData">todo: describe csvData parameter on MapPledge</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        private int MapPledge(CSVInstance csvData)
        {
            var lookupContext   = new RockContext();
            var accountList     = new FinancialAccountService(lookupContext).Queryable().AsNoTracking().ToList();
            var importedPledges = new FinancialPledgeService(lookupContext).Queryable().AsNoTracking()
                                  .Where(p => p.ForeignId != null)
                                  .ToDictionary(t => (int)t.ForeignId, t => (int?)t.Id);

            var pledgeFrequencies        = DefinedTypeCache.Read(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>();

            var completed = 0;

            ReportProgress(0, $"Verifying pledge import ({importedPledges.Count:N0} already exist).");

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                var amountKey    = row[TotalPledge];
                var amount       = amountKey.AsType <decimal?>();
                var startDateKey = row[StartDate];
                if (string.IsNullOrWhiteSpace(startDateKey))
                {
                    startDateKey = "01/01/0001";
                }
                var startDate  = startDateKey.AsType <DateTime?>();
                var endDateKey = row[EndDate];
                if (string.IsNullOrWhiteSpace(endDateKey))
                {
                    endDateKey = "12/31/9999";
                }
                var endDate        = endDateKey.AsType <DateTime?>();
                var createdDateKey = row[PledgeCreatedDate];
                if (string.IsNullOrWhiteSpace(createdDateKey))
                {
                    createdDateKey = ImportDateTime.ToString();
                }
                var createdDate     = createdDateKey.AsType <DateTime?>();
                var modifiedDateKey = row[PledgeModifiedDate];
                if (string.IsNullOrWhiteSpace(modifiedDateKey))
                {
                    modifiedDateKey = ImportDateTime.ToString();
                }
                var modifiedDate = modifiedDateKey.AsType <DateTime?>();

                var pledgeIdKey = row[PledgeId];
                var pledgeId    = pledgeIdKey.AsType <int?>();
                if (amount != null && !importedPledges.ContainsKey((int)pledgeId))
                {
                    var individualIdKey = row[IndividualID];

                    var personKeys = GetPersonKeys(individualIdKey);
                    if (personKeys != null && personKeys.PersonAliasId > 0)
                    {
                        var pledge = new FinancialPledge
                        {
                            PersonAliasId          = personKeys.PersonAliasId,
                            CreatedByPersonAliasId = ImportPersonAliasId,
                            StartDate               = (DateTime)startDate,
                            EndDate                 = (DateTime)endDate,
                            TotalAmount             = (decimal)amount,
                            CreatedDateTime         = createdDate,
                            ModifiedDateTime        = modifiedDate,
                            ModifiedByPersonAliasId = ImportPersonAliasId,
                            ForeignKey              = pledgeIdKey,
                            ForeignId               = pledgeId
                        };

                        var frequency = row[PledgeFrequencyName].ToString().ToLower();
                        if (!string.IsNullOrWhiteSpace(frequency))
                        {
                            frequency = frequency.ToLower();
                            if (frequency.Equals("one time") || frequency.Equals("one-time") || frequency.Equals("as can"))
                            {
                                pledge.PledgeFrequencyValueId = oneTimePledgeFrequencyId;
                            }
                            else
                            {
                                pledge.PledgeFrequencyValueId = pledgeFrequencies
                                                                .Where(f => f.Value.ToLower().StartsWith(frequency) || f.Description.ToLower().StartsWith(frequency))
                                                                .Select(f => f.Id).FirstOrDefault();
                            }
                        }

                        var fundName           = row[FundName] as string;
                        var subFund            = row[SubFundName] as string;
                        var fundGLAccount      = row[FundGLAccount] as string;
                        var subFundGLAccount   = row[SubFundGLAccount] as string;
                        var isFundActiveKey    = row[FundIsActive];
                        var isFundActive       = isFundActiveKey.AsType <bool?>();
                        var isSubFundActiveKey = row[SubFundIsActive];
                        var isSubFundActive    = isSubFundActiveKey.AsType <bool?>();

                        if (!string.IsNullOrWhiteSpace(fundName))
                        {
                            var parentAccount = accountList.FirstOrDefault(a => a.Name.Equals(fundName.Truncate(50)));
                            if (parentAccount == null)
                            {
                                parentAccount = AddAccount(lookupContext, fundName, string.Empty, null, null, isFundActive, null, null, null, null, "", "", null);
                                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.Contains(c.Name) || subFund.Contains(c.ShortCode));
                                if (campusFund != null)
                                {
                                    campusFundId = campusFund.Id;
                                }

                                // add info to easily find/assign this fund in the view
                                subFund = $"{fundName} {subFund}";

                                var childAccount = accountList.FirstOrDefault(c => c.Name.Equals(subFund.Truncate(50)) && c.ParentAccountId == parentAccount.Id);
                                if (childAccount == null)
                                {
                                    // create a child account with a campusId if it was set
                                    childAccount = AddAccount(lookupContext, subFund, string.Empty, campusFundId, parentAccount.Id, isSubFundActive, null, null, null, null, "", "", null);
                                    accountList.Add(childAccount);
                                }

                                pledge.AccountId = childAccount.Id;
                            }
                            else
                            {
                                pledge.AccountId = parentAccount.Id;
                            }
                        }

                        newPledges.Add(pledge);
                        completed++;
                        if (completed % (ReportingNumber * 10) < 1)
                        {
                            ReportProgress(0, $"{completed:N0} pledges imported.");
                        }
                        else if (completed % ReportingNumber < 1)
                        {
                            SavePledges(newPledges);
                            ReportPartialProgress();
                            newPledges.Clear();
                        }
                    }
                }
            }

            if (newPledges.Any())
            {
                SavePledges(newPledges);
            }

            ReportProgress(100, $"Finished pledge import: {completed:N0} pledges imported.");
            return(completed);
        }
Esempio n. 25
0
        /// <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.");
        }
Esempio n. 26
0
        /// <summary>
        /// Maps the pledge.
        /// </summary>
        /// <param name="queryable">The queryable.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        private void MapPledge( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();
            var accountList = new FinancialAccountService( lookupContext ).Queryable().AsNoTracking().ToList();
            var importedPledges = new FinancialPledgeService( lookupContext ).Queryable().AsNoTracking().ToList();

            var pledgeFrequencies = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY ), lookupContext ).DefinedValues;
            int oneTimePledgeFrequencyId = pledgeFrequencies.FirstOrDefault( f => f.Guid == new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_ONE_TIME ) ).Id;

            var newPledges = new List<FinancialPledge>();

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying pledge import ({0:N0} found).", totalRows ) );

            foreach ( var row in tableData.Where( r => r != null ) )
            {
                decimal? amount = row["Total_Pledge"] as decimal?;
                DateTime? startDate = row["Start_Date"] as DateTime?;
                DateTime? endDate = row["End_Date"] as DateTime?;
                if ( amount != null && startDate != null && endDate != null )
                {
                    int? individualId = row["Individual_ID"] as int?;
                    int? householdId = row["Household_ID"] as int?;

                    var personKeys = GetPersonKeys( individualId, householdId, includeVisitors: false );
                    if ( personKeys != null && personKeys.PersonAliasId > 0 )
                    {
                        var pledge = new FinancialPledge();
                        pledge.PersonAliasId = personKeys.PersonAliasId;
                        pledge.CreatedByPersonAliasId = ImportPersonAliasId;
                        pledge.ModifiedDateTime = ImportDateTime;
                        pledge.StartDate = (DateTime)startDate;
                        pledge.EndDate = (DateTime)endDate;
                        pledge.TotalAmount = (decimal)amount;
                        pledge.CreatedDateTime = ImportDateTime;
                        pledge.ModifiedDateTime = ImportDateTime;
                        pledge.ModifiedByPersonAliasId = ImportPersonAliasId;

                        string frequency = row["Pledge_Frequency_Name"].ToString().ToLower();
                        if ( frequency != null )
                        {
                            frequency = frequency.ToLower();
                            if ( frequency.Equals( "one time" ) || frequency.Equals( "as can" ) )
                            {
                                pledge.PledgeFrequencyValueId = oneTimePledgeFrequencyId;
                            }
                            else
                            {
                                pledge.PledgeFrequencyValueId = pledgeFrequencies
                                    .Where( f => f.Value.ToLower().StartsWith( frequency ) || f.Description.ToLower().StartsWith( frequency ) )
                                    .Select( f => f.Id ).FirstOrDefault();
                            }
                        }

                        string fundName = row["Fund_Name"] as string;
                        string subFund = row["Sub_Fund_Name"] as string;
                        if ( fundName != null )
                        {
                            var parentAccount = accountList.FirstOrDefault( a => a.Name.Equals( fundName ) && a.CampusId == null );
                            if ( parentAccount == null )
                            {
                                parentAccount = AddAccount( lookupContext, fundName, string.Empty, null, null, null );
                                accountList.Add( parentAccount );
                            }

                            if ( subFund != null )
                            {
                                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 = string.Format( "{0} {1}", subFund, fundName );

                                var childAccount = accountList.FirstOrDefault( c => c.Name.Equals( subFund ) && c.ParentAccountId == parentAccount.Id );
                                if ( childAccount == null )
                                {
                                    // create a child account with a campusId if it was set
                                    childAccount = AddAccount( lookupContext, subFund, string.Empty, campusFundId, parentAccount.Id, null );
                                    accountList.Add( childAccount );
                                }

                                pledge.AccountId = childAccount.Id;
                            }
                            else
                            {
                                pledge.AccountId = parentAccount.Id;
                            }
                        }

                        newPledges.Add( pledge );
                        completed++;
                        if ( completed % percentage < 1 )
                        {
                            int percentComplete = completed / percentage;
                            ReportProgress( percentComplete, string.Format( "{0:N0} pledges imported ({1}% complete).", completed, percentComplete ) );
                        }
                        else if ( completed % ReportingNumber < 1 )
                        {
                            SavePledges( newPledges );
                            ReportPartialProgress();
                            newPledges.Clear();
                        }
                    }
                }
            }

            if ( newPledges.Any() )
            {
                SavePledges( newPledges );
            }

            ReportProgress( 100, string.Format( "Finished pledge import: {0:N0} pledges imported.", completed ) );
        }
Esempio n. 27
0
        /// <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.PersonId = person.Id;
            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.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 = new Dictionary<string, object>();
            mergeObjects.Add( "Person", person );
            mergeObjects.Add( "FinancialPledge", financialPledge );
            mergeObjects.Add( "PledgeFrequency", pledgeFrequencySelection );
            mergeObjects.Add( "Account", financialAccount );
            lReceipt.Text = GetAttributeValue( "ReceiptText" ).ResolveMergeFields( mergeObjects );

            // show liquid help for debug
            if ( GetAttributeValue( "EnableDebug" ).AsBooleanOrNull() ?? false )
            {
                StringBuilder debugInfo = new StringBuilder();
                debugInfo.Append( "<p /><div class='alert alert-info'><h4>Debug Info</h4>" );

                debugInfo.Append( "<pre>" );

                debugInfo.Append( "<p /><strong>Liquid Data</strong> <br>" );
                debugInfo.Append( mergeObjects.LiquidHelpText() + "</pre>" );

                debugInfo.Append( "</div>" );

                lReceipt.Text += debugInfo.ToString();
            }

            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 Dictionary<string, Dictionary<string, object>>();

                // add person and the mergeObjects (same mergeobjects as receipt)
                recipients.Add( person.Email, mergeObjects );

                Rock.Communication.Email.Send( confirmationEmailTemplateGuid.Value, recipients, ResolveRockUrl( "~/" ), ResolveRockUrl( "~~/" ) );
            }
        }
Esempio n. 28
0
        /// <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("~~/"));
            }
        }
        public static FinancialPledge Translate(DataRow row)
        {
            var pledge = new FinancialPledge();

            pledge.Id        = row.Field <int>("Id");
            pledge.PersonId  = row.Field <int>("PersonId");
            pledge.AccountId = row.Field <int>("AccountId");

            var startDate = row.Field <DateTime?>("StartDate");

            if (startDate.HasValue)
            {
                pledge.StartDate = startDate;
            }

            var endDate = row.Field <DateTime?>("EndDate");

            if (endDate.HasValue)
            {
                pledge.EndDate = endDate;
            }

            var interval = row.Field <int>("PledgeFrequency");

            switch (interval)
            {
            case 0:
                pledge.PledgeFrequency = PledgeFrequency.OneTime;
                break;

            case 7:
                pledge.PledgeFrequency = PledgeFrequency.Weekly;
                break;

            case 30:
                pledge.PledgeFrequency = PledgeFrequency.Monthly;
                break;

            case 90:
                pledge.PledgeFrequency = PledgeFrequency.Quarterly;
                break;

            case 365:
                pledge.PledgeFrequency = PledgeFrequency.Yearly;
                break;

            default:
                pledge.PledgeFrequency = PledgeFrequency.OneTime;
                break;
            }

            pledge.TotalAmount = (decimal)row.Field <double>("TotalAmount");

            var createdDateTime = row.Field <DateTime?>("CreatedDateTime");

            if (createdDateTime.HasValue)
            {
                pledge.CreatedDateTime = createdDateTime;
            }

            var modifiedDateTime = row.Field <DateTime?>("ModifiedDateTime");

            if (modifiedDateTime.HasValue)
            {
                pledge.ModifiedDateTime = modifiedDateTime;
            }

            return(pledge);
        }
Esempio n. 30
0
        /// <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);
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Maps the pledge.
        /// </summary>
        /// <param name="queryable">The queryable.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        private int MapPledge( CSVInstance csvData )
        {
            var lookupContext = new RockContext();
            var accountList = new FinancialAccountService( lookupContext ).Queryable().AsNoTracking().ToList();
            var importedPledges = new FinancialPledgeService( lookupContext ).Queryable().AsNoTracking()
               .Where( p => p.ForeignId != null )
               .ToDictionary( t => ( int )t.ForeignId, t => ( int? )t.Id );

            var pledgeFrequencies = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY ), lookupContext ).DefinedValues;
            int oneTimePledgeFrequencyId = pledgeFrequencies.FirstOrDefault( f => f.Guid == new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_ONE_TIME ) ).Id;

            var newPledges = new List<FinancialPledge>();

            int completed = 0;
            ReportProgress( 0, string.Format( "Verifying pledge import ({0:N0} already exist).", importedPledges.Count ) );

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ( (row = csvData.Database.FirstOrDefault()) != null )
            {
                string amountKey = row[TotalPledge];
                decimal? amount = amountKey.AsType<decimal?>();
                string startDateKey = row[StartDate];
                if ( String.IsNullOrWhiteSpace( startDateKey ) )
                {
                    startDateKey = "01/01/0001";
                }
                DateTime? startDate = startDateKey.AsType<DateTime?>();
                string endDateKey = row[EndDate];
                if ( String.IsNullOrWhiteSpace( endDateKey ) )
                {
                    endDateKey = "12/31/9999";
                }
                DateTime? endDate = endDateKey.AsType<DateTime?>();
                string pledgeIdKey = row[PledgeId];
                int? pledgeId = pledgeIdKey.AsType<int?>();
                if ( amount != null && !importedPledges.ContainsKey( ( int )pledgeId ) )
                {
                    string individualIdKey = row[IndividualID];
                    int? individualId = individualIdKey.AsType<int?>();

                    var personKeys = GetPersonKeys( individualId );
                    if ( personKeys != null && personKeys.PersonAliasId > 0 )
                    {
                        var pledge = new FinancialPledge();
                        pledge.PersonAliasId = personKeys.PersonAliasId;
                        pledge.CreatedByPersonAliasId = ImportPersonAliasId;
                        pledge.StartDate = ( DateTime )startDate;
                        pledge.EndDate = ( DateTime )endDate;
                        pledge.TotalAmount = ( decimal )amount;
                        pledge.CreatedDateTime = ImportDateTime;
                        pledge.ModifiedDateTime = ImportDateTime;
                        pledge.ModifiedByPersonAliasId = ImportPersonAliasId;
                        pledge.ForeignKey = pledgeIdKey;
                        pledge.ForeignId = pledgeId;

                        string frequency = row[PledgeFrequencyName].ToString().ToLower();
                        if ( !String.IsNullOrWhiteSpace( frequency ) )
                        {
                            frequency = frequency.ToLower();
                            if ( frequency.Equals( "one time" ) || frequency.Equals( "one-time" ) || frequency.Equals( "as can" ) )
                            {
                                pledge.PledgeFrequencyValueId = oneTimePledgeFrequencyId;
                            }
                            else
                            {
                                pledge.PledgeFrequencyValueId = pledgeFrequencies
                                    .Where( f => f.Value.ToLower().StartsWith( frequency ) || f.Description.ToLower().StartsWith( frequency ) )
                                    .Select( f => f.Id ).FirstOrDefault();
                            }
                        }

                        string fundName = row[FundName] as string;
                        string subFund = row[SubFundName] as string;
                        string fundGLAccount = row[FundGLAccount] as string;
                        string subFundGLAccount = row[SubFundGLAccount] as string;
                        string isFundActiveKey = row[FundIsActive];
                        Boolean? isFundActive = isFundActiveKey.AsType<Boolean?>();
                        string isSubFundActiveKey = row[SubFundIsActive];
                        Boolean? isSubFundActive = isSubFundActiveKey.AsType<Boolean?>();

                        if ( !String.IsNullOrWhiteSpace( fundName ) )
                        {
                            var parentAccount = accountList.FirstOrDefault( a => a.Name.Equals( fundName.Truncate( 50 ) ) && a.CampusId == null );
                            if ( parentAccount == null )
                            {
                                parentAccount = AddAccount( lookupContext, fundName, string.Empty, null, null, isFundActive );
                                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 = string.Format( "{0} {1}", subFund, fundName );

                                var childAccount = accountList.FirstOrDefault( c => c.Name.Equals( subFund.Truncate( 50 ) ) && c.ParentAccountId == parentAccount.Id );
                                if ( childAccount == null )
                                {
                                    // create a child account with a campusId if it was set
                                    childAccount = AddAccount( lookupContext, subFund, string.Empty, campusFundId, parentAccount.Id, isSubFundActive );
                                    accountList.Add( childAccount );
                                }

                                pledge.AccountId = childAccount.Id;
                            }
                            else
                            {
                                pledge.AccountId = parentAccount.Id;
                            }
                        }

                        newPledges.Add( pledge );
                        completed++;
                        if ( completed % (ReportingNumber * 10) < 1 )
                        {
                            ReportProgress( 0, string.Format( "{0:N0} pledges imported.", completed ) );
                        }
                        else if ( completed % ReportingNumber < 1 )
                        {
                            SavePledges( newPledges );
                            ReportPartialProgress();
                            newPledges.Clear();
                        }
                    }
                }
            }

            if ( newPledges.Any() )
            {
                SavePledges( newPledges );
            }

            ReportProgress( 100, string.Format( "Finished pledge import: {0:N0} pledges imported.", completed ) );
            return completed;
        }