private AMotivationDetailRow GetCurrentMotivationDetailRow()
        {
            AMotivationDetailRow MotivationDetailRow = (AMotivationDetailRow)FMainDS.AMotivationDetail.Rows.Find(
                new object[] { FLedgerNumber, FMotivationGroup, FMotivationDetail });

            return(MotivationDetailRow);
        }
Пример #2
0
        private void LoadLists()
        {
            Int32 YPosDo   = lstDoExport.TopIndex;
            Int32 YPosDont = lstDontExport.TopIndex;

            lstDoExport.Items.Clear();
            lstDontExport.Items.Clear();
            lstDoExport.BeginUpdate();
            lstDontExport.BeginUpdate();

            for (Int32 RowIdx = 0; RowIdx < FMainDS.AMotivationDetail.Rows.Count; RowIdx++)
            {
                AMotivationDetailRow Row      = FMainDS.AMotivationDetail[RowIdx];
                RowItemDescr         RowDescr = new RowItemDescr(RowIdx, String.Format("[{0}] {1}", Row.MotivationDetailCode, Row.MotivationDetailDesc));

                if (Row.ExportToIntranet)
                {
                    lstDoExport.Items.Add(RowDescr);
                }
                else
                {
                    lstDontExport.Items.Add(RowDescr);
                }
            }

            lstDoExport.TopIndex   = YPosDo;
            lstDontExport.TopIndex = YPosDont;
            lstDoExport.EndUpdate();
            lstDontExport.EndUpdate();
            EnableAddRemoveButtons(null, null);
        }
