/// <summary>
        /// Manage the overlay
        /// </summary>
        public static void SetTextBoxOverlayOnKeyMinistryCombo(GiftBatchTDSAGiftDetailRow ACurrentDetailRow, bool AActiveOnly,
            TCmbAutoPopulated ACmbKeyMinistries, TCmbAutoPopulated ACmbMotivationDetailCode, TextBox ATxtDetailRecipientKeyMinistry,
            ref string AMotivationDetail, bool AInEditModeFlag, bool ABatchUnpostedFlag, bool AReadComboValue = false)
        {
            ResetMotivationDetailCodeFilter(ACmbMotivationDetailCode, ref AMotivationDetail, AActiveOnly);

            // Always enabled initially. Combobox may be diabled later once populated.
            ACmbKeyMinistries.Enabled = true;

            ATxtDetailRecipientKeyMinistry.Visible = true;
            ATxtDetailRecipientKeyMinistry.BringToFront();
            ATxtDetailRecipientKeyMinistry.Parent.Refresh();

            if (AReadComboValue)
            {
                ReconcileKeyMinistryFromCombo(ACurrentDetailRow,
                    ACmbKeyMinistries,
                    ATxtDetailRecipientKeyMinistry,
                    AInEditModeFlag,
                    ABatchUnpostedFlag);
            }
            else
            {
                ReconcileKeyMinistryFromTextbox(ACurrentDetailRow,
                    ACmbKeyMinistries,
                    ATxtDetailRecipientKeyMinistry,
                    AInEditModeFlag,
                    ABatchUnpostedFlag);
            }
        }
        private void UpdateAllRecipientDescriptions(Int32 ABatchNumber)
        {
            DataView giftDetailView = new DataView(FMainDS.AGiftDetail);

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

            foreach (DataRowView rv in giftDetailView)
            {
                GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                if ((row.RecipientKey == 0) && (row.RecipientDescription != row.MotivationDetailCode))
                {
                    if (row.MotivationGroupCode != MFinanceConstants.MOTIVATION_GROUP_GIFT)
                    {
                        row.RecipientDescription = row.MotivationDetailCode;
                    }
                    else
                    {
                        row.RecipientDescription = string.Empty;
                    }
                }
            }
        }
Example #3
0
        static partial void ValidateGiftDetailManual(ref TVerificationResultCollection AVerificationResult,
                                                     TTypedDataTable ASubmitTable)
        {
            TValidationControlsDict ValidationControlsDict = new TValidationControlsDict();

            ValidationControlsDict.Add(ASubmitTable.Columns[AGiftDetailTable.ColumnGiftCommentOneId],
                                       new TValidationControlsData(null, AGiftDetailTable.GetGiftCommentOneDBName()));

            TPartnerClass RecipientPartnerClass;
            string        RecipientDescription;

            for (int Counter = 0; Counter < ASubmitTable.Rows.Count; Counter++)
            {
                if (ASubmitTable.Rows[Counter].RowState != DataRowState.Deleted)
                {
                    TPartnerServerLookups.GetPartnerShortName(((GiftBatchTDSAGiftDetailRow)ASubmitTable.Rows[Counter]).RecipientKey,
                                                              out RecipientDescription,
                                                              out RecipientPartnerClass);
                    GiftBatchTDSAGiftDetailRow Row = (GiftBatchTDSAGiftDetailRow)ASubmitTable.Rows[Counter];
                    Row.RecipientClass = RecipientPartnerClass.ToString();

                    TSharedFinanceValidation_Gift.ValidateGiftDetailManual("TTransactionWebConnector" +
                                                                           " (Error in Row #" + Counter.ToString() + ")", // No translation of message text since the server's messages should be all in English
                                                                           Row, ref AVerificationResult,
                                                                           ValidationControlsDict);
                }
            }
        }
        /// <summary>
        /// Update all donor names in gift details table
        /// </summary>
        /// <param name="ABatchNumber"></param>
        private void UpdateAllDonorNames(Int32 ABatchNumber)
        {
            Dictionary <Int32, Int64>  GiftsDict  = new Dictionary <Int32, Int64>();
            Dictionary <Int64, string> DonorsDict = new Dictionary <Int64, string>();

            DataView GiftDV = new DataView(FMainDS.AGift);

            GiftDV.RowFilter = string.Format("{0}={1}",
                                             AGiftTable.GetBatchNumberDBName(),
                                             ABatchNumber);

            GiftDV.Sort = string.Format("{0} ASC", AGiftTable.GetGiftTransactionNumberDBName());

            foreach (DataRowView drv in GiftDV)
            {
                AGiftRow gr = (AGiftRow)drv.Row;

                Int64 donorKey = gr.DonorKey;

                GiftsDict.Add(gr.GiftTransactionNumber, donorKey);

                if (!DonorsDict.ContainsKey(donorKey))
                {
                    if (donorKey != 0)
                    {
                        PPartnerRow pr = RetrieveDonorRow(donorKey);

                        if (pr != null)
                        {
                            DonorsDict.Add(donorKey, pr.PartnerShortName);
                        }
                    }
                    else
                    {
                        DonorsDict.Add(0, "");
                    }
                }
            }

            //Add donor info to gift details
            DataView GiftDetailDV = new DataView(FMainDS.AGiftDetail);

            GiftDetailDV.RowFilter = string.Format("{0}={1}",
                                                   AGiftDetailTable.GetBatchNumberDBName(),
                                                   ABatchNumber);

            GiftDetailDV.Sort = string.Format("{0} ASC", AGiftDetailTable.GetGiftTransactionNumberDBName());

            foreach (DataRowView drv in GiftDetailDV)
            {
                GiftBatchTDSAGiftDetailRow giftDetail = (GiftBatchTDSAGiftDetailRow)drv.Row;

                Int64 donorKey = GiftsDict[giftDetail.GiftTransactionNumber];

                giftDetail.DonorKey  = donorKey;
                giftDetail.DonorName = DonorsDict[donorKey];
            }
        }
        private bool OnPreDeleteManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ADeletionQuestion)
        {
            bool allowDeletion = true;

            FGift = GetGiftRow(ARowToDelete.GiftTransactionNumber);
            FFilterAllDetailsOfGift = String.Format("{0}={1} and {2}={3}",
                AGiftDetailTable.GetBatchNumberDBName(),
                FPreviouslySelectedDetailRow.BatchNumber,
                AGiftDetailTable.GetGiftTransactionNumberDBName(),
                FPreviouslySelectedDetailRow.GiftTransactionNumber);

            FGiftDetailView = new DataView(FMainDS.AGiftDetail);
            FGiftDetailView.RowFilter = FFilterAllDetailsOfGift;
            FGiftDetailView.Sort = AGiftDetailTable.GetDetailNumberDBName() + " ASC";
            String formattedDetailAmount = StringHelper.FormatUsingCurrencyCode(ARowToDelete.GiftTransactionAmount, GetCurrentBatchRow().CurrencyCode);

            if (FGiftDetailView.Count == 1)
            {
                ADeletionQuestion = String.Format(Catalog.GetString("Are you sure you want to delete gift no. {1} from Gift Batch no. {2}?" +
                        "\n\r\n\r" + "     From:  {3}" +
                        "\n\r" + "         To:  {4}" +
                        "\n\r" + "Amount:  {5}"),
                    ARowToDelete.DetailNumber,
                    ARowToDelete.GiftTransactionNumber,
                    ARowToDelete.BatchNumber,
                    ARowToDelete.DonorName,
                    ARowToDelete.RecipientDescription,
                    formattedDetailAmount);
            }
            else if (FGiftDetailView.Count > 1)
            {
                ADeletionQuestion =
                    String.Format(Catalog.GetString("Are you sure you want to delete detail line: {0} from gift no. {1} in Gift Batch no. {2}?" +
                            "\n\r\n\r" + "     From:  {3}" +
                            "\n\r" + "         To:  {4}" +
                            "\n\r" + "Amount:  {5}"),
                        ARowToDelete.DetailNumber,
                        ARowToDelete.GiftTransactionNumber,
                        ARowToDelete.BatchNumber,
                        ARowToDelete.DonorName,
                        ARowToDelete.RecipientDescription,
                        formattedDetailAmount);
            }
            else //this should never happen
            {
                ADeletionQuestion =
                    String.Format(Catalog.GetString("Gift no. {0} in Batch no. {1} has no detail rows in the Gift Detail table!"),
                        ARowToDelete.GiftTransactionNumber,
                        ARowToDelete.BatchNumber);
                allowDeletion = false;
            }

            return allowDeletion;
        }
 private void UpdateGiftDestinationOnDateChange(ref GiftBatchTDSAGiftDetailRow ARow, DateTime ADate)
 {
     // only make changes if gift doesn't have a fixed gift destination
     if ((ARow.IsFixedGiftDestinationNull() || !ARow.FixedGiftDestination) &&
         (ARow.IsModifiedDetailNull() || !ARow.ModifiedDetail) &&
         (ARow.RecipientKey > 0) &&
         (ARow.RecipientClass == TPartnerClass.FAMILY.ToString()))
     {
         ARow.RecipientLedgerNumber = TRemote.MFinance.Gift.WebConnectors.GetRecipientFundNumber(ARow.RecipientKey, ADate);
     }
 }
Example #7
0
        private bool OnPreDeleteManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ADeletionQuestion)
        {
            bool allowDeletion = true;

            FGift = GetGiftRow(ARowToDelete.GiftTransactionNumber);
            FFilterAllDetailsOfGift = String.Format("{0}={1} and {2}={3}",
                                                    AGiftDetailTable.GetBatchNumberDBName(),
                                                    FPreviouslySelectedDetailRow.BatchNumber,
                                                    AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                    FPreviouslySelectedDetailRow.GiftTransactionNumber);

            FGiftDetailView           = new DataView(FMainDS.AGiftDetail);
            FGiftDetailView.RowFilter = FFilterAllDetailsOfGift;
            FGiftDetailView.Sort      = AGiftDetailTable.GetDetailNumberDBName() + " ASC";
            String formattedDetailAmount = StringHelper.FormatUsingCurrencyCode(ARowToDelete.GiftTransactionAmount, GetBatchRow().CurrencyCode);

            if (FGiftDetailView.Count == 1)
            {
                ADeletionQuestion = String.Format(Catalog.GetString("Are you sure you want to delete gift no. {1} from Gift Batch no. {2}?" +
                                                                    "\n\r\n\r" + "     From:  {3}" +
                                                                    "\n\r" + "         To:  {4}" +
                                                                    "\n\r" + "Amount:  {5}"),
                                                  ARowToDelete.DetailNumber,
                                                  ARowToDelete.GiftTransactionNumber,
                                                  ARowToDelete.BatchNumber,
                                                  ARowToDelete.DonorName,
                                                  ARowToDelete.RecipientDescription,
                                                  formattedDetailAmount);
            }
            else if (FGiftDetailView.Count > 1)
            {
                ADeletionQuestion =
                    String.Format(Catalog.GetString("Are you sure you want to delete detail line: {0} from gift no. {1} in Gift Batch no. {2}?" +
                                                    "\n\r\n\r" + "     From:  {3}" +
                                                    "\n\r" + "         To:  {4}" +
                                                    "\n\r" + "Amount:  {5}"),
                                  ARowToDelete.DetailNumber,
                                  ARowToDelete.GiftTransactionNumber,
                                  ARowToDelete.BatchNumber,
                                  ARowToDelete.DonorName,
                                  ARowToDelete.RecipientDescription,
                                  formattedDetailAmount);
            }
            else //this should never happen
            {
                ADeletionQuestion =
                    String.Format(Catalog.GetString("Gift no. {0} in Batch no. {1} has no detail rows in the Gift Detail table!"),
                                  ARowToDelete.GiftTransactionNumber,
                                  ARowToDelete.BatchNumber);
                allowDeletion = false;
            }

            return(allowDeletion);
        }
Example #8
0
        private void ValidateTaxDeductiblePct(GiftBatchTDSAGiftDetailRow ARow, ref TVerificationResultCollection AVerificationResultCollection)
        {
            int PreValidationResultCount = AVerificationResultCollection.Count;

            TSharedFinanceValidation_Gift.ValidateTaxDeductiblePct(this, ARow, ref AVerificationResultCollection, FValidationControlsDict);

            //No validation errors occurred
            if (PreValidationResultCount == AVerificationResultCollection.Count)
            {
                ReconcileTaxDeductibleAmounts(ARow);
            }
        }
