Service/Data access class for Rock.Model.FinancialPledge entity objects.
Esempio n. 1
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. 2
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;
        }
Esempio n. 3
0
        /// <summary>
        /// Handles the Delete event of the gPledges control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void gPledges_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            var pledgeService = new FinancialPledgeService( rockContext );
            var pledge = pledgeService.Get( e.RowKeyId );
            string errorMessage;

            if ( pledge == null )
            {
                return;
            }

            if ( !pledgeService.CanDelete( pledge, out errorMessage ) )
            {
                mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                return;
            }

            pledgeService.Delete( pledge );
            rockContext.SaveChanges();

            BindGrid();
        }
        /// <summary>
        /// Handles the Click event of the btnConfirmYes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnConfirmYes_Click( object sender, EventArgs e )
        {
            var pledges = Session["CachedPledges"] as List<FinancialPledge>;

            if ( pledges == null )
            {
                return;
            }

            var rockContext = new RockContext();
            var pledgeService = new FinancialPledgeService( rockContext );
            foreach ( var pledge in pledges )
            {
                if ( pledge == null || !pledge.IsValid )
                {
                    continue;
                }

                pledgeService.Add( pledge );
            }

            rockContext.SaveChanges();

            Session.Remove( "CachedPledges" );
            ShowReceipt( pledges.Select( p => p.Id ) );
        }
