Esempio n. 1
0
        /// <summary>
        /// Sets TaxDeductiblePct and uses it to calculate the tax deductibility amounts for a Gift Detail
        /// </summary>
        /// <param name="AGiftDetail">Calculated amounts are added to this row</param>
        /// <param name="ADateEntered"></param>
        /// <param name="ATransaction"></param>
        public static void SetDefaultTaxDeductibilityData(
            ref AGiftDetailRow AGiftDetail, DateTime ADateEntered, TDBTransaction ATransaction)
        {
            bool FoundTaxDeductiblePct = false;

            // if the gift it tax deductible
            if (AGiftDetail.TaxDeductible)
            {
                AMotivationDetailTable Tbl = AMotivationDetailAccess.LoadByPrimaryKey(
                    AGiftDetail.LedgerNumber, AGiftDetail.MotivationGroupCode, AGiftDetail.MotivationDetailCode, ATransaction);
                AMotivationDetailRow MotivationDetailRow;

                Boolean HasTaxDeductibleAccountCode = false;

                if (Tbl.Rows.Count > 0)
                {
                    MotivationDetailRow         = Tbl[0];
                    HasTaxDeductibleAccountCode = !string.IsNullOrEmpty(MotivationDetailRow.TaxDeductibleAccountCode);
                }

                // if the gift's motivation detail has a tax-deductible account
                if (HasTaxDeductibleAccountCode)
                {
                    // default pct is 100
                    AGiftDetail.TaxDeductiblePct = 100;
                    FoundTaxDeductiblePct        = true;

                    PPartnerTaxDeductiblePctTable PartnerTaxDeductiblePctTable =
                        PPartnerTaxDeductiblePctAccess.LoadViaPPartner(AGiftDetail.RecipientKey, ATransaction);

                    // search for tax deductible pct for recipient
                    foreach (PPartnerTaxDeductiblePctRow Row in PartnerTaxDeductiblePctTable.Rows)
                    {
                        if (Row.DateValidFrom <= ADateEntered)
                        {
                            AGiftDetail.TaxDeductiblePct = Row.PercentageTaxDeductible;
                            break;
                        }
                    }
                }
            }

            // if a tax deductible pct is set for the recipient
            if (FoundTaxDeductiblePct)
            {
                // calculate TaxDeductibleAmount and NonDeductibleAmount for all three currencies
                TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref AGiftDetail);
            }

            // if gift is not tax deductible or motivation detail does not hace a tax deductible account
            if (!AGiftDetail.TaxDeductible || !FoundTaxDeductiblePct)
            {
                AGiftDetail.TaxDeductiblePct        = 0;
                AGiftDetail.NonDeductibleAmount     = AGiftDetail.GiftTransactionAmount;
                AGiftDetail.NonDeductibleAmountBase = AGiftDetail.GiftAmount;
                AGiftDetail.NonDeductibleAmountIntl = AGiftDetail.GiftAmountIntl;
            }
        }
        /// <summary>
        /// Update tax deductibility amounts when the gift amount or the tax deductible percentage has changed
        /// </summary>
        private void UpdateTaxDeductibilityAmounts(object sender, EventArgs e)
        {
            if (!FSETUseTaxDeductiblePercentageFlag ||
                (FPreviouslySelectedDetailRow == null) ||
                FNewGiftInProcess ||
                (txtDeductiblePercentage.NumberValueDecimal == null))
            {
                return;
            }

            if (FBatchRow.BatchStatus == MFinanceConstants.BATCH_UNPOSTED)
            {
                if (!chkDetailTaxDeductible.Checked)
                {
                    FPreviouslySelectedDetailRow.TaxDeductible       = false;
                    FPreviouslySelectedDetailRow.TaxDeductiblePct    = 0.0m;
                    FPreviouslySelectedDetailRow.TaxDeductibleAmount = 0.0m;
                    FPreviouslySelectedDetailRow.NonDeductibleAmount = FPreviouslySelectedDetailRow.GiftTransactionAmount;
                }
                else
                {
                    FPreviouslySelectedDetailRow.TaxDeductible = true;

                    try
                    {
                        decimal percentageVal = txtDeductiblePercentage.NumberValueDecimal.Value;

                        if (percentageVal > 100)
                        {
                            //Avoid repeat event code running past initial check (see above)
                            FSETUseTaxDeductiblePercentageFlag = false;

                            //Reset the control
                            txtDeductiblePercentage.NumberValueDecimal = 100m;
                            percentageVal = 100m;
                        }

                        FPreviouslySelectedDetailRow.TaxDeductiblePct = percentageVal;
                    }
                    finally
                    {
                        FSETUseTaxDeductiblePercentageFlag = true;
                    }

                    AGiftDetailRow giftDetails = (AGiftDetailRow)FPreviouslySelectedDetailRow;
                    TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetails);
                }
            }

            txtTaxDeductAmount.NumberValueDecimal = FPreviouslySelectedDetailRow.TaxDeductibleAmount;
            txtNonDeductAmount.NumberValueDecimal = FPreviouslySelectedDetailRow.NonDeductibleAmount;
        }