Example #9
0
        private void ReconcileTaxDeductibleAmounts(GiftBatchTDSAGiftDetailRow ARow)
        {
            AGiftDetailRow GDR = (AGiftDetailRow)ARow;

            TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref GDR);

            if ((txtTaxDeductAmount.NumberValueDecimal != ARow.TaxDeductibleAmount) ||
                (txtNonDeductAmount.NumberValueDecimal != ARow.NonDeductibleAmount))
            {
                txtTaxDeductAmount.NumberValueDecimal = ARow.TaxDeductibleAmount;
                txtNonDeductAmount.NumberValueDecimal = ARow.NonDeductibleAmount;
            }
        }
        private void ReconcileKeyMinistryFromCombo(GiftBatchTDSAGiftDetailRow ACurrentDetailRow)
        {
            if (FBatchUnpostedFlag && FInEditModeFlag)
            {
                string keyMinistry      = string.Empty;
                bool   isEmptyDetailRow = (ACurrentDetailRow == null);

                if (!isEmptyDetailRow && (cmbKeyMinistries.SelectedIndex > -1))
                {
                    keyMinistry = cmbKeyMinistries.GetSelectedDescription();
                }

                txtDetailRecipientKeyMinistry.Text = keyMinistry;
            }
        }
        private void OnPostDeleteManual(GiftBatchTDSAGiftDetailRow ARowToDelete,
                                        bool AAllowDeletion,
                                        bool ADeletionPerformed,
                                        string ACompletionMessage)
        {
            if (ADeletionPerformed)
            {
                if (FGiftSelectedForDeletion)
                {
                    FGiftSelectedForDeletion = false;

                    SetBatchLastGiftNumber();

                    UpdateControlsProtection();

                    if (!pnlDetails.Enabled)
                    {
                        ClearControls();
                    }
                }

                UpdateTotals();

                ((TFrmGiftBatch)this.ParentForm).SaveChangesManual();

                //message to user
                MessageBox.Show(ACompletionMessage,
                                "Deletion Successful",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
            else if (!AAllowDeletion && (ACompletionMessage.Length > 0))
            {
                //message to user
                MessageBox.Show(ACompletionMessage,
                                "Deletion not allowed",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            else if (!ADeletionPerformed && (ACompletionMessage.Length > 0))
            {
                //message to user
                MessageBox.Show(ACompletionMessage,
                                "Deletion failed",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }
 private void UpdateRecipientKeyText(Int64 APartnerKey,
                                     GiftBatchTDSAGiftDetailRow ACurrentDetailRow,
                                     string AMotivationGroupCode,
                                     string AMotivationDetailCode)
 {
     if ((APartnerKey == 0) && (ACurrentDetailRow != null))
     {
         if (AMotivationGroupCode != MFinanceConstants.MOTIVATION_GROUP_GIFT)
         {
             ACurrentDetailRow.RecipientDescription = AMotivationDetailCode;
         }
         else
         {
             ACurrentDetailRow.RecipientDescription = string.Empty;
         }
     }
 }
        private void ReconcileKeyMinistryFromTextbox(GiftBatchTDSAGiftDetailRow ACurrentDetailRow)
        {
            if (FBatchUnpostedFlag && FInEditModeFlag)
            {
                bool   isEmptyDetailRow = (ACurrentDetailRow == null);
                string keyMinistry      = txtDetailRecipientKeyMinistry.Text;

                if (!isEmptyDetailRow && (keyMinistry.Length > 0))
                {
                    cmbKeyMinistries.SetSelectedString(keyMinistry);
                }
                else
                {
                    cmbKeyMinistries.SelectedIndex = -1;
                }
            }
        }
        // get tax deductible percentage data from controls
        private void GetTaxDeductibleDataFromControlsManual(ref GiftBatchTDSAGiftDetailRow ARow)
        {
            ARow.TaxDeductiblePct = (decimal)txtDeductiblePercentage.NumberValueDecimal;

            ARow.TaxDeductibleAmount = (decimal)txtTaxDeductAmount.NumberValueDecimal;

            ARow.NonDeductibleAmount = (decimal)txtNonDeductAmount.NumberValueDecimal;

            if (txtDeductibleAccount.Text.Length == 0)
            {
                ARow.SetTaxDeductibleAccountCodeNull();
            }
            else
            {
                ARow.TaxDeductibleAccountCode = txtDeductibleAccount.Text;
            }
        }
        private void ReconcileMotivationDetailFromTextbox(GiftBatchTDSAGiftDetailRow ACurrentDetailRow)
        {
            if (FBatchUnpostedFlag && FInEditModeFlag)
            {
                bool   isEmptyDetailRow = (ACurrentDetailRow == null);
                string motivationDetail = txtDetailMotivationDetailCode.Text;

                if (!isEmptyDetailRow && (motivationDetail.Length > 0))
                {
                    cmbMotivationDetailCode.SetSelectedString(motivationDetail);
                }
                else
                {
                    cmbMotivationDetailCode.SelectedIndex = -1;
                }

                txtMotivationDetailDesc.Text = cmbMotivationDetailCode.GetSelectedDescription();
            }
        }
Example #16
0
        // get tax deductible percentage data from controls
        private void GetTaxDeductibleDataFromControlsManual(GiftBatchTDSAGiftDetailRow ARow)
        {
            if (FNewGiftInProcess)
            {
                return;
            }

            ARow.TaxDeductiblePct = txtDeductiblePercentage.NumberValueDecimal.Value;

            ReconcileTaxDeductibleAmounts(ARow);

            if (txtDeductibleAccount.Text.Length == 0)
            {
                ARow.SetTaxDeductibleAccountCodeNull();
            }
            else
            {
                ARow.TaxDeductibleAccountCode = txtDeductibleAccount.Text;
            }
        }
        private void ReconcileMotivationDetailFromCombo(GiftBatchTDSAGiftDetailRow ACurrentDetailRow)
        {
            if (FBatchUnpostedFlag && FInEditModeFlag)
            {
                string motivationDetail     = string.Empty;
                string motivationDetailDesc = string.Empty;

                bool isEmptyDetailRow = (ACurrentDetailRow == null);

                if (!isEmptyDetailRow && (cmbMotivationDetailCode.SelectedIndex > -1))
                {
                    motivationDetail     = cmbMotivationDetailCode.GetSelectedString();
                    motivationDetailDesc = cmbMotivationDetailCode.GetSelectedDescription();
                }

                FMotivationDetail = motivationDetail;
                txtDetailMotivationDetailCode.Text = motivationDetail;
                txtMotivationDetailDesc.Text       = motivationDetailDesc;
            }
        }
Example #18
0
        // get tax deductible percentage data from controls
        private void GetTaxDeductibleDataFromControlsManual(GiftBatchTDSAGiftDetailRow ARow)
        {
            if (FCreatingNewGift)
            {
                return;
            }

            ARow.TaxDeductiblePct = txtDeductiblePercentage.NumberValueDecimal.Value;

            ARow.TaxDeductibleAmount = txtTaxDeductAmount.NumberValueDecimal.Value;

            ARow.NonDeductibleAmount = txtNonDeductAmount.NumberValueDecimal.Value;

            if (txtDeductibleAccount.Text.Length == 0)
            {
                ARow.SetTaxDeductibleAccountCodeNull();
            }
            else
            {
                ARow.TaxDeductibleAccountCode = txtDeductibleAccount.Text;
            }
        }
        // show tax deductible percentage data in controls
        private void ShowTaxDeductibleManual(GiftBatchTDSAGiftDetailRow ARow)
        {
            if (ARow.IsTaxDeductiblePctNull())
            {
                txtDeductiblePercentage.NumberValueDecimal = 0;
            }
            else
            {
                txtDeductiblePercentage.NumberValueDecimal = ARow.TaxDeductiblePct;
            }

            if (ARow.IsTaxDeductibleAccountCodeNull())
            {
                txtDeductibleAccount.Text = string.Empty;
            }
            else
            {
                txtDeductibleAccount.Text = ARow.TaxDeductibleAccountCode;
            }

            EnableOrDiasbleTaxDeductibilityPct(ARow.TaxDeductible);
        }
        private void ValidateDataDetailsManual(GiftBatchTDSAGiftDetailRow ARow)
        {
            //Ensure FBatchRow is correct, as this gets called from the batch tab validation
            FBatchRow = GetBatchRow();

            if ((ARow == null) || (ARow.RowState == DataRowState.Deleted) || (FBatchRow == null)
                || (FBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)
                || (FBatchRow.BatchNumber != ARow.BatchNumber))
            {
                return;
            }

            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;

            if ((ARow.RecipientField != 0)
                && (ARow.RecipientKey != 0)
                && ((int)ARow.RecipientField / 1000000 != ARow.LedgerNumber))
            {
                TVerificationResultCollection TempVerificationResultCollection;

                if (!TRemote.MFinance.Gift.WebConnectors.IsRecipientLedgerNumberSetupForILT(FLedgerNumber, FPreviouslySelectedDetailRow.RecipientKey,
                        Convert.ToInt64(txtDetailRecipientLedgerNumber.Text), out TempVerificationResultCollection))
                {
                    DataColumn ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnRecipientLedgerNumberId];
                    object ValidationContext = String.Format("Batch Number {0} (transaction:{1} detail:{2})",
                        ARow.BatchNumber,
                        ARow.GiftTransactionNumber,
                        ARow.DetailNumber);

                    TValidationControlsData ValidationControlsData;

                    if (FValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                    {
                        TVerificationResult VerificationResult = new TVerificationResult(this,
                            ValidationContext.ToString() + ": " + TempVerificationResultCollection[0].ResultText,
                            PetraErrorCodes.ERR_RECIPIENTFIELD_NOT_ILT, TResultSeverity.Resv_Critical);

                        VerificationResultCollection.Auto_Add_Or_AddOrRemove(this,
                            new TScreenVerificationResult(VerificationResult, ValidationColumn, ValidationControlsData.ValidationControl),
                            ValidationColumn, true);
                    }
                }
            }

            TSharedFinanceValidation_Gift.ValidateGiftDetailManual(this, ARow, ref VerificationResultCollection,
                FValidationControlsDict, txtDetailRecipientKey.CurrentPartnerClass, null, null, null);

            //It is necessary to validate the unbound control for date entered. This requires us to pass the control.
            AGiftRow giftRow = GetGiftRow(ARow.GiftTransactionNumber);

            TSharedFinanceValidation_Gift.ValidateGiftManual(this,
                giftRow,
                FBatchRow.BatchYear,
                FBatchRow.BatchPeriod,
                dtpDateEntered,
                ref VerificationResultCollection,
                FValidationControlsDict);

            if (FTaxDeductiblePercentageEnabled)
            {
                ValidateTaxDeductiblePct(ARow, ref VerificationResultCollection);
            }
        }
 private void ValidateTaxDeductiblePct(GiftBatchTDSAGiftDetailRow ARow, ref TVerificationResultCollection AVerificationResultCollection)
 {
     TSharedFinanceValidation_Gift.ValidateTaxDeductiblePct(this, ARow, ref AVerificationResultCollection, FValidationControlsDict);
 }
        private void ShowDetailsManual(GiftBatchTDSAGiftDetailRow ARow)
        {
            if ((ARow != null) && FActiveOnly)
            {
                // if selected gift has changed to being a reversal gift
                if ((ARow.GiftTransactionAmount < 0) && (GetGiftRow(ARow.GiftTransactionNumber).ReceiptNumber != 0)
                    && !string.IsNullOrEmpty(cmbDetailMotivationGroupCode.Filter))
                {
                    TFinanceControls.ChangeFilterMotivationGroupList(ref cmbDetailMotivationGroupCode, false);
                    cmbDetailMotivationGroupCode.SetSelectedString(ARow.MotivationGroupCode, -1);
                }
                // if selected gift has changed to being a non reversal gift
                else if (!((ARow.GiftTransactionAmount < 0) && (GetGiftRow(ARow.GiftTransactionNumber).ReceiptNumber != 0))
                         && string.IsNullOrEmpty(cmbDetailMotivationGroupCode.Filter))
                {
                    TFinanceControls.ChangeFilterMotivationGroupList(ref cmbDetailMotivationGroupCode, true);
                    cmbDetailMotivationGroupCode.SetSelectedString(ARow.MotivationGroupCode, -1);
                }
            }

            bool ShowGiftDetail = EditableGiftDetail(FPreviouslySelectedDetailRow);

            if (TUC_GiftTransactions_Recipient.OnStartShowDetailsManual(ARow, cmbKeyMinistries, cmbDetailMotivationGroupCode,
                    cmbDetailMotivationDetailCode,
                    txtDetailRecipientKeyMinistry, ref FMotivationGroup, ref FMotivationDetail, ShowGiftDetail, FGiftTransactionsLoaded, FInEditMode,
                    FBatchUnposted))
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;

                    FShowingDetails = true;

                    bool? DoEnableRecipientGiftDestination;
                    TUC_GiftTransactions_Recipient.FinishShowDetailsManual(ARow,
                        cmbDetailMotivationDetailCode,
                        txtDetailRecipientKey,
                        txtDetailRecipientLedgerNumber,
                        txtDetailCostCentreCode,
                        txtDetailAccountCode,
                        cmbDetailCommentOneType,
                        cmbDetailCommentTwoType,
                        cmbDetailCommentThreeType,
                        ref FMotivationGroup,
                        ref FMotivationDetail,
                        out DoEnableRecipientGiftDestination);

                    if (DoEnableRecipientGiftDestination.HasValue)
                    {
                        mniRecipientGiftDestination.Enabled = DoEnableRecipientGiftDestination.Value;
                    }

                    // set FAutoPopComment if needed
                    AMotivationDetailRow motivationDetail = (AMotivationDetailRow)FMainDS.AMotivationDetail.Rows.Find(
                        new object[] { FLedgerNumber, FMotivationGroup, FMotivationDetail });

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

                    //Show gift table values
                    AGiftRow giftRow = GetGiftRow(ARow.GiftTransactionNumber);
                    ShowDetailsForGift(giftRow);

                    ShowDonorInfo(Convert.ToInt64(txtDetailDonorKey.Text));

                    UpdateControlsProtection(ARow);

                    if (FTaxDeductiblePercentageEnabled)
                    {
                        ShowTaxDeductibleManual(ARow);
                    }
                }
                finally
                {
                    FShowingDetails = false;
                    this.Cursor = Cursors.Default;
                }
            }
        }
        private void DonorKeyChanged(Int64 APartnerKey,
                                     String APartnerShortName,
                                     bool AValidSelection)
        {
            if (!FAutoPopulatingGiftInProcess)
            {
                //This gets set to false when autopopulating gift
                txtDetailDonorKey.FocusTextBoxPartAfterFindScreenCloses = true;
            }

            if (FAutoPopulatingGiftInProcess)
            {
                return;
            }
            else if (!AValidSelection && (APartnerKey != 0))
            {
                //An invalid donor number can stop deletion of a new row, so need to stop invalid entries
                MessageBox.Show(String.Format(Catalog.GetString("Donor number {0} could not be found!"),
                                              APartnerKey));
                txtDetailDonorKey.Text = String.Format("{0:0000000000}", 0);
                return;
            }
            // At the moment this event is thrown twice
            // We want to deal only on manual entered changes, i.e. not on selections changes, and on non-zero keys
            else if (FPetraUtilsObject.SuppressChangeDetection || (APartnerKey == 0))
            {
                // FLastDonor should be the last donor key that has been entered for a gift (not 0)
                if (APartnerKey != 0)
                {
                    FLastDonor = APartnerKey;
                    mniDonorHistory.Enabled = true;
                }
                else
                {
                    mniDonorHistory.Enabled = false;
                    txtDonorInfo.Text       = string.Empty;

                    if (FNewGiftInProcess)
                    {
                        FLastDonor = 0;
                    }
                }
            }
            else
            {
                try
                {
                    Cursor = Cursors.WaitCursor;

                    // this is a different donor
                    if (APartnerKey != FLastDonor)
                    {
                        PPartnerRow pr = RetrieveDonorRow(APartnerKey);

                        if (pr == null)
                        {
                            string errMsg = String.Format(Catalog.GetString("Partner Key:'{0} - {1}' cannot be found in the Partner table!"),
                                                          APartnerKey,
                                                          APartnerShortName);
                            MessageBox.Show(errMsg, Catalog.GetString("Donor Changed"), MessageBoxButtons.OK, MessageBoxIcon.Error);

                            //An invalid donor number can stop deletion of a new row, so need to stop invalid entries
                            txtDetailDonorKey.Text = String.Format("{0:0000000000}", 0);
                            return;
                        }

                        chkDetailConfidentialGiftFlag.Checked = pr.AnonymousDonor;

                        Int32 giftTransactionNo = FPreviouslySelectedDetailRow.GiftTransactionNumber;

                        DataView giftDetailDV = new DataView(FMainDS.AGiftDetail);

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

                        foreach (DataRowView drv in giftDetailDV)
                        {
                            GiftBatchTDSAGiftDetailRow giftDetail = (GiftBatchTDSAGiftDetailRow)drv.Row;

                            giftDetail.DonorKey   = APartnerKey;
                            giftDetail.DonorName  = APartnerShortName;
                            giftDetail.DonorClass = pr.PartnerClass;
                        }

                        //Point to current gift row and specify as not a new donor
                        FGift = GetGiftRow(giftTransactionNo);
                        FGift.FirstTimeGift = false;

                        //Only autopopulate if this is a donor selection on a clean gift,
                        //  i.e. determine this is not a donor change where other changes have been made
                        //Sometimes you want to just change the donor without changing what already has been entered
                        //  e.g. when you realise you have entered the wrong donor after entering the correct recipient data
                        if (!DonorIsAlreadyLoaded(APartnerKey, giftTransactionNo) &&
                            !TRemote.MFinance.Gift.WebConnectors.DonorHasGiven(FLedgerNumber, APartnerKey))
                        {
                            FGift.FirstTimeGift = true;

                            // add donor key to list so that new donor warning can be shown
                            if (!FNewDonorsList.Contains(APartnerKey))
                            {
                                FNewDonorsList.Add(APartnerKey);
                            }
                        }
                        else if ((giftDetailDV.Count == 1) &&
                                 (Convert.ToInt64(txtDetailRecipientKey.Text) == 0) &&
                                 (txtDetailGiftTransactionAmount.NumberValueDecimal.Value == 0))
                        {
                            AutoPopulateGiftDetail(APartnerKey, APartnerShortName, giftTransactionNo);
                        }

                        mniDonorHistory.Enabled = true;
                    }

                    ShowDonorInfo(null, APartnerKey);

                    FLastDonor = APartnerKey;
                }
                finally
                {
                    Cursor = Cursors.Default;
                }
            }
        }
        /// <summary>
        /// ApplyMotivationDetailCodeFilter
        /// </summary>
        private static void ApplyMotivationDetailCodeFilter(GiftBatchTDSAGiftDetailRow ACurrentDetailRow,
            GiftBatchTDS AMainDS,
            Int32 ALedgerNumber,
            TFrmPetraEditUtils APetraUtilsObject,
            TCmbAutoPopulated ACmbKeyMinistries,
            ref TCmbAutoPopulated ACmbMotivationDetailCode,
            TtxtAutoPopulatedButtonLabel ATxtDetailRecipientKey,
            Int64 ARecipientKey,
            TtxtAutoPopulatedButtonLabel AtxtDetailRecipientLedgerNumber,
            TextBox ATxtDetailCostCentreCode,
            TextBox ATxtDetailAccountCode,
            TextBox ATxtDetailRecipientKeyMinistry,
            CheckBox AChkDetailTaxDeductible,
            TextBox ATxtDeductibleAccount,
            string AMotivationGroup,
            ref string AMotivationDetail,
            ref bool AMotivationDetailChangedFlag,
            bool AActiveOnly,
            bool ARecipientKeyChangingFlag,
            bool ACreatingNewGiftFlag,
            bool AInEditModeFlag,
            bool ABatchUnpostedFlag,
            bool ATaxDeductiblePercentageEnabledFlag,
            out bool ADoTaxUpdate)
        {
            //FMotivationbDetail will change by next process
            string motivationDetail = AMotivationDetail;

            string AutoPopComment;

            TFinanceControls.ChangeFilterMotivationDetailList(ref ACmbMotivationDetailCode, AMotivationGroup);
            AMotivationDetail = motivationDetail;

            if (AMotivationDetail.Length > 0)
            {
                ACmbMotivationDetailCode.SetSelectedString(AMotivationDetail);
                ACmbMotivationDetailCode.Text = AMotivationDetail;
                ADoTaxUpdate = false;
            }
            else if (ACmbMotivationDetailCode.Count > 0)
            {
                ACmbMotivationDetailCode.SelectedIndex = 0;

                //Force refresh of label
                OnMotivationDetailChanged(ACurrentDetailRow,
                    AMainDS,
                    ALedgerNumber,
                    APetraUtilsObject,
                    ACmbKeyMinistries,
                    ACmbMotivationDetailCode,
                    ATxtDetailRecipientKey,
                    ARecipientKey,
                    AtxtDetailRecipientLedgerNumber,
                    ATxtDetailCostCentreCode,
                    ATxtDetailAccountCode,
                    ATxtDetailRecipientKeyMinistry,
                    AChkDetailTaxDeductible,
                    ATxtDeductibleAccount,
                    AMotivationGroup,
                    ref AMotivationDetail,
                    ref AMotivationDetailChangedFlag,
                    ARecipientKeyChangingFlag,
                    ACreatingNewGiftFlag,
                    AInEditModeFlag,
                    ABatchUnpostedFlag,
                    ATaxDeductiblePercentageEnabledFlag,
                    false,
                    out ADoTaxUpdate,
                    out AutoPopComment);
            }
            else
            {
                ACmbMotivationDetailCode.SelectedIndex = -1;
                //Force refresh of label
                OnMotivationDetailChanged(ACurrentDetailRow,
                    AMainDS,
                    ALedgerNumber,
                    APetraUtilsObject,
                    ACmbKeyMinistries,
                    ACmbMotivationDetailCode,
                    ATxtDetailRecipientKey,
                    ARecipientKey,
                    AtxtDetailRecipientLedgerNumber,
                    ATxtDetailCostCentreCode,
                    ATxtDetailAccountCode,
                    ATxtDetailRecipientKeyMinistry,
                    AChkDetailTaxDeductible,
                    ATxtDeductibleAccount,
                    AMotivationGroup,
                    ref AMotivationDetail,
                    ref AMotivationDetailChangedFlag,
                    ARecipientKeyChangingFlag,
                    ACreatingNewGiftFlag,
                    AInEditModeFlag,
                    ABatchUnpostedFlag,
                    ATaxDeductiblePercentageEnabledFlag,
                    false,
                    out ADoTaxUpdate,
                    out AutoPopComment);
            }

            RetrieveMotivationDetailAccountCode(AMainDS, ALedgerNumber, ATxtDetailAccountCode, ATxtDeductibleAccount,
                AMotivationGroup, AMotivationDetail, ATaxDeductiblePercentageEnabledFlag);

            if ((ATxtDetailRecipientKey.Text == string.Empty) || (Convert.ToInt64(ATxtDetailRecipientKey.Text) == 0))
            {
                ATxtDetailRecipientKey.Text = String.Format("{0:0000000000}", 0);
                RetrieveMotivationDetailCostCentreCode(AMainDS, ALedgerNumber, ATxtDetailCostCentreCode, AMotivationGroup, AMotivationDetail);
            }
        }
 private bool DeleteRowManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ACompletionMessage)
 {
     return OnDeleteRowManual(ARowToDelete, ref ACompletionMessage);
 }
        /// <summary>
        /// Call when the recipient ledger number changes
        /// </summary>
        public static void OnRecipientLedgerNumberChanged(Int32 ALedgerNumber,
            GiftBatchTDSAGiftDetailRow ACurrentDetailRow,
            TFrmPetraEditUtils APetraUtilsObject,
            TextBox ATxtDetailCostCentreCode,
            bool ABatchUnpostedFlag,
            bool ARecipientKeyChangingFlag,
            bool AShowingDetailsFlag)
        {
            if (APetraUtilsObject.SuppressChangeDetection || AShowingDetailsFlag || ARecipientKeyChangingFlag || !ABatchUnpostedFlag)
            {
                return;
            }

            string NewCCCode = TRemote.MFinance.Gift.WebConnectors.RetrieveCostCentreCodeForRecipient(ALedgerNumber,
                ACurrentDetailRow.RecipientKey,
                ACurrentDetailRow.RecipientLedgerNumber,
                ACurrentDetailRow.DateEntered,
                ACurrentDetailRow.MotivationGroupCode,
                ACurrentDetailRow.MotivationDetailCode);

            if (ATxtDetailCostCentreCode.Text != NewCCCode)
            {
                ATxtDetailCostCentreCode.Text = NewCCCode;
            }
        }
        /// <summary>
        /// Call from ShowDetailsManual
        /// </summary>
        public static bool OnStartShowDetailsManual(GiftBatchTDSAGiftDetailRow ACurrentDetailRow, TCmbAutoPopulated ACmbKeyMinistries,
            TCmbAutoPopulated ACmbMotivationDetailCode, TextBox ATxtDetailRecipientKeyMinistry, ref string AMotivationDetail, bool AActiveOnly,
            bool ATransactionsLoadedFlag, bool AInEditModeFlag, bool ABatchUnpostedFlag)
        {
            if (!ATxtDetailRecipientKeyMinistry.Visible)
            {
                SetTextBoxOverlayOnKeyMinistryCombo(ACurrentDetailRow, AActiveOnly, ACmbKeyMinistries, ACmbMotivationDetailCode,
                    ATxtDetailRecipientKeyMinistry, ref AMotivationDetail, AInEditModeFlag, ABatchUnpostedFlag, true);
            }
            else if (!ATransactionsLoadedFlag)
            {
                SetTextBoxOverlayOnKeyMinistryCombo(ACurrentDetailRow, AActiveOnly, ACmbKeyMinistries, ACmbMotivationDetailCode,
                    ATxtDetailRecipientKeyMinistry, ref AMotivationDetail, AInEditModeFlag, ABatchUnpostedFlag);
            }

            if (ACurrentDetailRow == null)
            {
                return false;
            }

            return true;
        }
        /// <summary>
        /// Call when the Motivation Detail changes
        /// </summary>
        public static void OnMotivationDetailChanged(GiftBatchTDSAGiftDetailRow ACurrentDetailRow,
            GiftBatchTDS AMainDS,
            Int32 ALedgerNumber,
            TFrmPetraEditUtils APetraUtilsObject,
            TCmbAutoPopulated ACmbKeyMinistries,
            TCmbAutoPopulated ACmbMotivationDetailCode,
            TtxtAutoPopulatedButtonLabel ATxtDetailRecipientKey,
            Int64 ARecipientKey,
            TtxtAutoPopulatedButtonLabel AtxtDetailRecipientLedgerNumber,
            TextBox ATxtDetailCostCentreCode,
            TextBox ATxtDetailAccountCode,
            TextBox ATxtDetailRecipientKeyMinistry,
            CheckBox AChkDetailTaxDeductible,
            TextBox ATxtDeductibleAccount,
            string AMotivationGroup,
            ref string AMotivationDetail,
            ref bool AMotivationDetailChangedFlag,
            bool ARecipientKeyChangingFlag,
            bool ACreatingNewGiftFlag,
            bool AInEditModeFlag,
            bool ABatchUnpostedFlag,
            bool ATaxDeductiblePercentageEnabledFlag,
            bool AAutoPopulatingGift,
            out bool ADoTaxUpdate,
            out string AAutoPopComment)
        {
            ADoTaxUpdate = false;
            AAutoPopComment = null;

            if (!ABatchUnpostedFlag || !AInEditModeFlag || ATxtDetailRecipientKeyMinistry.Visible)
            {
                return;
            }

            Int64 MotivationRecipientKey = 0;
            AMotivationDetail = ACmbMotivationDetailCode.GetSelectedString();

            if (AMotivationDetail.Length > 0)
            {
                AMotivationDetailRow motivationDetail = (AMotivationDetailRow)AMainDS.AMotivationDetail.Rows.Find(
                    new object[] { ALedgerNumber, AMotivationGroup, AMotivationDetail });

                ACmbMotivationDetailCode.RefreshLabel();

                if (motivationDetail != null)
                {
                    RetrieveMotivationDetailAccountCode(motivationDetail,
                        ATxtDetailAccountCode,
                        ATxtDeductibleAccount,
                        ATaxDeductiblePercentageEnabledFlag);

                    MotivationRecipientKey = motivationDetail.RecipientKey;

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

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

                    if (ATaxDeductiblePercentageEnabledFlag)
                    {
                        if (string.IsNullOrEmpty(motivationDetail.TaxDeductibleAccount))
                        {
                            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
                {
                    AChkDetailTaxDeductible.Checked = false;
                }
            }

            if (!ACreatingNewGiftFlag && !AAutoPopulatingGift && (MotivationRecipientKey > 0))
            {
                AMotivationDetailChangedFlag = true;
                PopulateKeyMinistry(ACurrentDetailRow,
                    ACmbKeyMinistries,
                    ATxtDetailRecipientKey,
                    AtxtDetailRecipientLedgerNumber,
                    AMotivationDetailChangedFlag,
                    MotivationRecipientKey);
                AMotivationDetailChangedFlag = false;
            }
            else if (ARecipientKey == 0)
            {
                UpdateRecipientKeyText(0, ACurrentDetailRow, AMotivationGroup, AMotivationDetail);
            }

            if (ARecipientKey == 0)
            {
                RetrieveMotivationDetailCostCentreCode(AMainDS, ALedgerNumber, ATxtDetailCostCentreCode, AMotivationGroup, AMotivationDetail);
            }
            else
            {
                string NewCCCode = TRemote.MFinance.Gift.WebConnectors.RetrieveCostCentreCodeForRecipient(ALedgerNumber,
                    ARecipientKey,
                    ACurrentDetailRow.RecipientLedgerNumber,
                    ACurrentDetailRow.DateEntered,
                    AMotivationGroup,
                    AMotivationDetail);

                if (ATxtDetailCostCentreCode.Text != NewCCCode)
                {
                    ATxtDetailCostCentreCode.Text = NewCCCode;
                }
            }
        }
        /// <summary>
        /// Call when the recipient key changes
        /// </summary>
        public static void OnRecipientKeyChanged(Int64 APartnerKey,
            String APartnerShortName,
            bool AValidSelection,
            GiftBatchTDSAGiftDetailRow ACurrentDetailRow,
            GiftBatchTDS AMainDS,
            Int32 ALedgerNumber,
            TFrmPetraEditUtils APetraUtilsObject,
            ref TCmbAutoPopulated ACmbKeyMinistries,
            TCmbAutoPopulated ACmbMotivationGroupCode,
            TCmbAutoPopulated ACmbMotivationDetailCode,
            TtxtAutoPopulatedButtonLabel ATxtDetailRecipientKey,
            TtxtAutoPopulatedButtonLabel AtxtDetailRecipientLedgerNumber,
            TextBox ATxtDetailCostCentreCode,
            TextBox ATxtDetailAccountCode,
            TextBox ATxtDetailRecipientKeyMinistry,
            CheckBox AChkDetailTaxDeductible,
            TextBox ATxtDeductibleAccount,
            ref string AMotivationGroup,
            ref string AMotivationDetail,
            bool AShowingDetailsFlag,
            ref bool ARecipientKeyChangingFlag,
            bool AInKeyMinistryChangingFlag,
            bool AInEditModeFlag,
            bool ABatchUnpostedFlag,
            bool AMotivationDetailChangedFlag,
            bool ATaxDeductiblePercentageEnabledFlag,
            bool ACreatingNewGiftFlag,
            bool AActiveOnly,
            out bool ADoValidateGiftDestination,
            out bool ADoTaxUpdate)
        {
            ADoValidateGiftDestination = false;
            ADoTaxUpdate = false;

            if (ARecipientKeyChangingFlag || APetraUtilsObject.SuppressChangeDetection || AShowingDetailsFlag)
            {
                return;
            }

            ARecipientKeyChangingFlag = true;
            ATxtDetailRecipientKeyMinistry.Text = string.Empty;

            try
            {
                ACurrentDetailRow.RecipientKey = APartnerKey;
                ACurrentDetailRow.RecipientDescription = APartnerShortName;

                // do not want to update motivation comboboxes if recipient key is being changed due to a new gift or the motivation detail being changed
                if (!AMotivationDetailChangedFlag && !ACreatingNewGiftFlag
                    && TRemote.MFinance.Gift.WebConnectors.GetMotivationGroupAndDetail(APartnerKey, ref AMotivationGroup, ref AMotivationDetail))
                {
                    if (AMotivationGroup != ACmbMotivationGroupCode.GetSelectedString())
                    {
                        // note - this will also update the Motivation Detail
                        ACmbMotivationGroupCode.SetSelectedString(AMotivationGroup);
                    }

                    if (AMotivationDetail != ACmbMotivationDetailCode.GetSelectedString())
                    {
                        ACmbMotivationDetailCode.SetSelectedString(AMotivationDetail);
                    }

                    ACurrentDetailRow.MotivationGroupCode = AMotivationGroup;
                    ACurrentDetailRow.MotivationDetailCode = AMotivationDetail;
                }

                APetraUtilsObject.SuppressChangeDetection = true;

                //Set RecipientLedgerNumber
                if (APartnerKey > 0)
                {
                    ACurrentDetailRow.RecipientLedgerNumber = TRemote.MFinance.Gift.WebConnectors.GetRecipientFundNumber(APartnerKey,
                        ACurrentDetailRow.DateEntered);
                }
                else
                {
                    ACurrentDetailRow.RecipientLedgerNumber = 0;
                }

                if (!AInKeyMinistryChangingFlag)
                {
                    GetRecipientData(ACurrentDetailRow,
                        APartnerKey,
                        ref ACmbKeyMinistries,
                        ATxtDetailRecipientKey,
                        ref AtxtDetailRecipientLedgerNumber,
                        AMotivationDetailChangedFlag);
                    ADoValidateGiftDestination = true;
                }

                if (APartnerKey > 0)
                {
                    RetrieveRecipientCostCentreCode(ACurrentDetailRow, ATxtDetailCostCentreCode);
                }
                else
                {
                    UpdateRecipientKeyText(APartnerKey, ACurrentDetailRow, AMotivationGroup, AMotivationDetail);
                    RetrieveMotivationDetailCostCentreCode(AMainDS, ALedgerNumber, ATxtDetailCostCentreCode, AMotivationGroup, AMotivationDetail);
                }

                if (ATaxDeductiblePercentageEnabledFlag)
                {
                    ADoTaxUpdate = true;
                }
            }
            finally
            {
                ARecipientKeyChangingFlag = false;
                ReconcileKeyMinistryFromCombo(ACurrentDetailRow,
                    ACmbKeyMinistries,
                    ATxtDetailRecipientKeyMinistry,
                    AInEditModeFlag,
                    ABatchUnpostedFlag);

                APetraUtilsObject.SuppressChangeDetection = false;
            }
        }
        /// <summary>
        /// Call from ShowDetailsManual after ACurrentDetailRow is known to be non-NULL
        /// </summary>
        public static void FinishShowDetailsManual(GiftBatchTDSAGiftDetailRow ACurrentDetailRow, TCmbAutoPopulated ACmbMotivationDetailCode,
            TtxtAutoPopulatedButtonLabel ATxtDetailRecipientKey, TtxtAutoPopulatedButtonLabel AtxtDetailRecipientLedgerNumber,
            TextBox ATxtDetailCostCentreCode, TextBox ATxtDetailAccountCode, ref string AMotivationGroup, ref string AMotivationDetail,
            out bool ? AEnableRecipientGiftDestination)
        {
            AEnableRecipientGiftDestination = null;

            //Record current values for motivation
            AMotivationGroup = ACurrentDetailRow.MotivationGroupCode;
            AMotivationDetail = ACurrentDetailRow.MotivationDetailCode;

            if (ACurrentDetailRow.IsCostCentreCodeNull())
            {
                ATxtDetailCostCentreCode.Text = string.Empty;
            }
            else
            {
                ATxtDetailCostCentreCode.Text = ACurrentDetailRow.CostCentreCode;
            }

            if (ACurrentDetailRow.IsAccountCodeNull())
            {
                ATxtDetailAccountCode.Text = string.Empty;
            }
            else
            {
                ATxtDetailAccountCode.Text = ACurrentDetailRow.AccountCode;
            }

            if (ACurrentDetailRow.IsRecipientKeyNull())
            {
                ATxtDetailRecipientKey.Text = String.Format("{0:0000000000}", 0);
                UpdateRecipientKeyText(0, ACurrentDetailRow, AMotivationGroup, AMotivationDetail);
            }
            else
            {
                ATxtDetailRecipientKey.Text = String.Format("{0:0000000000}", ACurrentDetailRow.RecipientKey);
                UpdateRecipientKeyText(ACurrentDetailRow.RecipientKey, ACurrentDetailRow, AMotivationGroup, AMotivationDetail);
            }

            if (Convert.ToInt64(ATxtDetailRecipientKey.Text) == 0)
            {
                OnRecipientPartnerClassChanged(null, ATxtDetailRecipientKey, AtxtDetailRecipientLedgerNumber, out AEnableRecipientGiftDestination);
            }

            if (Convert.ToInt64(AtxtDetailRecipientLedgerNumber.Text) == 0)
            {
                OnRecipientPartnerClassChanged(ATxtDetailRecipientKey.CurrentPartnerClass,
                    ATxtDetailRecipientKey,
                    AtxtDetailRecipientLedgerNumber,
                    out AEnableRecipientGiftDestination);
            }
        }
        /// <summary>
        /// PopulateKeyMinistry
        /// </summary>
        private static void PopulateKeyMinistry(GiftBatchTDSAGiftDetailRow ACurrentDetailRow,
            TCmbAutoPopulated ACmbKeyMinistries,
            TtxtAutoPopulatedButtonLabel ATxtDetailRecipientKey,
            TtxtAutoPopulatedButtonLabel AtxtDetailRecipientLedgerNumber,
            bool AMotivationDetailChangedFlag,
            long APartnerKey = 0)
        {
            ACmbKeyMinistries.Clear();

            if (APartnerKey == 0)
            {
                APartnerKey = Convert.ToInt64(ATxtDetailRecipientKey.Text);

                if (APartnerKey == 0)
                {
                    return;
                }
            }

            GetRecipientData(ACurrentDetailRow,
                APartnerKey,
                ref ACmbKeyMinistries,
                ATxtDetailRecipientKey,
                ref AtxtDetailRecipientLedgerNumber,
                AMotivationDetailChangedFlag);
        }
 private void PostDeleteManual(GiftBatchTDSAGiftDetailRow ARowToDelete,
     bool AAllowDeletion,
     bool ADeletionPerformed,
     string ACompletionMessage)
 {
     OnPostDeleteManual(ARowToDelete, AAllowDeletion, ADeletionPerformed, ACompletionMessage);
 }
        /// <summary>
        /// update the transaction DateEntered from outside
        /// </summary>
        /// <param name="ABatchRow"></param>
        public void UpdateDateEntered(AGiftBatchRow ABatchRow)
        {
            Int32    ledgerNumber;
            Int32    batchNumber;
            DateTime batchEffectiveDate;

            if (ABatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)
            {
                return;
            }

            ledgerNumber       = ABatchRow.LedgerNumber;
            batchNumber        = ABatchRow.BatchNumber;
            batchEffectiveDate = ABatchRow.GlEffectiveDate;

            DataView giftDataView = new DataView(FMainDS.AGift);

            giftDataView.RowFilter = String.Format("{0}={1} And {2}={3}",
                                                   AGiftTable.GetLedgerNumberDBName(),
                                                   ledgerNumber,
                                                   AGiftTable.GetBatchNumberDBName(),
                                                   batchNumber);

            DataView giftDetailDataView = new DataView(FMainDS.AGiftDetail);

            giftDetailDataView.RowFilter = String.Format("{0}={1} And {2}={3}",
                                                         AGiftDetailTable.GetLedgerNumberDBName(),
                                                         ledgerNumber,
                                                         AGiftDetailTable.GetBatchNumberDBName(),
                                                         batchNumber);

            ((TFrmGiftBatch)ParentForm).EnsureGiftDataPresent(ledgerNumber, batchNumber);

            if ((FPreviouslySelectedDetailRow != null) && (FBatchNumber == batchNumber))
            {
                //Rows already active in transaction tab. Need to set current row as code below will not update currently selected row
                FGLEffectivePeriodHasChangedFlag   = true;
                GetSelectedDetailRow().DateEntered = batchEffectiveDate;
            }

            TFrmGiftBatch ParentGiftBatchForm = (TFrmGiftBatch)ParentForm;

            ParentGiftBatchForm.Cursor = Cursors.WaitCursor;

            //Update all gift rows in this batch
            foreach (DataRowView dv in giftDataView)
            {
                AGiftRow giftRow = (AGiftRow)dv.Row;
                giftRow.DateEntered = batchEffectiveDate;
            }

            //Update all gift detail rows in this batch
            foreach (DataRowView dv in giftDetailDataView)
            {
                GiftBatchTDSAGiftDetailRow giftDetailRow = (GiftBatchTDSAGiftDetailRow)dv.Row;
                UpdateGiftDestinationOnDateChange(ref giftDetailRow, batchEffectiveDate);
            }

            ParentGiftBatchForm.Cursor = Cursors.Default;

            //If current row exists then refresh details
            if (FGLEffectivePeriodHasChangedFlag)
            {
                ShowDetails();
            }
        }
        /// <summary>
        /// Call when the motivation group changes
        /// </summary>
        public static void OnMotivationGroupChanged(GiftBatchTDSAGiftDetailRow AGiftBatchDetail,
            GiftBatchTDS AMainDS,
            Int32 ALedgerNumber,
            TFrmPetraEditUtils APetraUtilsObject,
            TCmbAutoPopulated ACmbKeyMinistries,
            TCmbAutoPopulated ACmbMotivationGroupCode,
            ref TCmbAutoPopulated ACmbMotivationDetailCode,
            TtxtAutoPopulatedButtonLabel ATxtDetailRecipientKey,
            Int64 ARecipientKey,
            TtxtAutoPopulatedButtonLabel AtxtDetailRecipientLedgerNumber,
            TextBox ATxtDetailCostCentreCode,
            TextBox ATxtDetailAccountCode,
            TextBox ATxtDetailRecipientKeyMinistry,
            CheckBox AChkDetailTaxDeductible,
            TextBox ATxtDeductibleAccount,
            ref string AMotivationGroup,
            ref string AMotivationDetail,
            ref bool AMotivationDetailChangedFlag,
            bool AActiveOnly,
            bool ACreatingNewGiftFlag,
            bool ARecipientKeyChangingFlag,
            bool AInEditModeFlag,
            bool ABatchUnpostedFlag,
            bool ATaxDeductiblePercentageEnabledFlag,
            out bool ADoTaxUpdate)
        {
            if (!ABatchUnpostedFlag || APetraUtilsObject.SuppressChangeDetection || !AInEditModeFlag || ATxtDetailRecipientKeyMinistry.Visible)
            {
                ADoTaxUpdate = false;
                return;
            }

            AMotivationGroup = ACmbMotivationGroupCode.GetSelectedString();

            if (!ARecipientKeyChangingFlag)
            {
                AMotivationDetail = string.Empty;
            }

            ApplyMotivationDetailCodeFilter(AGiftBatchDetail,
                AMainDS,
                ALedgerNumber,
                APetraUtilsObject,
                ACmbKeyMinistries,
                ref ACmbMotivationDetailCode,
                ATxtDetailRecipientKey,
                ARecipientKey,
                AtxtDetailRecipientLedgerNumber,
                ATxtDetailCostCentreCode,
                ATxtDetailAccountCode,
                ATxtDetailRecipientKeyMinistry,
                AChkDetailTaxDeductible,
                ATxtDeductibleAccount,
                AMotivationGroup,
                ref AMotivationDetail,
                ref AMotivationDetailChangedFlag,
                AActiveOnly,
                ARecipientKeyChangingFlag,
                ACreatingNewGiftFlag,
                AInEditModeFlag,
                ABatchUnpostedFlag,
                ATaxDeductiblePercentageEnabledFlag,
                out ADoTaxUpdate);
        }
        /// <summary>
        /// Keep the combo and textboxes together
        /// </summary>
        private static void ReconcileKeyMinistryFromTextbox(GiftBatchTDSAGiftDetailRow ACurrentDetailRow, TCmbAutoPopulated ACmbKeyMinistries,
            TextBox ATxtDetailRecipientKeyMinistry, bool AInEditModeFlag, bool ABatchUnpostedFlag)
        {
            if (ABatchUnpostedFlag && AInEditModeFlag)
            {
                bool isEmptyDetailRow = (ACurrentDetailRow == null);
                string keyMinistry = ATxtDetailRecipientKeyMinistry.Text;

                if (!isEmptyDetailRow && (keyMinistry.Length > 0))
                {
                    ACmbKeyMinistries.SetSelectedString(keyMinistry);
                }
                else
                {
                    ACmbKeyMinistries.SelectedIndex = -1;
                }
            }
        }
Example #36
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);

            FCreatingNewGift = true;

            try
            {
                if (ValidateAllData(true, true))
                {
                    if (!ACompletelyNewGift)      //i.e. a gift detail
                    {
                        ACompletelyNewGift = IsEmptyGrid;
                    }

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

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

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

                        FMainDS.AGift.Rows.Add(giftRow);

                        CurrentGiftRow = giftRow;

                        mniDonorHistory.Enabled = false;
                    }
                    else
                    {
                        CurrentGiftRow = GetGiftRow(FPreviouslySelectedDetailRow.GiftTransactionNumber);
                        CurrentGiftRow.LastDetailNumber++;
                    }

                    //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 (!ACompletelyNewGift && (FPreviouslySelectedDetailRow != null))
                    {
                        newRow.DonorName            = FPreviouslySelectedDetailRow.DonorName;
                        newRow.ConfidentialGiftFlag = FPreviouslySelectedDetailRow.ConfidentialGiftFlag;
                        newRow.ChargeFlag           = FPreviouslySelectedDetailRow.ChargeFlag;
                        newRow.TaxDeductible        = FPreviouslySelectedDetailRow.TaxDeductible;
                        newRow.MotivationGroupCode  = FPreviouslySelectedDetailRow.MotivationGroupCode;
                        newRow.MotivationDetailCode = FPreviouslySelectedDetailRow.MotivationDetailCode;
                    }
                    else
                    {
                        newRow.MotivationGroupCode  = MFinanceConstants.MOTIVATION_GROUP_GIFT;
                        newRow.MotivationDetailCode = MFinanceConstants.GROUP_DETAIL_SUPPORT;
                    }

                    newRow.DateEntered = CurrentGiftRow.DateEntered;

                    if (FTaxDeductiblePercentageEnabled)
                    {
                        newRow.TaxDeductiblePct = 100;
                    }

                    FMainDS.AGiftDetail.Rows.Add(newRow);

                    FPetraUtilsObject.SetChangedFlag();

                    if (!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 && (FFilterAndFindObject.IsActiveFilterEqualToBase);
                    UpdateRecordNumberDisplay();
                    FLastDonor = -1;

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

                    TUC_GiftTransactions_Recipient.UpdateRecipientKeyText(0,
                                                                          FPreviouslySelectedDetailRow,
                                                                          cmbDetailMotivationGroupCode.GetSelectedString(),
                                                                          cmbDetailMotivationDetailCode.GetSelectedString());
                    cmbKeyMinistries.Clear();
                    mniRecipientHistory.Enabled = false;
                }
            }
            finally
            {
                FCreatingNewGift = false;
            }
        }
        /// <summary>
        /// RetrieveRecipientCostCentreCode
        /// </summary>
        private static void RetrieveRecipientCostCentreCode(GiftBatchTDSAGiftDetailRow ARow, TextBox ATxtDetailCostCentreCode)
        {
            if (ARow == null)
            {
                return;
            }

            try
            {
                string NewCostCentreCode = TRemote.MFinance.Gift.WebConnectors.RetrieveCostCentreCodeForRecipient(ARow.LedgerNumber,
                    ARow.RecipientKey,
                    ARow.RecipientLedgerNumber,
                    ARow.DateEntered,
                    ARow.MotivationGroupCode,
                    ARow.MotivationDetailCode);

                if (ARow.CostCentreCode != NewCostCentreCode)
                {
                    ARow.CostCentreCode = NewCostCentreCode;
                }
            }
            catch (Exception ex)
            {
                string errMsg = Catalog.GetString("Error accessing Cost Centre Code:" + Environment.NewLine + ex.Message);

                MessageBox.Show(errMsg, "Cost Centre Code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            if (ATxtDetailCostCentreCode.Text != ARow.CostCentreCode)
            {
                ATxtDetailCostCentreCode.Text = ARow.CostCentreCode;
            }
        }
Example #38
0
        /// <summary>
        /// Validates the Gift Detail data.
        /// </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="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>True if the validation found no data validation errors, otherwise false.</returns>
        public static bool ValidateTaxDeductiblePct(object AContext,
            GiftBatchTDSAGiftDetailRow ARow,
            ref TVerificationResultCollection AVerificationResultCollection,
            TValidationControlsDict AValidationControlsDict)
        {
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TVerificationResult VerificationResult = null;
            object ValidationContext;
            int VerifResultCollAddedCount = 0;

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

            // Tax deductible account code must not be null or empty string if there is a percent specified
            ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnTaxDeductiblePctId];
            ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})",
                ARow.BatchNumber,
                ARow.GiftTransactionNumber,
                ARow.DetailNumber);

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                // it should be impossible for this to ever happen
                if (ARow.TaxDeductiblePct != 0)
                {
                    VerificationResult = TGeneralChecks.ValueMustNotBeNullOrEmptyString(ARow.TaxDeductibleAccountCode,
                        "Tax-Deductible Account " + ValidationContext,
                        AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                    // Handle addition/removal to/from TVerificationResultCollection
                    if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true))
                    {
                        VerifResultCollAddedCount++;
                    }
                }
            }

            return VerifResultCollAddedCount == 0;
        }
        /// <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;
            }
        }
 private bool PreDeleteManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ADeletionQuestion)
 {
     return OnPreDeleteManual(ARowToDelete, ref ADeletionQuestion);
 }