Пример #3
0
        private void NewRowManual(ref AMotivationDetailRow ARow)
        {
            ARow.LedgerNumber = FLedgerNumber;

            if ((FMainDS.AMotivationGroup == null) || (FMainDS.AMotivationGroup.Rows.Count == 0))
            {
                MessageBox.Show(Catalog.GetString("You must define at least one Motivation Group."), Catalog.GetString("New Motivation Detail"),
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            ARow.MotivationGroupCode = FMainDS.AMotivationGroup[0].MotivationGroupCode;

            string newName        = Catalog.GetString("NEWDETAIL");
            Int32  countNewDetail = 0;

            if (FMainDS.AMotivationDetail.Rows.Find(new object[] { FLedgerNumber, ARow.MotivationGroupCode, newName }) != null)
            {
                while (FMainDS.AMotivationDetail.Rows.Find(new object[] { FLedgerNumber, ARow.MotivationGroupCode, newName +
                                                                          countNewDetail.ToString() }) != null)
                {
                    countNewDetail++;
                }

                newName += countNewDetail.ToString();
            }

            ARow.MotivationDetailCode = newName;
            ARow.MotivationDetailDesc = Catalog.GetString("PLEASE ENTER DESCRIPTION");
        }
        private void DisplayMotivationDetailAccountCode(AMotivationDetailRow AMotivationDetail = null)
        {
            string AcctCode = string.Empty;
            string TaxDeductibleAcctCode = string.Empty;

            if (FMotivationDetail.Length > 0)
            {
                if (AMotivationDetail == null)
                {
                    AMotivationDetail = GetCurrentMotivationDetailRow();
                }

                if (AMotivationDetail != null)
                {
                    AcctCode = AMotivationDetail.AccountCode;

                    if (FSETUseTaxDeductiblePercentageFlag)
                    {
                        TaxDeductibleAcctCode = AMotivationDetail.TaxDeductibleAccountCode;
                    }
                }
            }

            if (txtDetailAccountCode.Text != AcctCode)
            {
                txtDetailAccountCode.Text = AcctCode;
            }

            if (FSETUseTaxDeductiblePercentageFlag && (txtDeductibleAccount.Text != TaxDeductibleAcctCode))
            {
                txtDeductibleAccount.Text = TaxDeductibleAcctCode;
            }
        }
Пример #5
0
        private void ShowDetailsManual(AMotivationDetailRow ARow)
        {
            string FeesPayable    = string.Empty;
            string FeesReceivable = string.Empty;

            if (ARow != null)
            {
                FMainDS.AMotivationDetailFee.DefaultView.RowFilter =
                    String.Format("{0}={1} and {2}='{3}' and {4}='{5}'",
                                  AMotivationDetailFeeTable.GetLedgerNumberDBName(),
                                  ARow.LedgerNumber,
                                  AMotivationDetailFeeTable.GetMotivationGroupCodeDBName(),
                                  ARow.MotivationGroupCode,
                                  AMotivationDetailFeeTable.GetMotivationDetailCodeDBName(),
                                  ARow.MotivationDetailCode);

                foreach (DataRowView rv in FMainDS.AMotivationDetailFee.DefaultView)
                {
                    AMotivationDetailFeeRow detailFeeRow = (AMotivationDetailFeeRow)rv.Row;

                    if (StringHelper.StrSplit(clbDetailFeesPayable.GetAllStringList(), ",").Contains(detailFeeRow.FeeCode))
                    {
                        FeesPayable = StringHelper.AddCSV(FeesPayable, detailFeeRow.FeeCode);
                    }
                    else
                    {
                        FeesReceivable = StringHelper.AddCSV(FeesReceivable, detailFeeRow.FeeCode);
                    }
                }
            }

            // set the ORDER column to true if row is checked
            clbDetailFeesPayable.CheckedColumn    = "ORDER";
            clbDetailFeesReceivable.CheckedColumn = "ORDER";
            clbDetailFeesPayable.SetCheckedStringList(FeesPayable);
            clbDetailFeesReceivable.SetCheckedStringList(FeesReceivable);

            // set the CHECKED column to true if row is checked
            clbDetailFeesPayable.CheckedColumn    = "CHECKED";
            clbDetailFeesReceivable.CheckedColumn = "CHECKED";
            clbDetailFeesPayable.SetCheckedStringList(FeesPayable);
            clbDetailFeesReceivable.SetCheckedStringList(FeesReceivable);

            if (FTaxDeductiblePercentageEnabled)
            {
                if (ARow.IsTaxDeductibleAccountNull())
                {
                    cmbDeductibleAccountCode.SelectedIndex = 0;
                }
                else
                {
                    cmbDeductibleAccountCode.SetSelectedString(ARow.TaxDeductibleAccount);
                }
            }
        }
Пример #6
0
 private bool PreDeleteManual(AMotivationDetailRow ARowToDelete, ref string ADeletionQuestion)
 {
     ADeletionQuestion  = Catalog.GetString("Are you sure you want to delete the current row?");
     ADeletionQuestion += String.Format("{0}{0}({1} {2}, {3} {4})",
                                        Environment.NewLine,
                                        lblDetailMotivationGroupCode.Text,
                                        cmbDetailMotivationGroupCode.GetSelectedString(),
                                        lblDetailMotivationDetailCode.Text,
                                        txtDetailMotivationDetailCode.Text);
     return(true);
 }
Пример #7
0
        private void GetDetailDataFromControlsManual(AMotivationDetailRow ARow)
        {
            StringCollection TickedFees = StringHelper.StrSplit(
                StringHelper.ConcatCSV(clbDetailFeesPayable.GetCheckedStringList(), clbDetailFeesReceivable.GetCheckedStringList()),
                ",");

            FMainDS.AMotivationDetailFee.DefaultView.RowFilter =
                String.Format("{0}={1} and {2}='{3}' and {4}='{5}'",
                              AMotivationDetailFeeTable.GetLedgerNumberDBName(),
                              ARow.LedgerNumber,
                              AMotivationDetailFeeTable.GetMotivationGroupCodeDBName(),
                              ARow.MotivationGroupCode,
                              AMotivationDetailFeeTable.GetMotivationDetailCodeDBName(),
                              ARow.MotivationDetailCode);

            StringCollection ExistingFees = new StringCollection();

            foreach (DataRowView rv in FMainDS.AMotivationDetailFee.DefaultView)
            {
                AMotivationDetailFeeRow detailFeeRow = (AMotivationDetailFeeRow)rv.Row;

                if (!TickedFees.Contains(detailFeeRow.FeeCode))
                {
                    // delete existing fees that have been unticked
                    detailFeeRow.Delete();
                }
                else
                {
                    ExistingFees.Add(detailFeeRow.FeeCode);
                }
            }

            // add new fees
            foreach (string fee in TickedFees)
            {
                if (!ExistingFees.Contains(fee))
                {
                    AMotivationDetailFeeRow NewRow = FMainDS.AMotivationDetailFee.NewRowTyped();
                    NewRow.LedgerNumber         = ARow.LedgerNumber;
                    NewRow.MotivationGroupCode  = ARow.MotivationGroupCode;
                    NewRow.MotivationDetailCode = ARow.MotivationDetailCode;
                    NewRow.FeeCode = fee;
                    FMainDS.AMotivationDetailFee.Rows.Add(NewRow);
                }
            }

            if (FTaxDeductiblePercentageEnabled)
            {
                ARow.TaxDeductibleAccount = cmbDeductibleAccountCode.GetSelectedString();
            }
        }
Пример #8
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)
            {
                AMotivationDetailRow MotivationDetailRow = AMotivationDetailAccess.LoadByPrimaryKey(
                    AGiftDetail.LedgerNumber, AGiftDetail.MotivationGroupCode, AGiftDetail.MotivationDetailCode, ATransaction)[0];

                // if the gift's motivation detail has a tax-deductible account
                if (!string.IsNullOrEmpty(MotivationDetailRow.TaxDeductibleAccount))
                {
                    // 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;
            }
        }
Пример #9
0
        private void ValidateDataDetailsManual(AMotivationDetailRow ARow)
        {
            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TVerificationResult     VerificationResult;
            Boolean KeyMinistryActive;

            // Partner Key must be for a Key Ministry and Key Ministry must not be deactivated
            if (Convert.ToInt64(txtDetailRecipientKey.Text) != 0)
            {
                ValidationColumn = FMainDS.AMotivationDetail[0].Table.Columns[AMotivationDetailTable.ColumnRecipientKeyId];

                if (FPetraUtilsObject.ValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    if (TRemote.MFinance.Gift.WebConnectors.KeyMinistryExists(Convert.ToInt64(txtDetailRecipientKey.Text), out KeyMinistryActive))
                    {
                        if (!KeyMinistryActive)
                        {
                            // Key Ministry is deactivated and therefore can't be used here
                            VerificationResult = new TScreenVerificationResult(new TVerificationResult(this,
                                                                                                       ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_KEY_MINISTRY_DEACTIVATED)),
                                                                               ValidationColumn, ValidationControlsData.ValidationControl);

                            // Handle addition to/removal from TVerificationResultCollection.
                            VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn);
                        }
                    }
                    else
                    {
                        // Partner Key does not refer to Key Ministry
                        VerificationResult = new TScreenVerificationResult(new TVerificationResult(this,
                                                                                                   ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_NOT_A_KEY_MINISTRY)),
                                                                           ValidationColumn, ValidationControlsData.ValidationControl);

                        // Handle addition to/removal from TVerificationResultCollection.
                        VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn);
                    }
                }
            }

            TSharedFinanceValidation_Gift.ValidateGiftMotivationSetupManual(this,
                                                                            ARow, FTaxDeductiblePercentageEnabled,
                                                                            ref VerificationResultCollection,
                                                                            FPetraUtilsObject.ValidationControlsDict);
        }
        private void DisplayMotivationDetailCostCentreCode()
        {
            string CostCentreCode = string.Empty;

            if (FMotivationDetail.Length > 0)
            {
                AMotivationDetailRow motivationDetail = GetCurrentMotivationDetailRow();

                if (motivationDetail != null)
                {
                    CostCentreCode = motivationDetail.CostCentreCode.ToString();
                }
            }

            if (txtDetailCostCentreCode.Text != CostCentreCode)
            {
                txtDetailCostCentreCode.Text = CostCentreCode;
            }
        }
        private void GetDetailDataFromControlsManual(AMotivationDetailRow ARow)
        {
            StringCollection TickedFees = StringHelper.StrSplit(
                StringHelper.ConcatCSV(clbDetailFeesPayable.GetCheckedStringList(), clbDetailFeesReceivable.GetCheckedStringList()),
                ",");

            FMainDS.AMotivationDetailFee.DefaultView.RowFilter =
                String.Format("{0}={1} and {2}='{3}' and {4}='{5}'",
                    AMotivationDetailFeeTable.GetLedgerNumberDBName(),
                    ARow.LedgerNumber,
                    AMotivationDetailFeeTable.GetMotivationGroupCodeDBName(),
                    ARow.MotivationGroupCode,
                    AMotivationDetailFeeTable.GetMotivationDetailCodeDBName(),
                    ARow.MotivationDetailCode);

            StringCollection ExistingFees = new StringCollection();

            foreach (DataRowView rv in FMainDS.AMotivationDetailFee.DefaultView)
            {
                AMotivationDetailFeeRow detailFeeRow = (AMotivationDetailFeeRow)rv.Row;

                if (!TickedFees.Contains(detailFeeRow.FeeCode))
                {
                    // delete existing fees that have been unticked
                    detailFeeRow.Delete();
                }
                else
                {
                    ExistingFees.Add(detailFeeRow.FeeCode);
                }
            }

            // add new fees
            foreach (string fee in TickedFees)
            {
                if (!ExistingFees.Contains(fee))
                {
                    AMotivationDetailFeeRow NewRow = FMainDS.AMotivationDetailFee.NewRowTyped();
                    NewRow.LedgerNumber = ARow.LedgerNumber;
                    NewRow.MotivationGroupCode = ARow.MotivationGroupCode;
                    NewRow.MotivationDetailCode = ARow.MotivationDetailCode;
                    NewRow.FeeCode = fee;
                    FMainDS.AMotivationDetailFee.Rows.Add(NewRow);
                }
            }

            if (FTaxDeductiblePercentageEnabled)
            {
                ARow.TaxDeductibleAccountCode = cmbDeductibleAccountCode.GetSelectedString();
            }
        }
 /// <summary>
 /// To be called on the display of a new record
 /// </summary>
 private void RetrieveMotivationDetailAccountCode(AMotivationDetailRow AMotivationDetail)
 {
     if (AMotivationDetail != null)
     {
         if (txtDetailAccountCode.Text != AMotivationDetail.AccountCode)
         {
             txtDetailAccountCode.Text = AMotivationDetail.AccountCode;
         }
     }
 }
        private void ProcessMotivationDetailRow(out bool ADoTaxUpdate)
        {
            Int64 MotivationRecipientKey = 0;

            ADoTaxUpdate = false;

            if (FMotivationDetail.Length > 0)
            {
                AMotivationDetailRow motivationDetail = GetCurrentMotivationDetailRow();

                if (motivationDetail != null)
                {
                    DisplayMotivationDetailAccountCode(motivationDetail);

                    MotivationRecipientKey = motivationDetail.RecipientKey;

                    // if motivation detail autopopulation is set to true
                    if (motivationDetail.Autopopdesc)
                    {
                        FAutoPopComment = motivationDetail.MotivationDetailDesc;
                    }
                    else
                    {
                        FAutoPopComment = null;
                    }

                    // set tax deductible checkbox if motivation detail has been changed by the user (i.e. not a row change)
                    if (!FInBeginEditModeFlag && (!FPetraUtilsObject.SuppressChangeDetection || FRecipientKeyChangedInProcess))
                    {
                        if (chkDetailTaxDeductible.Checked != motivationDetail.TaxDeductible)
                        {
                            chkDetailTaxDeductible.Checked = motivationDetail.TaxDeductible;
                        }
                    }

                    if (FSETUseTaxDeductiblePercentageFlag)
                    {
                        if (string.IsNullOrEmpty(motivationDetail.TaxDeductibleAccountCode))
                        {
                            MessageBox.Show(Catalog.GetString("This Motivation Detail does not have an associated Tax Deductible Account. " +
                                                              "This can be added in Finance / Setup / Motivation Details.\n\n" +
                                                              "Unless this is changed it will be impossible to assign a Tax Deductible Percentage to this gift."),
                                            Catalog.GetString("Incomplete Motivation Detail"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        ADoTaxUpdate = true;
                    }
                }
                else
                {
                    chkDetailTaxDeductible.Checked = false;
                }
            }

            if (!FNewGiftInProcess && !FAutoPopulatingGiftInProcess && (MotivationRecipientKey > 0))
            {
                FMotivationDetailHasChangedFlag = true;
                PopulateKeyMinistry(MotivationRecipientKey, FMotivationDetailHasChangedFlag);
                FMotivationDetailHasChangedFlag = false;
            }
            else if (FRecipientKey == 0)
            {
                UpdateRecipientKeyText(0, FPreviouslySelectedDetailRow, FMotivationGroup, FMotivationDetail);
            }

            if (FRecipientKey == 0)
            {
                DisplayMotivationDetailCostCentreCode();
            }
            else
            {
                string NewCCCode = string.Empty;

                // it is possible that there are no active motivation details and so AMotivationDetail is blank
                if (!string.IsNullOrEmpty(FMotivationDetail))
                {
                    bool partnerIsMissingLink = false;

                    NewCCCode = TRemote.MFinance.Gift.WebConnectors.RetrieveCostCentreCodeForRecipient(FLedgerNumber,
                                                                                                       FRecipientKey,
                                                                                                       FPreviouslySelectedDetailRow.RecipientLedgerNumber,
                                                                                                       FPreviouslySelectedDetailRow.DateEntered,
                                                                                                       FMotivationGroup,
                                                                                                       FMotivationDetail,
                                                                                                       out partnerIsMissingLink);
                }

                if (txtDetailCostCentreCode.Text != NewCCCode)
                {
                    txtDetailCostCentreCode.Text = NewCCCode;
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Creates a new Recurring Gift or Recurring Gift detail depending upon the parameter
        /// </summary>
        /// <param name="ACompletelyNewRecurringGift"></param>
        private void CreateANewRecurringGift(bool ACompletelyNewRecurringGift)
        {
            // Using a button's keyboard shortcut results in a different sequence of Events from clicking it with the mouse. If the current control is in pnlDetails,
            // then when the New or Delete button's processing attempts to save the current record and calls TFrmPetraUtils.ForceOnLeaveForActiveControl(),
            // it inadvertently re-raises the pnlDetails.Enter event which activates BeginEditMode() at a point when it's not supposed to be activated, putting
            // TCmbAutoComplete controls in a state they're not supposed to be in, resulting in a NullReferenceException from FPreviouslySelectedDetailRow
            // in UC_RecurringGiftTransactions.Motivation.ManualCode.cs, MotivationDetailChanged().
            // To fix it, put the focus outside pnlDetails, preventing the whole chain of events from happening.
            grdDetails.Focus();

            ARecurringGiftRow CurrentRecurringGiftRow = null;
            bool IsEmptyGrid  = (grdDetails.Rows.Count == 1);
            bool HasChanges   = FPetraUtilsObject.HasChanges;
            bool SelectEndRow = false;

            bool FPrevRowIsNull = (FPreviouslySelectedDetailRow == null);
            bool CopyDetails    = false;

            bool AutoSaveSuccessful = FSETAutoSaveFlag && HasChanges && ((TFrmRecurringGiftBatch)ParentForm).SaveChangesManual();

            FNewGiftInProcess = true;

            try
            {
                //May need to copy values down if a new detail row inside current Recurring Gift
                int    recurringGiftTransactionNumber = 0;
                string donorName  = string.Empty;
                string donorClass = string.Empty;
                bool   confidentialRecurringGiftFlag = false;
                bool   chargeFlag           = false;
                bool   taxDeductible        = false;
                string motivationGroupCode  = string.Empty;
                string motivationDetailCode = string.Empty;

                if (AutoSaveSuccessful || ((!FSETAutoSaveFlag || !HasChanges) && ValidateAllData(true, TErrorProcessingMode.Epm_IgnoreNonCritical)))
                {
                    if (!ACompletelyNewRecurringGift)      //i.e. a RecurringGift detail
                    {
                        ACompletelyNewRecurringGift = IsEmptyGrid;
                    }

                    CopyDetails = (!ACompletelyNewRecurringGift && !FPrevRowIsNull);

                    if (CopyDetails)
                    {
                        //Allow for possibility that FPrev... may have some null column values
                        recurringGiftTransactionNumber = FPreviouslySelectedDetailRow.GiftTransactionNumber;
                        donorName  = FPreviouslySelectedDetailRow.IsDonorNameNull() ? string.Empty : FPreviouslySelectedDetailRow.DonorName;
                        donorClass = FPreviouslySelectedDetailRow.IsDonorClassNull() ? string.Empty : FPreviouslySelectedDetailRow.DonorClass;
                        confidentialRecurringGiftFlag =
                            FPreviouslySelectedDetailRow.IsConfidentialGiftFlagNull() ? false : FPreviouslySelectedDetailRow.ConfidentialGiftFlag;
                        chargeFlag          = FPreviouslySelectedDetailRow.IsChargeFlagNull() ? true : FPreviouslySelectedDetailRow.ChargeFlag;
                        taxDeductible       = FPreviouslySelectedDetailRow.IsTaxDeductibleNull() ? true : FPreviouslySelectedDetailRow.TaxDeductible;
                        motivationGroupCode =
                            FPreviouslySelectedDetailRow.IsMotivationGroupCodeNull() ? string.Empty : FPreviouslySelectedDetailRow.
                            MotivationGroupCode;
                        motivationDetailCode =
                            FPreviouslySelectedDetailRow.IsMotivationDetailCodeNull() ? string.Empty : FPreviouslySelectedDetailRow.
                            MotivationDetailCode;
                    }

                    //Set previous row to Null.
                    FPreviouslySelectedDetailRow = null;

                    if (ACompletelyNewRecurringGift)
                    {
                        //Run this if a new Recurring Gift is requested or required.
                        SelectEndRow = true;

                        // we create the row locally, no dataset
                        ARecurringGiftRow recurringGiftRow = FMainDS.ARecurringGift.NewRowTyped(true);

                        recurringGiftRow.LedgerNumber          = FBatchRow.LedgerNumber;
                        recurringGiftRow.BatchNumber           = FBatchRow.BatchNumber;
                        recurringGiftRow.GiftTransactionNumber = ++FBatchRow.LastGiftNumber;
                        recurringGiftRow.MethodOfPaymentCode   = FBatchRow.MethodOfPaymentCode;
                        recurringGiftRow.Active           = true;
                        recurringGiftRow.LastDetailNumber = 1;

                        FMainDS.ARecurringGift.Rows.Add(recurringGiftRow);

                        CurrentRecurringGiftRow = recurringGiftRow;

                        mniDonorHistory.Enabled = false;

                        //Reset textboxes to zero
                        txtGiftTotal.NumberValueDecimal = 0;
                    }
                    else
                    {
                        CurrentRecurringGiftRow = GetRecurringGiftRow(recurringGiftTransactionNumber);
                        CurrentRecurringGiftRow.LastDetailNumber++;

                        //If adding detail to current last Recurring Gift, then new detail will be bottom row in grid
                        if (FBatchRow.LastGiftNumber == recurringGiftTransactionNumber)
                        {
                            SelectEndRow = true;
                        }
                    }

                    //New Recurring Gifts will require a new detail anyway, so this code always runs
                    GiftBatchTDSARecurringGiftDetailRow newRow = FMainDS.ARecurringGiftDetail.NewRowTyped(true);

                    newRow.LedgerNumber          = FBatchRow.LedgerNumber;
                    newRow.BatchNumber           = FBatchRow.BatchNumber;
                    newRow.GiftTransactionNumber = CurrentRecurringGiftRow.GiftTransactionNumber;
                    newRow.DetailNumber          = CurrentRecurringGiftRow.LastDetailNumber;
                    newRow.DonorKey            = CurrentRecurringGiftRow.DonorKey;
                    newRow.Active              = CurrentRecurringGiftRow.Active;
                    newRow.MethodOfPaymentCode = CurrentRecurringGiftRow.MethodOfPaymentCode;
                    newRow.MethodOfGivingCode  = CurrentRecurringGiftRow.MethodOfGivingCode;
                    newRow.DateEntered         = DateTime.Now;

                    if (CopyDetails)
                    {
                        newRow.DonorName            = donorName;
                        newRow.DonorClass           = donorClass;
                        newRow.ConfidentialGiftFlag = confidentialRecurringGiftFlag;
                        newRow.ChargeFlag           = chargeFlag;
                        newRow.TaxDeductible        = taxDeductible;
                        newRow.MotivationGroupCode  = motivationGroupCode;
                        newRow.MotivationDetailCode = motivationDetailCode;

                        // set the auto-populate comment if needed
                        AMotivationDetailRow motivationDetail = (AMotivationDetailRow)FMainDS.AMotivationDetail.Rows.Find(
                            new object[] { FLedgerNumber, newRow.MotivationGroupCode, newRow.MotivationDetailCode });

                        if ((motivationDetail != null) && motivationDetail.Autopopdesc)
                        {
                            newRow.GiftCommentOne = motivationDetail.MotivationDetailDesc;
                        }
                    }
                    else
                    {
                        newRow.MotivationGroupCode  = MFinanceConstants.MOTIVATION_GROUP_GIFT;
                        newRow.MotivationDetailCode = MFinanceConstants.GROUP_DETAIL_SUPPORT;
                    }

                    cmbMotivationDetailCode.SetSelectedString(newRow.MotivationDetailCode, -1);
                    txtDetailMotivationDetailCode.Text = newRow.MotivationDetailCode;

                    FMainDS.ARecurringGiftDetail.Rows.Add(newRow);

                    FPetraUtilsObject.SetChangedFlag();

                    if (!SelectEndRow && !SelectDetailRowByDataTableIndex(FMainDS.ARecurringGiftDetail.Rows.Count - 1))
                    {
                        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(FMainDS.ARecurringGiftDetail.Rows.Count - 1);
                        }
                    }

                    btnDeleteAll.Enabled = btnDelete.Enabled;
                    UpdateRecordNumberDisplay();
                    FLastDonor = -1;

                    //Select end row
                    if (SelectEndRow)
                    {
                        grdDetails.SelectRowInGrid(grdDetails.Rows.Count - 1);
                    }

                    //Focus accordingly
                    if (ACompletelyNewRecurringGift)
                    {
                        txtDetailDonorKey.Focus();
                    }
                    else
                    {
                        txtDetailRecipientKey.Focus();
                    }

                    //FPreviouslySelectedDetailRow should now be pointing to the newly added row
                    UpdateRecipientKeyText(0,
                                           FPreviouslySelectedDetailRow,
                                           cmbDetailMotivationGroupCode.GetSelectedString(),
                                           cmbMotivationDetailCode.GetSelectedString());

                    ClearKeyMinistries();
                    mniRecipientHistory.Enabled = false;
                }
            }
            finally
            {
                FNewGiftInProcess = false;

                if (AutoSaveSuccessful)
                {
                    FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataSuccessful);
                }
            }
        }
        /// <summary>
        /// To be called on the display of a new record
        /// </summary>
        private static void RetrieveMotivationDetailAccountCode(AMotivationDetailRow AMotivationDetail, TextBox ATxtDetailAccountCode,
            TextBox ATxtDeductibleAccount, bool ATaxDeductiblePercentageEnabledFlag)
        {
            if (AMotivationDetail != null)
            {
                if (ATxtDetailAccountCode.Text != AMotivationDetail.AccountCode)
                {
                    ATxtDetailAccountCode.Text = AMotivationDetail.AccountCode;
                }

                if (ATaxDeductiblePercentageEnabledFlag && (ATxtDeductibleAccount.Text != AMotivationDetail.TaxDeductibleAccount))
                {
                    ATxtDeductibleAccount.Text = AMotivationDetail.TaxDeductibleAccount;
                }
            }
        }
        /// <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;
            }
        }
Пример #17
0
        /// <summary>
        /// Validates the Gift Motivation Setup.
        /// </summary>
        /// <param name="AContext">Context that describes where the data validation failed.</param>
        /// <param name="ARow">The <see cref="DataRow" /> which holds the the data against which the validation is run.</param>
        /// <param name="ATaxDeductiblePercentageEnabled">True if Tax Deductible Percentage is enabled</param>
        /// <param name="AVerificationResultCollection">Will be filled with any <see cref="TVerificationResult" /> items if
        /// data validation errors occur.</param>
        /// <param name="AValidationControlsDict">A <see cref="TValidationControlsDict" /> containing the Controls that
        /// display data that is about to be validated.</param>
        /// <returns>void</returns>
        public static void ValidateGiftMotivationSetupManual(object AContext, AMotivationDetailRow ARow, bool ATaxDeductiblePercentageEnabled,
            ref TVerificationResultCollection AVerificationResultCollection, TValidationControlsDict AValidationControlsDict)
        {
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TVerificationResult VerificationResult;

            // Don't validate deleted DataRows
            if (ARow.RowState == DataRowState.Deleted)
            {
                return;
            }

            // 'Motivation Group' must not be unassignable
            ValidationColumn = ARow.Table.Columns[AMotivationDetailTable.ColumnMotivationGroupCodeId];

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                AMotivationGroupTable MotivationGroupTable;
                AMotivationGroupRow MotivationGroupPointRow;

                VerificationResult = null;

                if ((!ARow.IsMotivationGroupCodeNull())
                    && (ARow.MotivationGroupCode != String.Empty))
                {
                    MotivationGroupTable = (AMotivationGroupTable)TSharedDataCache.TMFinance.GetCacheableFinanceTable(
                        TCacheableFinanceTablesEnum.MotivationGroupList);
                    MotivationGroupPointRow = (AMotivationGroupRow)MotivationGroupTable.Rows.Find(
                        new object[] { ARow.LedgerNumber, ARow.MotivationGroupCode });

                    // 'Motivation Group' must not be unassignable
                    if ((MotivationGroupPointRow != null)
                        && !MotivationGroupPointRow.GroupStatus)
                    {
                        // if 'Motivation Group' is unassignable then check if the value has been changed or if it is a new record
                        if (TSharedValidationHelper.IsRowAddedOrFieldModified(ARow, AMotivationDetailTable.GetMotivationGroupCodeDBName()))
                        {
                            VerificationResult = new TScreenVerificationResult(new TVerificationResult(AContext,
                                    ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_VALUEUNASSIGNABLE_WARNING,
                                        new string[] { ValidationControlsData.ValidationControlLabel, ARow.MotivationGroupCode })),
                                ValidationColumn, ValidationControlsData.ValidationControl);
                        }
                    }
                }

                // Handle addition/removal to/from TVerificationResultCollection
                AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
            }

            if (ATaxDeductiblePercentageEnabled)
            {
                // 'TaxDeductibleAccount' must have a value (NOT NULL constraint)
                ValidationColumn = ARow.Table.Columns[AMotivationDetailTable.ColumnTaxDeductibleAccountCodeId];

                if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    VerificationResult = TStringChecks.StringMustNotBeEmpty(ARow.TaxDeductibleAccountCode,
                        ValidationControlsData.ValidationControlLabel,
                        AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                    // Handle addition to/removal from TVerificationResultCollection
                    AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
                }
            }
        }