Esempio n. 5
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 ) );
        }
        private void DisplayResults()
        {
            RockContext rockContext = new RockContext();

            var statementYear = RockDateTime.Now.Year;

            if ( Request["StatementYear"] != null )
            {
                Int32.TryParse( Request["StatementYear"].ToString(), out statementYear );
            }

            FinancialTransactionDetailService financialTransactionDetailService = new FinancialTransactionDetailService( rockContext );

            var qry = financialTransactionDetailService.Queryable().AsNoTracking()
                        .Where( t=> t.Transaction.AuthorizedPersonAlias.Person.GivingId == CurrentPerson.GivingId);

            qry = qry.Where( t => t.Transaction.TransactionDateTime.Value.Year == statementYear );

            if ( string.IsNullOrWhiteSpace( GetAttributeValue( "Accounts" ) ) )
            {
                qry = qry.Where( t => t.Account.IsTaxDeductible );
            } else
            {
                var accountGuids = GetAttributeValue( "Accounts" ).Split( ',' ).Select( Guid.Parse ).ToList();
                qry = qry.Where( t => accountGuids.Contains( t.Account.Guid ) );
            }

            qry = qry.OrderByDescending( t => t.Transaction.TransactionDateTime );

            var mergeFields = new Dictionary<string, object>();
            mergeFields.Add( "StatementStartDate", "1/1/" + statementYear.ToString() );
            if ( statementYear == RockDateTime.Now.Year )
            {
                mergeFields.Add( "StatementEndDate", RockDateTime.Now );
            }
            else
            {
                mergeFields.Add( "StatementEndDate", "12/31/" + statementYear.ToString() );
            }

            var familyGroupTypeId = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY ).Id;
            var groupMemberQry = new GroupMemberService( rockContext ).Queryable().Where( m => m.Group.GroupTypeId == familyGroupTypeId );

            // get giving group members in order by family role (adult -> child) and then gender (male -> female)
            var givingGroup = new PersonService( rockContext ).Queryable().AsNoTracking()
                                    .Where( p => p.GivingId == CurrentPerson.GivingId )
                                    .GroupJoin(
                                        groupMemberQry,
                                        p => p.Id,
                                        m => m.PersonId,
                                        (p, m) => new {p, m})
                                    .SelectMany( x => x.m.DefaultIfEmpty(), (y,z) => new { Person = y.p, GroupMember = z} )
                                    .Select( p => new { FirstName = p.Person.NickName, LastName = p.Person.LastName, FamilyRoleOrder = p.GroupMember.GroupRole.Order, Gender = p.Person.Gender, PersonId = p.Person.Id } )
                                    .DistinctBy(p => p.PersonId)
                                    .OrderBy(p => p.FamilyRoleOrder).ThenBy(p => p.Gender)
                                    .ToList();

            // make a list of person ids in the giving group
            List<int> givingGroupIdsOnly = new List<int>();
            foreach ( var x in givingGroup )
            {
                givingGroupIdsOnly.Add(x.PersonId);
            }

            string salutation = string.Empty;

            if (givingGroup.GroupBy(g => g.LastName).Count() == 1 )
            {
                salutation = string.Join( ", ", givingGroup.Select( g => g.FirstName ) ) + " " + givingGroup.FirstOrDefault().LastName;
                if ( salutation.Contains( "," ) )
                {
                    salutation = salutation.ReplaceLastOccurrence( ",", " &" );
                }
            }
            else
            {
                salutation = string.Join( ", ", givingGroup.Select( g => g.FirstName + " " + g.LastName ) );
                if ( salutation.Contains( "," ) )
                {
                    salutation = salutation.ReplaceLastOccurrence( ",", " &" );
                }
            }
            mergeFields.Add( "Salutation", salutation );

            var homeAddress = CurrentPerson.GetHomeLocation();
            if ( homeAddress != null )
            {
                mergeFields.Add( "StreetAddress1", homeAddress.Street1 );
                mergeFields.Add( "StreetAddress2", homeAddress.Street2 );
                mergeFields.Add( "City", homeAddress.City );
                mergeFields.Add( "State", homeAddress.State );
                mergeFields.Add( "PostalCode", homeAddress.PostalCode );
                mergeFields.Add( "Country", homeAddress.Country );
            }
            else
            {
                mergeFields.Add( "StreetAddress1", string.Empty );
                mergeFields.Add( "StreetAddress2", string.Empty );
                mergeFields.Add( "City", string.Empty );
                mergeFields.Add( "State", string.Empty );
                mergeFields.Add( "PostalCode", string.Empty );
                mergeFields.Add( "Country", string.Empty );
            }

            mergeFields.Add( "TransactionDetails", qry.ToList() );

            mergeFields.Add( "AccountSummary", qry.GroupBy( t => t.Account.Name ).Select( s => new AccountSummary { AccountName = s.Key, Total = s.Sum( a => a.Amount ), Order = s.Max(a => a.Account.Order) } ).OrderBy(s => s.Order ));

            // pledge information
            var pledges = new FinancialPledgeService( rockContext ).Queryable().AsNoTracking()
                                .Where(p =>
                                    p.PersonAlias.Person.GivingId == CurrentPerson.GivingId
                                    && (p.StartDate.Year == statementYear || p.EndDate.Year == statementYear))
                                .GroupBy(p => p.Account)
                                .Select(g => new PledgeSummary {
                                                    AccountId = g.Key.Id,
                                                    AccountName = g.Key.Name,
                                                    AmountPledged = g.Sum( p => p.TotalAmount ),
                                                    PledgeStartDate = g.Min(p => p.StartDate),
                                                    PledgeEndDate = g.Max( p => p.EndDate)
                                } )
                                .ToList();

            // add detailed pledge information
            foreach(var pledge in pledges )
            {
                var adjustedPedgeEndDate = pledge.PledgeEndDate.Value.Date.AddHours( 23 ).AddMinutes( 59 ).AddSeconds( 59 );
                pledge.AmountGiven = new FinancialTransactionDetailService( rockContext ).Queryable()
                                            .Where( t =>
                                                 t.AccountId == pledge.AccountId
                                                 && givingGroupIdsOnly.Contains(t.Transaction.AuthorizedPersonAlias.PersonId)
                                                 && t.Transaction.TransactionDateTime >= pledge.PledgeStartDate
                                                 && t.Transaction.TransactionDateTime <= adjustedPedgeEndDate )
                                            .Sum( t => t.Amount );

                pledge.AmountRemaining = (pledge.AmountGiven > pledge.AmountPledged) ? 0 : (pledge.AmountPledged - pledge.AmountGiven);

                if ( pledge.AmountPledged > 0 )
                {
                    var test = (double)pledge.AmountGiven / (double)pledge.AmountPledged;
                    pledge.PercentComplete = (int)((pledge.AmountGiven * 100) / pledge.AmountPledged);
                }
            }

            mergeFields.Add( "Pledges", pledges );

            var template = GetAttributeValue( "LavaTemplate" );

            lResults.Text = template.ResolveMergeFields( mergeFields );

            // show debug info
            if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
            {
                lDebug.Visible = true;
                lDebug.Text = mergeFields.lavaDebugInfo();
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Maps the contribution.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="selectedColumns">The selected columns.</param>
        private void MapContribution( IQueryable<Row> tableData, List<string> selectedColumns = null )
        {
            var lookupContext = new RockContext();
            int transactionEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialTransaction" ).Id;
            var transactionTypeContributionId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ), lookupContext ).Id;
            var transactionTypeEventRegistrationId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_EVENT_REGISTRATION ), lookupContext ).Id;

            int currencyTypeACH = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH ), lookupContext ).Id;
            int currencyTypeCash = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CASH ), lookupContext ).Id;
            int currencyTypeCheck = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK ), lookupContext ).Id;
            int currencyTypeCreditCard = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD ), lookupContext ).Id;

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

            List<FinancialPledge> pledgeList = new FinancialPledgeService( lookupContext ).Queryable().ToList();
            List<FinancialAccount> accountList = new FinancialAccountService( lookupContext ).Queryable().ToList();

            // Get all imported contributions
            var importedContributions = new FinancialTransactionService( lookupContext ).Queryable()
               .Select( t => new { ContributionId = t.ForeignId, TransactionId = t.Id } )
               .ToDictionary( t => t.ContributionId.AsType<int?>(), t => (int?)t.TransactionId );

            var householdAVList = new AttributeValueService( lookupContext ).Queryable().Where( av => av.AttributeId == HouseholdAttributeId ).ToList();

            // List for batching new contributions
            var newTransactions = new List<FinancialTransaction>();

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

            foreach ( var row in tableData )
            {
                int? individualId = row["Individual_ID"] as int?;
                int? householdId = row["Household_ID"] as int?;
                int? contributionId = row["ContributionID"] as int?;

                if ( contributionId != null && !importedContributions.ContainsKey( contributionId ) )
                {
                    var transaction = new FinancialTransaction();

                    string fundName = row["Fund_Name"] as string;

                    //Crossroads - Anything under a fund name that starts with Receipt - is an Event Registration.
                    if ( fundName.StartsWith( "Receipt -" ) ) { transaction.TransactionTypeValueId = transactionTypeEventRegistrationId; }
                    else { transaction.TransactionTypeValueId = transactionTypeContributionId; }

                    int? associatedPersonId;
                    if ( individualId != null ) { associatedPersonId = GetPersonAliasId( individualId, householdId ); } //will get the exact person if Individual Id is not null.
                    else { associatedPersonId = GetPersonId( householdAVList, householdId ); } //Will attempt to get the Head first, then Spouse, then Child. Will exclude Other and Visitor
                    if ( associatedPersonId != null )
                    {
                        transaction.AuthorizedPersonAliasId = associatedPersonId;
                        transaction.CreatedByPersonAliasId = ImportPersonAlias.Id;
                        transaction.ProcessedByPersonAliasId = associatedPersonId;
                        transaction.ForeignId = contributionId.ToString();

                        string summary = row["Memo"] as string;
                        if ( summary != null )
                        {
                            transaction.Summary = summary;
                        }

                        int? batchId = row["BatchID"] as int?;
                        if ( batchId != null && ImportedBatches.Any( b => b.Key == batchId ) )
                        {
                            transaction.BatchId = ImportedBatches.FirstOrDefault( b => b.Key == batchId ).Value;
                        }

                        DateTime? receivedDate = row["Received_Date"] as DateTime?;
                        if ( receivedDate != null )
                        {
                            transaction.TransactionDateTime = receivedDate;
                            transaction.CreatedDateTime = receivedDate;
                        }

                        bool isTypeNonCash = false;
                        string contributionType = row["Contribution_Type_Name"].ToString().ToLower();
                        if ( contributionType != null )
                        {
                            if ( contributionType == "ach" )
                            {
                                transaction.CurrencyTypeValueId = currencyTypeACH;
                            }
                            else if ( contributionType == "cash" )
                            {
                                transaction.CurrencyTypeValueId = currencyTypeCash;
                            }
                            else if ( contributionType == "check" )
                            {
                                transaction.CurrencyTypeValueId = currencyTypeCheck;
                            }
                            else if ( contributionType == "credit card" )
                            {
                                transaction.CurrencyTypeValueId = currencyTypeCreditCard;
                            }
                            else
                            {
                                isTypeNonCash = true;
                            }
                        }

                        string checkNumber = row["Check_Number"] as string;
                        if ( checkNumber != null && checkNumber.AsType<int?>() != null )
                        {
                            // routing & account set to zero
                            transaction.CheckMicrEncrypted = Encryption.EncryptString( string.Format( "{0}_{1}_{2}", 0, 0, checkNumber ) );
                        }

                        decimal? amount = row["Amount"] as decimal?;
                        if ( fundName != null & amount != null )
                        {
                            FinancialAccount matchingAccount = null;
                            int? parentAccountId = null;
                            string parentAccountName = String.Empty;
                            int? fundCampusId = null;
                            fundName = fundName.Trim();

                            string subFund = row["Sub_Fund_Name"] as string;
                            if ( subFund != null )
                            {
                                subFund = subFund.Trim();

                                // Check if subfund was used to mark a multi-site campus
                                fundCampusId = CampusList.Where( c => subFund.StartsWith( c.Name ) || subFund.StartsWith( c.ShortCode ) )
                                    .Select( c => (int?)c.Id ).FirstOrDefault();

                                // Matched a campus, check to see if an account exists for that campus already
                                if ( fundCampusId != null )
                                {
                                    matchingAccount = accountList.FirstOrDefault( a => a.Name.Equals( fundName )
                                        && a.CampusId != null && a.CampusId.Equals( fundCampusId ) );
                                }
                                else
                                {
                                    // No campus match, look for an account that matches parent name and subfund name
                                    matchingAccount = accountList.FirstOrDefault( a => a.ParentAccountId != null && a.ParentAccount.Name.Equals( fundName ) && a.Name.Equals( subFund ) );

                                    if ( matchingAccount == null )
                                    {
                                        // Check if a parent account exists already
                                        FinancialAccount parentAccount = accountList.FirstOrDefault( a => a.Name.Equals( fundName ) );
                                        if ( parentAccount == null )
                                        {

                                            parentAccount = AddAccount( lookupContext, fundName, fundCampusId );
                                            accountList.Add( parentAccount );
                                        }

                                        // set data for subfund to be created
                                        parentAccountId = parentAccount.Id;
                                        fundName = subFund;
                                        parentAccountName = parentAccount.Name;
                                    }
                                }
                            }
                            else
                            {
                                matchingAccount = accountList.FirstOrDefault( a => a.Name.Equals( fundName ) && a.CampusId == null );
                            }

                            if ( matchingAccount == null )
                            {

                                // No account matches, create the new account with campus Id and parent Id if they were set
                                matchingAccount = AddAccount( lookupContext, fundName, fundCampusId, parentAccountName, parentAccountId );

                                accountList.Add( matchingAccount );
                            }

                            var transactionDetail = new FinancialTransactionDetail();
                            transactionDetail.Amount = (decimal)amount;
                            transactionDetail.CreatedDateTime = receivedDate;
                            transactionDetail.AccountId = matchingAccount.Id;
                            transactionDetail.IsNonCash = isTypeNonCash;
                            transaction.TransactionDetails.Add( transactionDetail );

                            if ( amount < 0 )
                            {
                                var transactionRefund = new FinancialTransactionRefund();
                                transactionRefund.CreatedDateTime = receivedDate;
                                transactionRefund.RefundReasonSummary = summary;
                                transactionRefund.RefundReasonValueId = refundReasons.Where( dv => summary != null && dv.Value.Contains( summary ) )
                                    .Select( dv => (int?)dv.Id ).FirstOrDefault();
                                transaction.Refund = transactionRefund;
                            }
                        }

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

            if ( newTransactions.Any() )
            {
                SaveContributions( newTransactions );
            }

            ReportProgress( 100, string.Format( "Finished contribution import: {0:N0} contributions imported.", completed ) );
        }
Esempio n. 8
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. 9
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. 10
0
        /// <summary>
        /// Maps the contribution.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="selectedColumns">The selected columns.</param>
        private void MapContribution( IQueryable<Row> tableData, List<string> selectedColumns = null )
        {
            int transactionEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialTransaction" ).Id;
            var accountService = new FinancialAccountService();
            var attributeService = new AttributeService();

            var transactionTypeContributionId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ) ).Id;

            int currencyTypeACH = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH ) ).Id;
            int currencyTypeCash = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CASH ) ).Id;
            int currencyTypeCheck = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK ) ).Id;
            int currencyTypeCreditCard = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD ) ).Id;

            List<DefinedValue> refundReasons = new DefinedValueService().Queryable().Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON ) ).ToList();

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

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

            // Add an Attribute for the unique F1 Contribution Id
            int contributionAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == transactionEntityTypeId
                && a.Key == "F1ContributionId" ).Select( a => a.Id ).FirstOrDefault();
            if ( contributionAttributeId == 0 )
            {
                var newContributionAttribute = new Rock.Model.Attribute();
                newContributionAttribute.Key = "F1ContributionId";
                newContributionAttribute.Name = "F1 Contribution Id";
                newContributionAttribute.FieldTypeId = IntegerFieldTypeId;
                newContributionAttribute.EntityTypeId = transactionEntityTypeId;
                newContributionAttribute.EntityTypeQualifierValue = string.Empty;
                newContributionAttribute.EntityTypeQualifierColumn = string.Empty;
                newContributionAttribute.Description = "The FellowshipOne identifier for the contribution that was imported";
                newContributionAttribute.DefaultValue = string.Empty;
                newContributionAttribute.IsMultiValue = false;
                newContributionAttribute.IsRequired = false;
                newContributionAttribute.Order = 0;

                attributeService.Add( newContributionAttribute, ImportPersonAlias );
                attributeService.Save( newContributionAttribute, ImportPersonAlias );
                contributionAttributeId = newContributionAttribute.Id;
            }

            var contributionAttribute = AttributeCache.Read( contributionAttributeId );

            // Get all imported contributions
            var importedContributions = new AttributeValueService().GetByAttributeId( contributionAttributeId )
               .Select( av => new { ContributionId = av.Value.AsType<int?>(), TransactionId = av.EntityId } )
               .ToDictionary( t => t.ContributionId, t => t.TransactionId );

            // List for batching new contributions
            var newTransactions = new List<FinancialTransaction>();

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Checking contribution import ({0:N0} found, {1:N0} already exist).", totalRows, importedContributions.Count() ) );
            foreach ( var row in tableData )
            {
                int? individualId = row["Individual_ID"] as int?;
                int? householdId = row["Household_ID"] as int?;
                int? contributionId = row["ContributionID"] as int?;

                if ( contributionId != null && !importedContributions.ContainsKey( contributionId ) )
                {
                    var transaction = new FinancialTransaction();
                    transaction.TransactionTypeValueId = transactionTypeContributionId;
                    transaction.AuthorizedPersonId = GetPersonId( individualId, householdId );
                    transaction.CreatedByPersonAliasId = ImportPersonAlias.Id;
                    transaction.AuthorizedPersonId = GetPersonId( individualId, householdId );

                    string summary = row["Memo"] as string;
                    if ( summary != null )
                    {
                        transaction.Summary = summary;
                    }

                    int? batchId = row["BatchID"] as int?;
                    if ( batchId != null && ImportedBatches.Any( b => b.Key == batchId ) )
                    {
                        transaction.BatchId = ImportedBatches.FirstOrDefault( b => b.Key == batchId ).Value;
                    }

                    DateTime? receivedDate = row["Received_Date"] as DateTime?;
                    if ( receivedDate != null )
                    {
                        transaction.TransactionDateTime = receivedDate;
                        transaction.CreatedDateTime = receivedDate;
                    }

                    bool isTypeNonCash = false;
                    string contributionType = row["Contribution_Type_Name"] as string;
                    if ( contributionType != null )
                    {
                        if ( contributionType == "ACH" )
                        {
                            transaction.CurrencyTypeValueId = currencyTypeACH;
                        }
                        else if ( contributionType == "Cash" )
                        {
                            transaction.CurrencyTypeValueId = currencyTypeCash;
                        }
                        else if ( contributionType == "Check" )
                        {
                            transaction.CurrencyTypeValueId = currencyTypeCheck;
                        }
                        else if ( contributionType == "Credit Card" )
                        {
                            transaction.CurrencyTypeValueId = currencyTypeCreditCard;
                        }
                        else
                        {
                            isTypeNonCash = true;
                        }
                    }

                    string checkNumber = row["Check_Number"] as string;
                    if ( checkNumber != null && checkNumber.AsType<int?>() != null )
                    {
                        // routing & account set to zero
                        transaction.CheckMicrEncrypted = Encryption.EncryptString( string.Format( "{0}_{1}_{2}", 0, 0, checkNumber ) );
                    }

                    string fundName = row["Fund_Name"] as string;
                    string subFund = row["Sub_Fund_Name"] as string;
                    decimal? amount = row["Amount"] as decimal?;
                    if ( fundName != null & amount != null )
                    {
                        FinancialAccount matchingAccount = null;
                        fundName = fundName.Trim();

                        int? fundCampusId = null;
                        if ( subFund != null )
                        {
                            subFund = subFund.Trim();
                            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 ) && a.CampusId == null );
                        }

                        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 );
                            accountList.Add( matchingAccount );
                        }

                        var transactionDetail = new FinancialTransactionDetail();
                        transactionDetail.Amount = (decimal)amount;
                        transactionDetail.CreatedDateTime = receivedDate;
                        transactionDetail.AccountId = matchingAccount.Id;
                        transactionDetail.IsNonCash = isTypeNonCash;
                        transaction.TransactionDetails.Add( transactionDetail );

                        if ( amount < 0 )
                        {
                            var transactionRefund = new FinancialTransactionRefund();
                            transactionRefund.CreatedDateTime = receivedDate;
                            transactionRefund.RefundReasonSummary = summary;
                            transactionRefund.RefundReasonValueId = refundReasons.Where( dv => summary != null && dv.Name.Contains( summary ) )
                                .Select( dv => (int?)dv.Id ).FirstOrDefault();
                            transaction.Refund = transactionRefund;
                        }
                    }

                    // Other Attributes to create:
                    // Pledge_Drive_Name
                    // Stated_Value
                    // True_Value
                    // Liquidation_cost

                    transaction.Attributes = new Dictionary<string, AttributeCache>();
                    transaction.AttributeValues = new Dictionary<string, List<AttributeValue>>();
                    transaction.Attributes.Add( contributionAttribute.Key, contributionAttribute );
                    transaction.AttributeValues.Add( contributionAttribute.Key, new List<AttributeValue>() );
                    transaction.AttributeValues[contributionAttribute.Key].Add( new AttributeValue()
                    {
                        AttributeId = contributionAttribute.Id,
                        Value = contributionId.ToString(),
                        Order = 0
                    } );

                    newTransactions.Add( transaction );
                    completed++;
                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} contributions imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        RockTransactionScope.WrapTransaction( () =>
                        {
                            var transactionService = new FinancialTransactionService();
                            transactionService.RockContext.FinancialTransactions.AddRange( newTransactions );
                            transactionService.RockContext.SaveChanges();

                            var attributeValueService = new AttributeValueService();
                            foreach ( var contribution in newTransactions.Where( c => c.Attributes.Any() ) )
                            {
                                var attributeValue = contribution.AttributeValues[contributionAttribute.Key].FirstOrDefault();
                                if ( attributeValue != null )
                                {
                                    attributeValue.EntityId = contribution.Id;
                                    attributeValueService.RockContext.AttributeValues.Add( attributeValue );
                                }
                            }

                            attributeValueService.RockContext.SaveChanges();
                        } );

                        newTransactions.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if ( newTransactions.Any() )
            {
                RockTransactionScope.WrapTransaction( () =>
                {
                    var transactionService = new FinancialTransactionService();
                    transactionService.RockContext.FinancialTransactions.AddRange( newTransactions );
                    transactionService.RockContext.SaveChanges();

                    var attributeValueService = new AttributeValueService();
                    foreach ( var contribution in newTransactions.Where( c => c.Attributes.Any() ) )
                    {
                        var attributeValue = contribution.AttributeValues[contributionAttribute.Key].FirstOrDefault();
                        if ( attributeValue != null )
                        {
                            attributeValue.EntityId = contribution.Id;
                            attributeValueService.RockContext.AttributeValues.Add( attributeValue );
                        }
                    }

                    attributeValueService.RockContext.SaveChanges();
                } );
            }

            ReportProgress( 100, string.Format( "Finished contribution import: {0:N0} contributions imported.", completed ) );
        }