Esempio n. 3
0
        private void ReconcileTaxDeductibleAmounts(GiftBatchTDSAGiftDetailRow ARow)
        {
            AGiftDetailRow GDR = (AGiftDetailRow)ARow;

            TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref GDR);

            if ((txtTaxDeductAmount.NumberValueDecimal != ARow.TaxDeductibleAmount) ||
                (txtNonDeductAmount.NumberValueDecimal != ARow.NonDeductibleAmount))
            {
                txtTaxDeductAmount.NumberValueDecimal = ARow.TaxDeductibleAmount;
                txtNonDeductAmount.NumberValueDecimal = ARow.NonDeductibleAmount;
            }
        }
        public static void UpdateUnpostedGiftsTaxDeductiblePct(Int64 ARecipientKey, decimal ANewPct, DateTime ADateFrom)
        {
            TDBTransaction Transaction  = null;
            bool           SubmissionOK = false;

            DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.ReadCommitted,
                                                       ref Transaction,
                                                       ref SubmissionOK,
                                                       delegate
            {
                string Query = "SELECT a_gift_detail.*" +

                               " FROM a_gift_detail, a_gift_batch, a_gift" +

                               " WHERE a_gift_detail.p_recipient_key_n = " + ARecipientKey +
                               " AND a_gift_detail.a_tax_deductible_pct_n <> " + ANewPct +
                               " AND a_gift_detail.a_modified_detail_l <> true" +
                               " AND a_gift_detail.a_tax_deductible_l = true" +
                               " AND a_gift_batch.a_ledger_number_i = a_gift_detail.a_ledger_number_i" +
                               " AND a_gift_batch.a_batch_number_i = a_gift_detail.a_batch_number_i" +
                               " AND a_gift_batch.a_batch_status_c = 'Unposted'" +
                               " AND a_gift.a_ledger_number_i = a_gift_detail.a_ledger_number_i" +
                               " AND a_gift.a_batch_number_i = a_gift_detail.a_batch_number_i" +
                               " AND a_gift.a_gift_transaction_number_i = a_gift_detail.a_gift_transaction_number_i" +
                               " AND a_gift.a_date_entered_d >= '" + ADateFrom.ToString("yyyy-MM-dd") + "'";

                AGiftDetailTable Table = new AGiftDetailTable();

                DBAccess.GDBAccessObj.SelectDT(Table, Query, Transaction);

                // update fields for each row
                for (int i = 0; i < Table.Rows.Count; i++)
                {
                    AGiftDetailRow Row = Table[i];

                    Row.TaxDeductiblePct = ANewPct;
                    TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref Row);
                }

                AGiftDetailAccess.SubmitChanges(Table, Transaction);

                SubmissionOK = true;
            });
        }
        private void UpdateTransactionsCurrencyAmounts(AGiftBatchRow ABatchRow,
                                                       Decimal AIntlToBaseCurrencyExchRate,
                                                       Boolean ATransactionInIntlCurrency)
        {
            int     LedgerNumber            = ABatchRow.LedgerNumber;
            int     BatchNumber             = ABatchRow.BatchNumber;
            decimal BatchExchangeRateToBase = ABatchRow.ExchangeRateToBase;

            if (!LoadGiftDataForBatch(LedgerNumber, BatchNumber))
            {
                return;
            }

            DataView transDV = new DataView(FMainDS.AGiftDetail);

            transDV.RowFilter = String.Format("{0}={1}",
                                              AGiftDetailTable.GetBatchNumberDBName(),
                                              BatchNumber);

            foreach (DataRowView drvTrans in transDV)
            {
                AGiftDetailRow gdr = (AGiftDetailRow)drvTrans.Row;

                gdr.GiftAmount = GLRoutines.Divide(gdr.GiftTransactionAmount, BatchExchangeRateToBase);

                if (!ATransactionInIntlCurrency)
                {
                    gdr.GiftAmountIntl = (AIntlToBaseCurrencyExchRate == 0) ? 0 : GLRoutines.Divide(gdr.GiftAmount, AIntlToBaseCurrencyExchRate);
                }
                else
                {
                    gdr.GiftAmountIntl = gdr.GiftTransactionAmount;
                }

                if (FSETUseTaxDeductiblePercentageFlag)
                {
                    TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref gdr);
                }
            }
        }
        // update tax deductibility amounts when the gift amount or the tax deductible percentage has changed
        private void UpdateTaxDeductibilityAmounts(object sender, EventArgs e)
        {
            if (FCreatingNewGift || (txtDeductiblePercentage.NumberValueDecimal == null) || (FPreviouslySelectedDetailRow == null))
            {
                return;
            }

            if (FPreviouslySelectedDetailRow.IsTaxDeductiblePctNull())
            {
                FPreviouslySelectedDetailRow.TaxDeductiblePct = 0;
            }

            if (sender == txtDeductiblePercentage)
            {
                FPreviouslySelectedDetailRow.TaxDeductiblePct = (decimal)txtDeductiblePercentage.NumberValueDecimal;
            }

            AGiftDetailRow giftDetails = (AGiftDetailRow)FPreviouslySelectedDetailRow;

            TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetails);

            txtTaxDeductAmount.NumberValueDecimal = FPreviouslySelectedDetailRow.TaxDeductibleAmount;
            txtNonDeductAmount.NumberValueDecimal = FPreviouslySelectedDetailRow.NonDeductibleAmount;
        }