Пример #18
0
        private void ProcessMotivationDetailRow()
        {
            Int64 MotivationRecipientKey = 0;

            if (FMotivationDetail.Length > 0)
            {
                AMotivationDetailRow motivationDetail = GetCurrentMotivationDetailRow();

                if (motivationDetail != null)
                {
                    DisplayMotivationDetailAccountCode(motivationDetail);

                    MotivationRecipientKey = motivationDetail.RecipientKey;

                    // if motivation detail autopopulation is set to true
                    if (motivationDetail.Autopopdesc)
                    {
                        FAutoPopComment = motivationDetail.MotivationDetailDesc;
                    }
                    else
                    {
                        FAutoPopComment = null;
                    }

                    // set tax deductible checkbox if motivation detail has been changed by the user (i.e. not a row change)
                    if (!FInBeginEditModeFlag && (!FPetraUtilsObject.SuppressChangeDetection || FRecipientKeyChangedInProcess))
                    {
                        if (chkDetailTaxDeductible.Checked != motivationDetail.TaxDeductible)
                        {
                            chkDetailTaxDeductible.Checked = motivationDetail.TaxDeductible;
                        }
                    }
                }
                else
                {
                    chkDetailTaxDeductible.Checked = false;
                }
            }

            if (!FNewGiftInProcess && !FAutoPopulatingGiftInProcess && (MotivationRecipientKey > 0))
            {
                FMotivationDetailHasChangedFlag = true;
                PopulateKeyMinistry(MotivationRecipientKey, FMotivationDetailHasChangedFlag);
                FMotivationDetailHasChangedFlag = false;
            }
            else if (FRecipientKey == 0)
            {
                UpdateRecipientKeyText(0, FPreviouslySelectedDetailRow, FMotivationGroup, FMotivationDetail);
            }

            if (FRecipientKey == 0)
            {
                DisplayMotivationDetailCostCentreCode();
            }
            else
            {
                string NewCCCode = string.Empty;

                // it is possible that there are no active motivation details and so AMotivationDetail is blank
                if (!string.IsNullOrEmpty(FMotivationDetail))
                {
                    bool partnerIsMissingLink = false;

                    NewCCCode = TRemote.MFinance.Gift.WebConnectors.RetrieveCostCentreCodeForRecipient(FLedgerNumber,
                                                                                                       FRecipientKey,
                                                                                                       FPreviouslySelectedDetailRow.RecipientLedgerNumber,
                                                                                                       FPreviouslySelectedDetailRow.DateEntered,
                                                                                                       FMotivationGroup,
                                                                                                       FMotivationDetail,
                                                                                                       out partnerIsMissingLink);
                }

                if (txtDetailCostCentreCode.Text != NewCCCode)
                {
                    txtDetailCostCentreCode.Text = NewCCCode;
                }
            }
        }