Esempio n. 11
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. 12
0
        /// <summary>
        /// Handles the Delete event of the gPledges control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void gPledges_Delete( object sender, RowEventArgs e )
        {
            RockTransactionScope.WrapTransaction( () =>
                {
                    var pledgeService = new FinancialPledgeService();
                    var pledge = pledgeService.Get( (int) e.RowKeyValue );
                    string errorMessage;
                    
                    if ( pledge == null )
                    {
                        return;
                    }

                    if ( !pledgeService.CanDelete( pledge, out errorMessage ) )
                    {
                        mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                        return;
                    }

                    pledgeService.Delete( pledge, CurrentPersonId );
                    pledgeService.Save( pledge, CurrentPersonId );
                });

            BindGrid();
        }
Esempio n. 13
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;
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var pledgeService = new FinancialPledgeService( new RockContext() );
            var sortProperty = gPledges.SortProperty;
            var pledges = pledgeService.Queryable();

            int? personId = gfPledges.GetUserPreference("Person").AsIntegerOrNull();

            if ( personId.HasValue )
            {
                pledges = pledges.Where( p => p.PersonAlias.PersonId == personId );
            }

            var accountIds = gfPledges.GetUserPreference( "Accounts" ).Split( ',' ).AsIntegerList();

            if ( accountIds.Any() )
            {
                pledges = pledges.Where( p => p.AccountId.HasValue && accountIds.Contains( p.AccountId.Value ) );
            }

            // Date Range
            var drp = new DateRangePicker();
            drp.DelimitedValues = gfPledges.GetUserPreference( "Date Range" );
            var filterStartDate = drp.LowerValue ?? DateTime.MinValue;
            var filterEndDate = drp.UpperValue ?? DateTime.MaxValue;
            /****
             * Include any pledges whose Start/EndDates overlap with the Filtered Date Range
             *
             * * Pledge1 Range 1/1/2011 - 12/31/2011
             * * Pledge2 Range 1/1/0000 - 1/1/9999
             * * Pledge3 Range 6/1/2011 - 6/1/2012
             *
             * Filter1 Range 1/1/2010 - 1/1/2013
             * * * All Pledges should show
             * Filter1 Range 1/1/2012 - 1/1/2013
             * * * Pledge2 and Pledge3 should show
             * Filter2 Range 5/1/2012 - 5/2/2012
             * * * Pledge2 and Pledge3 should show
             * Filter3 Range 5/1/2012 - 1/1/9999
             * * * Pledge2 and Pledge3 should show
             * Filter4 Range 5/1/2010 - 5/1/2010
             * * * Pledge2 should show
             ***/

            // exclude pledges that start after the filter's end date or end before the filter's start date
            pledges = pledges.Where( p => !( p.StartDate > filterEndDate ) && !( p.EndDate < filterStartDate ) );

            gPledges.DataSource = sortProperty != null ? pledges.Sort( sortProperty ).ToList() : pledges.OrderBy( p => p.AccountId ).ToList();
            gPledges.DataBind();
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            var pledgeService = new FinancialPledgeService( rockContext );
            var person = FindPerson( rockContext );
            var pledges = GetPledges( person ).ToList();

            // Does this person already have a pledge for these accounts?
            // If so, give them the option to create a new one?
            var personPledgeAccountIds = pledgeService.Queryable()
                .Where( p => p.PersonId == person.Id )
                .Select( p => p.AccountId )
                .ToList();

            if ( Accounts.Any( a => personPledgeAccountIds.Contains( a.Id ) ) )
            {
                pnlConfirm.Visible = true;
                Session.Add( "CachedPledges", pledges );
                return;
            }

            foreach ( var pledge in pledges )
            {
                if ( !pledge.IsValid )
                {
                    continue;
                }

                pledgeService.Add( pledge );
            }

            rockContext.SaveChanges();

            ShowReceipt( pledges.Select( p => p.Id ) );
        }