Example #41
0
        /// <summary>
        /// Validates the Gift Detail data.
        /// </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="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>
        /// <param name="ARecipientPartnerClass">Recipient's Partner Class (used for Motivation Detail validation).</param>
        /// <param name="ASetupForILT">Optional - Is the recipient set up for inter-ledger transfers.</param>
        /// <param name="ACostCentres">Optional - a CostCentres table.  Is required for import validation. </param>
        /// <param name="AAccounts">Optional - a Accounts table.  Is required for import validation. </param>
        /// <param name="AMotivationGroups">Optional - a MotivationGroups table.  Is required for import validation. </param>
        /// <param name="AMotivationDetails">Optional - a MotivationDetails table.  Is required for import validation. </param>
        /// <param name="AMailingTable">Optional - a Mailing table.  Is required for import validation. </param>
        /// <param name="ARecipientField">Optional The recipient field for the gift.  Is required for import validation. </param>
        /// <returns>True if the validation found no data validation errors, otherwise false.</returns>
        public static bool ValidateGiftDetailManual(object AContext,
            GiftBatchTDSAGiftDetailRow ARow,
            ref TVerificationResultCollection AVerificationResultCollection,
            TValidationControlsDict AValidationControlsDict,
            TPartnerClass? ARecipientPartnerClass,
            bool? ASetupForILT = null,
            ACostCentreTable ACostCentres = null,
            AAccountTable AAccounts = null,
            AMotivationGroupTable AMotivationGroups = null,
            AMotivationDetailTable AMotivationDetails = null,
            PMailingTable AMailingTable = null,
            Int64 ARecipientField = -1)
        {
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TVerificationResult VerificationResult = null;
            object ValidationContext;
            int VerifResultCollAddedCount = 0;
            bool ValidPartner = true;

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

            bool isImporting = AContext.ToString().Contains("Importing");

            // Check if valid recipient
            ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnRecipientKeyId];
            ValidationContext = String.Format("Batch no. {0}, gift no. {1}, detail no. {2}",
                ARow.BatchNumber,
                ARow.GiftTransactionNumber,
                ARow.DetailNumber);

            VerificationResult = TSharedPartnerValidation_Partner.IsValidPartner(
                ARow.RecipientKey, new TPartnerClass[] { TPartnerClass.FAMILY, TPartnerClass.UNIT }, true,
                isImporting ? Catalog.GetString("Recipient key") :
                "Recipient of " + THelper.NiceValueDescription(ValidationContext.ToString()),
                AContext, ValidationColumn, null);

            if (VerificationResult != null)
            {
                AVerificationResultCollection.Remove(ValidationColumn);
                AVerificationResultCollection.AddAndIgnoreNullValue(VerificationResult);
                ValidPartner = false;
            }

            // 'Gift amount must be non-zero
            ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnGiftTransactionAmountId];
            ValidationContext = String.Format("Batch Number {0} (transaction:{1} detail:{2})",
                ARow.BatchNumber,
                ARow.GiftTransactionNumber,
                ARow.DetailNumber);

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                VerificationResult = TNumericalChecks.IsNonZeroDecimal(ARow.GiftTransactionAmount,
                    ValidationControlsData.ValidationControlLabel + (isImporting ? String.Empty : " of " + ValidationContext),
                    AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                // Handle addition/removal to/from TVerificationResultCollection
                if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true))
                {
                    VerifResultCollAddedCount++;
                }
            }

            // If recipient is non-zero, field must also be non-zero. Only check for valid recipient keys.
            ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnRecipientLedgerNumberId];
            ValidationContext = String.Format("batch:{0} transaction:{1} detail:{2}",
                ARow.BatchNumber,
                ARow.GiftTransactionNumber,
                ARow.DetailNumber);

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                if ((ARow.RecipientKey > 0) && ValidPartner && (ARow.RecipientLedgerNumber == 0))
                {
                    VerificationResult = TNumericalChecks.IsGreaterThanZero(ARow.RecipientLedgerNumber,
                        "Recipient field of " + ValidationContext + " is 0",
                        AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                    // Handle addition/removal to/from TVerificationResultCollection
                    if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true))
                    {
                        VerifResultCollAddedCount++;
                    }
                }

                // Motivation Group code must exist
                if (!ARow.IsMotivationGroupCodeNull() && (AMotivationGroups != null))
                {
                    AMotivationGroupRow foundRow = (AMotivationGroupRow)AMotivationGroups.Rows.Find(
                        new object[] { ARow.LedgerNumber, ARow.MotivationGroupCode });

                    if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                            AContext,
                            new TVerificationResult(ValidationContext,
                                String.Format(Catalog.GetString("Unknown motivation group code '{0}'."),
                                    ARow.MotivationGroupCode),
                                TResultSeverity.Resv_Critical),
                            ValidationColumn))
                    {
                        VerifResultCollAddedCount++;
                    }
                }
            }

            if (!isImporting)
            {
                // NOTE AlanP Oct 2014.  This gets checked by standard validation so may no longer be necessary?
                //  (There was a bug in standard validation where NULL and empty string checks did not quite work as they should ...
                //   so maybe this was necessary before.  Anyway I am leaving it in for now.  I know that importing works fine,
                //   but maybe it is necessary in other circumstances?)

                // Motivation Detail must not be null
                ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnMotivationDetailCodeId];
                ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})",
                    ARow.BatchNumber,
                    ARow.GiftTransactionNumber,
                    ARow.DetailNumber);

                if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    if (ARow.IsMotivationDetailCodeNull() || (ARow.MotivationDetailCode == String.Empty))
                    {
                        VerificationResult = TGeneralChecks.ValueMustNotBeNullOrEmptyString(ARow.MotivationDetailCode,
                            (isImporting ? ValidationControlsData.ValidationControlLabel : "Motivation Detail code " + ValidationContext),
                            AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                        // Handle addition/removal to/from TVerificationResultCollection
                        if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }
                }
            }

            // Motivation Detail must be valid
            ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnMotivationDetailCodeId];
            ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})",
                ARow.BatchNumber,
                ARow.GiftTransactionNumber,
                ARow.DetailNumber);

            if (!ARow.IsMotivationDetailCodeNull() && (AMotivationDetails != null))
            {
                AMotivationDetailRow foundRow = (AMotivationDetailRow)AMotivationDetails.Rows.Find(
                    new object[] { ARow.LedgerNumber, ARow.MotivationGroupCode, ARow.MotivationDetailCode });

                if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                        AContext,
                        new TVerificationResult(ValidationContext,
                            String.Format(Catalog.GetString("Unknown motivation detail code '{0}' for group '{1}'."),
                                ARow.MotivationDetailCode, ARow.MotivationGroupCode),
                            TResultSeverity.Resv_Critical),
                        ValidationColumn))
                {
                    VerifResultCollAddedCount++;
                }

                if ((foundRow != null) && (foundRow.MotivationStatus == false) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                        AContext,
                        new TVerificationResult(ValidationContext,
                            String.Format(Catalog.GetString("Motivation detail code '{0}' is no longer in use."),
                                ARow.MotivationDetailCode),
                            TResultSeverity.Resv_Critical),
                        ValidationColumn))
                {
                    VerifResultCollAddedCount++;
                }

                if ((foundRow != null) && (foundRow.RecipientKey != 0) && (ARow.RecipientKey != 0) && (foundRow.RecipientKey != ARow.RecipientKey)
                    && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                        AContext,
                        new TVerificationResult(ValidationContext,
                            String.Format(Catalog.GetString(
                                    "The recipient partner key for motivation detail code '{0}' does not match the recipient partner key in the import line."),
                                ARow.MotivationDetailCode),
                            TResultSeverity.Resv_Critical),
                        ValidationColumn))
                {
                    VerifResultCollAddedCount++;
                }
            }

            // Motivation Detail must not be 'Field' or 'Keymin' if the recipient is a Family partner
            ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnMotivationDetailCodeId];
            ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})",
                ARow.BatchNumber,
                ARow.GiftTransactionNumber,
                ARow.DetailNumber);

            if (!ARow.IsMotivationDetailCodeNull()
                && (ARow.MotivationGroupCode == MFinanceConstants.MOTIVATION_GROUP_GIFT) && (ARecipientPartnerClass != null)
                && ((ARow.MotivationDetailCode == MFinanceConstants.GROUP_DETAIL_FIELD)
                    || (ARow.MotivationDetailCode == MFinanceConstants.GROUP_DETAIL_KEY_MIN))
                && (ARecipientPartnerClass == TPartnerClass.FAMILY))
            {
                if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    VerificationResult = new TVerificationResult(AContext,
                        String.Format(Catalog.GetString("Motivation Detail code '{0}' is not allowed for Family recipients."),
                            ARow.MotivationDetailCode),
                        TResultSeverity.Resv_Critical);

                    if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext,
                            new TScreenVerificationResult(VerificationResult, ValidationColumn, ValidationControlsData.ValidationControl),
                            ValidationColumn, true))
                    {
                        VerifResultCollAddedCount++;
                    }
                }
            }

            // Cost Centre Code must exist and be active.  Only required for importing because the GUI does this for us otherwise.
            if (isImporting && (ACostCentres != null) && !ARow.IsCostCentreCodeNull())
            {
                ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnCostCentreCodeId];
                ValidationContext = ARow.CostCentreCode;

                if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    // We even need to check that the code exists!
                    DataRow foundRow = ACostCentres.Rows.Find(new object[] { ARow.LedgerNumber, ARow.CostCentreCode });

                    if ((foundRow == null)
                        && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                            AContext,
                            new TScreenVerificationResult(ValidationContext,
                                ValidationColumn,
                                String.Format(Catalog.GetString("Unknown cost centre code '{0}'."), ARow.CostCentreCode),
                                ValidationControlsData.ValidationControl,
                                TResultSeverity.Resv_Critical),

/*
 *                          new TVerificationResult(ValidationContext,
 *                              String.Format(Catalog.GetString("Unknown cost centre code '{0}'."), ARow.CostCentreCode),
 *                              TResultSeverity.Resv_Critical),
 */
                            ValidationColumn))
                    {
                        VerifResultCollAddedCount++;
                    }

                    VerificationResult = (TScreenVerificationResult)TStringChecks.ValidateValueIsActive(ARow.LedgerNumber,
                        ACostCentres,
                        ValidationContext.ToString(),
                        ACostCentreTable.GetCostCentreActiveFlagDBName(),
                        AContext,
                        ValidationColumn,
                        ValidationControlsData.ValidationControl);

                    // Handle addition/removal to/from TVerificationResultCollection
                    if ((VerificationResult != null)
                        && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true))
                    {
                        VerifResultCollAddedCount++;
                    }
                }
            }

            // Account Code must exist and be active.  Only required for importing because the GUI does this for us otherwise.
            if (isImporting && (AAccounts != null) && !ARow.IsAccountCodeNull())
            {
                DataColumn[] ValidationColumns = new DataColumn[] {
                    ARow.Table.Columns[AGiftDetailTable.ColumnAccountCodeId], ARow.Table.Columns[AGiftDetailTable.ColumnTaxDeductibleAccountCodeId]
                };
                string[] AccountCodes = new string[] {
                    ARow.AccountCode, ARow.TaxDeductibleAccountCode
                };

                for (int i = 0; i < 2; i++)
                {
                    if (AValidationControlsDict.TryGetValue(ValidationColumns[i], out ValidationControlsData))
                    {
                        // We even need to check that the code exists!
                        DataRow foundRow = AAccounts.Rows.Find(new object[] { ARow.LedgerNumber, AccountCodes[i] });

                        if ((foundRow == null)
                            && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                AContext,
                                new TVerificationResult(AccountCodes[i],
                                    String.Format(Catalog.GetString("Unknown account code '{0}'."), AccountCodes[i]),
                                    TResultSeverity.Resv_Critical),
                                ValidationColumns[i]))
                        {
                            VerifResultCollAddedCount++;
                        }

                        VerificationResult = (TScreenVerificationResult)TStringChecks.ValidateValueIsActive(ARow.LedgerNumber,
                            AAccounts,
                            AccountCodes[i],
                            AAccountTable.GetAccountActiveFlagDBName(),
                            AContext,
                            ValidationColumns[i],
                            ValidationControlsData.ValidationControl);

                        // Handle addition/removal to/from TVerificationResultCollection
                        if ((VerificationResult != null)
                            && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumns[i], true))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }
                }
            }

            // Mailing code must exist
            ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnMailingCodeId];
            ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})",
                ARow.BatchNumber,
                ARow.GiftTransactionNumber,
                ARow.DetailNumber);

            if (!ARow.IsMailingCodeNull() && (AMailingTable != null))
            {
                PMailingRow foundRow = (PMailingRow)AMailingTable.Rows.Find(ARow.MailingCode);

                if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                        AContext,
                        new TVerificationResult(ValidationContext,
                            String.Format(Catalog.GetString("Unknown mailing code '{0}'."),
                                ARow.MailingCode),
                            TResultSeverity.Resv_Critical),
                        ValidationColumn))
                {
                    VerifResultCollAddedCount++;
                }
            }

            // Detail comments type 1 must not be null if associated comment is not null
            ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnCommentOneTypeId];
            ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})",
                ARow.BatchNumber,
                ARow.GiftTransactionNumber,
                ARow.DetailNumber);

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                if (!ARow.IsGiftCommentOneNull() && (ARow.GiftCommentOne != String.Empty))
                {
                    VerificationResult = TGeneralChecks.ValueMustNotBeNullOrEmptyString(ARow.CommentOneType,
                        (isImporting ? ValidationControlsData.ValidationControlLabel : "Comment 1 type " + ValidationContext),
                        AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                    // Handle addition/removal to/from TVerificationResultCollection
                    if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true))
                    {
                        VerifResultCollAddedCount++;
                    }

                    if (VerificationResult == null)
                    {
                        // There is a comment type for the comment - but it needs to be one of the valid types
                        if ((ARow.CommentOneType != MFinanceConstants.GIFT_COMMENT_TYPE_DONOR)
                            && (ARow.CommentOneType != MFinanceConstants.GIFT_COMMENT_TYPE_RECIPIENT)
                            && (ARow.CommentOneType != MFinanceConstants.GIFT_COMMENT_TYPE_BOTH)
                            && (ARow.CommentOneType != MFinanceConstants.GIFT_COMMENT_TYPE_OFFICE)
                            && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                AContext,
                                new TVerificationResult(ValidationContext,
                                    String.Format(Catalog.GetString("Comment type must be one of '{0}', '{1}', '{2}' or '{3}'."),
                                        MFinanceConstants.GIFT_COMMENT_TYPE_DONOR,
                                        MFinanceConstants.GIFT_COMMENT_TYPE_RECIPIENT,
                                        MFinanceConstants.GIFT_COMMENT_TYPE_BOTH,
                                        MFinanceConstants.GIFT_COMMENT_TYPE_OFFICE),
                                    TResultSeverity.Resv_Critical),
                                ValidationColumn))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }
                }
            }

            // Detail comments type 2 must not be null if associated comment is not null
            ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnCommentTwoTypeId];
            ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})",
                ARow.BatchNumber,
                ARow.GiftTransactionNumber,
                ARow.DetailNumber);

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                if (!ARow.IsGiftCommentTwoNull() && (ARow.GiftCommentTwo != String.Empty))
                {
                    VerificationResult = TGeneralChecks.ValueMustNotBeNullOrEmptyString(ARow.CommentTwoType,
                        (isImporting ? ValidationControlsData.ValidationControlLabel : "Comment 2 type " + ValidationContext),
                        AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                    // Handle addition/removal to/from TVerificationResultCollection
                    if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true))
                    {
                        VerifResultCollAddedCount++;
                    }

                    if (VerificationResult == null)
                    {
                        // There is a comment type for the comment - but it needs to be one of the valid types
                        if ((ARow.CommentTwoType != MFinanceConstants.GIFT_COMMENT_TYPE_DONOR)
                            && (ARow.CommentTwoType != MFinanceConstants.GIFT_COMMENT_TYPE_RECIPIENT)
                            && (ARow.CommentTwoType != MFinanceConstants.GIFT_COMMENT_TYPE_BOTH)
                            && (ARow.CommentTwoType != MFinanceConstants.GIFT_COMMENT_TYPE_OFFICE)
                            && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                AContext,
                                new TVerificationResult(ValidationContext,
                                    String.Format(Catalog.GetString("Comment type must be one of '{0}', '{1}', '{2}' or '{3}'."),
                                        MFinanceConstants.GIFT_COMMENT_TYPE_DONOR,
                                        MFinanceConstants.GIFT_COMMENT_TYPE_RECIPIENT,
                                        MFinanceConstants.GIFT_COMMENT_TYPE_BOTH,
                                        MFinanceConstants.GIFT_COMMENT_TYPE_OFFICE),
                                    TResultSeverity.Resv_Critical),
                                ValidationColumn))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }
                }
            }

            // Detail comments type 3 must not be null if associated comment is not null
            ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnCommentThreeTypeId];
            ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})",
                ARow.BatchNumber,
                ARow.GiftTransactionNumber,
                ARow.DetailNumber);

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                if (!ARow.IsGiftCommentThreeNull() && (ARow.GiftCommentThree != String.Empty))
                {
                    VerificationResult = TGeneralChecks.ValueMustNotBeNullOrEmptyString(ARow.CommentThreeType,
                        (isImporting ? ValidationControlsData.ValidationControlLabel : "Comment 3 type " + ValidationContext),
                        AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                    // Handle addition/removal to/from TVerificationResultCollection
                    if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true))
                    {
                        VerifResultCollAddedCount++;
                    }

                    if (VerificationResult == null)
                    {
                        // There is a comment type for the comment - but it needs to be one of the valid types
                        if ((ARow.CommentThreeType != MFinanceConstants.GIFT_COMMENT_TYPE_DONOR)
                            && (ARow.CommentThreeType != MFinanceConstants.GIFT_COMMENT_TYPE_RECIPIENT)
                            && (ARow.CommentThreeType != MFinanceConstants.GIFT_COMMENT_TYPE_BOTH)
                            && (ARow.CommentThreeType != MFinanceConstants.GIFT_COMMENT_TYPE_OFFICE)
                            && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                AContext,
                                new TVerificationResult(ValidationContext,
                                    String.Format(Catalog.GetString("Comment type must be one of '{0}', '{1}', '{2}' or '{3}'."),
                                        MFinanceConstants.GIFT_COMMENT_TYPE_DONOR,
                                        MFinanceConstants.GIFT_COMMENT_TYPE_RECIPIENT,
                                        MFinanceConstants.GIFT_COMMENT_TYPE_BOTH,
                                        MFinanceConstants.GIFT_COMMENT_TYPE_OFFICE),
                                    TResultSeverity.Resv_Critical),
                                ValidationColumn))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }
                }
            }

            return VerifResultCollAddedCount == 0;
        }