Пример #19
0
        public static bool MaintainMotivationDetails(string action, Int32 ALedgerNumber,
                                                     String AMotivationGroupCode, String AMotivationDetailCode,
                                                     String AMotivationDetailDesc,
                                                     String AAccountCode, String ACostCentreCode, bool AMotivationStatus,
                                                     out TVerificationResultCollection AVerificationResult)
        {
            AVerificationResult = new TVerificationResultCollection();
            GiftBatchTDS MainDS = new GiftBatchTDS();

            if (action == "create")
            {
                AMotivationDetailRow row = MainDS.AMotivationDetail.NewRowTyped();
                row.LedgerNumber         = ALedgerNumber;
                row.MotivationGroupCode  = AMotivationGroupCode.ToUpper();
                row.MotivationDetailCode = AMotivationDetailCode.ToUpper();
                row.MotivationDetailDesc = AMotivationDetailDesc;
                row.AccountCode          = AAccountCode;
                row.CostCentreCode       = ACostCentreCode;
                row.MotivationStatus     = AMotivationStatus;
                MainDS.AMotivationDetail.Rows.Add(row);

                try
                {
                    GiftBatchTDSAccess.SubmitChanges(MainDS);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            else if (action == "update")
            {
                MainDS = LoadMotivationDetails(ALedgerNumber, AMotivationGroupCode);

                foreach (AMotivationDetailRow row in MainDS.AMotivationDetail.Rows)
                {
                    if (row.MotivationGroupCode == AMotivationGroupCode &&
                        row.MotivationDetailCode == AMotivationDetailCode)
                    {
                        row.MotivationDetailDesc = AMotivationDetailDesc;
                        row.AccountCode          = AAccountCode;
                        row.CostCentreCode       = ACostCentreCode;
                        row.MotivationStatus     = AMotivationStatus;
                    }
                }

                try
                {
                    GiftBatchTDSAccess.SubmitChanges(MainDS);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            else if (action == "delete")
            {
                MainDS = LoadMotivationDetails(ALedgerNumber, AMotivationGroupCode);

                foreach (AMotivationDetailRow row in MainDS.AMotivationDetail.Rows)
                {
                    if (row.MotivationGroupCode == AMotivationGroupCode &&
                        row.MotivationDetailCode == AMotivationDetailCode)
                    {
                        row.Delete();
                    }
                }

                try
                {
                    GiftBatchTDSAccess.SubmitChanges(MainDS);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }

            return(true);
        }
        private void ShowDetailsManual(AMotivationDetailRow ARow)
        {
            string FeesPayable = string.Empty;
            string FeesReceivable = string.Empty;

            if (ARow != null)
            {
                FMainDS.AMotivationDetailFee.DefaultView.RowFilter =
                    String.Format("{0}={1} and {2}='{3}' and {4}='{5}'",
                        AMotivationDetailFeeTable.GetLedgerNumberDBName(),
                        ARow.LedgerNumber,
                        AMotivationDetailFeeTable.GetMotivationGroupCodeDBName(),
                        ARow.MotivationGroupCode,
                        AMotivationDetailFeeTable.GetMotivationDetailCodeDBName(),
                        ARow.MotivationDetailCode);

                foreach (DataRowView rv in FMainDS.AMotivationDetailFee.DefaultView)
                {
                    AMotivationDetailFeeRow detailFeeRow = (AMotivationDetailFeeRow)rv.Row;

                    if (StringHelper.StrSplit(clbDetailFeesPayable.GetAllStringList(false), ",").Contains(detailFeeRow.FeeCode))
                    {
                        FeesPayable = StringHelper.AddCSV(FeesPayable, detailFeeRow.FeeCode);
                    }
                    else
                    {
                        FeesReceivable = StringHelper.AddCSV(FeesReceivable, detailFeeRow.FeeCode);
                    }
                }

                if (ARow.AccountCode == String.Empty)
                {
                    cmbDetailAccountCode.AttachedLabel.Text = TFinanceControls.SELECT_VALID_ACCOUNT;
                }

                if (ARow.CostCentreCode == String.Empty)
                {
                    cmbDetailCostCentreCode.AttachedLabel.Text = TFinanceControls.SELECT_VALID_COST_CENTRE;
                }
            }

            // set the ORDER column to true if row is checked
            clbDetailFeesPayable.CheckedColumn = "ORDER";
            clbDetailFeesReceivable.CheckedColumn = "ORDER";
            clbDetailFeesPayable.SetCheckedStringList(FeesPayable);
            clbDetailFeesReceivable.SetCheckedStringList(FeesReceivable);

            // set the CHECKED column to true if row is checked
            clbDetailFeesPayable.CheckedColumn = "CHECKED";
            clbDetailFeesReceivable.CheckedColumn = "CHECKED";
            clbDetailFeesPayable.SetCheckedStringList(FeesPayable);
            clbDetailFeesReceivable.SetCheckedStringList(FeesReceivable);

            if (FTaxDeductiblePercentageEnabled)
            {
                if (ARow.IsTaxDeductibleAccountCodeNull())
                {
                    cmbDeductibleAccountCode.SelectedIndex = 0;
                }
                else
                {
                    cmbDeductibleAccountCode.SetSelectedString(ARow.TaxDeductibleAccountCode, -1);
                }
            }
        }
        private void NewRowManual(ref AMotivationDetailRow ARow)
        {
            ARow.LedgerNumber = FLedgerNumber;

            if ((FMainDS.AMotivationGroup == null) || (FMainDS.AMotivationGroup.Rows.Count == 0))
            {
                MessageBox.Show(Catalog.GetString("You must define at least one Motivation Group."), Catalog.GetString("New Motivation Detail"),
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            ARow.MotivationGroupCode = FMainDS.AMotivationGroup[0].MotivationGroupCode;

            string newName = Catalog.GetString("NEWDETAIL");
            Int32 countNewDetail = 0;

            if (FMainDS.AMotivationDetail.Rows.Find(new object[] { FLedgerNumber, ARow.MotivationGroupCode, newName }) != null)
            {
                while (FMainDS.AMotivationDetail.Rows.Find(new object[] { FLedgerNumber, ARow.MotivationGroupCode, newName +
                                                                          countNewDetail.ToString() }) != null)
                {
                    countNewDetail++;
                }

                newName += countNewDetail.ToString();
            }

            ARow.MotivationDetailCode = newName;
            ARow.MotivationDetailDesc = Catalog.GetString("PLEASE ENTER DESCRIPTION");
        }
Пример #22
0
        /// <summary>
        /// Creates a new gift or gift detail depending upon the parameter
        /// </summary>
        /// <param name="ACompletelyNewGift"></param>
        private void CreateANewGift(bool ACompletelyNewGift)
        {
            AGiftRow CurrentGiftRow = null;
            bool     IsEmptyGrid    = (grdDetails.Rows.Count == 1);
            bool     HasChanges     = FPetraUtilsObject.HasChanges;
            bool     SelectEndRow   = false;

            bool FPrevRowIsNull = (FPreviouslySelectedDetailRow == null);
            bool CopyDetails    = false;

            bool AutoSaveSuccessful = FAutoSave && HasChanges && ((TFrmGiftBatch)ParentForm).SaveChangesManual();

            FCreatingNewGift = true;

            try
            {
                //May need to copy values down if a new detail row inside current gift
                int    giftTransactionNumber = 0;
                string donorName             = string.Empty;
                string donorClass            = string.Empty;
                bool   confidentialGiftFlag  = false;
                bool   chargeFlag            = false;
                bool   taxDeductible         = false;
                string motivationGroupCode   = string.Empty;
                string motivationDetailCode  = string.Empty;

                if (AutoSaveSuccessful || ((!FAutoSave || !HasChanges) && ValidateAllData(true, TErrorProcessingMode.Epm_IgnoreNonCritical)))
                {
                    if (!ACompletelyNewGift)      //i.e. a gift detail
                    {
                        ACompletelyNewGift = IsEmptyGrid;
                    }

                    CopyDetails = (!ACompletelyNewGift && !FPrevRowIsNull);

                    if (CopyDetails)
                    {
                        //Allow for possibility that FPrev... may have some null column values
                        giftTransactionNumber = FPreviouslySelectedDetailRow.GiftTransactionNumber;
                        donorName             = FPreviouslySelectedDetailRow.IsDonorNameNull() ? string.Empty : FPreviouslySelectedDetailRow.DonorName;
                        donorClass            = FPreviouslySelectedDetailRow.IsDonorClassNull() ? string.Empty : FPreviouslySelectedDetailRow.DonorClass;
                        confidentialGiftFlag  =
                            FPreviouslySelectedDetailRow.IsConfidentialGiftFlagNull() ? false : FPreviouslySelectedDetailRow.ConfidentialGiftFlag;
                        chargeFlag          = FPreviouslySelectedDetailRow.IsChargeFlagNull() ? true : FPreviouslySelectedDetailRow.ChargeFlag;
                        taxDeductible       = FPreviouslySelectedDetailRow.IsTaxDeductibleNull() ? true : FPreviouslySelectedDetailRow.TaxDeductible;
                        motivationGroupCode =
                            FPreviouslySelectedDetailRow.IsMotivationGroupCodeNull() ? string.Empty : FPreviouslySelectedDetailRow.
                            MotivationGroupCode;
                        motivationDetailCode =
                            FPreviouslySelectedDetailRow.IsMotivationDetailCodeNull() ? string.Empty : FPreviouslySelectedDetailRow.
                            MotivationDetailCode;
                    }

                    //Set previous row to Null.
                    FPreviouslySelectedDetailRow = null;

                    if (ACompletelyNewGift)
                    {
                        //Run this if a new gift is requested or required.
                        SelectEndRow = true;

                        // we create the row locally, no dataset
                        AGiftRow giftRow = FMainDS.AGift.NewRowTyped(true);

                        giftRow.LedgerNumber          = FBatchRow.LedgerNumber;
                        giftRow.BatchNumber           = FBatchRow.BatchNumber;
                        giftRow.GiftTransactionNumber = ++FBatchRow.LastGiftNumber;
                        giftRow.MethodOfPaymentCode   = FBatchRow.MethodOfPaymentCode;
                        giftRow.LastDetailNumber      = 1;
                        giftRow.DateEntered           = FBatchRow.GlEffectiveDate;

                        FMainDS.AGift.Rows.Add(giftRow);

                        CurrentGiftRow = giftRow;

                        mniDonorHistory.Enabled = false;

                        //Reset textboxes to zero
                        txtGiftTotal.NumberValueDecimal = 0;
                    }
                    else
                    {
                        CurrentGiftRow = GetGiftRow(giftTransactionNumber);
                        CurrentGiftRow.LastDetailNumber++;

                        //If adding detail to current last gift, then new detail will be bottom row in grid
                        if (FBatchRow.LastGiftNumber == giftTransactionNumber)
                        {
                            SelectEndRow = true;
                        }
                    }

                    //New gifts will require a new detail anyway, so this code always runs
                    GiftBatchTDSAGiftDetailRow newRow = FMainDS.AGiftDetail.NewRowTyped(true);

                    newRow.LedgerNumber          = FBatchRow.LedgerNumber;
                    newRow.BatchNumber           = FBatchRow.BatchNumber;
                    newRow.GiftTransactionNumber = CurrentGiftRow.GiftTransactionNumber;
                    newRow.DetailNumber          = CurrentGiftRow.LastDetailNumber;
                    newRow.MethodOfPaymentCode   = CurrentGiftRow.MethodOfPaymentCode;
                    newRow.MethodOfGivingCode    = CurrentGiftRow.MethodOfGivingCode;
                    newRow.DonorKey = CurrentGiftRow.DonorKey;

                    if (CopyDetails)
                    {
                        newRow.DonorName            = donorName;
                        newRow.DonorClass           = donorClass;
                        newRow.ConfidentialGiftFlag = confidentialGiftFlag;
                        newRow.ChargeFlag           = chargeFlag;
                        newRow.TaxDeductible        = taxDeductible;
                        newRow.MotivationGroupCode  = motivationGroupCode;
                        newRow.MotivationDetailCode = motivationDetailCode;

                        // set the auto-populate comment if needed
                        AMotivationDetailRow motivationDetail = (AMotivationDetailRow)FMainDS.AMotivationDetail.Rows.Find(
                            new object[] { FLedgerNumber, newRow.MotivationGroupCode, newRow.MotivationDetailCode });

                        if ((motivationDetail != null) && motivationDetail.Autopopdesc)
                        {
                            newRow.GiftCommentOne = motivationDetail.MotivationDetailDesc;
                        }
                    }
                    else
                    {
                        newRow.MotivationGroupCode  = MFinanceConstants.MOTIVATION_GROUP_GIFT;
                        newRow.MotivationDetailCode = MFinanceConstants.GROUP_DETAIL_SUPPORT;
                    }

                    newRow.DateEntered    = CurrentGiftRow.DateEntered;
                    newRow.ReceiptPrinted = false;
                    newRow.ReceiptNumber  = 0;

                    if (FTaxDeductiblePercentageEnabled)
                    {
                        newRow.TaxDeductiblePct = newRow.TaxDeductible ? 100.0m : 0.0m;

                        //Set unbound textboxes to 0
                        txtTaxDeductAmount.NumberValueDecimal = 0.0m;
                        txtNonDeductAmount.NumberValueDecimal = 0.0m;
                    }

                    FMainDS.AGiftDetail.Rows.Add(newRow);

                    FPetraUtilsObject.SetChangedFlag();

                    if (!SelectEndRow && !SelectDetailRowByDataTableIndex(FMainDS.AGiftDetail.Rows.Count - 1))
                    {
                        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(FMainDS.AGiftDetail.Rows.Count - 1);
                        }
                    }

                    btnDeleteAll.Enabled = btnDelete.Enabled;
                    UpdateRecordNumberDisplay();
                    FLastDonor = -1;

                    //Select end row
                    if (SelectEndRow)
                    {
                        grdDetails.SelectRowInGrid(grdDetails.Rows.Count - 1);
                    }

                    //Focus accordingly
                    if (ACompletelyNewGift)
                    {
                        txtDetailDonorKey.Focus();
                    }
                    else
                    {
                        txtDetailRecipientKey.Focus();
                    }

                    //FPreviouslySelectedDetailRow should now be pointing to the newly added row
                    TUC_GiftTransactions_Recipient.UpdateRecipientKeyText(0,
                                                                          FPreviouslySelectedDetailRow,
                                                                          cmbDetailMotivationGroupCode.GetSelectedString(),
                                                                          cmbDetailMotivationDetailCode.GetSelectedString());
                    cmbKeyMinistries.Clear();
                    mniRecipientHistory.Enabled = false;
                }
            }
            finally
            {
                FCreatingNewGift = false;

                if (AutoSaveSuccessful)
                {
                    FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataSuccessful);
                }
            }
        }
 private bool PreDeleteManual(AMotivationDetailRow ARowToDelete, ref string ADeletionQuestion)
 {
     ADeletionQuestion = Catalog.GetString("Are you sure you want to delete the current row?");
     ADeletionQuestion += String.Format("{0}{0}({1} {2}, {3} {4})",
         Environment.NewLine,
         lblDetailMotivationGroupCode.Text,
         cmbDetailMotivationGroupCode.GetSelectedString(),
         lblDetailMotivationDetailCode.Text,
         txtDetailMotivationDetailCode.Text);
     return true;
 }
        public static Int32 CreateGiftBatch(
            Int32 ALedgerNumber,
            Int32 AStatementKey,
            Int32 AGiftBatchNumber,
            out TVerificationResultCollection AVerificationResult)
        {
            BankImportTDS MainDS = GetBankStatementTransactionsAndMatches(AStatementKey, ALedgerNumber);

            string MyClientID = DomainManager.GClientID.ToString();

            TProgressTracker.InitProgressTracker(MyClientID,
                                                 Catalog.GetString("Creating gift batch"),
                                                 MainDS.AEpTransaction.DefaultView.Count + 10);

            AVerificationResult = new TVerificationResultCollection();

            MainDS.AEpTransaction.DefaultView.RowFilter =
                String.Format("{0}={1}",
                              AEpTransactionTable.GetStatementKeyDBName(),
                              AStatementKey);
            MainDS.AEpStatement.DefaultView.RowFilter =
                String.Format("{0}={1}",
                              AEpStatementTable.GetStatementKeyDBName(),
                              AStatementKey);
            AEpStatementRow stmt = (AEpStatementRow)MainDS.AEpStatement.DefaultView[0].Row;

            // TODO: optional: use the preselected gift batch, AGiftBatchNumber

            Int32          DateEffectivePeriodNumber, DateEffectiveYearNumber;
            DateTime       BatchDateEffective = stmt.Date;
            TDBTransaction Transaction        = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);

            if (!TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber, ref BatchDateEffective, out DateEffectiveYearNumber,
                                                           out DateEffectivePeriodNumber,
                                                           Transaction, true))
            {
                // just use the latest possible date
                string msg =
                    String.Format(Catalog.GetString("Date {0} is not in an open period of the ledger, using date {1} instead for the gift batch."),
                                  stmt.Date.ToShortDateString(),
                                  BatchDateEffective.ToShortDateString());
                AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating Gift Batch"), msg, TResultSeverity.Resv_Info));
            }

            ACostCentreAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
            AMotivationDetailAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);

            MainDS.AEpMatch.DefaultView.Sort =
                AEpMatchTable.GetActionDBName() + ", " +
                AEpMatchTable.GetMatchTextDBName();

            if (MainDS.AEpTransaction.DefaultView.Count == 0)
            {
                AVerificationResult.Add(new TVerificationResult(
                                            Catalog.GetString("Creating Gift Batch"),
                                            String.Format(Catalog.GetString("There are no transactions for statement #{0}."), AStatementKey),
                                            TResultSeverity.Resv_Info));
                return(-1);
            }

            foreach (DataRowView dv in MainDS.AEpTransaction.DefaultView)
            {
                AEpTransactionRow transactionRow = (AEpTransactionRow)dv.Row;

                DataRowView[] matches = MainDS.AEpMatch.DefaultView.FindRows(new object[] {
                    MFinanceConstants.BANK_STMT_STATUS_MATCHED_GIFT,
                    transactionRow.MatchText
                });

                if (matches.Length > 0)
                {
                    AEpMatchRow match = (AEpMatchRow)matches[0].Row;

                    if (match.IsDonorKeyNull() || (match.DonorKey == 0))
                    {
                        string msg =
                            String.Format(Catalog.GetString("Cannot create a gift for transaction {0} since there is no valid donor."),
                                          transactionRow.Description);
                        AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating Gift Batch"), msg, TResultSeverity.Resv_Critical));
                        DBAccess.GDBAccessObj.RollbackTransaction();
                        return(-1);
                    }
                }
            }

            string MatchedGiftReference = stmt.Filename;

            if (!stmt.IsBankAccountKeyNull())
            {
                string sqlGetBankSortCode =
                    "SELECT bank.p_branch_code_c " +
                    "FROM PUB_p_banking_details details, PUB_p_bank bank " +
                    "WHERE details.p_banking_details_key_i = ?" +
                    "AND details.p_bank_key_n = bank.p_partner_key_n";
                OdbcParameter param = new OdbcParameter("detailkey", OdbcType.Int);
                param.Value = stmt.BankAccountKey;

                PBankTable bankTable = new PBankTable();
                DBAccess.GDBAccessObj.SelectDT(bankTable, sqlGetBankSortCode, Transaction, new OdbcParameter[] { param }, 0, 0);

                MatchedGiftReference = bankTable[0].BranchCode + " " + stmt.Date.Day.ToString();
            }

            DBAccess.GDBAccessObj.RollbackTransaction();

            GiftBatchTDS GiftDS = TGiftTransactionWebConnector.CreateAGiftBatch(
                ALedgerNumber,
                BatchDateEffective,
                String.Format(Catalog.GetString("bank import for date {0}"), stmt.Date.ToShortDateString()));

            AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];

            giftbatchRow.BankAccountCode = stmt.BankAccountCode;

            decimal HashTotal = 0.0M;

            MainDS.AEpTransaction.DefaultView.Sort =
                AEpTransactionTable.GetNumberOnPaperStatementDBName();

            MainDS.AEpMatch.DefaultView.RowFilter = String.Empty;
            MainDS.AEpMatch.DefaultView.Sort      =
                AEpMatchTable.GetActionDBName() + ", " +
                AEpMatchTable.GetMatchTextDBName();

            int counter = 5;

            foreach (DataRowView dv in MainDS.AEpTransaction.DefaultView)
            {
                TProgressTracker.SetCurrentState(MyClientID,
                                                 Catalog.GetString("Preparing the gifts"),
                                                 counter++);

                AEpTransactionRow transactionRow = (AEpTransactionRow)dv.Row;

                DataRowView[] matches = MainDS.AEpMatch.DefaultView.FindRows(new object[] {
                    MFinanceConstants.BANK_STMT_STATUS_MATCHED_GIFT,
                    transactionRow.MatchText
                });

                if (matches.Length > 0)
                {
                    AEpMatchRow match = (AEpMatchRow)matches[0].Row;

                    AGiftRow gift = GiftDS.AGift.NewRowTyped();
                    gift.LedgerNumber          = giftbatchRow.LedgerNumber;
                    gift.BatchNumber           = giftbatchRow.BatchNumber;
                    gift.GiftTransactionNumber = giftbatchRow.LastGiftNumber + 1;
                    gift.DonorKey    = match.DonorKey;
                    gift.DateEntered = transactionRow.DateEffective;
                    gift.Reference   = MatchedGiftReference;
                    GiftDS.AGift.Rows.Add(gift);
                    giftbatchRow.LastGiftNumber++;

                    foreach (DataRowView r in matches)
                    {
                        match = (AEpMatchRow)r.Row;

                        AGiftDetailRow detail = GiftDS.AGiftDetail.NewRowTyped();
                        detail.LedgerNumber          = gift.LedgerNumber;
                        detail.BatchNumber           = gift.BatchNumber;
                        detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                        detail.DetailNumber          = gift.LastDetailNumber + 1;
                        gift.LastDetailNumber++;

                        detail.GiftTransactionAmount = match.GiftTransactionAmount;
                        detail.GiftAmount            = match.GiftTransactionAmount;
                        HashTotal += match.GiftTransactionAmount;
                        detail.MotivationGroupCode  = match.MotivationGroupCode;
                        detail.MotivationDetailCode = match.MotivationDetailCode;

                        // do not use the description in comment one, because that could show up on the gift receipt???
                        // detail.GiftCommentOne = transactionRow.Description;

                        detail.CommentOneType        = MFinanceConstants.GIFT_COMMENT_TYPE_BOTH;
                        detail.CostCentreCode        = match.CostCentreCode;
                        detail.RecipientKey          = match.RecipientKey;
                        detail.RecipientLedgerNumber = match.RecipientLedgerNumber;

                        AMotivationDetailRow motivation = (AMotivationDetailRow)MainDS.AMotivationDetail.Rows.Find(
                            new object[] { ALedgerNumber, detail.MotivationGroupCode, detail.MotivationDetailCode });

                        if (motivation == null)
                        {
                            AVerificationResult.Add(new TVerificationResult(
                                                        String.Format(Catalog.GetString("creating gift for match {0}"), transactionRow.Description),
                                                        String.Format(Catalog.GetString("Cannot find motivation group '{0}' and motivation detail '{1}'"),
                                                                      detail.MotivationGroupCode, detail.MotivationDetailCode),
                                                        TResultSeverity.Resv_Critical));
                        }

                        if (detail.CostCentreCode.Length == 0)
                        {
                            // try to retrieve the current costcentre for this recipient
                            if (detail.RecipientKey != 0)
                            {
                                detail.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(detail.RecipientKey);

                                detail.CostCentreCode = TGiftTransactionWebConnector.IdentifyPartnerCostCentre(detail.LedgerNumber,
                                                                                                               detail.RecipientLedgerNumber);
                            }
                            else
                            {
                                if (motivation != null)
                                {
                                    detail.CostCentreCode = motivation.CostCentreCode;
                                }
                            }
                        }

                        // check for active cost centre
                        ACostCentreRow costcentre = (ACostCentreRow)MainDS.ACostCentre.Rows.Find(new object[] { ALedgerNumber, detail.CostCentreCode });

                        if ((costcentre == null) || !costcentre.CostCentreActiveFlag)
                        {
                            AVerificationResult.Add(new TVerificationResult(
                                                        String.Format(Catalog.GetString("creating gift for match {0}"), transactionRow.Description),
                                                        Catalog.GetString("Invalid or inactive cost centre"),
                                                        TResultSeverity.Resv_Critical));
                        }

                        GiftDS.AGiftDetail.Rows.Add(detail);
                    }
                }
            }

            TProgressTracker.SetCurrentState(MyClientID,
                                             Catalog.GetString("Submit to database"),
                                             counter++);

            if (AVerificationResult.HasCriticalErrors)
            {
                return(-1);
            }

            giftbatchRow.HashTotal  = HashTotal;
            giftbatchRow.BatchTotal = HashTotal;

            // do not overwrite the parameter, because there might be the hint for a different gift batch date
            TVerificationResultCollection VerificationResultSubmitChanges;

            TSubmitChangesResult result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref GiftDS,
                                                                                        out VerificationResultSubmitChanges);

            TProgressTracker.FinishJob(MyClientID);

            if (result == TSubmitChangesResult.scrOK)
            {
                return(giftbatchRow.BatchNumber);
            }

            return(-1);
        }
        private void ValidateDataDetailsManual(AMotivationDetailRow ARow)
        {
            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TVerificationResult VerificationResult;
            Boolean KeyMinistryActive;

            // Partner Key must be for a Key Ministry and Key Ministry must not be deactivated
            if (Convert.ToInt64(txtDetailRecipientKey.Text) != 0)
            {
                ValidationColumn = FMainDS.AMotivationDetail[0].Table.Columns[AMotivationDetailTable.ColumnRecipientKeyId];

                if (FPetraUtilsObject.ValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    if (TRemote.MFinance.Gift.WebConnectors.KeyMinistryExists(Convert.ToInt64(txtDetailRecipientKey.Text), out KeyMinistryActive))
                    {
                        if (!KeyMinistryActive)
                        {
                            // Key Ministry is deactivated and therefore can't be used here
                            VerificationResult = new TScreenVerificationResult(new TVerificationResult(this,
                                    ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_KEY_MINISTRY_DEACTIVATED)),
                                ValidationColumn, ValidationControlsData.ValidationControl);

                            // Handle addition to/removal from TVerificationResultCollection.
                            VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn);
                        }
                    }
                    else
                    {
                        // Partner Key does not refer to Key Ministry
                        VerificationResult = new TScreenVerificationResult(new TVerificationResult(this,
                                ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_NOT_A_KEY_MINISTRY)),
                            ValidationColumn, ValidationControlsData.ValidationControl);

                        // Handle addition to/removal from TVerificationResultCollection.
                        VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn);
                    }
                }
            }

            TSharedFinanceValidation_Gift.ValidateGiftMotivationSetupManual(this,
                ARow, FTaxDeductiblePercentageEnabled,
                ref VerificationResultCollection,
                FPetraUtilsObject.ValidationControlsDict);
        }