Esempio n. 16
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 )
        {
            using ( new UnitOfWorkScope() )
            {
                RockTransactionScope.WrapTransaction( () =>
                    {
                        var pledgeService = new FinancialPledgeService();
                        var person = FindPerson();
                        var pledges = GetPledges( person ).ToList();

                        // Does this person already have a pledge for these accounts?
                        // If so, give them the option to create a new one?
                        var personPledgeAccountIds = pledgeService.Queryable()
                            .Where( p => p.PersonId == person.Id )
                            .Select( p => p.AccountId )
                            .ToList();

                        if ( Accounts.Any( a => personPledgeAccountIds.Contains( a.Id ) ) )
                        {
                            pnlConfirm.Visible = true;
                            Session.Add( "CachedPledges", pledges );
                            return;
                        }

                        foreach ( var pledge in pledges )
                        {
                            if ( !pledge.IsValid )
                                continue;

                            pledgeService.Add( pledge, person.Id );
                            pledgeService.Save( pledge, person.Id );
                        }

                        ShowReceipt( pledges.Select( p => p.Id ) );
                    } );
            }
        }
        /// <summary>
        /// Shows the receipt.
        /// </summary>
        /// <param name="ids">The ids.</param>
        private void ShowReceipt( IEnumerable<int> ids )
        {
            // Pledges need to be loaded fresh from the database so they can
            // be attached to a context and be fully hydrated with data.
            var pledgeService = new FinancialPledgeService( new RockContext() );
            var pledges = pledgeService.Queryable().Where( p => ids.Contains( p.Id ) );
            var person = pledges.Select( p => p.Person ).FirstOrDefault();
            rptCompletedPledges.DataSource = pledges.ToList();
            rptCompletedPledges.DataBind();

            if ( person != null )
            {
                lPersonFullName.Text = person.FullName;
            }

            pnlForm.Visible = false;
            pnlReceipt.Visible = true;
        }