Example #42
0
        private bool OnDeleteRowManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ACompletionMessage)
        {
            bool DeletionSuccessful = false;

            List <string> OriginatingDetailRef = new List <string>();

            ACompletionMessage = string.Empty;

            if (ARowToDelete == null)
            {
                return(DeletionSuccessful);
            }

            bool RowToDeleteIsNew = (ARowToDelete.RowState == DataRowState.Added);

            if (!RowToDeleteIsNew)
            {
                try
                {
                    // temporarily disable  New Donor Warning
                    ((TFrmGiftBatch)this.ParentForm).NewDonorWarning = false;

                    //Return modified row to last saved state to avoid validation failures
                    ARowToDelete.RejectChanges();
                    ShowDetails(ARowToDelete);

                    if (!((TFrmGiftBatch)this.ParentForm).SaveChanges())
                    {
                        MessageBox.Show(Catalog.GetString("Error in trying to save prior to deleting current gift detail!"),
                                        Catalog.GetString("Deletion Error"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);

                        return(DeletionSuccessful);
                    }
                }
                finally
                {
                    ((TFrmGiftBatch)this.ParentForm).NewDonorWarning = true;
                }
            }

            //Backup the Dataset for reversion purposes
            GiftBatchTDS BackupMainDS = (GiftBatchTDS)FMainDS.Copy();

            BackupMainDS.Merge(FMainDS);

            //To be used later....Pass copy to delete method.
            //GiftBatchTDS TempDS = (GiftBatchTDS)FMainDS.Copy();
            //TempDS.Merge(FMainDS);

            int    SelectedDetailNumber        = ARowToDelete.DetailNumber;
            int    GiftToDeleteTransNo         = 0;
            string FilterAllGiftsOfBatch       = String.Empty;
            string FilterAllGiftDetailsOfBatch = String.Empty;

            int DetailRowCount = FGiftDetailView.Count;

            try
            {
                this.Cursor = Cursors.WaitCursor;

                //Speeds up deletion of larger gift sets
                FMainDS.EnforceConstraints = false;

                if ((ARowToDelete.ModifiedDetailKey != null) && (ARowToDelete.ModifiedDetailKey.Length > 0))
                {
                    OriginatingDetailRef.Add(ARowToDelete.ModifiedDetailKey);
                }

                //Delete current detail row
                ARowToDelete.Delete();

                //If there existed (before the delete row above) more than one detail row, then no need to delete gift header row
                if (DetailRowCount > 1)
                {
                    ACompletionMessage = Catalog.GetString("Gift Detail row deleted successfully!");

                    FGiftSelectedForDeletion = false;

                    foreach (DataRowView rv in FGiftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        if (row.DetailNumber > SelectedDetailNumber)
                        {
                            row.DetailNumber--;
                        }
                    }

                    FGift.LastDetailNumber--;

                    FPetraUtilsObject.SetChangedFlag();
                }
                else
                {
                    ACompletionMessage = Catalog.GetString("Gift deleted successfully!");

                    GiftToDeleteTransNo = FGift.GiftTransactionNumber;

                    // Reduce all Gift Detail row Transaction numbers by 1 if they are greater then gift to be deleted
                    FilterAllGiftDetailsOfBatch = String.Format("{0}={1} And {2}>{3}",
                                                                AGiftDetailTable.GetBatchNumberDBName(),
                                                                FBatchNumber,
                                                                AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                GiftToDeleteTransNo);

                    DataView giftDetailView = new DataView(FMainDS.AGiftDetail);
                    giftDetailView.RowFilter = FilterAllGiftDetailsOfBatch;
                    giftDetailView.Sort      = String.Format("{0} ASC", AGiftDetailTable.GetGiftTransactionNumberDBName());

                    foreach (DataRowView rv in giftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        row.GiftTransactionNumber--;
                    }

                    //Cannot delete the gift row, just copy the data of rows above down by 1 row
                    // and then mark the top row for deletion
                    //In other words, bubble the gift row to be deleted to the top
                    FilterAllGiftsOfBatch = String.Format("{0}={1} And {2}>={3}",
                                                          AGiftTable.GetBatchNumberDBName(),
                                                          FBatchNumber,
                                                          AGiftTable.GetGiftTransactionNumberDBName(),
                                                          GiftToDeleteTransNo);

                    DataView giftView = new DataView(FMainDS.AGift);
                    giftView.RowFilter = FilterAllGiftsOfBatch;
                    giftView.Sort      = String.Format("{0} ASC", AGiftTable.GetGiftTransactionNumberDBName());

                    AGiftRow giftRowToReceive  = null;
                    AGiftRow giftRowToCopyDown = null;
                    AGiftRow giftRowCurrent    = null;

                    int currentGiftTransNo = 0;

                    foreach (DataRowView gv in giftView)
                    {
                        giftRowCurrent = (AGiftRow)gv.Row;

                        currentGiftTransNo = giftRowCurrent.GiftTransactionNumber;

                        if (currentGiftTransNo > GiftToDeleteTransNo)
                        {
                            giftRowToCopyDown = giftRowCurrent;

                            //Copy column values down
                            for (int j = 3; j < giftRowToCopyDown.Table.Columns.Count; j++)
                            {
                                //Update all columns except the pk fields that remain the same
                                if (!giftRowToCopyDown.Table.Columns[j].ColumnName.EndsWith("_text"))
                                {
                                    giftRowToReceive[j] = giftRowToCopyDown[j];
                                }
                            }
                        }

                        if (currentGiftTransNo == FBatchRow.LastGiftNumber)
                        {
                            //Mark last record for deletion
                            giftRowCurrent.GiftStatus = MFinanceConstants.MARKED_FOR_DELETION;
                        }

                        //Will always be previous row
                        giftRowToReceive = giftRowCurrent;
                    }

                    FPreviouslySelectedDetailRow = null;

                    FPetraUtilsObject.SetChangedFlag();

                    FGiftSelectedForDeletion = true;

                    FBatchRow.LastGiftNumber--;
                }

                //Try to save changes
                if (((TFrmGiftBatch)this.ParentForm).SaveChangesManual())
                {
                    //Check if have deleted a reversing gift detail
                    if (OriginatingDetailRef.Count > 0)
                    {
                        TRemote.MFinance.Gift.WebConnectors.ReversedGiftReset(FLedgerNumber, OriginatingDetailRef);
                    }

                    //Clear current batch's gift data and reload from server
                    RefreshCurrentBatchGiftData(FBatchNumber, true);
                }
                else
                {
                    throw new Exception("Unable to save after deleting a gift!");
                }

                DeletionSuccessful = true;
            }
            catch (Exception ex)
            {
                //Revert to previous state
                RevertDataSet(FMainDS, BackupMainDS);

                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                FMainDS.EnforceConstraints = true;
                SetGiftDetailDefaultView();
                FFilterAndFindObject.ApplyFilter();
                this.Cursor = Cursors.Default;
            }

            UpdateRecordNumberDisplay();

            return(DeletionSuccessful);
        }
        /// <summary>
        /// Main method to post a specified batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch row to post</param>
        /// <param name="APostingAlreadyConfirmed">True means ask user if they want to post</param>
        /// <param name="AWarnOfInactiveValues">True means user is warned if inactive values exist</param>
        /// <param name="ADonorZeroIsValid"></param>
        /// <param name="ARecipientZeroIsValid"></param>
        /// <returns>True if the batch was successfully posted</returns>
        public bool PostBatch(AGiftBatchRow ACurrentBatchRow,
                              bool APostingAlreadyConfirmed = false,
                              bool AWarnOfInactiveValues    = true,
                              bool ADonorZeroIsValid        = false,
                              bool ARecipientZeroIsValid    = false)
        {
            //This assumes that all gift data etc is loaded into the batch before arriving here

            bool RetVal = false;

            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return(RetVal);
            }

            FSelectedBatchNumber = ACurrentBatchRow.BatchNumber;
            TVerificationResultCollection Verifications;

            try
            {
                //Make sure that all control data is in dataset
                FMyForm.GetControlDataForPosting();

                GiftBatchTDSAGiftDetailTable batchGiftDetails = new GiftBatchTDSAGiftDetailTable();
                DataView batchGiftDetailsDV = new DataView(FMainDS.AGiftDetail);

                batchGiftDetailsDV.RowFilter = string.Format("{0}={1}",
                                                             AGiftDetailTable.GetBatchNumberDBName(),
                                                             FSelectedBatchNumber);

                batchGiftDetailsDV.Sort = string.Format("{0} ASC, {1} ASC, {2} ASC",
                                                        AGiftDetailTable.GetBatchNumberDBName(),
                                                        AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                        AGiftDetailTable.GetDetailNumberDBName());

                foreach (DataRowView drv in batchGiftDetailsDV)
                {
                    GiftBatchTDSAGiftDetailRow gBRow = (GiftBatchTDSAGiftDetailRow)drv.Row;

                    batchGiftDetails.Rows.Add((object[])gBRow.ItemArray.Clone());
                }

                bool CancelledDueToExWorkerOrAnonDonor;

                // save first, then post
                if (!FMyForm.SaveChangesForPosting(batchGiftDetails, out CancelledDueToExWorkerOrAnonDonor))
                {
                    FMyForm.Cursor = Cursors.Default;

                    if (!CancelledDueToExWorkerOrAnonDonor)
                    {
                        // saving failed, therefore do not try to post
                        MessageBox.Show(Catalog.GetString("The batch was not posted due to problems during saving; ") + Environment.NewLine +
                                        Catalog.GetString("Please first correct and save the batch, and then post it!"));
                    }

                    return(RetVal);
                }
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }

            //Check for missing international exchange rate
            bool IsTransactionInIntlCurrency = false;

            FMyForm.WarnAboutMissingIntlExchangeRate = true;

            if (FMyForm.InternationalCurrencyExchangeRate(ACurrentBatchRow, out IsTransactionInIntlCurrency, true) == 0)
            {
                return(RetVal);
            }

            //Check for zero Donors or Recipients
            if (!ADonorZeroIsValid)
            {
                DataView batchGiftDV = new DataView(FMainDS.AGift);

                batchGiftDV.RowFilter = string.Format("{0}={1} And {2}=0",
                                                      AGiftTable.GetBatchNumberDBName(),
                                                      FSelectedBatchNumber,
                                                      AGiftTable.GetDonorKeyDBName());

                int numDonorZeros = batchGiftDV.Count;

                if (numDonorZeros > 0)
                {
                    string messageListOfOffendingGifts =
                        String.Format(Catalog.GetString(
                                          "Gift Batch {0} contains {1} gift detail(s) with Donor 0000000. Please fix before posting!{2}{2}"),
                                      FSelectedBatchNumber,
                                      numDonorZeros,
                                      Environment.NewLine);

                    string listOfOffendingRows = string.Empty;

                    listOfOffendingRows += "Gift" + Environment.NewLine;
                    listOfOffendingRows += "------------";

                    foreach (DataRowView drv in batchGiftDV)
                    {
                        AGiftRow giftRow = (AGiftRow)drv.Row;

                        listOfOffendingRows += String.Format("{0}{1:0000}",
                                                             Environment.NewLine,
                                                             giftRow.GiftTransactionNumber);
                    }

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(RetVal);
                }
            }

            if (!ARecipientZeroIsValid)
            {
                DataView batchGiftDetailsDV = new DataView(FMainDS.AGiftDetail);

                batchGiftDetailsDV.RowFilter = string.Format("{0}={1} And {2}=0",
                                                             AGiftDetailTable.GetBatchNumberDBName(),
                                                             FSelectedBatchNumber,
                                                             AGiftDetailTable.GetRecipientKeyDBName());

                int numRecipientZeros = batchGiftDetailsDV.Count;

                if (numRecipientZeros > 0)
                {
                    string messageListOfOffendingGifts =
                        String.Format(Catalog.GetString(
                                          "Gift Batch {0} contains {1} gift detail(s) with Recipient 0000000. Please fix before posting!{2}{2}"),
                                      FSelectedBatchNumber,
                                      numRecipientZeros,
                                      Environment.NewLine);

                    string listOfOffendingRows = string.Empty;

                    listOfOffendingRows += "Gift   Detail" + Environment.NewLine;
                    listOfOffendingRows += "-------------------";

                    foreach (DataRowView drv in batchGiftDetailsDV)
                    {
                        AGiftDetailRow giftDetailRow = (AGiftDetailRow)drv.Row;

                        listOfOffendingRows += String.Format("{0}{1:0000}  {2:00}",
                                                             Environment.NewLine,
                                                             giftDetailRow.GiftTransactionNumber,
                                                             giftDetailRow.DetailNumber);
                    }

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(RetVal);
                }
            }

            //Check for inactive KeyMinistries
            DataTable GiftsWithInactiveKeyMinistries;
            bool      ModifiedDetails = false;

            if (AWarnOfInactiveValues && TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber,
                                                                                                               out GiftsWithInactiveKeyMinistries, false))
            {
                int numInactiveValues = GiftsWithInactiveKeyMinistries.Rows.Count;

                string messageNonModifiedBatch =
                    String.Format(Catalog.GetString("Gift Batch {0} contains {1} inactive key ministries. Please fix before posting!{2}{2}"),
                                  FSelectedBatchNumber,
                                  numInactiveValues,
                                  Environment.NewLine);
                string messageModifiedBatch =
                    String.Format(Catalog.GetString(
                                      "Reversal/Adjustment Gift Batch {0} contains {1} inactive key ministries. Do you still want to post?{2}{2}"),
                                  FSelectedBatchNumber,
                                  numInactiveValues,
                                  Environment.NewLine);

                string listOfOffendingRows = string.Empty;

                listOfOffendingRows += "Gift      Detail   Recipient          KeyMinistry" + Environment.NewLine;
                listOfOffendingRows += "-------------------------------------------------------------------------------";

                foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows)
                {
                    listOfOffendingRows += String.Format("{0}{1:0000}    {2:00}        {3:00000000000}    {4}",
                                                         Environment.NewLine,
                                                         dr[0],
                                                         dr[1],
                                                         dr[2],
                                                         dr[3]);

                    bool isModified = Convert.ToBoolean(dr[4]);

                    if (isModified)
                    {
                        ModifiedDetails = true;
                    }
                }

                TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                if (ModifiedDetails)
                {
                    if (extendedMessageBox.ShowDialog((messageModifiedBatch + listOfOffendingRows),
                                                      Catalog.GetString("Post Batch"), string.Empty,
                                                      TFrmExtendedMessageBox.TButtons.embbYesNo,
                                                      TFrmExtendedMessageBox.TIcon.embiWarning) == TFrmExtendedMessageBox.TResult.embrYes)
                    {
                        APostingAlreadyConfirmed = true;
                    }
                    else
                    {
                        return(RetVal);
                    }
                }
                else
                {
                    extendedMessageBox.ShowDialog((messageNonModifiedBatch + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(RetVal);
                }
            }

            // ask if the user really wants to post the batch
            if (!APostingAlreadyConfirmed &&
                (MessageBox.Show(String.Format(Catalog.GetString("Do you really want to post gift batch {0}?"), FSelectedBatchNumber),
                                 Catalog.GetString("Confirm posting of Gift Batch"),
                                 MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes))
            {
                return(RetVal);
            }

            Verifications = new TVerificationResultCollection();

            try
            {
                FPostingInProgress = true;

                Thread postingThread = new Thread(() => PostGiftBatch(out Verifications));

                using (TProgressDialog dialog = new TProgressDialog(postingThread))
                {
                    dialog.ShowDialog();
                }

                if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications))
                {
                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    StringBuilder errorMessages = new StringBuilder();
                    int           counter       = 0;

                    errorMessages.AppendLine(Catalog.GetString("________________________Gift Posting Errors________________________"));
                    errorMessages.AppendLine();

                    foreach (TVerificationResult verif in Verifications)
                    {
                        counter++;
                        errorMessages.AppendLine(counter.ToString("000") + " - " + verif.ResultText);
                        errorMessages.AppendLine();
                    }

                    extendedMessageBox.ShowDialog(errorMessages.ToString(),
                                                  Catalog.GetString("Post Batch Error"),
                                                  string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);
                }
                else
                {
                    MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"));

                    RetVal = true;
                }
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                FPostingInProgress = false;
            }

            return(RetVal);
        }
        private bool EditableGiftDetail(GiftBatchTDSAGiftDetailRow ARow)
        {
            if (ARow != null)
            {
                if (!FActiveOnly || (ARow.GiftTransactionAmount < 0) && (GetGiftRow(ARow.GiftTransactionNumber).ReceiptNumber != 0))
                {
                    return false;
                }

                return true;
            }

            return FActiveOnly;
        }
 private void ValidateTaxDeductiblePct(GiftBatchTDSAGiftDetailRow ARow, ref TVerificationResultCollection AVerificationResultCollection)
 {
     TSharedFinanceValidation_Gift.ValidateTaxDeductiblePct(this, ARow, ref AVerificationResultCollection, FValidationControlsDict);
 }
        private void OnPostDeleteManual(GiftBatchTDSAGiftDetailRow ARowToDelete,
            bool AAllowDeletion,
            bool ADeletionPerformed,
            string ACompletionMessage)
        {
            if (ADeletionPerformed)
            {
                if (FGiftSelectedForDeletion)
                {
                    FGiftSelectedForDeletion = false;

                    SetBatchLastGiftNumber();

                    UpdateControlsProtection();
                }

                UpdateTotals();

                ((TFrmGiftBatch) this.ParentForm).SaveChangesManual();

                //message to user
                MessageBox.Show(ACompletionMessage,
                    "Deletion Successful",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
            else if (!AAllowDeletion && (ACompletionMessage.Length > 0))
            {
                //message to user
                MessageBox.Show(ACompletionMessage,
                    "Deletion not allowed",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
            else if (!ADeletionPerformed && (ACompletionMessage.Length > 0))
            {
                //message to user
                MessageBox.Show(ACompletionMessage,
                    "Deletion failed",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }
Example #47
0
        private bool OnDeleteRowManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ACompletionMessage)
        {
            //TODO: Make this like deleton on GL Transactions form
            // e.g. pass copy to delete method on server...
            //GiftBatchTDS TempDS = (GiftBatchTDS)FMainDS.Copy();
            //TempDS.Merge(FMainDS);

            bool DeletionSuccessful = false;

            ACompletionMessage = string.Empty;

            if (FBatchRow == null)
            {
                FBatchRow = GetBatchRow();
            }

            if ((ARowToDelete == null) || (FBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return(false);
            }

            int  CurrentBatchNo   = ARowToDelete.BatchNumber;
            bool RowToDeleteIsNew = (ARowToDelete.RowState == DataRowState.Added);
            int  CurrentRowIndex  = GetSelectedRowIndex();

            TFrmGiftBatch FMyForm = (TFrmGiftBatch)this.ParentForm;

            GiftBatchTDS  BackupMainDS         = null;
            List <string> OriginatingDetailRef = new List <string>();

            int    SelectedDetailNumber        = ARowToDelete.DetailNumber;
            int    GiftToDeleteTransNo         = 0;
            string FilterAllGiftsOfBatch       = String.Empty;
            string FilterAllGiftDetailsOfBatch = String.Empty;

            int DetailRowCount = FGiftDetailView.Count;

            try
            {
                this.Cursor = Cursors.WaitCursor;
                //Specify current action
                FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.DELETINGTRANS;
                //Speeds up deletion of larger gift sets
                FMainDS.EnforceConstraints = false;
                // temporarily disable  New Donor Warning
                FMyForm.NewDonorWarning = false;

                //Backup the Dataset for reversion purposes
                BackupMainDS = (GiftBatchTDS)FMainDS.GetChangesTyped(false);

                //Don't run an inactive fields check on this batch
                FMyForm.GetBatchControl().UpdateUnpostedBatchDictionary(CurrentBatchNo);

                if ((ARowToDelete.ModifiedDetailKey != null) && (ARowToDelete.ModifiedDetailKey.Length > 0))
                {
                    OriginatingDetailRef.Add(ARowToDelete.ModifiedDetailKey);
                }

                //Delete current row
                ARowToDelete.RejectChanges();

                if (!RowToDeleteIsNew)
                {
                    ShowDetails(ARowToDelete);
                }

                ARowToDelete.Delete();

                //If there existed (before the delete row above) more than one detail row, then no need to delete gift header row
                if (DetailRowCount > 1)
                {
                    ACompletionMessage = Catalog.GetString("Gift Detail row deleted successfully!");

                    FGiftSelectedForDeletionFlag = false;

                    foreach (DataRowView rv in FGiftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        if (row.DetailNumber > SelectedDetailNumber)
                        {
                            row.DetailNumber--;
                        }
                    }

                    FGift.LastDetailNumber--;
                }
                else
                {
                    ACompletionMessage = Catalog.GetString("Gift deleted successfully!");

                    GiftToDeleteTransNo = FGift.GiftTransactionNumber;

                    // Reduce all Gift Detail row Transaction numbers by 1 if they are greater then gift to be deleted
                    FilterAllGiftDetailsOfBatch = String.Format("{0}={1} And {2}>{3}",
                                                                AGiftDetailTable.GetBatchNumberDBName(),
                                                                FBatchNumber,
                                                                AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                GiftToDeleteTransNo);

                    DataView giftDetailView = new DataView(FMainDS.AGiftDetail);
                    giftDetailView.RowFilter = FilterAllGiftDetailsOfBatch;
                    giftDetailView.Sort      = String.Format("{0} ASC", AGiftDetailTable.GetGiftTransactionNumberDBName());

                    foreach (DataRowView rv in giftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        row.GiftTransactionNumber--;
                    }

                    //Cannot delete the gift row, just copy the data of rows above down by 1 row
                    // and then mark the top row for deletion
                    //In other words, bubble the gift row to be deleted to the top
                    FilterAllGiftsOfBatch = String.Format("{0}={1} And {2}>={3}",
                                                          AGiftTable.GetBatchNumberDBName(),
                                                          FBatchNumber,
                                                          AGiftTable.GetGiftTransactionNumberDBName(),
                                                          GiftToDeleteTransNo);

                    DataView giftView = new DataView(FMainDS.AGift);
                    giftView.RowFilter = FilterAllGiftsOfBatch;
                    giftView.Sort      = String.Format("{0} ASC", AGiftTable.GetGiftTransactionNumberDBName());

                    AGiftRow giftRowToReceive  = null;
                    AGiftRow giftRowToCopyDown = null;
                    AGiftRow giftRowCurrent    = null;

                    int currentGiftTransNo = 0;

                    foreach (DataRowView gv in giftView)
                    {
                        giftRowCurrent = (AGiftRow)gv.Row;

                        currentGiftTransNo = giftRowCurrent.GiftTransactionNumber;

                        if (currentGiftTransNo > GiftToDeleteTransNo)
                        {
                            giftRowToCopyDown = giftRowCurrent;

                            //Copy column values down
                            for (int j = 3; j < giftRowToCopyDown.Table.Columns.Count; j++)
                            {
                                //Update all columns except the pk fields that remain the same
                                if (!giftRowToCopyDown.Table.Columns[j].ColumnName.EndsWith("_text"))
                                {
                                    giftRowToReceive[j] = giftRowToCopyDown[j];
                                }
                            }
                        }

                        if (currentGiftTransNo == FBatchRow.LastGiftNumber)
                        {
                            //Mark last record for deletion
                            giftRowCurrent.GiftStatus = MFinanceConstants.MARKED_FOR_DELETION;
                        }

                        //Will always be previous row
                        giftRowToReceive = giftRowCurrent;
                    }

                    FPreviouslySelectedDetailRow = null;
                    FGiftSelectedForDeletionFlag = true;
                    FBatchRow.LastGiftNumber--;
                }

                //Save and check for inactive values and ex-workers and anonymous gifts
                //  in other unsaved Batches
                FPetraUtilsObject.SetChangedFlag();

                if (!FMyForm.SaveChangesManual(Logic.TExtraGiftBatchChecks.GiftBatchAction.DELETINGTRANS, false, false))
                {
                    FMyForm.GetBatchControl().UpdateUnpostedBatchDictionary();

                    MessageBox.Show(Catalog.GetString("The gift detail has been deleted but the changes are not saved!"),
                                    Catalog.GetString("Deletion Warning"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);

                    ACompletionMessage = string.Empty;

                    if (FGiftSelectedForDeletionFlag)
                    {
                        FGiftSelectedForDeletionFlag = false;
                        SetBatchLastGiftNumber();
                        UpdateControlsProtection();
                    }

                    UpdateTotals();

                    return(false);
                }

                //Check if have deleted a reversing gift detail
                if (OriginatingDetailRef.Count > 0)
                {
                    TRemote.MFinance.Gift.WebConnectors.ReversedGiftReset(FLedgerNumber, OriginatingDetailRef);
                }

                //Clear current batch's gift data and reload from server
                RefreshBatchGiftData(FBatchNumber, true);

                DeletionSuccessful = true;
            }
            catch (Exception ex)
            {
                //Revert to previous state
                RevertDataSet(FMainDS, BackupMainDS, CurrentRowIndex);

                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                FMyForm.NewDonorWarning         = true;
                FMainDS.EnforceConstraints      = true;
                FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.NONE;
                this.Cursor = Cursors.Default;
            }

            SetGiftDetailDefaultView();
            FFilterAndFindObject.ApplyFilter();
            UpdateRecordNumberDisplay();

            return(DeletionSuccessful);
        }
        private void GetDetailDataFromControlsManual(GiftBatchTDSAGiftDetailRow ARow)
        {
            if (ARow == null)
            {
                return;
            }

            //Handle gift table fields for first detail only
            if (ARow.DetailNumber == 1)
            {
                AGiftRow giftRow = GetGiftRow(ARow.GiftTransactionNumber);

                giftRow.DonorKey = Convert.ToInt64(txtDetailDonorKey.Text);
                giftRow.DateEntered = (dtpDateEntered.Date.HasValue ? dtpDateEntered.Date.Value : FBatchRow.GlEffectiveDate);

                if (cmbDetailMethodOfGivingCode.SelectedIndex == -1)
                {
                    giftRow.SetMethodOfGivingCodeNull();
                }
                else
                {
                    giftRow.MethodOfGivingCode = cmbDetailMethodOfGivingCode.GetSelectedString();
                }

                if (cmbDetailMethodOfPaymentCode.SelectedIndex == -1)
                {
                    giftRow.SetMethodOfPaymentCodeNull();
                }
                else
                {
                    giftRow.MethodOfPaymentCode = cmbDetailMethodOfPaymentCode.GetSelectedString();
                }

                if (txtDetailReference.Text.Length == 0)
                {
                    giftRow.SetReferenceNull();
                }
                else
                {
                    giftRow.Reference = txtDetailReference.Text;
                }

                if (cmbDetailReceiptLetterCode.SelectedIndex == -1)
                {
                    giftRow.SetReceiptLetterCodeNull();
                }
                else
                {
                    giftRow.ReceiptLetterCode = cmbDetailReceiptLetterCode.GetSelectedString();
                }
            }

            if (txtDetailCostCentreCode.Text.Length == 0)
            {
                ARow.SetCostCentreCodeNull();
            }
            else
            {
                ARow.CostCentreCode = txtDetailCostCentreCode.Text;
            }

            if (txtDetailAccountCode.Text.Length == 0)
            {
                ARow.SetAccountCodeNull();
            }
            else
            {
                ARow.AccountCode = txtDetailAccountCode.Text;
            }

            if (ARow.IsRecipientKeyNull())
            {
                ARow.SetRecipientDescriptionNull();
            }
            else
            {
                TUC_GiftTransactions_Recipient.UpdateRecipientKeyText(ARow.RecipientKey, ARow,
                    cmbDetailMotivationGroupCode.GetSelectedString(), cmbDetailMotivationDetailCode.GetSelectedString());
            }

            if (txtDetailRecipientLedgerNumber.Text.Length == 0)
            {
                ARow.SetRecipientFieldNull();
                ARow.SetRecipientLedgerNumberNull();
            }
            else
            {
                ARow.RecipientLedgerNumber = Convert.ToInt64(txtDetailRecipientLedgerNumber.Text);
                ARow.RecipientField = ARow.RecipientLedgerNumber;
            }

            if (string.IsNullOrEmpty(ARow.GiftCommentOne))
            {
                ARow.CommentOneType = null;
            }

            if (string.IsNullOrEmpty(ARow.GiftCommentTwo))
            {
                ARow.CommentTwoType = null;
            }

            if (string.IsNullOrEmpty(ARow.GiftCommentThree))
            {
                ARow.CommentThreeType = null;
            }

            if (FTaxDeductiblePercentageEnabled)
            {
                GetTaxDeductibleDataFromControlsManual(ref ARow);
            }

            if (chkNoReceiptOnAdjustment.Visible)
            {
                GetGiftRow(ARow.GiftTransactionNumber).PrintReceipt = (chkNoReceiptOnAdjustment.Checked == false);
            }
        }
        /// <summary>
        /// SetKeyMinistryTextBoxInvisible
        /// </summary>
        public static void SetKeyMinistryTextBoxInvisible(GiftBatchTDSAGiftDetailRow ACurrentDetailRow,
            GiftBatchTDS AMainDS,
            Int32 ALedgerNumber,
            TFrmPetraEditUtils APetraUtilsObject,
            TCmbAutoPopulated ACmbKeyMinistries,
            ref TCmbAutoPopulated ACmbMotivationDetailCode,
            TtxtAutoPopulatedButtonLabel ATxtDetailRecipientKey,
            Int64 ARecipientKey,
            TtxtAutoPopulatedButtonLabel AtxtDetailRecipientLedgerNumber,
            TextBox ATxtDetailCostCentreCode,
            TextBox ATxtDetailAccountCode,
            TextBox ATxtDetailRecipientKeyMinistry,
            CheckBox AChkDetailTaxDeductible,
            TextBox ATxtDeductibleAccount,
            string AMotivationGroup,
            ref string AMotivationDetail,
            ref bool AMotivationDetailChangedFlag,
            bool AActiveOnly,
            bool ARecipientKeyChangingFlag,
            bool ACreatingNewGiftFlag,
            bool AInEditModeFlag,
            bool ABatchUnpostedFlag,
            bool ATaxDeductiblePercentageEnabledFlag,
            out bool ADoTaxUpdate)
        {
            if (ATxtDetailRecipientKeyMinistry.Visible)
            {
                ApplyMotivationDetailCodeFilter(ACurrentDetailRow,
                    AMainDS,
                    ALedgerNumber,
                    APetraUtilsObject,
                    ACmbKeyMinistries,
                    ref ACmbMotivationDetailCode,
                    ATxtDetailRecipientKey,
                    ARecipientKey,
                    AtxtDetailRecipientLedgerNumber,
                    ATxtDetailCostCentreCode,
                    ATxtDetailAccountCode,
                    ATxtDetailRecipientKeyMinistry,
                    AChkDetailTaxDeductible,
                    ATxtDeductibleAccount,
                    AMotivationGroup,
                    ref AMotivationDetail,
                    ref AMotivationDetailChangedFlag,
                    AActiveOnly,
                    ARecipientKeyChangingFlag,
                    ACreatingNewGiftFlag,
                    AInEditModeFlag,
                    ABatchUnpostedFlag,
                    ATaxDeductiblePercentageEnabledFlag,
                    out ADoTaxUpdate);

                PopulateKeyMinistry(ACurrentDetailRow, ACmbKeyMinistries, ATxtDetailRecipientKey, AtxtDetailRecipientLedgerNumber, false);

                ReconcileKeyMinistryFromTextbox(ACurrentDetailRow,
                    ACmbKeyMinistries,
                    ATxtDetailRecipientKeyMinistry,
                    AInEditModeFlag,
                    ABatchUnpostedFlag);

                //hide the overlay box during editing
                ATxtDetailRecipientKeyMinistry.Visible = false;
            }
            else
            {
                ADoTaxUpdate = false;
            }
        }
        private bool OnDeleteRowManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ACompletionMessage)
        {
            bool deletionSuccessful = false;
            string originatingDetailRef = string.Empty;

            ACompletionMessage = string.Empty;

            if (ARowToDelete == null)
            {
                return deletionSuccessful;
            }

            // temporarily disable  New Donor Warning
            ((TFrmGiftBatch) this.ParentForm).NewDonorWarning = false;

            if ((ARowToDelete.RowState != DataRowState.Added) && !((TFrmGiftBatch) this.ParentForm).SaveChangesManual())
            {
                MessageBox.Show("Error in trying to save prior to deleting current gift detail!");
                return deletionSuccessful;
            }

            ((TFrmGiftBatch) this.ParentForm).NewDonorWarning = true;

            //Backup the Dataset for reversion purposes
            GiftBatchTDS FTempDS = (GiftBatchTDS)FMainDS.Copy();
            FTempDS.Merge(FMainDS);

            if (ARowToDelete.RowState != DataRowState.Added)
            {
                //Required to deal with concurrency errors
                FMainDS.AcceptChanges();
            }

            int selectedDetailNumber = ARowToDelete.DetailNumber;
            int giftToDeleteTransNo = 0;
            string filterAllGiftsOfBatch = String.Empty;
            string filterAllGiftDetailsOfBatch = String.Empty;

            int detailRowCount = FGiftDetailView.Count;

            try
            {
                //Speeds up deletion of larger gift sets
                FMainDS.EnforceConstraints = false;

                if (ARowToDelete.ModifiedDetailKey != null)
                {
                    originatingDetailRef = ARowToDelete.ModifiedDetailKey;
                }

                //Delete current detail row
                ARowToDelete.Delete();

                //If there existed (before the delete row above) more than one detail row, then no need to delete gift header row
                if (detailRowCount > 1)
                {
                    FGiftSelectedForDeletion = false;

                    foreach (DataRowView rv in FGiftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        if (row.DetailNumber > selectedDetailNumber)
                        {
                            row.DetailNumber--;
                        }
                    }

                    FGift.LastDetailNumber--;

                    FPetraUtilsObject.SetChangedFlag();
                }
                else
                {
                    giftToDeleteTransNo = FGift.GiftTransactionNumber;

                    TLogging.Log("Delete row: " + giftToDeleteTransNo.ToString());

                    // Reduce all Gift Detail row Transaction numbers by 1 if they are greater then gift to be deleted
                    filterAllGiftDetailsOfBatch = String.Format("{0}={1} And {2}>{3}",
                        AGiftDetailTable.GetBatchNumberDBName(),
                        FBatchNumber,
                        AGiftDetailTable.GetGiftTransactionNumberDBName(),
                        giftToDeleteTransNo);

                    DataView giftDetailView = new DataView(FMainDS.AGiftDetail);
                    giftDetailView.RowFilter = filterAllGiftDetailsOfBatch;
                    giftDetailView.Sort = String.Format("{0} ASC", AGiftDetailTable.GetGiftTransactionNumberDBName());

                    foreach (DataRowView rv in giftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        row.GiftTransactionNumber--;
                    }

                    //Cannot delete the gift row, just copy the data of rows above down by 1 row
                    // and then mark the top row for deletion
                    //In other words, bubble the gift row to be deleted to the top
                    filterAllGiftsOfBatch = String.Format("{0}={1} And {2}>={3}",
                        AGiftTable.GetBatchNumberDBName(),
                        FBatchNumber,
                        AGiftTable.GetGiftTransactionNumberDBName(),
                        giftToDeleteTransNo);

                    DataView giftView = new DataView(FMainDS.AGift);
                    giftView.RowFilter = filterAllGiftsOfBatch;
                    giftView.Sort = String.Format("{0} ASC", AGiftTable.GetGiftTransactionNumberDBName());

                    AGiftRow giftRowToReceive = null;
                    AGiftRow giftRowToCopyDown = null;
                    AGiftRow giftRowCurrent = null;

                    int currentGiftTransNo = 0;

                    foreach (DataRowView gv in giftView)
                    {
                        giftRowCurrent = (AGiftRow)gv.Row;

                        currentGiftTransNo = giftRowCurrent.GiftTransactionNumber;

                        if (currentGiftTransNo > giftToDeleteTransNo)
                        {
                            giftRowToCopyDown = giftRowCurrent;

                            //Copy column values down
                            for (int j = 3; j < giftRowToCopyDown.Table.Columns.Count; j++)
                            {
                                //Update all columns except the pk fields that remain the same
                                if (!giftRowToCopyDown.Table.Columns[j].ColumnName.EndsWith("_text"))
                                {
                                    giftRowToReceive[j] = giftRowToCopyDown[j];
                                }
                            }
                        }

                        if (currentGiftTransNo == FBatchRow.LastGiftNumber)
                        {
                            //Mark last record for deletion
                            giftRowCurrent.GiftStatus = MFinanceConstants.MARKED_FOR_DELETION;
                        }

                        //Will always be previous row
                        giftRowToReceive = giftRowCurrent;
                    }

                    FPreviouslySelectedDetailRow = null;

                    FPetraUtilsObject.SetChangedFlag();

                    FGiftSelectedForDeletion = true;

                    FBatchRow.LastGiftNumber--;
                }

                //Force a change in the batch row to make sure it exists in the dataset to save
                FBatchRow.DateModified = DateTime.Now;

                //Check if deleting a reversed gift detail
                if (originatingDetailRef.StartsWith("|"))
                {
                    bool ok = TRemote.MFinance.Gift.WebConnectors.ReversedGiftReset(FLedgerNumber, originatingDetailRef);

                    if (!ok)
                    {
                        throw new Exception("Error in trying to reset Modified Detail field of the originating gift detail.");
                    }
                }

                //Try to save changes
                if (((TFrmGiftBatch) this.ParentForm).SaveChangesManual())
                {
                    //Clear current batch's gift data and reload from server
                    RefreshCurrentBatchGiftData(FBatchNumber);
                }
                else
                {
                    throw new Exception("Unable to save after deleting a gift!");
                }

                ACompletionMessage = Catalog.GetString("Gift row deleted successfully!");

                deletionSuccessful = true;
            }
            catch (Exception ex)
            {
                ACompletionMessage = ex.Message;
                MessageBox.Show(ex.Message,
                    "Gift Deletion Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                //Revert to previous state
                FMainDS.Merge(FTempDS);
            }
            finally
            {
                FMainDS.EnforceConstraints = true;
                SetGiftDetailDefaultView();
                FFilterAndFindObject.ApplyFilter();
            }

            UpdateRecordNumberDisplay();

            return deletionSuccessful;
        }
Example #51
0
        private bool OnDeleteRowManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ACompletionMessage)
        {
            bool   deletionSuccessful   = false;
            string originatingDetailRef = string.Empty;

            ACompletionMessage = string.Empty;

            if (ARowToDelete == null)
            {
                return(deletionSuccessful);
            }

            // temporarily disable  New Donor Warning
            ((TFrmGiftBatch)this.ParentForm).NewDonorWarning = false;

            if ((ARowToDelete.RowState != DataRowState.Added) && !((TFrmGiftBatch)this.ParentForm).SaveChangesManual())
            {
                MessageBox.Show("Error in trying to save prior to deleting current gift detail!");
                return(deletionSuccessful);
            }

            ((TFrmGiftBatch)this.ParentForm).NewDonorWarning = true;

            //Backup the Dataset for reversion purposes
            GiftBatchTDS FTempDS = (GiftBatchTDS)FMainDS.Copy();

            FTempDS.Merge(FMainDS);

            if (ARowToDelete.RowState != DataRowState.Added)
            {
                //Required to deal with concurrency errors
                FMainDS.AcceptChanges();
            }

            int    selectedDetailNumber        = ARowToDelete.DetailNumber;
            int    giftToDeleteTransNo         = 0;
            string filterAllGiftsOfBatch       = String.Empty;
            string filterAllGiftDetailsOfBatch = String.Empty;

            int detailRowCount = FGiftDetailView.Count;

            try
            {
                //Speeds up deletion of larger gift sets
                FMainDS.EnforceConstraints = false;

                if (ARowToDelete.ModifiedDetailKey != null)
                {
                    originatingDetailRef = ARowToDelete.ModifiedDetailKey;
                }

                //Delete current detail row
                ARowToDelete.Delete();

                //If there existed (before the delete row above) more than one detail row, then no need to delete gift header row
                if (detailRowCount > 1)
                {
                    FGiftSelectedForDeletion = false;

                    foreach (DataRowView rv in FGiftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        if (row.DetailNumber > selectedDetailNumber)
                        {
                            row.DetailNumber--;
                        }
                    }

                    FGift.LastDetailNumber--;

                    FPetraUtilsObject.SetChangedFlag();
                }
                else
                {
                    giftToDeleteTransNo = FGift.GiftTransactionNumber;

                    TLogging.Log("Delete row: " + giftToDeleteTransNo.ToString());

                    // Reduce all Gift Detail row Transaction numbers by 1 if they are greater then gift to be deleted
                    filterAllGiftDetailsOfBatch = String.Format("{0}={1} And {2}>{3}",
                                                                AGiftDetailTable.GetBatchNumberDBName(),
                                                                FBatchNumber,
                                                                AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                giftToDeleteTransNo);

                    DataView giftDetailView = new DataView(FMainDS.AGiftDetail);
                    giftDetailView.RowFilter = filterAllGiftDetailsOfBatch;
                    giftDetailView.Sort      = String.Format("{0} ASC", AGiftDetailTable.GetGiftTransactionNumberDBName());

                    foreach (DataRowView rv in giftDetailView)
                    {
                        GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row;

                        row.GiftTransactionNumber--;
                    }

                    //Cannot delete the gift row, just copy the data of rows above down by 1 row
                    // and then mark the top row for deletion
                    //In other words, bubble the gift row to be deleted to the top
                    filterAllGiftsOfBatch = String.Format("{0}={1} And {2}>={3}",
                                                          AGiftTable.GetBatchNumberDBName(),
                                                          FBatchNumber,
                                                          AGiftTable.GetGiftTransactionNumberDBName(),
                                                          giftToDeleteTransNo);

                    DataView giftView = new DataView(FMainDS.AGift);
                    giftView.RowFilter = filterAllGiftsOfBatch;
                    giftView.Sort      = String.Format("{0} ASC", AGiftTable.GetGiftTransactionNumberDBName());

                    AGiftRow giftRowToReceive  = null;
                    AGiftRow giftRowToCopyDown = null;
                    AGiftRow giftRowCurrent    = null;

                    int currentGiftTransNo = 0;

                    foreach (DataRowView gv in giftView)
                    {
                        giftRowCurrent = (AGiftRow)gv.Row;

                        currentGiftTransNo = giftRowCurrent.GiftTransactionNumber;

                        if (currentGiftTransNo > giftToDeleteTransNo)
                        {
                            giftRowToCopyDown = giftRowCurrent;

                            //Copy column values down
                            for (int j = 3; j < giftRowToCopyDown.Table.Columns.Count; j++)
                            {
                                //Update all columns except the pk fields that remain the same
                                if (!giftRowToCopyDown.Table.Columns[j].ColumnName.EndsWith("_text"))
                                {
                                    giftRowToReceive[j] = giftRowToCopyDown[j];
                                }
                            }
                        }

                        if (currentGiftTransNo == FBatchRow.LastGiftNumber)
                        {
                            //Mark last record for deletion
                            giftRowCurrent.GiftStatus = MFinanceConstants.MARKED_FOR_DELETION;
                        }

                        //Will always be previous row
                        giftRowToReceive = giftRowCurrent;
                    }

                    FPreviouslySelectedDetailRow = null;

                    FPetraUtilsObject.SetChangedFlag();

                    FGiftSelectedForDeletion = true;

                    FBatchRow.LastGiftNumber--;
                }

                //Force a change in the batch row to make sure it exists in the dataset to save
                FBatchRow.DateModified = DateTime.Now;

                //Check if deleting a reversed gift detail
                if (originatingDetailRef.StartsWith("|"))
                {
                    bool ok = TRemote.MFinance.Gift.WebConnectors.ReversedGiftReset(FLedgerNumber, originatingDetailRef);

                    if (!ok)
                    {
                        throw new Exception("Error in trying to reset Modified Detail field of the originating gift detail.");
                    }
                }

                //Try to save changes
                if (((TFrmGiftBatch)this.ParentForm).SaveChangesManual())
                {
                    //Clear current batch's gift data and reload from server
                    RefreshCurrentBatchGiftData(FBatchNumber);
                }
                else
                {
                    throw new Exception("Unable to save after deleting a gift!");
                }

                ACompletionMessage = Catalog.GetString("Gift row deleted successfully!");

                deletionSuccessful = true;
            }
            catch (Exception ex)
            {
                ACompletionMessage = ex.Message;
                MessageBox.Show(ex.Message,
                                "Gift Deletion Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                //Revert to previous state
                FMainDS.Merge(FTempDS);
            }
            finally
            {
                FMainDS.EnforceConstraints = true;
                SetGiftDetailDefaultView();
                FFilterAndFindObject.ApplyFilter();
            }

            UpdateRecordNumberDisplay();

            return(deletionSuccessful);
        }
Example #52
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);
                }
            }
        }
 /// <summary>
 /// OnEndEditMode
 /// </summary>
 public static void OnEndEditMode(GiftBatchTDSAGiftDetailRow ACurrentDetailRow, TCmbAutoPopulated ACmbKeyMinistries,
     TCmbAutoPopulated ACmbMotivationDetailCode, TextBox ATxtDetailRecipientKeyMinistry,
     ref string AMotivationDetail, bool AActiveOnly, bool AInEditModeFlag, bool ABatchUnpostedFlag)
 {
     if (!ATxtDetailRecipientKeyMinistry.Visible)
     {
         SetTextBoxOverlayOnKeyMinistryCombo(ACurrentDetailRow,
             AActiveOnly,
             ACmbKeyMinistries,
             ACmbMotivationDetailCode,
             ATxtDetailRecipientKeyMinistry,
             ref AMotivationDetail,
             AInEditModeFlag,
             ABatchUnpostedFlag);
     }
 }
        /// <summary>
        /// Main method to post a specified batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch row to post</param>
        /// <param name="ARefreshGUIAfterPosting">Will be set to true if the GUI should be updated.  Can be true even if Posting fails
        /// <param name="AWarnOfInactiveValues">True means user is warned if inactive values exist</param>
        /// <param name="ADonorZeroIsValid"></param>
        /// <param name="ARecipientZeroIsValid"></param>
        /// <param name="APostingAlreadyConfirmed">True means ask user if they want to post</param>
        /// if the server gets a SerializableTransactionException</param>
        /// <returns>True if the batch was successfully posted</returns>
        public bool PostBatch(AGiftBatchRow ACurrentBatchRow,
                              out bool ARefreshGUIAfterPosting,
                              bool AWarnOfInactiveValues    = true,
                              bool ADonorZeroIsValid        = false,
                              bool ARecipientZeroIsValid    = false,
                              bool APostingAlreadyConfirmed = false)
        {
            ARefreshGUIAfterPosting = false;

            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return(false);
            }

            FSelectedBatchNumber = ACurrentBatchRow.BatchNumber;

            //Make sure that all control data is in dataset
            FMyForm.GetLatestControlData();

            //Copy all batch data to new table
            GiftBatchTDSAGiftDetailTable BatchGiftDetails = new GiftBatchTDSAGiftDetailTable();
            DataView BatchGiftDetailsDV = new DataView(FMainDS.AGiftDetail);

            BatchGiftDetailsDV.RowFilter = string.Format("{0}={1}",
                                                         AGiftDetailTable.GetBatchNumberDBName(),
                                                         FSelectedBatchNumber);

            BatchGiftDetailsDV.Sort = string.Format("{0} ASC, {1} ASC, {2} ASC",
                                                    AGiftDetailTable.GetBatchNumberDBName(),
                                                    AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                    AGiftDetailTable.GetDetailNumberDBName());

            foreach (DataRowView drv in BatchGiftDetailsDV)
            {
                GiftBatchTDSAGiftDetailRow gBRow = (GiftBatchTDSAGiftDetailRow)drv.Row;
                BatchGiftDetails.Rows.Add((object[])gBRow.ItemArray.Clone());
            }

            //Save and check for inactive values and ex-workers and anonymous gifts
            if (FPetraUtilsObject.HasChanges)
            {
                //Keep this conditional check separate from the one above so that it only gets called
                // when necessary and doesn't result in the executon of the same method
                if (!FMyForm.SaveChangesForPosting(BatchGiftDetails))
                {
                    return(false);
                }
                else
                {
                    APostingAlreadyConfirmed = true;
                }
            }
            else
            {
                //This has to be called here because if there are no changes then the DataSavingValidating
                // method which calls the method below, will not run.
                if (!FMyForm.GetBatchControl().AllowInactiveFieldValues(ref APostingAlreadyConfirmed,
                                                                        TExtraGiftBatchChecks.GiftBatchAction.POSTING) ||
                    FMyForm.GiftHasExWorkerOrAnon(BatchGiftDetails)
                    )
                {
                    return(false);
                }
            }

            //Check hash total validity
            if ((ACurrentBatchRow.HashTotal != 0) &&
                (ACurrentBatchRow.BatchTotal != ACurrentBatchRow.HashTotal))
            {
                MessageBox.Show(String.Format(Catalog.GetString(
                                                  "The gift batch total ({0}) for batch {1} does not equal the hash total ({2})!"),
                                              StringHelper.FormatUsingCurrencyCode(ACurrentBatchRow.BatchTotal, ACurrentBatchRow.CurrencyCode),
                                              ACurrentBatchRow.BatchNumber,
                                              StringHelper.FormatUsingCurrencyCode(ACurrentBatchRow.HashTotal, ACurrentBatchRow.CurrencyCode)),
                                "Post Gift Batch");

                return(false);
            }

            //Check for missing international exchange rate
            bool IsTransactionInIntlCurrency = false;

            FMyForm.WarnAboutMissingIntlExchangeRate = true;

            if (FMyForm.InternationalCurrencyExchangeRate(ACurrentBatchRow, out IsTransactionInIntlCurrency, true) == 0)
            {
                return(false);
            }

            //Check for zero Donors or Recipients
            if (!ADonorZeroIsValid)
            {
                DataView batchGiftDV = new DataView(FMainDS.AGift);

                batchGiftDV.RowFilter = string.Format("{0}={1} And {2}=0",
                                                      AGiftTable.GetBatchNumberDBName(),
                                                      FSelectedBatchNumber,
                                                      AGiftTable.GetDonorKeyDBName());

                int numDonorZeros = batchGiftDV.Count;

                if (numDonorZeros > 0)
                {
                    string messageListOfOffendingGifts =
                        String.Format(Catalog.GetString(
                                          "Gift Batch {0} contains {1} gift detail(s) with Donor 0000000. Please fix before posting!{2}{2}"),
                                      FSelectedBatchNumber,
                                      numDonorZeros,
                                      Environment.NewLine);

                    string listOfOffendingRows = string.Empty;

                    listOfOffendingRows += "Gift" + Environment.NewLine;
                    listOfOffendingRows += "------------";

                    foreach (DataRowView drv in batchGiftDV)
                    {
                        AGiftRow giftRow = (AGiftRow)drv.Row;

                        listOfOffendingRows += String.Format("{0}{1:0000}",
                                                             Environment.NewLine,
                                                             giftRow.GiftTransactionNumber);
                    }

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(false);
                }
            }

            if (!ARecipientZeroIsValid)
            {
                DataView batchGiftDetailsDV = new DataView(FMainDS.AGiftDetail);

                batchGiftDetailsDV.RowFilter = string.Format("{0}={1} And {2}=0",
                                                             AGiftDetailTable.GetBatchNumberDBName(),
                                                             FSelectedBatchNumber,
                                                             AGiftDetailTable.GetRecipientKeyDBName());

                int numRecipientZeros = batchGiftDetailsDV.Count;

                if (numRecipientZeros > 0)
                {
                    string messageListOfOffendingGifts =
                        String.Format(Catalog.GetString(
                                          "Gift Batch {0} contains {1} gift detail(s) with Recipient 0000000. Please fix before posting!{2}{2}"),
                                      FSelectedBatchNumber,
                                      numRecipientZeros,
                                      Environment.NewLine);

                    string listOfOffendingRows = string.Empty;

                    listOfOffendingRows += "Gift   Detail" + Environment.NewLine;
                    listOfOffendingRows += "-------------------";

                    foreach (DataRowView drv in batchGiftDetailsDV)
                    {
                        AGiftDetailRow giftDetailRow = (AGiftDetailRow)drv.Row;

                        listOfOffendingRows += String.Format("{0}{1:0000}  {2:00}",
                                                             Environment.NewLine,
                                                             giftDetailRow.GiftTransactionNumber,
                                                             giftDetailRow.DetailNumber);
                    }

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(false);
                }
            }

            //Check for inactive KeyMinistries
            DataTable GiftsWithInactiveKeyMinistries;
            bool      ModifiedDetails = false;

            if (AWarnOfInactiveValues && TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber,
                                                                                                               out GiftsWithInactiveKeyMinistries, false))
            {
                int numInactiveValues = GiftsWithInactiveKeyMinistries.Rows.Count;

                string messageNonModifiedBatch =
                    String.Format(Catalog.GetString("Gift Batch {0} contains {1} inactive key ministries. Please fix before posting!{2}{2}"),
                                  FSelectedBatchNumber,
                                  numInactiveValues,
                                  Environment.NewLine);
                string messageModifiedBatch =
                    String.Format(Catalog.GetString(
                                      "Reversal/Adjustment Gift Batch {0} contains {1} inactive key ministries. Do you still want to post?{2}{2}"),
                                  FSelectedBatchNumber,
                                  numInactiveValues,
                                  Environment.NewLine);

                string listOfOffendingRows = string.Empty;

                listOfOffendingRows += "Gift      Detail   Recipient          KeyMinistry" + Environment.NewLine;
                listOfOffendingRows += "-------------------------------------------------------------------------------";

                foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows)
                {
                    listOfOffendingRows += String.Format("{0}{1:0000}    {2:00}        {3:00000000000}    {4}",
                                                         Environment.NewLine,
                                                         dr[0],
                                                         dr[1],
                                                         dr[2],
                                                         dr[3]);

                    bool isModified = Convert.ToBoolean(dr[4]);

                    if (isModified)
                    {
                        ModifiedDetails = true;
                    }
                }

                TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                if (ModifiedDetails)
                {
                    if (extendedMessageBox.ShowDialog((messageModifiedBatch + listOfOffendingRows),
                                                      Catalog.GetString("Post Batch"), string.Empty,
                                                      TFrmExtendedMessageBox.TButtons.embbYesNo,
                                                      TFrmExtendedMessageBox.TIcon.embiWarning) == TFrmExtendedMessageBox.TResult.embrYes)
                    {
                        APostingAlreadyConfirmed = true;
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    extendedMessageBox.ShowDialog((messageNonModifiedBatch + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(false);
                }
            }

            // ask if the user really wants to post the batch
            if (!APostingAlreadyConfirmed &&
                (MessageBox.Show(String.Format(Catalog.GetString("Do you really want to post gift batch {0}?"), FSelectedBatchNumber),
                                 Catalog.GetString("Confirm posting of Gift Batch"),
                                 MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes))
            {
                return(false);
            }

            TVerificationResultCollection Verifications = new TVerificationResultCollection();

            try
            {
                FPostingInProgress = true;

                Thread postingThread = new Thread(() => PostGiftBatch(out Verifications));
                postingThread.SetApartmentState(ApartmentState.STA);
                using (TProgressDialog dialog = new TProgressDialog(postingThread))
                {
                    dialog.ShowDialog();
                }

                if (TVerificationHelper.ResultsContainErrorCode(Verifications, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                {
                    TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                    ARefreshGUIAfterPosting = true;
                    return(false);
                }
                else if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications))
                {
                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    StringBuilder errorMessages = new StringBuilder();
                    int           counter       = 0;

                    errorMessages.AppendLine(Catalog.GetString("________________________Gift Posting Errors________________________"));
                    errorMessages.AppendLine();

                    foreach (TVerificationResult verif in Verifications)
                    {
                        counter++;
                        errorMessages.AppendLine(counter.ToString("000") + " - " + verif.ResultText);
                        errorMessages.AppendLine();
                    }

                    extendedMessageBox.ShowDialog(errorMessages.ToString(),
                                                  Catalog.GetString("Post Batch Error"),
                                                  string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);
                }
                else
                {
                    MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"));
                    ARefreshGUIAfterPosting = true;
                }
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                FPostingInProgress = false;
            }

            return(true);
        }
        /// <summary>
        /// GetRecipientData
        /// </summary>
        public static void GetRecipientData(GiftBatchTDSAGiftDetailRow ACurrentDetailRow,
            long APartnerKey,
            ref TCmbAutoPopulated ACmbKeyMinistries,
            TtxtAutoPopulatedButtonLabel ATxtDetailRecipientKey,
            ref TtxtAutoPopulatedButtonLabel AtxtDetailRecipientLedgerNumber,
            bool AMotivationDetailChangedFlag)
        {
            if (APartnerKey == 0)
            {
                APartnerKey = Convert.ToInt64(ATxtDetailRecipientKey.Text);
            }

            // If this method has been called as a result of a change in motivation detail then txtDetailRecipientKey has not yet been set...
            // but we do know that the recipient must be a Unit.

            // if Family Recipient
            if (!AMotivationDetailChangedFlag && (ATxtDetailRecipientKey.CurrentPartnerClass == TPartnerClass.FAMILY))
            {
                AtxtDetailRecipientLedgerNumber.Text = ACurrentDetailRow.RecipientLedgerNumber.ToString();
                ACmbKeyMinistries.Clear();
                ACmbKeyMinistries.Enabled = false;
            }
            // if Unit Recipient
            else
            {
                TFinanceControls.GetRecipientData(ref ACmbKeyMinistries, ref AtxtDetailRecipientLedgerNumber, APartnerKey, true);

                // enable / disable combo box depending on whether it contains any key ministries
                if ((ACmbKeyMinistries.Table == null) || (ACmbKeyMinistries.Table.Rows.Count == 0))
                {
                    ACmbKeyMinistries.Enabled = false;
                }
                else
                {
                    ACmbKeyMinistries.Enabled = true;
                }
            }
        }
        /// <summary>
        /// Keep the combo and textboxes together
        /// </summary>
        public static void ReconcileKeyMinistryFromCombo(GiftBatchTDSAGiftDetailRow ACurrentDetailRow, TCmbAutoPopulated ACmbKeyMinistries,
            TextBox ATxtDetailRecipientKeyMinistry, bool AInEditModeFlag, bool ABatchUnpostedFlag)
        {
            if (ABatchUnpostedFlag && AInEditModeFlag)
            {
                string keyMinistry = string.Empty;
                bool isEmptyDetailRow = (ACurrentDetailRow == null);

                if (!isEmptyDetailRow && (ACmbKeyMinistries.SelectedIndex > -1))
                {
                    keyMinistry = ACmbKeyMinistries.GetSelectedDescription();
                }

                ATxtDetailRecipientKeyMinistry.Text = keyMinistry;
            }
        }
        /// <summary>
        /// Call when the key ministry changes
        /// </summary>
        public static void OnKeyMinistryChanged(GiftBatchTDSAGiftDetailRow ACurrentDetailRow, TFrmPetraEditUtils APetraUtilsObject,
            TCmbAutoPopulated ACmbKeyMinistries, TtxtAutoPopulatedButtonLabel ATxtDetailRecipientKey, TextBox ATxtDetailRecipientKeyMinistry,
            bool ARecipientKeyChangingFlag, ref bool AInKeyMinistryChangingFlag)
        {
            if ((ACurrentDetailRow == null) || AInKeyMinistryChangingFlag || ARecipientKeyChangingFlag
                || APetraUtilsObject.SuppressChangeDetection || ATxtDetailRecipientKeyMinistry.Visible)
            {
                return;
            }

            string KeyMinistry = ACmbKeyMinistries.GetSelectedDescription();
            string RecipientKey = ACmbKeyMinistries.GetSelectedInt64().ToString();

            try
            {
                AInKeyMinistryChangingFlag = true;

                if (ACmbKeyMinistries.Count == 0)
                {
                    ACmbKeyMinistries.SelectedIndex = -1;

                    if (ATxtDetailRecipientKeyMinistry.Text != string.Empty)
                    {
                        ATxtDetailRecipientKeyMinistry.Text = string.Empty;
                    }
                }
                else
                {
                    // if key ministry has actually changed
                    if ((ATxtDetailRecipientKeyMinistry.Text != KeyMinistry)
                        || (ACurrentDetailRow.RecipientKeyMinistry != KeyMinistry))
                    {
                        ATxtDetailRecipientKeyMinistry.Text = KeyMinistry;
                        ACurrentDetailRow.RecipientKeyMinistry = KeyMinistry;
                    }

                    if (Convert.ToInt64(ATxtDetailRecipientKey.Text) != Convert.ToInt64(RecipientKey))
                    {
                        ATxtDetailRecipientKey.Text = RecipientKey;
                    }
                }
            }
            finally
            {
                AInKeyMinistryChangingFlag = false;
            }
        }
        /// <summary>
        /// Update the transaction method payment from outside
        /// </summary>
        public void UpdateMethodOfPayment()
        {
            Int32 LedgerNumber;
            Int32 BatchNumber;

            if (!((TFrmGiftBatch)this.ParentForm).GetBatchControl().FBatchLoaded)
            {
                return;
            }

            FBatchRow = GetBatchRow();

            if (FBatchRow == null)
            {
                FBatchRow = ((TFrmGiftBatch)this.ParentForm).GetBatchControl().GetSelectedDetailRow();
            }

            FBatchMethodOfPayment = ((TFrmGiftBatch)this.ParentForm).GetBatchControl().MethodOfPaymentCode;

            LedgerNumber = FBatchRow.LedgerNumber;
            BatchNumber  = FBatchRow.BatchNumber;

            if (!LoadGiftDataForBatch(LedgerNumber, BatchNumber))
            {
                //No transactions exist to process or corporate exchange rate not found
                return;
            }

            if ((FLedgerNumber == LedgerNumber) && (FBatchNumber == BatchNumber))
            {
                //Rows already active in transaction tab. Need to set current row ac code below will not update selected row
                if (FPreviouslySelectedDetailRow != null)
                {
                    FPreviouslySelectedDetailRow.MethodOfPaymentCode = FBatchMethodOfPayment;
                    cmbDetailMethodOfPaymentCode.SetSelectedString(FBatchMethodOfPayment);
                }
            }

            //Update all transactions
            DataView GiftView = new DataView(FMainDS.AGift);

            GiftView.RowStateFilter = DataViewRowState.CurrentRows;
            GiftView.RowFilter      = String.Format("{0}={1}",
                                                    AGiftTable.GetBatchNumberDBName(),
                                                    BatchNumber);

            foreach (DataRowView drv in GiftView)
            {
                AGiftRow giftRow = (AGiftRow)drv.Row;
                giftRow.MethodOfPaymentCode = FBatchMethodOfPayment;
            }

            //Do same at detail level to update the grid
            DataView GiftDetailView = new DataView(FMainDS.AGiftDetail);

            GiftDetailView.RowStateFilter = DataViewRowState.CurrentRows;
            GiftDetailView.RowFilter      = String.Format("{0}={1}",
                                                          AGiftDetailTable.GetBatchNumberDBName(),
                                                          BatchNumber);

            foreach (DataRowView drv in GiftDetailView)
            {
                GiftBatchTDSAGiftDetailRow giftDetailRow = (GiftBatchTDSAGiftDetailRow)drv.Row;
                giftDetailRow.MethodOfPaymentCode = FBatchMethodOfPayment;
            }
        }
Example #59
0
        public static Int32 FieldChangeAdjustment(Int32 ALedgerNumber,
                                                  Int64 ARecipientKey,
                                                  DateTime AStartDate,
                                                  DateTime AEndDate,
                                                  Int64 AOldField,
                                                  DateTime ADateCorrection,
                                                  bool AWithReceipt)
        {
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);
            GiftBatchTDS   oldGiftDS   = new GiftBatchTDS();

            try
            {
                // find all gifts that need reversing.
                // criteria:
                // posted gift batches only
                // no adjusted/reversed gifts
                // date of gift batch in specified date range
                // recipient field is the old field
                string SqlStmt = TDataBase.ReadSqlFile("Gift.GetGiftsToReverse.sql");

                List <OdbcParameter> parameters = new List <OdbcParameter>();
                OdbcParameter        param      = new OdbcParameter("LedgerNumber", OdbcType.Int);
                param.Value = ALedgerNumber;
                parameters.Add(param);
                param       = new OdbcParameter("StartDate", OdbcType.Date);
                param.Value = AStartDate;
                parameters.Add(param);
                param       = new OdbcParameter("EndDate", OdbcType.Date);
                param.Value = AEndDate;
                parameters.Add(param);
                param       = new OdbcParameter("RecipientKey", OdbcType.BigInt);
                param.Value = ARecipientKey;
                parameters.Add(param);
                param       = new OdbcParameter("OldField", OdbcType.BigInt);
                param.Value = AOldField;
                parameters.Add(param);

                DBAccess.GDBAccessObj.Select(oldGiftDS, SqlStmt, oldGiftDS.AGiftDetail.TableName, Transaction, parameters.ToArray());

                // load the gift and the gift batch records if they have not been loaded yet
                foreach (AGiftDetailRow giftdetail in oldGiftDS.AGiftDetail.Rows)
                {
                    oldGiftDS.AGift.DefaultView.RowFilter = String.Format("{0} = {1} and {2} = {3}",
                                                                          AGiftTable.GetBatchNumberDBName(),
                                                                          giftdetail.BatchNumber,
                                                                          AGiftTable.GetGiftTransactionNumberDBName(),
                                                                          giftdetail.GiftTransactionNumber);

                    if (oldGiftDS.AGift.DefaultView.Count == 0)
                    {
                        AGiftTable tempGiftTable =
                            AGiftAccess.LoadByPrimaryKey(giftdetail.LedgerNumber,
                                                         giftdetail.BatchNumber,
                                                         giftdetail.GiftTransactionNumber,
                                                         Transaction);
                        oldGiftDS.AGift.Merge(tempGiftTable);
                    }

                    oldGiftDS.AGiftBatch.DefaultView.RowFilter = String.Format("{0} = {1}",
                                                                               AGiftTable.GetBatchNumberDBName(),
                                                                               giftdetail.BatchNumber);

                    if (oldGiftDS.AGiftBatch.DefaultView.Count == 0)
                    {
                        AGiftBatchTable tempGiftBatchTable =
                            AGiftBatchAccess.LoadByPrimaryKey(giftdetail.LedgerNumber,
                                                              giftdetail.BatchNumber,
                                                              Transaction);
                        oldGiftDS.AGiftBatch.Merge(tempGiftBatchTable);
                    }
                }

                DBAccess.GDBAccessObj.RollbackTransaction();
            }
            catch (Exception)
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
                throw;
            }

            // we need to create a gift batch for each set of gifts with the same Currency, BankAccountCode, BankCostCentre, and Gift Type
            SortedList <string, GiftBatchTDS> NewGiftBatches = new SortedList <string, GiftBatchTDS>();

            foreach (GiftBatchTDSAGiftDetailRow oldGiftDetail in oldGiftDS.AGiftDetail.Rows)
            {
                // get the gift batch row for this detail
                oldGiftDS.AGiftBatch.DefaultView.RowFilter =
                    String.Format("{0} = {1}",
                                  AGiftTable.GetBatchNumberDBName(), oldGiftDetail.BatchNumber);

                AGiftBatchRow oldGiftBatch = (AGiftBatchRow)oldGiftDS.AGiftBatch.DefaultView[0].Row;

                GiftBatchTDS GiftDS = CreateNewGiftBatch(NewGiftBatches, oldGiftBatch, ADateCorrection);

                AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];

                // get the gift row for this detail
                DataView v = oldGiftDS.AGift.DefaultView;
                v.RowFilter =
                    String.Format("{0} = {1} and {2} = {3}",
                                  AGiftTable.GetBatchNumberDBName(), oldGiftDetail.BatchNumber,
                                  AGiftTable.GetGiftTransactionNumberDBName(), oldGiftDetail.GiftTransactionNumber);

                AGiftRow oldGift = (AGiftRow)v[0].Row;

                AGiftRow gift = GiftDS.AGift.NewRowTyped();
                gift.LedgerNumber          = giftbatchRow.LedgerNumber;
                gift.BatchNumber           = giftbatchRow.BatchNumber;
                gift.GiftTransactionNumber = giftbatchRow.LastGiftNumber + 1;
                gift.DonorKey    = oldGift.DonorKey;
                gift.DateEntered = ADateCorrection;
                giftbatchRow.LastGiftNumber++;
                GiftDS.AGift.Rows.Add(gift);

                if (!AWithReceipt)
                {
                    gift.ReceiptLetterCode = "NO*RECET";
                }

                // reverse the original gift
                GiftBatchTDSAGiftDetailRow detail = GiftDS.AGiftDetail.NewRowTyped();

                DataUtilities.CopyAllColumnValues(oldGiftDetail, detail);

                detail.LedgerNumber          = gift.LedgerNumber;
                detail.BatchNumber           = gift.BatchNumber;
                detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                detail.DetailNumber          = gift.LastDetailNumber + 1;
                detail.GiftAmount            = detail.GiftAmount * -1;
                detail.GiftAmountIntl        = detail.GiftAmountIntl * -1;
                detail.GiftTransactionAmount = detail.GiftTransactionAmount * -1;
                gift.LastDetailNumber++;

                GiftDS.AGiftDetail.Rows.Add(detail);

                // create the detail for the corrected gift to the new field
                detail = GiftDS.AGiftDetail.NewRowTyped();

                DataUtilities.CopyAllColumnValues(oldGiftDetail, detail);

                detail.LedgerNumber          = gift.LedgerNumber;
                detail.BatchNumber           = gift.BatchNumber;
                detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                detail.DetailNumber          = gift.LastDetailNumber + 1;
                detail.GiftCommentOne        = String.Format(Catalog.GetString("posted on {0}"), oldGiftBatch.GlEffectiveDate.ToShortDateString());
                gift.LastDetailNumber++;

                // TODO: calculate costcentre code from current commitment; this currently is done only at time of posting
                // detail.RecipientLedgerNumber = oldGiftDetail.RecipientLedgerNumber;
                // detail.CostCentreCode = oldGiftDetail.CostCentreCode;

                GiftDS.AGiftDetail.Rows.Add(detail);

                // TODO: how to make sure that the gl transaction is marked as System generated? avoid display on HOSA?

                // mark original gift detail as modified
                oldGiftDetail.ModifiedDetail = true;
            }

            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = TSubmitChangesResult.scrOK;

            for (Int32 batchCounter = 0; batchCounter < NewGiftBatches.Count; batchCounter++)
            {
                if (result == TSubmitChangesResult.scrOK)
                {
                    GiftBatchTDS GiftDS = NewGiftBatches.Values[batchCounter];
                    result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref GiftDS, out VerificationResult);
                }
            }

            if (result == TSubmitChangesResult.scrOK)
            {
                result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref oldGiftDS, out VerificationResult);

                if ((result == TSubmitChangesResult.scrOK) && (NewGiftBatches.Count > 0))
                {
                    return(NewGiftBatches.Values[0].AGiftBatch[0].BatchNumber);
                }
            }

            return(-1);
        }
 /// <summary>
 /// UpdateRecipientKeyText
 /// </summary>
 public static void UpdateRecipientKeyText(Int64 APartnerKey,
     GiftBatchTDSAGiftDetailRow ACurrentDetailRow,
     string AMotivationGroupCode,
     string AMotivationDetailCode)
 {
     if ((APartnerKey == 0) && (ACurrentDetailRow != null))
     {
         if (AMotivationGroupCode != MFinanceConstants.MOTIVATION_GROUP_GIFT)
         {
             ACurrentDetailRow.RecipientDescription = AMotivationDetailCode;
         }
         else
         {
             ACurrentDetailRow.RecipientDescription = string.Empty;
         }
     }
 }