Esempio n. 7
0
        /// <summary>
        /// Adds a duplicate Gift Detail (or reversed duplicate GiftDetail) to Gift.
        /// </summary>
        /// <param name="AMainDS"></param>
        /// <param name="AGift"></param>
        /// <param name="AOldGiftDetail"></param>
        /// <param name="AReversal">True for reverse or false for straight duplicate</param>
        /// <param name="ATransaction"></param>
        /// <param name="AFunction"></param>
        /// <param name="ANewPct"></param>
        /// <param name="AAutoCompleteComments"></param>
        /// <param name="AReversalCommentOne"></param>
        /// <param name="AReversalCommentTwo"></param>
        /// <param name="AReversalCommentThree"></param>
        /// <param name="AReversalCommentOneType"></param>
        /// <param name="AReversalCommentTwoType"></param>
        /// <param name="AReversalCommentThreeType"></param>
        /// <param name="AUpdateTaxDeductiblePctRecipients"></param>
        /// <param name="AGeneralFixedGiftDestination"></param>
        /// <param name="AFixedGiftDestination"></param>
        private static void AddDuplicateGiftDetailToGift(ref GiftBatchTDS AMainDS,
                                                         ref AGiftRow AGift,
                                                         AGiftDetailRow AOldGiftDetail,
                                                         bool AReversal,
                                                         TDBTransaction ATransaction,
                                                         GiftAdjustmentFunctionEnum AFunction,
                                                         Decimal ANewPct,
                                                         bool AAutoCompleteComments       = false,
                                                         string AReversalCommentOne       = "",
                                                         string AReversalCommentTwo       = "",
                                                         string AReversalCommentThree     = "",
                                                         string AReversalCommentOneType   = "",
                                                         string AReversalCommentTwoType   = "",
                                                         string AReversalCommentThreeType = "",
                                                         List <string[]> AUpdateTaxDeductiblePctRecipients = null,
                                                         bool AGeneralFixedGiftDestination   = false,
                                                         List <string> AFixedGiftDestination = null
                                                         )
        {
            bool TaxDeductiblePercentageEnabled =
                new TSystemDefaults(ATransaction.DataBaseObj).GetBooleanDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, false);

            AGiftDetailRow giftDetail = AMainDS.AGiftDetail.NewRowTyped(true);

            DataUtilities.CopyAllColumnValuesWithoutPK(AOldGiftDetail, giftDetail);

            giftDetail.DetailNumber = AGift.LastDetailNumber + 1;
            AGift.LastDetailNumber++;

            giftDetail.LedgerNumber          = AGift.LedgerNumber;
            giftDetail.BatchNumber           = AGift.BatchNumber;
            giftDetail.GiftTransactionNumber = AGift.GiftTransactionNumber;
            giftDetail.IchNumber             = 0;

            decimal signum = (AReversal) ? -1 : 1;

            giftDetail.GiftTransactionAmount = signum * AOldGiftDetail.GiftTransactionAmount;
            giftDetail.GiftAmount            = signum * AOldGiftDetail.GiftAmount;
            giftDetail.GiftAmountIntl        = signum * AOldGiftDetail.GiftAmountIntl;

            if (TaxDeductiblePercentageEnabled)
            {
                if (!AReversal && AFunction.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust))
                {
                    giftDetail.TaxDeductiblePct = ANewPct;
                    TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetail);
                }
                else if (!AReversal)
                {
                    if (AUpdateTaxDeductiblePctRecipients != null)
                    {
                        string[] Result = AUpdateTaxDeductiblePctRecipients.Find(x => x[0] == giftDetail.RecipientKey.ToString());

                        // true if a new percentage is available and the user wants to use it
                        if (Result != null)
                        {
                            giftDetail.TaxDeductiblePct = Convert.ToDecimal(Result[1]);
                            TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetail);
                        }
                    }
                }
                else
                {
                    giftDetail.TaxDeductibleAmount     = signum * AOldGiftDetail.TaxDeductibleAmount;
                    giftDetail.TaxDeductibleAmountBase = signum * AOldGiftDetail.TaxDeductibleAmountBase;
                    giftDetail.TaxDeductibleAmountIntl = signum * AOldGiftDetail.TaxDeductibleAmountIntl;
                    giftDetail.NonDeductibleAmount     = signum * AOldGiftDetail.NonDeductibleAmount;
                    giftDetail.NonDeductibleAmountBase = signum * AOldGiftDetail.NonDeductibleAmountBase;
                    giftDetail.NonDeductibleAmountIntl = signum * AOldGiftDetail.NonDeductibleAmountIntl;
                }
            }

            if (AAutoCompleteComments) // only used for tax deductible pct gift adjustments
            {
                AGiftRow OldGiftRow = (AGiftRow)AMainDS.AGift.Rows.Find(
                    new object[] { AOldGiftDetail.LedgerNumber, AOldGiftDetail.BatchNumber, AOldGiftDetail.GiftTransactionNumber });

                giftDetail.GiftCommentThree = Catalog.GetString("Original gift date: " + OldGiftRow.DateEntered.ToString("dd-MMM-yyyy"));
                giftDetail.CommentThreeType = "Both";
            }
            else // user defined
            {
                giftDetail.GiftCommentOne   = AReversalCommentOne;
                giftDetail.GiftCommentTwo   = AReversalCommentTwo;
                giftDetail.GiftCommentThree = AReversalCommentThree;
                giftDetail.CommentOneType   = AReversalCommentOneType;
                giftDetail.CommentTwoType   = AReversalCommentTwoType;
                giftDetail.CommentThreeType = AReversalCommentThreeType;
            }

            // If reversal: mark the new gift as a reversal
            if (AReversal)
            {
                giftDetail.ModifiedDetail = true;

                //Identify the reversal source
                giftDetail.ModifiedDetailKey = "|" + AOldGiftDetail.BatchNumber.ToString() + "|" +
                                               AOldGiftDetail.GiftTransactionNumber.ToString() + "|" +
                                               AOldGiftDetail.DetailNumber.ToString();
            }
            else
            {
                giftDetail.ModifiedDetail = false;

                // Make sure the motivation detail is still active. If not then we need a new one.
                AMotivationDetailTable MotivationDetailTable = AMotivationDetailAccess.LoadViaAMotivationGroup(
                    giftDetail.LedgerNumber, giftDetail.MotivationGroupCode, ATransaction);
                DataRow CurrentMotivationDetail = MotivationDetailTable.Rows.Find(
                    new object[] { giftDetail.LedgerNumber, giftDetail.MotivationGroupCode, giftDetail.MotivationDetailCode });

                // Motivation detail has been made inactive (or doesn't exist) then use default
                if (!((MotivationDetailTable != null) && (MotivationDetailTable.Rows.Count > 0) && (CurrentMotivationDetail != null)) ||
                    !Convert.ToBoolean(CurrentMotivationDetail[AMotivationDetailTable.GetMotivationStatusDBName()]))
                {
                    bool ActiveRowFound = false;

                    // search for first alternative active detail that is part of the same group
                    foreach (AMotivationDetailRow Row in MotivationDetailTable.Rows)
                    {
                        if ((Row.MotivationDetailCode != giftDetail.MotivationDetailCode) && Row.MotivationStatus)
                        {
                            ActiveRowFound = true;
                            giftDetail.MotivationGroupCode  = Row.MotivationGroupCode;
                            giftDetail.MotivationDetailCode = Row.MotivationDetailCode;
                            break;
                        }
                    }

                    // if none found then use default group and detail
                    if (!ActiveRowFound)
                    {
                        giftDetail.MotivationGroupCode  = MFinanceConstants.MOTIVATION_GROUP_GIFT;
                        giftDetail.MotivationDetailCode = MFinanceConstants.GROUP_DETAIL_SUPPORT;
                    }
                }

                // if the gift destination should be fixed
                if ((AFunction.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust) && AGeneralFixedGiftDestination) ||
                    ((AFixedGiftDestination != null) && (AFixedGiftDestination.Exists(x => x == giftDetail.RecipientKey.ToString()))))
                {
                    giftDetail.FixedGiftDestination = true;
                }
                else
                {
                    giftDetail.FixedGiftDestination = false;
                }
            }

            AMainDS.AGiftDetail.Rows.Add(giftDetail);
        }
        /// <summary>
        /// auto populate new gift recipient info using the donor's last gift
        /// </summary>
        /// <param name="ADonorKey"></param>
        /// <param name="APartnerShortName"></param>
        /// <param name="AGiftTransactionNumber"></param>
        private void AutoPopulateGiftDetail(Int64 ADonorKey, String APartnerShortName, Int32 AGiftTransactionNumber)
        {
            FAutoPopulatingGiftInProcess = true;

            bool IsSplitGift = false;

            DateTime LatestUnpostedGiftDateEntered = new DateTime(1900, 1, 1);

            try
            {
                //Check for Donor in loaded gift batches
                // and record most recent date entered
                AGiftTable DonorRecentGiftsTable             = new AGiftTable();
                GiftBatchTDSAGiftDetailTable GiftDetailTable = new GiftBatchTDSAGiftDetailTable();

                AGiftRow MostRecentLoadedGiftForDonorRow = null;

                DataView giftDV = new DataView(FMainDS.AGift);

                giftDV.RowStateFilter = DataViewRowState.CurrentRows;

                giftDV.RowFilter = string.Format("{0}={1} And Not ({2}={3} And {4}={5})",
                                                 AGiftTable.GetDonorKeyDBName(),
                                                 ADonorKey,
                                                 AGiftTable.GetBatchNumberDBName(),
                                                 FBatchNumber,
                                                 AGiftTable.GetGiftTransactionNumberDBName(),
                                                 AGiftTransactionNumber);

                giftDV.Sort = String.Format("{0} DESC, {1} DESC",
                                            AGiftTable.GetDateEnteredDBName(),
                                            AGiftTable.GetGiftTransactionNumberDBName());

                if (giftDV.Count > 0)
                {
                    //Take first row = most recent date entered value
                    MostRecentLoadedGiftForDonorRow = (AGiftRow)giftDV[0].Row;
                    LatestUnpostedGiftDateEntered   = MostRecentLoadedGiftForDonorRow.DateEntered;
                    DonorRecentGiftsTable.Rows.Add((object[])MostRecentLoadedGiftForDonorRow.ItemArray.Clone());
                }

                //Check for even more recent saved gifts on server (i.e. not necessarily loaded)
                GiftDetailTable = TRemote.MFinance.Gift.WebConnectors.LoadDonorLastPostedGift(ADonorKey, FLedgerNumber, LatestUnpostedGiftDateEntered);

                if (((GiftDetailTable != null) && (GiftDetailTable.Count > 0)))
                {
                    //UnLoaded/Saved gift from donor is more recent
                    IsSplitGift = (GiftDetailTable.Count > 1);
                }
                else if (MostRecentLoadedGiftForDonorRow != null)
                {
                    //Loaded/unsaved gift from donor is more recent
                    DataView giftDetailDV = new DataView(FMainDS.AGiftDetail);

                    giftDetailDV.RowStateFilter = DataViewRowState.CurrentRows;

                    giftDetailDV.RowFilter = string.Format("{0}={1} And {2}={3}",
                                                           AGiftDetailTable.GetBatchNumberDBName(),
                                                           MostRecentLoadedGiftForDonorRow.BatchNumber,
                                                           AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                           MostRecentLoadedGiftForDonorRow.GiftTransactionNumber);

                    foreach (DataRowView drv in giftDetailDV)
                    {
                        GiftBatchTDSAGiftDetailRow gDR = (GiftBatchTDSAGiftDetailRow)drv.Row;
                        GiftDetailTable.Rows.Add((object[])gDR.ItemArray.Clone());
                    }

                    IsSplitGift = (GiftDetailTable.Count > 1);
                }
                else
                {
                    //nothing to autocopy
                    return;
                }

                // if the last gift was a split gift (multiple details) then ask the user if they would like this new gift to also be split
                if (IsSplitGift)
                {
                    GiftDetailTable.DefaultView.Sort = GiftBatchTDSAGiftDetailTable.GetDetailNumberDBName() + " ASC";

                    string Message = string.Format(Catalog.GetString(
                                                       "The last gift from this donor was a split gift.{0}{0}Here are the details:{0}"), "\n");
                    int DetailNumber = 1;

                    foreach (DataRowView dvr in GiftDetailTable.DefaultView)
                    {
                        GiftBatchTDSAGiftDetailRow Row = (GiftBatchTDSAGiftDetailRow)dvr.Row;

                        Message += DetailNumber + ")  ";

                        if (Row.RecipientKey > 0)
                        {
                            Message +=
                                string.Format(Catalog.GetString("Recipient: {0} ({1});  Motivation Group: {2};  Motivation Detail: {3};  Amount: {4}"),
                                              Row.RecipientDescription, Row.RecipientKey, Row.MotivationGroupCode, Row.MotivationDetailCode,
                                              StringHelper.FormatUsingCurrencyCode(Row.GiftTransactionAmount, GetBatchRow().CurrencyCode) +
                                              " " + FBatchRow.CurrencyCode) +
                                "\n";
                        }

                        DetailNumber++;
                    }

                    Message += "\n" + Catalog.GetString("Do you want to create the same split gift again?");

                    if (!(MessageBox.Show(Message, Catalog.GetString(
                                              "Create Split Gift"), MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                          == DialogResult.Yes))
                    {
                        if (cmbDetailMethodOfGivingCode.CanFocus)
                        {
                            cmbDetailMethodOfGivingCode.Focus();
                        }
                        else if (txtDetailReference.CanFocus)
                        {
                            txtDetailReference.Focus();
                        }

                        return;
                    }
                }

                this.Cursor = Cursors.WaitCursor;

                GiftBatchTDSAGiftDetailRow giftDetailRow = (GiftBatchTDSAGiftDetailRow)GiftDetailTable.DefaultView[0].Row;

                // Handle first row, which is FPreviouslySelectedDetailRow
                txtDetailDonorKey.Text     = String.Format("{0:0000000000}", ADonorKey);
                txtDetailRecipientKey.Text = String.Format("{0:0000000000}", giftDetailRow.RecipientKey);
                cmbDetailMotivationGroupCode.SetSelectedString(giftDetailRow.MotivationGroupCode);
                txtDetailMotivationDetailCode.Text = giftDetailRow.MotivationDetailCode;
                cmbMotivationDetailCode.SetSelectedString(giftDetailRow.MotivationDetailCode);
                chkDetailConfidentialGiftFlag.Checked = giftDetailRow.ConfidentialGiftFlag;
                // Change #5481
                chkDetailChargeFlag.Checked = true;
                cmbDetailMethodOfPaymentCode.SetSelectedString(FBatchMethodOfPayment, -1);
                cmbDetailMethodOfGivingCode.SetSelectedString(giftDetailRow.MethodOfGivingCode, -1);

                //Handle mailing code
                if (FSETAutoCopyIncludeMailingCodeFlag)
                {
                    cmbDetailMailingCode.SetSelectedString(giftDetailRow.MailingCode, -1);
                }
                else
                {
                    cmbDetailMailingCode.SelectedIndex = -1;
                }

                //Copy the comments and comment types if required
                if (FSETAutoCopyIncludeCommentsFlag)
                {
                    txtDetailGiftCommentOne.Text = giftDetailRow.GiftCommentOne;
                    cmbDetailCommentOneType.SetSelectedString(giftDetailRow.CommentOneType);
                    txtDetailGiftCommentTwo.Text = giftDetailRow.GiftCommentTwo;
                    cmbDetailCommentTwoType.SetSelectedString(giftDetailRow.CommentTwoType);
                    txtDetailGiftCommentThree.Text = giftDetailRow.GiftCommentThree;
                    cmbDetailCommentThreeType.SetSelectedString(giftDetailRow.CommentThreeType);
                }

                //Handle tax fields on current row
                if (FSETUseTaxDeductiblePercentageFlag)
                {
                    bool taxDeductible = (giftDetailRow.IsTaxDeductibleNull() ? true : giftDetailRow.TaxDeductible);
                    giftDetailRow.TaxDeductible = taxDeductible;

                    try
                    {
                        FPetraUtilsObject.SuppressChangeDetection = true;
                        chkDetailTaxDeductible.Checked            = taxDeductible;
                        EnableTaxDeductibilityPct(taxDeductible);
                    }
                    finally
                    {
                        FPetraUtilsObject.SuppressChangeDetection = false;
                    }

                    if (!IsSplitGift)
                    {
                        //Most commonly not a split gift (?)
                        if (!taxDeductible)
                        {
                            txtDeductiblePercentage.NumberValueDecimal = 0.0m;
                        }

                        txtTaxDeductAmount.NumberValueDecimal = 0.0m;
                        txtNonDeductAmount.NumberValueDecimal = 0.0m;
                    }
                    else
                    {
                        if (taxDeductible)
                        {
                            //In case the tax percentage has changed or null values in amount fields
                            ReconcileTaxDeductibleAmounts(giftDetailRow);
                        }
                        else
                        {
                            //Changing this will update the unbound amount textboxes
                            txtDeductiblePercentage.NumberValueDecimal = 0.0m;
                        }
                    }
                }

                //Process values that are not bound to a control
                giftDetailRow.ReceiptPrinted = false;
                giftDetailRow.ReceiptNumber  = 0;

                //Now process other gift details if they exist
                if (IsSplitGift)
                {
                    //Only copy amount to first row if copying split gifts
                    txtDetailGiftTransactionAmount.NumberValueDecimal = giftDetailRow.GiftTransactionAmount;

                    // clear previous validation errors.
                    // otherwise we get an error if the user has changed the control immediately after changing the donor key.
                    FPetraUtilsObject.VerificationResultCollection.Clear();

                    bool SelectEndRow = (FBatchRow.LastGiftNumber == FPreviouslySelectedDetailRow.GiftTransactionNumber);

                    //Just retain other details to add
                    giftDetailRow.Delete();
                    GiftDetailTable.AcceptChanges();

                    foreach (DataRowView drv in GiftDetailTable.DefaultView)
                    {
                        GiftBatchTDSAGiftDetailRow detailRow = (GiftBatchTDSAGiftDetailRow)drv.Row;

                        //______________________
                        //Update basic field values
                        detailRow.LedgerNumber          = FLedgerNumber;
                        detailRow.BatchNumber           = FBatchNumber;
                        detailRow.GiftTransactionNumber = AGiftTransactionNumber;
                        detailRow.DetailNumber          = ++FGift.LastDetailNumber;
                        detailRow.DonorName             = APartnerShortName;
                        detailRow.DonorClass            = FPreviouslySelectedDetailRow.DonorClass;
                        detailRow.DateEntered           = FGift.DateEntered;
                        detailRow.MethodOfPaymentCode   = FPreviouslySelectedDetailRow.MethodOfPaymentCode;
                        detailRow.ReceiptPrinted        = false;
                        detailRow.ReceiptNumber         = 0;
                        // Change #5481
                        detailRow.ChargeFlag = true;

                        if (!FSETAutoCopyIncludeMailingCodeFlag)
                        {
                            detailRow.MailingCode = string.Empty;
                        }

                        //______________________
                        //process recipient details to get most recent data
                        Int64         partnerKey       = detailRow.RecipientKey;
                        string        partnerShortName = string.Empty;
                        TPartnerClass partnerClass;
                        bool          recipientIsValid = true;

                        if (TServerLookup.TMPartner.GetPartnerShortName(partnerKey, out partnerShortName, out partnerClass))
                        {
                            detailRow.RecipientDescription = partnerShortName;
                            detailRow.RecipientClass       = partnerClass.ToString();

                            if (partnerClass == TPartnerClass.FAMILY)
                            {
                                detailRow.RecipientLedgerNumber = TRemote.MFinance.Gift.WebConnectors.GetRecipientFundNumber(partnerKey,
                                                                                                                             FGift.DateEntered);
                                detailRow.RecipientField       = detailRow.RecipientLedgerNumber;
                                detailRow.RecipientKeyMinistry = string.Empty;
                            }
                            else
                            {
                                //Class - UNIT
                                Int64  field;
                                string keyMinName;

                                recipientIsValid = TFinanceControls.GetRecipientKeyMinData(partnerKey, out field, out keyMinName);

                                detailRow.RecipientLedgerNumber = field;
                                detailRow.RecipientField        = field;
                                detailRow.RecipientKeyMinistry  = keyMinName;

                                if (!recipientIsValid)
                                {
                                    string msg =
                                        String.Format(Catalog.GetString(
                                                          "Gift: {0}, Detail: {1} has a recipient: '{2}-{3}' that is an inactive Key Ministry!"),
                                                      AGiftTransactionNumber,
                                                      detailRow.DetailNumber,
                                                      partnerKey,
                                                      keyMinName);
                                    MessageBox.Show(msg, Catalog.GetString(
                                                        "Copying Previous Split Gift"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }
                            }
                        }
                        else
                        {
                            recipientIsValid = false;
                            string msg = String.Format(Catalog.GetString("Gift: {0}, Detail: {1} has an invalid Recipient key: '{2}'!"),
                                                       AGiftTransactionNumber,
                                                       detailRow.DetailNumber,
                                                       partnerKey);
                            MessageBox.Show(msg, Catalog.GetString("Copying Previous Split Gift"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        //______________________
                        //Process motivation
                        if (string.IsNullOrEmpty(detailRow.MotivationGroupCode))
                        {
                            detailRow.MotivationGroupCode = string.Empty;
                            string msg = String.Format(Catalog.GetString("Gift: {0}, Detail: {1} has no Motivation Group!"),
                                                       AGiftTransactionNumber,
                                                       detailRow.DetailNumber);
                            MessageBox.Show(msg, Catalog.GetString("Copying Previous Split Gift"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (string.IsNullOrEmpty(detailRow.MotivationDetailCode))
                        {
                            detailRow.MotivationDetailCode = string.Empty;
                            string msg = String.Format(Catalog.GetString("Gift: {0}, Detail: {1} has no Motivation Detail!"),
                                                       AGiftTransactionNumber,
                                                       detailRow.DetailNumber);
                            MessageBox.Show(msg, Catalog.GetString("Copying Previous Split Gift"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            AMotivationDetailRow motivationDetailRow = null;
                            string motivationGroup  = detailRow.MotivationGroupCode;
                            string motivationDetail = detailRow.MotivationDetailCode;

                            motivationDetailRow = (AMotivationDetailRow)FMainDS.AMotivationDetail.Rows.Find(
                                new object[] { FLedgerNumber, motivationGroup, motivationDetail });

                            if (motivationDetailRow != null)
                            {
                                if (partnerKey > 0)
                                {
                                    bool partnerIsMissingLink = false;

                                    detailRow.CostCentreCode = TRemote.MFinance.Gift.WebConnectors.RetrieveCostCentreCodeForRecipient(FLedgerNumber,
                                                                                                                                      partnerKey,
                                                                                                                                      detailRow.RecipientLedgerNumber,
                                                                                                                                      detailRow.DateEntered,
                                                                                                                                      motivationGroup,
                                                                                                                                      motivationDetail,
                                                                                                                                      out partnerIsMissingLink);
                                }
                                else
                                {
                                    if (motivationGroup != MFinanceConstants.MOTIVATION_GROUP_GIFT)
                                    {
                                        detailRow.RecipientDescription = motivationGroup;
                                    }
                                    else
                                    {
                                        detailRow.RecipientDescription = string.Empty;
                                    }

                                    detailRow.CostCentreCode = motivationDetailRow.CostCentreCode;
                                }

                                detailRow.AccountCode = motivationDetailRow.AccountCode;

                                if (FSETUseTaxDeductiblePercentageFlag && string.IsNullOrEmpty(motivationDetailRow.TaxDeductibleAccountCode))
                                {
                                    detailRow.TaxDeductibleAccountCode = string.Empty;

                                    string msg = String.Format(Catalog.GetString(
                                                                   "Gift: {0}, Detail: {1} has  Motivation Detail: {2} which has no Tax Deductible Account!" +
                                                                   "This can be added in Finance / Setup / Motivation Details.{3}{3}" +
                                                                   "Unless this is changed it will be impossible to assign a Tax Deductible Percentage to this gift."),
                                                               AGiftTransactionNumber,
                                                               detailRow.DetailNumber,
                                                               motivationDetail,
                                                               Environment.NewLine);
                                    MessageBox.Show(msg, Catalog.GetString(
                                                        "Copying Previous Split Gift"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }
                                else
                                {
                                    detailRow.TaxDeductibleAccountCode = motivationDetailRow.TaxDeductibleAccountCode;
                                }
                            }
                            else
                            {
                                string msg =
                                    String.Format(Catalog.GetString(
                                                      "Gift: {0}, Detail: {1} has Motivation Group and Detail codes ('{2} : {3}') not found in the database!"),
                                                  AGiftTransactionNumber,
                                                  detailRow.DetailNumber,
                                                  motivationGroup,
                                                  motivationDetail);
                                MessageBox.Show(msg, Catalog.GetString("Copying Previous Split Gift"), MessageBoxButtons.OK, MessageBoxIcon.Warning);

                                detailRow.TaxDeductible = false;
                            }
                        }

                        //______________________
                        //Handle tax fields
                        detailRow.TaxDeductiblePct = RetrieveTaxDeductiblePct((recipientIsValid ? detailRow.RecipientKey : 0),
                                                                              detailRow.TaxDeductible);

                        AGiftDetailRow giftDetails = (AGiftDetailRow)detailRow;
                        TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetails);

                        //______________________
                        //Process comments
                        if (!FSETAutoCopyIncludeCommentsFlag)
                        {
                            detailRow.SetCommentOneTypeNull();
                            detailRow.SetCommentTwoTypeNull();
                            detailRow.SetCommentThreeTypeNull();
                            detailRow.SetGiftCommentOneNull();
                            detailRow.SetGiftCommentTwoNull();
                            detailRow.SetGiftCommentThreeNull();
                        }

                        detailRow.AcceptChanges();
                        detailRow.SetAdded();
                    }

                    //Add in the new records (latter two arguments put in to parallel recurring form)
                    FMainDS.AGiftDetail.Merge(GiftDetailTable, false, MissingSchemaAction.Ignore);

                    int indexOfLatestRow = FMainDS.AGiftDetail.Rows.Count - 1;

                    //Select last row added
                    if (SelectEndRow)
                    {
                        grdDetails.SelectRowInGrid(grdDetails.Rows.Count - 1);
                    }
                    else if (!SelectDetailRowByDataTableIndex(indexOfLatestRow))
                    {
                        if (!FFilterAndFindObject.IsActiveFilterEqualToBase)
                        {
                            MessageBox.Show(
                                MCommonResourcestrings.StrNewRecordIsFiltered,
                                MCommonResourcestrings.StrAddNewRecordTitle,
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                            FFilterAndFindObject.FilterPanelControls.ClearAllDiscretionaryFilters();

                            if (FFilterAndFindObject.FilterFindPanel.ShowApplyFilterButton != TUcoFilterAndFind.FilterContext.None)
                            {
                                FFilterAndFindObject.ApplyFilter();
                            }

                            SelectDetailRowByDataTableIndex(indexOfLatestRow);
                        }
                    }

                    ClearKeyMinistries();
                    cmbMotivationDetailCode.Clear();
                    mniRecipientHistory.Enabled = false;
                    btnDeleteAll.Enabled        = btnDelete.Enabled;
                    UpdateRecordNumberDisplay();
                    FLastDonor = -1;
                }
                else
                {
                    txtDetailDonorKey.FocusTextBoxPartAfterFindScreenCloses = false;
                    txtDetailGiftTransactionAmount.Focus();
                }

                FPetraUtilsObject.SetChangedFlag();
            }
            finally
            {
                this.Cursor = Cursors.Default;
                FAutoPopulatingGiftInProcess = false;
            }
        }