Esempio n. 18
0
        /// <summary>
        /// Handles the Click event of the btnConfirmYes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnConfirmYes_Click( object sender, EventArgs e )
        {
            var pledges = Session["CachedPledges"] as List<FinancialPledge>;

            if ( pledges == null )
                return;

            RockTransactionScope.WrapTransaction( () =>
                {
                    foreach ( var pledge in pledges )
                    {
                        if ( pledge == null || !pledge.IsValid )
                            continue;

                        var pledgeService = new FinancialPledgeService();
                        pledgeService.Add( pledge, CurrentPersonId );
                        pledgeService.Save( pledge, CurrentPersonId );
                    }

                    Session.Remove( "CachedPledges" );
                    ShowReceipt( pledges.Select( p => p.Id ) );
                } );
        }
Esempio n. 19
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. 20
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var pledgeService = new FinancialPledgeService( new RockContext() );
            var sortProperty = gPledges.SortProperty;
            var pledges = pledgeService.Queryable();

            if ( ppFilterPerson.PersonId.HasValue )
            {
                pledges = pledges.Where( p => p.PersonId == ppFilterPerson.PersonId.Value );
            }

            var accountIds = fpFilterAccount.SelectedValuesAsInt().Where( i => i != 0 ).ToList();

            if ( accountIds.Any() )
            {
                pledges = pledges.Where( p => p.AccountId.HasValue && accountIds.Contains( p.AccountId.Value ) );
            }

            gPledges.DataSource = sortProperty != null ? pledges.Sort( sortProperty ).ToList() : pledges.OrderBy( p => p.AccountId ).ToList();
            gPledges.DataBind();
        }
Esempio n. 21
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();
            var pledgeService = new FinancialPledgeService( rockContext );
            var sortProperty = gPledges.SortProperty;
            var pledges = pledgeService.Queryable();

            Person person = null;
            if ( TargetPerson != null )
            {
                person = TargetPerson;
            }
            else
            {
                int? personId = gfPledges.GetUserPreference( "Person" ).AsIntegerOrNull();
                if ( personId.HasValue && ppFilterPerson.Visible )
                {
                    person = new PersonService( rockContext ).Get( personId.Value );
                }
            }

            if ( person != null )
            {
                // if a person is specified, get pledges for that person ( and also anybody in their GivingUnit )
                pledges = pledges.Where( p => p.PersonAlias.Person.GivingId == person.GivingId );
            }

            // get the accounts and make sure they still exist by checking the database
            var accountIds = gfPledges.GetUserPreference( "Accounts" ).Split( ',' ).AsIntegerList();
            accountIds = new FinancialAccountService( rockContext ).GetByIds( accountIds ).Select( a => a.Id ).ToList();

            if ( accountIds.Any() && apFilterAccount.Visible )
            {
                pledges = pledges.Where( p => p.AccountId.HasValue && accountIds.Contains( p.AccountId.Value ) );
            }

            // Date Range
            var drp = new DateRangePicker();
            drp.DelimitedValues = gfPledges.GetUserPreference( "Date Range" );
            var filterStartDate = drp.LowerValue ?? DateTime.MinValue;
            var filterEndDate = drp.UpperValue ?? DateTime.MaxValue;

            if (filterEndDate != DateTime.MaxValue)
            {
                filterEndDate = filterEndDate.AddDays( 1 );
            }

            /****
             * Include any pledges whose Start/EndDates overlap with the Filtered Date Range
             *
             * * Pledge1 Range 1/1/2011 - 12/31/2011
             * * Pledge2 Range 1/1/0000 - 1/1/9999
             * * Pledge3 Range 6/1/2011 - 6/1/2012
             *
             * Filter1 Range 1/1/2010 - 1/1/2013
             * * * All Pledges should show
             * Filter1 Range 1/1/2012 - 1/1/2013
             * * * Pledge2 and Pledge3 should show
             * Filter2 Range 5/1/2012 - 5/2/2012
             * * * Pledge2 and Pledge3 should show
             * Filter3 Range 5/1/2012 - 1/1/9999
             * * * Pledge2 and Pledge3 should show
             * Filter4 Range 5/1/2010 - 5/1/2010
             * * * Pledge2 should show
             ***/

            // exclude pledges that start after the filter's end date or end before the filter's start date
            if ( drpDates.Visible )
            {
                pledges = pledges.Where( p => !(p.StartDate > filterEndDate) && !(p.EndDate < filterStartDate) );
            }

            // Last Modified
            drp.DelimitedValues = gfPledges.GetUserPreference( "Last Modified" );
            filterStartDate = drp.LowerValue ?? DateTime.MinValue;
            filterEndDate = drp.UpperValue ?? DateTime.MaxValue;

            if (filterEndDate != DateTime.MaxValue)
            {
                filterEndDate = filterEndDate.AddDays( 1 );
            }

            if ( drpLastModifiedDates.Visible )
            {
                pledges = pledges.Where( p => !(p.ModifiedDateTime >= filterEndDate) && !(p.ModifiedDateTime <= filterStartDate) );
            }

            gPledges.DataSource = sortProperty != null ? pledges.Sort( sortProperty ).ToList() : pledges.OrderBy( p => p.AccountId ).ToList();
            gPledges.DataBind();
        }
Esempio n. 22
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;
        }