Example #1
0
        private String InferCostCentre(AGiftDetailRow AgiftDetails)
        {
            String costCentre = "";

            if (!Common.Common.HasPartnerCostCentreLink(AgiftDetails.RecipientKey, out costCentre))
            {
                // There's no helpful entry in a_valid_ledger_number - I'll see about using the MotivationDetail.
                AMotivationDetailRow mdRow = FMainDS.AMotivationDetail.NewRowTyped(false);
                mdRow.LedgerNumber = AgiftDetails.LedgerNumber;
                mdRow.MotivationGroupCode = AgiftDetails.MotivationGroupCode;
                mdRow.MotivationDetailCode = AgiftDetails.MotivationDetailCode;
                AMotivationDetailTable tempTbl = null;

                TDBTransaction Transaction = null;
                DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                    TEnforceIsolationLevel.eilMinimum,
                    ref Transaction,
                    delegate
                    {
                        tempTbl = AMotivationDetailAccess.LoadUsingTemplate(mdRow, Transaction);
                    });

                if (tempTbl.Rows.Count > 0)
                {
                    costCentre = tempTbl[0].CostCentreCode;
                }
            }

            return costCentre;
        }
        /// <summary>
        /// Calculate the Tax-Deductible and Non-Deductible Transaction, Base and Intl amounts for a Gift Detail
        /// </summary>
        /// <param name="AGiftDetail"></param>
        public static void UpdateTaxDeductibiltyAmounts(ref AGiftDetailRow AGiftDetail)
        {
            /* Update transaction amounts */

            decimal TaxDeductAmount;
            decimal NonDeductAmount;

            CalculateTaxDeductibilityAmounts(
                out TaxDeductAmount, out NonDeductAmount, AGiftDetail.GiftTransactionAmount, AGiftDetail.TaxDeductiblePct);

            AGiftDetail.TaxDeductibleAmount = TaxDeductAmount;
            AGiftDetail.NonDeductibleAmount = NonDeductAmount;

            /* Update base amounts */

            CalculateTaxDeductibilityAmounts(
                out TaxDeductAmount, out NonDeductAmount, AGiftDetail.GiftAmount, AGiftDetail.TaxDeductiblePct);

            AGiftDetail.TaxDeductibleAmountBase = TaxDeductAmount;
            AGiftDetail.NonDeductibleAmountBase = NonDeductAmount;

            /* Update intl amounts */

            CalculateTaxDeductibilityAmounts(
                out TaxDeductAmount, out NonDeductAmount, AGiftDetail.GiftAmountIntl, AGiftDetail.TaxDeductiblePct);

            AGiftDetail.TaxDeductibleAmountIntl = TaxDeductAmount;
            AGiftDetail.NonDeductibleAmountIntl = NonDeductAmount;
        }
Example #3
0
        /// <summary>
        /// Calculate the Tax-Deductible and Non-Deductible Transaction, Base and Intl amounts for a Gift Detail
        /// </summary>
        /// <param name="AGiftDetail"></param>
        public static void UpdateTaxDeductibiltyAmounts(ref AGiftDetailRow AGiftDetail)
        {
            decimal TaxDeductAmount;
            decimal NonDeductAmount;

            if (AGiftDetail == null)
            {
                return;
            }
            else if (AGiftDetail.IsTaxDeductiblePctNull())
            {
                AGiftDetail.TaxDeductiblePct = 0.0m;
            }

            AGiftDetail.TaxDeductiblePct = Math.Max(AGiftDetail.TaxDeductiblePct, 0);
            AGiftDetail.TaxDeductiblePct = Math.Min(AGiftDetail.TaxDeductiblePct, 100);

            /* Update transaction amounts */
            CalculateTaxDeductibilityAmounts(
                out TaxDeductAmount, out NonDeductAmount, AGiftDetail.GiftTransactionAmount, AGiftDetail.TaxDeductiblePct);

            if (AGiftDetail.IsTaxDeductibleAmountNull() ||
                AGiftDetail.IsNonDeductibleAmountNull() ||
                (AGiftDetail.TaxDeductibleAmount != TaxDeductAmount) ||
                (AGiftDetail.NonDeductibleAmount != NonDeductAmount))
            {
                AGiftDetail.TaxDeductibleAmount = TaxDeductAmount;
                AGiftDetail.NonDeductibleAmount = NonDeductAmount;
            }

            /* Update base amounts */
            TaxDeductAmount = 0.0m;
            NonDeductAmount = 0.0m;
            CalculateTaxDeductibilityAmounts(
                out TaxDeductAmount, out NonDeductAmount, AGiftDetail.GiftAmount, AGiftDetail.TaxDeductiblePct);

            if (AGiftDetail.IsTaxDeductibleAmountBaseNull() ||
                AGiftDetail.IsNonDeductibleAmountBaseNull() ||
                (AGiftDetail.TaxDeductibleAmountBase != TaxDeductAmount) ||
                (AGiftDetail.NonDeductibleAmountBase != NonDeductAmount))
            {
                AGiftDetail.TaxDeductibleAmountBase = TaxDeductAmount;
                AGiftDetail.NonDeductibleAmountBase = NonDeductAmount;
            }

            /* Update intl amounts */
            TaxDeductAmount = 0.0m;
            NonDeductAmount = 0.0m;
            CalculateTaxDeductibilityAmounts(
                out TaxDeductAmount, out NonDeductAmount, AGiftDetail.GiftAmountIntl, AGiftDetail.TaxDeductiblePct);

            if (AGiftDetail.IsTaxDeductibleAmountIntlNull() ||
                AGiftDetail.IsNonDeductibleAmountIntlNull() ||
                (AGiftDetail.TaxDeductibleAmountIntl != TaxDeductAmount) ||
                (AGiftDetail.NonDeductibleAmountIntl != NonDeductAmount))
            {
                AGiftDetail.TaxDeductibleAmountIntl = TaxDeductAmount;
                AGiftDetail.NonDeductibleAmountIntl = NonDeductAmount;
            }
        }
Example #4
0
        private Boolean IsAdjustmentToReversedDetail(AGiftDetailRow ARow)
        {
            // This method returns true if the gift detail row is an unposted adjustement to a reversed gift detail
            // We use the LinkToPreviousGift property to discover if this gift is associated with the previous gift row.
            // Then we check if that row has a modifiedDetail flag sets for its first detail.
            if ((ARow == null) || (FBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return(false);
            }

            AGiftRow giftRow = GetGiftRow(ARow.GiftTransactionNumber);

            if ((giftRow != null) && (giftRow.LinkToPreviousGift == true))
            {
                if (ARow.GiftTransactionNumber > 1)
                {
                    AGiftDetailRow prevDetailRow = (AGiftDetailRow)FMainDS.AGiftDetail.Rows.Find(
                        new object[] { ARow.LedgerNumber, ARow.BatchNumber, ARow.GiftTransactionNumber - 1, 1 });

                    return(prevDetailRow.ModifiedDetail == true);
                }
            }

            return(false);
        }
Example #5
0
        public void TestModifyGiftBatch()
        {
            TDataBase      db = DBAccess.Connect("test");
            TDBTransaction t  = db.BeginTransaction(IsolationLevel.Serializable);

            GiftBatchTDS MainDS;

            ALedgerAccess.LoadAll(MainDS, t);

            MainDS.ALedger[0].LastGiftBatchNumber++;

            AGiftBatchRow batch = MainDS.AGiftBatch.NewRowTyped();

            batch.LedgerNumber    = MainDS.ALedger[0].LedgerNumber;
            batch.BatchNumber     = MainDS.ALedger[0].LastGiftBatchNumber;
            batch.BankAccountCode = "6000";
            batch.BatchYear       = 1;
            batch.BatchPeriod     = 1;
            batch.CurrencyCode    = "EUR";
            batch.BankCostCentre  = MainDS.ALedger[0].LedgerNumber.ToString() + "00";
            batch.LastGiftNumber  = 2;
            MainDS.AGiftBatch.Rows.Add(batch);

            AGiftRow gift = MainDS.AGift.NewRowTyped();

            gift.LedgerNumber          = batch.LedgerNumber;
            gift.BatchNumber           = batch.BatchNumber;
            gift.GiftTransactionNumber = 1;
            MainDS.AGift.Rows.Add(gift);

            gift = MainDS.AGift.NewRowTyped();
            gift.LedgerNumber          = batch.LedgerNumber;
            gift.BatchNumber           = batch.BatchNumber;
            gift.GiftTransactionNumber = 2;
            gift.LastDetailNumber      = 1;
            MainDS.AGift.Rows.Add(gift);

            AGiftDetailRow giftdetail = MainDS.AGiftDetail.NewRowTyped();

            giftdetail.LedgerNumber          = gift.LedgerNumber;
            giftdetail.BatchNumber           = gift.BatchNumber;
            giftdetail.GiftTransactionNumber = gift.GiftTransactionNumber;
            giftdetail.DetailNumber          = 1;
            giftdetail.MotivationGroupCode   = "GIFT";
            giftdetail.MotivationDetailCode  = "SUPPORT";
            MainDS.AGiftDetail.Rows.Add(giftdetail);

            MainDS.SubmitChanges(t);
            t.Commit();

            // now delete the first gift, and fix the gift detail of the second gift
            t = db.BeginTransaction(IsolationLevel.Serializable);
            MainDS.AGift.Rows.RemoveAt(0);
            MainDS.AGift[0].GiftTransactionNumber       = 1;
            MainDS.AGiftDetail[0].GiftTransactionNumber = 1;
            MainDS.AGiftBatch[0].LastGiftNumber         = 1;

            MainDS.SubmitChanges(t);
            g.Commit();
        }
Example #6
0
 /// <summary>
 /// find a special gift detail
 /// </summary>
 public void FindGiftDetail(AGiftDetailRow gdr)
 {
     //TODO add to other forms
     ucoBatches.SelectBatchNumber(gdr.BatchNumber);
     ucoTransactions.SelectGiftDetailNumber(gdr.GiftTransactionNumber, gdr.DetailNumber);
     DefaultTabIndex = 1;     // later we switch to the detail tab
 }
Example #7
0
        /// <summary>
        /// Sets TaxDeductiblePct and uses it to calculate the tax deductibility amounts for a Gift Detail
        /// </summary>
        /// <param name="AGiftDetail">Calculated amounts are added to this row</param>
        /// <param name="ADateEntered"></param>
        /// <param name="ATransaction"></param>
        public static void SetDefaultTaxDeductibilityData(
            ref AGiftDetailRow AGiftDetail, DateTime ADateEntered, TDBTransaction ATransaction)
        {
            bool FoundTaxDeductiblePct = false;

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

                Boolean HasTaxDeductibleAccountCode = false;

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

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

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

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

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

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

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

                    try
                    {
                        decimal percentageVal = txtDeductiblePercentage.NumberValueDecimal.Value;

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

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

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

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

            txtTaxDeductAmount.NumberValueDecimal = FPreviouslySelectedDetailRow.TaxDeductibleAmount;
            txtNonDeductAmount.NumberValueDecimal = FPreviouslySelectedDetailRow.NonDeductibleAmount;
        }
        /// create new gift info
        public static AGiftBatchRow CreateNewGiftInfo(Int64 APartnerKey, ref GiftBatchTDS AGiftDS, TDataBase ADataBase = null)
        {
            TDataBase      db = DBAccess.Connect("CreateNewGiftInfo", ADataBase);
            bool           NewTransaction;
            TDBTransaction Transaction = db.GetNewOrExistingTransaction(IsolationLevel.Serializable, out NewTransaction);

            ALedgerAccess.LoadAll(AGiftDS, Transaction);

            AGiftDS = TGiftTransactionWebConnector.CreateAGiftBatch(AGiftDS.ALedger[0].LedgerNumber, DateTime.Today, "Test batch", db);

            // Create a new GiftBatch
            AGiftBatchRow Batch = AGiftDS.AGiftBatch[0];

            Batch.BankAccountCode    = "6000";
            Batch.BatchYear          = 1;
            Batch.BatchPeriod        = 1;
            Batch.CurrencyCode       = "EUR";
            Batch.BankCostCentre     = Batch.LedgerNumber.ToString() + "00";
            Batch.LastGiftNumber     = 1;
            Batch.ExchangeRateToBase = 0.5M;

            // Create a new Gift record
            AGiftRow Gift = AGiftDS.AGift.NewRowTyped();

            Gift.LedgerNumber          = Batch.LedgerNumber;
            Gift.BatchNumber           = Batch.BatchNumber;
            Gift.GiftTransactionNumber = 1;
            Gift.DonorKey = APartnerKey;
            AGiftDS.AGift.Rows.Add(Gift);

            // Create a new GiftDetail record
            AGiftDetailRow GiftDetail = AGiftDS.AGiftDetail.NewRowTyped();

            GiftDetail.LedgerNumber          = Gift.LedgerNumber;
            GiftDetail.BatchNumber           = Gift.BatchNumber;
            GiftDetail.GiftTransactionNumber = Gift.GiftTransactionNumber;
            GiftDetail.DetailNumber          = 1;
            GiftDetail.MotivationGroupCode   = "GIFT";
            GiftDetail.MotivationDetailCode  = "SUPPORT";
            // this won't work with RecipientKey 0 anymore. see https://github.com/openpetra/openpetra/issues/183
            GiftDetail.RecipientKey          = 43000000;
            GiftDetail.RecipientLedgerNumber = APartnerKey;
            GiftDetail.GiftTransactionAmount = 10;
            AGiftDS.AGiftDetail.Rows.Add(GiftDetail);

            if (NewTransaction)
            {
                Transaction.Rollback();
            }

            return(Batch);
        }
Example #10
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;
            }
        }
Example #11
0
        public static bool CheckGiftsNotPreviouslyReversed(GiftBatchTDS AGiftDS, out TVerificationResultCollection AMessages)
        {
            string Message   = string.Empty;
            int    GiftCount = 0;

            AMessages = new TVerificationResultCollection();

            // sort gifts
            AGiftDS.AGiftDetail.DefaultView.Sort = string.Format("{0}, {1}, {2}",
                                                                 AGiftDetailTable.GetBatchNumberDBName(),
                                                                 AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                 AGiftDetailTable.GetDetailNumberDBName());

            foreach (DataRowView RowView in AGiftDS.AGiftDetail.DefaultView)
            {
                AGiftDetailRow GiftDetailRow = (AGiftDetailRow)RowView.Row;

                if (GiftDetailRow.ModifiedDetail)
                {
                    Message += "\n" + String.Format(Catalog.GetString("Gift {0} with Detail {1} in Batch {2}"),
                                                    GiftDetailRow.GiftTransactionNumber, GiftDetailRow.DetailNumber, GiftDetailRow.BatchNumber);

                    GiftCount++;
                }
            }

            if (GiftCount != 0)
            {
                if (GiftCount > 1)
                {
                    Message = String.Format(Catalog.GetString("Cannot reverse or adjust the following gifts:")) + "\n" + Message +
                              "\n\n" + Catalog.GetString("They have already been adjusted or reversed.");
                }
                else if (GiftCount == 1)
                {
                    Message = String.Format(Catalog.GetString("Cannot reverse or adjust the following gift:")) + "\n" + Message +
                              "\n\n" + Catalog.GetString("It has already been adjusted or reversed.");
                }

                AMessages.Add(new TVerificationResult(null, Message, TResultSeverity.Resv_Critical));

                return(false);
            }

            return(true);
        }
        public static void UpdateUnpostedGiftsTaxDeductiblePct(Int64 ARecipientKey, decimal ANewPct, DateTime ADateFrom)
        {
            TDBTransaction Transaction  = null;
            bool           SubmissionOK = false;

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

                               " FROM a_gift_detail, a_gift_batch, a_gift" +

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

                AGiftDetailTable Table = new AGiftDetailTable();

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

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

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

                AGiftDetailAccess.SubmitChanges(Table, Transaction);

                SubmissionOK = true;
            });
        }
        /// create new gift info
        public static AGiftBatchRow CreateNewGiftInfo(Int64 APartnerKey, ref GiftBatchTDS AGiftDS)
        {
            ALedgerAccess.LoadAll(AGiftDS, DBAccess.GDBAccessObj.Transaction);

            AGiftDS = TGiftTransactionWebConnector.CreateAGiftBatch(AGiftDS.ALedger[0].LedgerNumber, DateTime.Today, "Test batch");

            // Create a new GiftBatch
            AGiftBatchRow Batch = AGiftDS.AGiftBatch[0];

            Batch.BankAccountCode    = "6000";
            Batch.BatchYear          = 1;
            Batch.BatchPeriod        = 1;
            Batch.CurrencyCode       = "EUR";
            Batch.BankCostCentre     = Batch.LedgerNumber.ToString() + "00";
            Batch.LastGiftNumber     = 1;
            Batch.ExchangeRateToBase = 0.5M;

            // Create a new Gift record
            AGiftRow Gift = AGiftDS.AGift.NewRowTyped();

            Gift.LedgerNumber          = Batch.LedgerNumber;
            Gift.BatchNumber           = Batch.BatchNumber;
            Gift.GiftTransactionNumber = 1;
            Gift.DonorKey = APartnerKey;
            AGiftDS.AGift.Rows.Add(Gift);

            // Create a new GiftDetail record
            AGiftDetailRow GiftDetail = AGiftDS.AGiftDetail.NewRowTyped();

            GiftDetail.LedgerNumber          = Gift.LedgerNumber;
            GiftDetail.BatchNumber           = Gift.BatchNumber;
            GiftDetail.GiftTransactionNumber = Gift.GiftTransactionNumber;
            GiftDetail.DetailNumber          = 1;
            GiftDetail.MotivationGroupCode   = "GIFT";
            GiftDetail.MotivationDetailCode  = "SUPPORT";
            GiftDetail.RecipientKey          = 0;
            GiftDetail.RecipientLedgerNumber = APartnerKey;
            AGiftDS.AGiftDetail.Rows.Add(GiftDetail);

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

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

            DataView transDV = new DataView(FMainDS.AGiftDetail);

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

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

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

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

                if (FSETUseTaxDeductiblePercentageFlag)
                {
                    TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref gdr);
                }
            }
        }
Example #15
0
        /// <summary>
        /// Delete data from current gift batch
        /// </summary>
        /// <param name="ABatchNumber"></param>
        /// <param name="AModifiedDetailKeyRows"></param>
        public void DeleteBatchGiftData(Int32 ABatchNumber, ref List <string> AModifiedDetailKeyRows)
        {
            DataView giftDetailView = new DataView(FMainDS.AGiftDetail);

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

            giftDetailView.Sort = String.Format("{0} DESC, {1} DESC",
                                                AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                AGiftDetailTable.GetDetailNumberDBName());

            foreach (DataRowView dr in giftDetailView)
            {
                AGiftDetailRow gdr = (AGiftDetailRow)dr.Row;

                if (gdr.ModifiedDetail && !string.IsNullOrEmpty(gdr.ModifiedDetailKey))
                {
                    AModifiedDetailKeyRows.Add(gdr.ModifiedDetailKey);
                }

                dr.Delete();
            }

            DataView GiftView = new DataView(FMainDS.AGift);

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

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

            foreach (DataRowView dr in GiftView)
            {
                dr.Delete();
            }
        }
Example #16
0
        private void DeleteCurrentBatchGiftData(Int32 ABatchNumber, ref List <string> AModifiedDetailKeyRows)
        {
            DataView giftDetailView = new DataView(FMainDS.AGiftDetail);

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

            giftDetailView.Sort = String.Format("{0} DESC, {1} DESC",
                                                AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                AGiftDetailTable.GetDetailNumberDBName());

            foreach (DataRowView dr in giftDetailView)
            {
                AGiftDetailRow gdr = (AGiftDetailRow)dr.Row;

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

                dr.Delete();
            }

            DataView giftView = new DataView(FMainDS.AGift);

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

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

            foreach (DataRowView dr in giftView)
            {
                dr.Delete();
            }
        }
        // update tax deductibility amounts when the gift amount or the tax deductible percentage has changed
        private void UpdateTaxDeductibilityAmounts(object sender, EventArgs e)
        {
            if (FCreatingNewGift || (txtDeductiblePercentage.NumberValueDecimal == null) || (FPreviouslySelectedDetailRow == null))
            {
                return;
            }

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

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

            AGiftDetailRow giftDetails = (AGiftDetailRow)FPreviouslySelectedDetailRow;

            TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetails);

            txtTaxDeductAmount.NumberValueDecimal = FPreviouslySelectedDetailRow.TaxDeductibleAmount;
            txtNonDeductAmount.NumberValueDecimal = FPreviouslySelectedDetailRow.NonDeductibleAmount;
        }
Example #18
0
        public void TestRecurringBatchSubmitRecalculations()
        {
            TVerificationResultCollection VerificationResult;

            Int64 RecipientKey;
            Int64 RealRecipientLedgerNumber;
            Int64 FalseRecipientLedgerNumber;
            Int32 RecurringGiftBatchNumber;
            Int32 GiftBatchNumber = -1;

            //
            // Arrange: Create all data needed for this test (Recurring Gift Detail will have 'fake' RecipientLedgerNumber)
            //
            TestRecurringBatchSubmitRecalculations_Arrange(out RecipientKey, out RealRecipientLedgerNumber,
                                                           out FalseRecipientLedgerNumber, out RecurringGiftBatchNumber);

            //
            // Act: Submit the batch
            //

            Hashtable requestParams = new Hashtable();

            requestParams.Add("ALedgerNumber", FLedgerNumber);
            requestParams.Add("ABatchNumber", RecurringGiftBatchNumber);
            requestParams.Add("AEffectiveDate", DateTime.Today);
            requestParams.Add("AExchangeRateToBase", (decimal)1);
            requestParams.Add("AExchangeRateIntlToBase", (decimal)1);

            TGiftTransactionWebConnector.SubmitRecurringGiftBatch(requestParams);

            //
            // Assert
            //

            // Primary Assert: Chaeck that the RecurringGiftDetail and the newly created GiftDetail have the correct RecipientLedgerNumber
            TDBTransaction          Transaction            = null;
            ARecurringGiftDetailRow RecurringGiftDetailRow = null;
            AGiftDetailRow          GiftDetailRow          = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.Serializable,
                                                                      TEnforceIsolationLevel.eilMinimum,
                                                                      ref Transaction,
                                                                      delegate
            {
                RecurringGiftDetailRow =
                    ARecurringGiftDetailAccess.LoadByPrimaryKey(FLedgerNumber, RecurringGiftBatchNumber, 1, 1, Transaction)[0];

                GiftBatchNumber = ALedgerAccess.LoadByPrimaryKey(FLedgerNumber, Transaction)[0].LastGiftBatchNumber;
                GiftDetailRow   = AGiftDetailAccess.LoadByPrimaryKey(FLedgerNumber, GiftBatchNumber, 1, 1, Transaction)[0];
            });

            Assert.IsNotNull(
                RecurringGiftDetailRow, "TestRecurringBatchSubmitRecalculations fail: Obtaining RecurringGiftDetailRow from database failed");
            Assert.IsNotNull(
                GiftDetailRow, "TestRecurringBatchSubmitRecalculations fail: Obtaining GiftDetailRow from database failed");

            Assert.AreEqual(RealRecipientLedgerNumber, RecurringGiftDetailRow.RecipientLedgerNumber,
                            "TestRecurringBatchSubmitRecalculations fail: RecipientLedgerNumber for RecurringGiftDetailRow is incorrect");
            Assert.AreEqual(RealRecipientLedgerNumber, GiftDetailRow.RecipientLedgerNumber,
                            "TestRecurringBatchSubmitRecalculations fail: RecipientLedgerNumber for GiftDetailRow is incorrect");

            // Cleanup: Delete test records

            bool SubmissionOK = true;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable,
                                                                  TEnforceIsolationLevel.eilMinimum,
                                                                  ref Transaction,
                                                                  ref SubmissionOK,
                                                                  delegate
            {
                AGiftDetailAccess.DeleteRow(AGiftDetailTable.TableId, GiftDetailRow, Transaction);
                ARecurringGiftDetailAccess.DeleteRow(ARecurringGiftDetailTable.TableId, RecurringGiftDetailRow, Transaction);
            });

            TPartnerWebConnector.DeletePartner(RecipientKey, out VerificationResult);
            TPartnerWebConnector.DeletePartner(RealRecipientLedgerNumber, out VerificationResult);
            TPartnerWebConnector.DeletePartner(FalseRecipientLedgerNumber, out VerificationResult);
        }
Example #19
0
 /// <summary>
 /// find a special gift detail
 /// </summary>
 public void FindGiftDetail(AGiftDetailRow gdr)
 {
     ucoBatches.SelectBatchNumber(gdr.BatchNumber);
     ucoTransactions.SelectGiftDetailNumber(gdr.GiftTransactionNumber, gdr.DetailNumber);
     standardTabIndex = 1;     // later we switch to the detail tab
 }
Example #20
0
        public void TestBatchLoadingRecalculations()
        {
            TVerificationResultCollection VerificationResult;

            Int64        RecipientKey;
            Int64        RealRecipientLedgerNumber;
            Int64        FalseRecipientLedgerNumber;
            const string REALCOSTCENTRECODE  = "4300";
            const string FALSECOSTCENTRECODE = "3500";
            Int32        GiftBatchNumber;

            //
            // Arrange: Create all data needed for this test (Gift Detail has a 'fake' RecipientLedgerNumber and CostCentreCode)
            //
            TestBatchPostingRecalculations_Arrange(out RecipientKey, out RealRecipientLedgerNumber,
                                                   out FalseRecipientLedgerNumber, REALCOSTCENTRECODE, FALSECOSTCENTRECODE, out GiftBatchNumber);

            //
            // Act: Load the batch
            //
            GiftBatchTDS GiftBatchDS = TGiftTransactionWebConnector.LoadAGiftBatchAndRelatedData(FLedgerNumber, GiftBatchNumber);

            //
            // Assert
            //

            // Initial Assert: Tests that the load returns results
            Assert.IsNotNull(GiftBatchDS, "TestBatchLoadingRecalculations fail: Loading GiftBatch failed");
            Assert.IsNotNull(GiftBatchDS.AGiftDetail, "TestBatchLoadingRecalculations fail: Loading GiftBatch failed");

            // Primary Assert: Chaeck that the gift has the correct RecipientLedgerNumber and CostCentreCode
            TDBTransaction Transaction           = null;
            AGiftDetailRow PositiveGiftDetailRow = null;
            AGiftDetailRow NegativeGiftDetailRow = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                      TEnforceIsolationLevel.eilMinimum,
                                                                      ref Transaction,
                                                                      delegate
            {
                PositiveGiftDetailRow = AGiftDetailAccess.LoadByPrimaryKey(FLedgerNumber, GiftBatchNumber, 1, 1, Transaction)[0];
                NegativeGiftDetailRow = AGiftDetailAccess.LoadByPrimaryKey(FLedgerNumber, GiftBatchNumber, 2, 1, Transaction)[0];
            });

            Assert.IsNotNull(PositiveGiftDetailRow, "TestBatchPostingRecalculations fail: Obtaining PositiveGiftDetailRow from database failed");
            Assert.IsNotNull(NegativeGiftDetailRow, "TestBatchPostingRecalculations fail: Obtaining NegativeGiftDetailRow from database failed");

            Assert.AreEqual(RealRecipientLedgerNumber, PositiveGiftDetailRow.RecipientLedgerNumber,
                            "TestBatchPostingRecalculations fail: RecipientLedgerNumber for PositiveGiftDetailRow is incorrect");
            Assert.AreEqual(FalseRecipientLedgerNumber, NegativeGiftDetailRow.RecipientLedgerNumber,
                            "TestBatchPostingRecalculations fail: RecipientLedgerNumber for NegativeGiftDetailRow is incorrect");
            Assert.AreEqual(REALCOSTCENTRECODE, PositiveGiftDetailRow.CostCentreCode,
                            "TestBatchPostingRecalculations fail: CostCentreCode for PositiveGiftDetailRow is incorrect");
            Assert.AreEqual(FALSECOSTCENTRECODE, NegativeGiftDetailRow.CostCentreCode,
                            "TestBatchPostingRecalculations fail: CostCentreCode for NegativeGiftDetailRow is incorrect");

            // Cleanup: Delete test records

            bool SubmissionOK = true;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable,
                                                                  TEnforceIsolationLevel.eilMinimum,
                                                                  ref Transaction,
                                                                  ref SubmissionOK,
                                                                  delegate
            {
                AGiftDetailAccess.DeleteRow(AGiftDetailTable.TableId, PositiveGiftDetailRow, Transaction);
                AGiftDetailAccess.DeleteRow(AGiftDetailTable.TableId, NegativeGiftDetailRow, Transaction);
            });

            TPartnerWebConnector.DeletePartner(RecipientKey, out VerificationResult);
            TPartnerWebConnector.DeletePartner(RealRecipientLedgerNumber, out VerificationResult);
            TPartnerWebConnector.DeletePartner(FalseRecipientLedgerNumber, out VerificationResult);
        }
Example #21
0
        /// <summary>
        /// Creates data needed to test posting recalculations
        /// </summary>
        /// <param name="ARecipientKey">Partner Key of the recipient.</param>
        /// <param name="ARealRecipientLedgerNumber">What the RecipientLedgerNumber should be.</param>
        /// <param name="AFalseRecipientLedgerNumber">What the RecipientLedgerNumber is.</param>
        /// <param name="ARealCostCentreCode">What the CostCentreCode should be.</param>
        /// <param name="AFalseCostCentreCode">What the CostCentreCode is.</param>
        /// <param name="AGiftBatchNumber">Batch Number.</param>
        private void TestBatchPostingRecalculations_Arrange(out long ARecipientKey,
                                                            out long ARealRecipientLedgerNumber,
                                                            out long AFalseRecipientLedgerNumber,
                                                            string ARealCostCentreCode,
                                                            string AFalseCostCentreCode,
                                                            out Int32 AGiftBatchNumber)
        {
            TVerificationResultCollection VerificationResult;
            TSubmitChangesResult          Result;
            DataSet ResponseDS;
            TPartnerEditUIConnector PartnerEditUIUIConnector = new TPartnerEditUIConnector();

            GiftBatchTDS   MainDS        = new GiftBatchTDS();
            PartnerEditTDS PartnerEditDS = new PartnerEditTDS();
            //GLSetupTDS GLSetupDS = new GLSetupTDS();

            // this is a family partner in the test database
            const Int64 DONORKEY = 43005001;

            // create a new recipient
            TCreateTestPartnerData.CreateNewFamilyPartner(PartnerEditDS);
            ARecipientKey = PartnerEditDS.PFamily[0].PartnerKey;

            // create two new Unit partners
            TCreateTestPartnerData.CreateNewUnitPartner(PartnerEditDS);
            TCreateTestPartnerData.CreateNewUnitPartner(PartnerEditDS);
            AFalseRecipientLedgerNumber = PartnerEditDS.PPartner[0].PartnerKey;
            ARealRecipientLedgerNumber  = PartnerEditDS.PPartner[1].PartnerKey;

            // create a Gift Destination for family
            PPartnerGiftDestinationRow GiftDestination = PartnerEditDS.PPartnerGiftDestination.NewRowTyped(true);

            GiftDestination.Key           = TPartnerDataReaderWebConnector.GetNewKeyForPartnerGiftDestination();
            GiftDestination.PartnerKey    = ARecipientKey;
            GiftDestination.DateEffective = new DateTime(2011, 01, 01);
            GiftDestination.FieldKey      = ARealRecipientLedgerNumber;

            PartnerEditDS.PPartnerGiftDestination.Rows.Add(GiftDestination);

            // Guard Assertions
            Assert.That(PartnerEditDS.PFamily[0], Is.Not.Null);
            Assert.That(PartnerEditDS.PPartner[0], Is.Not.Null);
            Assert.That(PartnerEditDS.PPartner[1], Is.Not.Null);

            // Submit the new PartnerEditTDS records to the database
            ResponseDS = new PartnerEditTDS();
            Result     = PartnerEditUIUIConnector.SubmitChanges(ref PartnerEditDS, ref ResponseDS, out VerificationResult);

            // Guard Assertion
            Assert.That(Result, Is.EqualTo(
                            TSubmitChangesResult.scrOK), "SubmitChanges for PartnerEditDS failed: " + VerificationResult.BuildVerificationResultString());

            // link unit to Cost Centre
            DataTable PartnerCostCentreTbl = TGLSetupWebConnector.LoadCostCentrePartnerLinks(FLedgerNumber, 0);
            DataRow   PartnerCostCentreRow = PartnerCostCentreTbl.NewRow();

            PartnerCostCentreRow["PartnerKey"] = ARealRecipientLedgerNumber;
            PartnerCostCentreRow["IsLinked"]   = ARealCostCentreCode;
            PartnerCostCentreTbl.Rows.Add(PartnerCostCentreRow);
            TGLSetupWebConnector.SaveCostCentrePartnerLinks(FLedgerNumber, PartnerCostCentreTbl);

            // create a new Gift Batch
            MainDS           = TGiftTransactionWebConnector.CreateAGiftBatch(FLedgerNumber);
            AGiftBatchNumber = MainDS.AGiftBatch[0].BatchNumber;

            // create two new gifts
            AGiftRow GiftRow = MainDS.AGift.NewRowTyped(true);

            GiftRow.LedgerNumber          = FLedgerNumber;
            GiftRow.BatchNumber           = AGiftBatchNumber;
            GiftRow.DonorKey              = DONORKEY;
            GiftRow.GiftTransactionNumber = 1;
            GiftRow.LastDetailNumber      = 1;

            MainDS.AGift.Rows.Add(GiftRow);

            GiftRow = MainDS.AGift.NewRowTyped(true);

            GiftRow.LedgerNumber          = FLedgerNumber;
            GiftRow.BatchNumber           = AGiftBatchNumber;
            GiftRow.DonorKey              = DONORKEY;
            GiftRow.GiftTransactionNumber = 2;
            GiftRow.LastDetailNumber      = 1;

            MainDS.AGift.Rows.Add(GiftRow);

            // create a new GiftDetail with a positive amount
            AGiftDetailRow GiftDetail = MainDS.AGiftDetail.NewRowTyped(true);

            GiftDetail.LedgerNumber          = FLedgerNumber;
            GiftDetail.BatchNumber           = AGiftBatchNumber;
            GiftDetail.GiftTransactionNumber = 1;
            GiftDetail.DetailNumber          = 1;
            GiftDetail.RecipientLedgerNumber = AFalseRecipientLedgerNumber;
            GiftDetail.GiftAmount            = 100;
            GiftDetail.MotivationGroupCode   = "GIFT";
            GiftDetail.MotivationDetailCode  = "SUPPORT";
            GiftDetail.RecipientKey          = ARecipientKey;
            GiftDetail.CostCentreCode        = AFalseCostCentreCode;
            GiftDetail.GiftTransactionAmount = 100;

            MainDS.AGiftDetail.Rows.Add(GiftDetail);

            // create a new GiftDetail with a negative amount
            GiftDetail = MainDS.AGiftDetail.NewRowTyped(true);

            GiftDetail.LedgerNumber          = FLedgerNumber;
            GiftDetail.BatchNumber           = AGiftBatchNumber;
            GiftDetail.GiftTransactionNumber = 2;
            GiftDetail.DetailNumber          = 1;
            GiftDetail.RecipientLedgerNumber = AFalseRecipientLedgerNumber;
            GiftDetail.GiftAmount            = -100;
            GiftDetail.MotivationGroupCode   = "GIFT";
            GiftDetail.MotivationDetailCode  = "SUPPORT";
            GiftDetail.RecipientKey          = ARecipientKey;
            GiftDetail.CostCentreCode        = AFalseCostCentreCode;
            GiftDetail.GiftTransactionAmount = -100;

            MainDS.AGiftDetail.Rows.Add(GiftDetail);

            // Submit the new GiftBatchTDS records to the database
            Result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref MainDS, out VerificationResult);

            // Guard Assertion
            Assert.That(Result, Is.EqualTo(
                            TSubmitChangesResult.scrOK), "SaveGiftBatchTDS failed: " + VerificationResult.BuildVerificationResultString());
        }
 /// <summary>
 /// find a special gift detail
 /// </summary>
 public void FindGiftDetail(AGiftDetailRow gdr)
 {
     ucoBatches.SelectBatchNumber(gdr.BatchNumber);
     ucoTransactions.SelectGiftDetailNumber(gdr.GiftTransactionNumber, gdr.DetailNumber);
     standardTabIndex = 1;     // later we switch to the detail tab
 }
Example #23
0
        private void ParseTransactionLine(AGiftRow AGift, AGiftBatchRow AGiftBatch, ref AGiftRow APreviousGift, int ANumberOfColumns,
            ref decimal ATotalBatchAmount, ref string AImportMessage, int ARowNumber, TVerificationResultCollection AMessages,
            TValidationControlsDict AValidationControlsDictGift, TValidationControlsDict AValidationControlsDictGiftDetail,
            ACostCentreTable AValidationCostCentreTable, AMotivationGroupTable AValidationMotivationGroupTable,
            AMotivationDetailTable AValidationMotivationDetailTable, AMethodOfGivingTable AValidationMethodOfGivingTable,
            AMethodOfPaymentTable AValidationMethodOfPaymentTable,
            ref GiftBatchTDSAGiftDetailTable ANeedRecipientLedgerNumber, out AGiftDetailRow AGiftDetails)
        {
            // Is this the format with extra columns?
            // Actually if it has the extra columns but does not have the optional final 8 columns we cannot distiguish using this test...
            //   A file without extra columns will have between 13 and 21 columns - depending on whether some of the optional ones at the end are included.
            //   A file with extra columns will be between 19 and 27.
            //  So any count between 19 and 21 is ambiguous.  We will assume that if the file has extra columns it also has
            //   at least enough of the optional ones to exceed 21.
            bool HasExtraColumns = (ANumberOfColumns > 21);

            AImportMessage = Catalog.GetString("Importing the gift data");

            AGift.DonorKey = ImportInt64(Catalog.GetString("Donor key"),
                FMainDS.AGift.ColumnDonorKey, ARowNumber, AMessages, AValidationControlsDictGift);

            ImportString(Catalog.GetString("short name of donor (unused)"), null, null); // unused

            // This group is optional and database NULL's are allowed
            AGift.MethodOfGivingCode = ImportString(Catalog.GetString("Method of giving Code"),
                FMainDS.AGift.ColumnMethodOfGivingCode, AValidationControlsDictGift, false);
            AGift.MethodOfPaymentCode = ImportString(Catalog.GetString("Method Of Payment Code"),
                FMainDS.AGift.ColumnMethodOfPaymentCode, AValidationControlsDictGift, false);
            AGift.Reference = ImportString(Catalog.GetString("Reference"),
                FMainDS.AGift.ColumnReference, AValidationControlsDictGift, false);
            AGift.ReceiptLetterCode = ImportString(Catalog.GetString("Receipt letter code"),
                FMainDS.AGift.ColumnReceiptLetterCode, AValidationControlsDictGift, false);

            if (HasExtraColumns)
            {
                ImportInt32(Catalog.GetString("Receipt number"),
                    FMainDS.AGift.ColumnReceiptNumber, ARowNumber, AMessages, AValidationControlsDictGift);
                ImportBoolean(Catalog.GetString("First time gift"),
                    FMainDS.AGift.ColumnFirstTimeGift, AValidationControlsDictGift);
                ImportBoolean(Catalog.GetString("Receipt printed"),
                    FMainDS.AGift.ColumnReceiptPrinted, AValidationControlsDictGift);
            }

            AImportMessage = Catalog.GetString("Importing the gift details");

            AGiftDetails = FMainDS.AGiftDetail.NewRowTyped(true);

            if ((APreviousGift != null) && (AGift.DonorKey == APreviousGift.DonorKey)
                && (AGift.MethodOfGivingCode == APreviousGift.MethodOfGivingCode)
                && (AGift.MethodOfPaymentCode == APreviousGift.MethodOfPaymentCode)
                && (AGift.Reference == APreviousGift.Reference)
                && (AGift.ReceiptLetterCode == APreviousGift.ReceiptLetterCode)
                && (AGift.ReceiptNumber == APreviousGift.ReceiptNumber)
                && (AGift.FirstTimeGift == APreviousGift.FirstTimeGift)
                && (AGift.ReceiptPrinted == APreviousGift.ReceiptPrinted))
            {
                // this row is a new detail for the previousGift
                AGift = APreviousGift;
                AGift.LastDetailNumber++;
                AGiftDetails.DetailNumber = AGift.LastDetailNumber;
            }
            else
            {
                APreviousGift = AGift;
                AGift.LedgerNumber = AGiftBatch.LedgerNumber;
                AGift.BatchNumber = AGiftBatch.BatchNumber;
                AGift.GiftTransactionNumber = AGiftBatch.LastGiftNumber + 1;
                AGiftBatch.LastGiftNumber++;
                AGift.LastDetailNumber = 1;
                FMainDS.AGift.Rows.Add(AGift);
                AGiftDetails.DetailNumber = 1;
            }

            AGiftDetails.LedgerNumber = AGift.LedgerNumber;
            AGiftDetails.BatchNumber = AGiftBatch.BatchNumber;
            AGiftDetails.GiftTransactionNumber = AGift.GiftTransactionNumber;
            FMainDS.AGiftDetail.Rows.Add(AGiftDetails);

            AGiftDetails.RecipientKey = ImportInt64(Catalog.GetString("Recipient key"),
                FMainDS.AGiftDetail.ColumnRecipientKey, ARowNumber, AMessages, AValidationControlsDictGiftDetail);

            ImportString(Catalog.GetString("short name of recipient (unused)"), null, null); // unused

            if (HasExtraColumns)
            {
                ImportInt32(Catalog.GetString("Recipient ledger number"),
                    FMainDS.AGiftDetail.ColumnRecipientLedgerNumber, ARowNumber, AMessages, AValidationControlsDictGiftDetail);
            }

            // we always calculate RecipientLedgerNumber
            AGiftDetails.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(
                AGiftDetails.RecipientKey, AGiftBatch.GlEffectiveDate);

            decimal currentGiftAmount = ImportDecimal(Catalog.GetString("Gift amount"),
                FMainDS.AGiftDetail.ColumnGiftTransactionAmount, ARowNumber, AMessages, AValidationControlsDictGiftDetail);
            AGiftDetails.GiftTransactionAmount = currentGiftAmount;     // amount in batch currency
            ATotalBatchAmount += currentGiftAmount;

            AGiftDetails.GiftAmount = GLRoutines.Divide(currentGiftAmount, AGiftBatch.ExchangeRateToBase);      // amount in ledger currency

            if (HasExtraColumns)
            {
                // amount in international currency
                ImportDecimal(Catalog.GetString("Gift amount intl"),
                    FMainDS.AGiftDetail.ColumnGiftAmountIntl, ARowNumber, AMessages, AValidationControlsDictGiftDetail);
            }

            AGiftDetails.ConfidentialGiftFlag = ImportBoolean(Catalog.GetString("Confidential gift"),
                FMainDS.AGiftDetail.ColumnConfidentialGiftFlag, AValidationControlsDictGiftDetail, "no");
            AGiftDetails.MotivationGroupCode = ImportString(Catalog.GetString("Motivation group code"),
                FMainDS.AGiftDetail.ColumnMotivationGroupCode, AValidationControlsDictGiftDetail);
            AGiftDetails.MotivationDetailCode = ImportString(Catalog.GetString("Motivation detail"),
                FMainDS.AGiftDetail.ColumnMotivationDetailCode, AValidationControlsDictGiftDetail);

            if (HasExtraColumns)
            {
                ImportString(Catalog.GetString("Cost centre code"),
                    FMainDS.AGiftDetail.ColumnCostCentreCode, AValidationControlsDictGiftDetail);
            }

            // "In Petra Cost Centre is always inferred from recipient field and motivation detail so is not needed in the import."
            AGiftDetails.CostCentreCode = InferCostCentre(AGiftDetails);

            // All the remaining columns are optional and can contain database NULL
            AGiftDetails.GiftCommentOne = ImportString(Catalog.GetString("Gift comment one"),
                FMainDS.AGiftDetail.ColumnGiftCommentOne, AValidationControlsDictGiftDetail, false);
            string commentOneType = ImportString(Catalog.GetString("Comment one type"),
                FMainDS.AGiftDetail.ColumnCommentOneType, AValidationControlsDictGiftDetail, false);

            AGiftDetails.MailingCode = ImportString(Catalog.GetString("Mailing code"),
                FMainDS.AGiftDetail.ColumnMailingCode, AValidationControlsDictGiftDetail, false);

            AGiftDetails.GiftCommentTwo = ImportString(Catalog.GetString("Gift comment two"),
                FMainDS.AGiftDetail.ColumnGiftCommentTwo, AValidationControlsDictGiftDetail, false);
            string commentTwoType = ImportString(Catalog.GetString("Comment two type"),
                FMainDS.AGiftDetail.ColumnCommentTwoType, AValidationControlsDictGiftDetail, false);
            AGiftDetails.GiftCommentThree = ImportString(Catalog.GetString("Gift comment three"),
                FMainDS.AGiftDetail.ColumnGiftCommentThree, AValidationControlsDictGiftDetail, false);
            string commentThreeType = ImportString(Catalog.GetString("Comment three type"),
                FMainDS.AGiftDetail.ColumnCommentThreeType, AValidationControlsDictGiftDetail, false);

            SetCommentTypeCase(ref commentOneType);
            AGiftDetails.CommentOneType = commentOneType;

            SetCommentTypeCase(ref commentTwoType);
            AGiftDetails.CommentOneType = commentTwoType;

            SetCommentTypeCase(ref commentThreeType);
            AGiftDetails.CommentOneType = commentThreeType;

            // Find the default Tax deductabilty from the motivation detail. This ensures that the column can be missing.
            AMotivationDetailRow motivationDetailRow = (AMotivationDetailRow)AValidationMotivationDetailTable.Rows.Find(
                new object[] { FLedgerNumber, AGiftDetails.MotivationGroupCode, AGiftDetails.MotivationDetailCode });
            string defaultTaxDeductible =
                ((motivationDetailRow != null) && !motivationDetailRow.IsTaxDeductibleAccountNull()
                 && motivationDetailRow.TaxDeductible) ? "yes" : "no";

            AGiftDetails.TaxDeductible = ImportBoolean(Catalog.GetString("Tax deductible"),
                FMainDS.AGiftDetail.ColumnTaxDeductible, AValidationControlsDictGiftDetail, defaultTaxDeductible);

            // Date entered cannot be imported although it can be modified in the GUI.
            // This is because it would have to be the last column in the import for compatibility
            // but it belongs with the gift and not the detail so it would need to go in an earlier column.
            // For now the import date entered is the effective date.
            AGift.DateEntered = AGiftBatch.GlEffectiveDate;

            // Enforce the correct case for our GIFT constant
            if (String.Compare(AGiftDetails.MotivationGroupCode, MFinanceConstants.MOTIVATION_GROUP_GIFT, true) == 0)
            {
                AGiftDetails.MotivationGroupCode = MFinanceConstants.MOTIVATION_GROUP_GIFT;
            }

            TPartnerClass RecipientClass;
            string RecipientDescription;
            TPartnerServerLookups.GetPartnerShortName(AGiftDetails.RecipientKey, out RecipientDescription, out RecipientClass);

            // If the gift has a Family recipient with no Gift Destination then the import will fail. Gift is added to a table and returned to client.
            if ((AGiftDetails.RecipientLedgerNumber == 0) && (AGiftDetails.MotivationGroupCode == MFinanceConstants.MOTIVATION_GROUP_GIFT))
            {
                if (RecipientClass == TPartnerClass.FAMILY)
                {
                    ((GiftBatchTDSAGiftDetailRow)AGiftDetails).RecipientDescription = RecipientDescription;
                    ANeedRecipientLedgerNumber.Rows.Add((object[])AGiftDetails.ItemArray.Clone());
                }
            }

            AImportMessage = Catalog.GetString("Validating the gift data");

            int messageCountBeforeValidate = AMessages.Count;

            // Do our standard validation on this gift
            AGiftValidation.Validate(this, AGift, ref AMessages, AValidationControlsDictGift);
            TSharedFinanceValidation_Gift.ValidateGiftManual(this, AGift, AGiftBatch.BatchYear, AGiftBatch.BatchPeriod,
                null, ref AMessages, AValidationControlsDictGift, AValidationMethodOfGivingTable, AValidationMethodOfPaymentTable);

            AImportMessage = Catalog.GetString("Validating the gift details data");

            AGiftDetailValidation.Validate(this, AGiftDetails, ref AMessages, AValidationControlsDictGiftDetail);
            TSharedFinanceValidation_Gift.ValidateGiftDetailManual(this, (GiftBatchTDSAGiftDetailRow)AGiftDetails,
                ref AMessages, AValidationControlsDictGiftDetail, RecipientClass, AValidationCostCentreTable, AValidationMotivationGroupTable,
                AValidationMotivationDetailTable, AGiftDetails.RecipientKey);

            for (int i = messageCountBeforeValidate; i < AMessages.Count; i++)
            {
                ((TVerificationResult)AMessages[i]).OverrideResultContext(String.Format(MCommonConstants.StrValidationErrorInLine, ARowNumber));

                if (AMessages[i] is TScreenVerificationResult)
                {
                    TVerificationResult downgrade = new TVerificationResult((TScreenVerificationResult)AMessages[i]);
                    AMessages.RemoveAt(i);
                    AMessages.Insert(i, downgrade);
                }
            }
        }
Example #24
0
        /// <summary>
        /// Loads tables needed for the calculation of admin fees for a gift detail.
        /// </summary>
        private static void LoadAdminFeeTablesForGiftDetail(GiftBatchTDS AMainDS,
            AGiftDetailRow AGiftDetail,
            TDBTransaction ATransaction)
        {
            // only needs to be loaded once for the whole batch
            if ((AMainDS.AProcessedFee == null) || (AMainDS.AProcessedFee.Rows.Count == 0))
            {
                AProcessedFeeAccess.LoadViaAGiftBatch(AMainDS, AGiftDetail.LedgerNumber, AGiftDetail.BatchNumber, ATransaction);
            }

            // only needs to be loaded once for the whole batch
            if ((AMainDS.AFeesPayable == null) || (AMainDS.AFeesPayable.Rows.Count == 0))
            {
                AFeesPayableAccess.LoadViaALedger(AMainDS, AGiftDetail.LedgerNumber, ATransaction);
            }

            // if motivation detail has changed from the last gift detail
            if ((AMainDS.AMotivationDetailFee == null) || (AMainDS.AMotivationDetailFee.Rows.Count == 0)
                || (AMainDS.AMotivationDetailFee[0].MotivationGroupCode != AGiftDetail.MotivationGroupCode)
                || (AMainDS.AMotivationDetailFee[0].MotivationDetailCode != AGiftDetail.MotivationDetailCode))
            {
                AMainDS.AMotivationDetailFee.Rows.Clear();
                AMotivationDetailFeeAccess.LoadViaAMotivationDetail(
                    AMainDS, AGiftDetail.LedgerNumber, AGiftDetail.MotivationGroupCode, AGiftDetail.MotivationDetailCode, ATransaction);
            }

            // If this gift is for the local field, don't charge the fee to itself. So we don't need the fees receivable.
            string Query = "SELECT a_fees_receivable.* FROM a_fees_receivable" +
                           " WHERE EXISTS (SELECT * FROM a_cost_centre" +
                           " WHERE a_cost_centre.a_ledger_number_i = " + AGiftDetail.LedgerNumber +
                           " AND a_cost_centre.a_cost_centre_code_c = '" + AGiftDetail.CostCentreCode + "'" +
                           " AND a_cost_centre.a_cost_centre_type_c = '" + MFinanceConstants.FOREIGN_CC_TYPE + "')" +
                           " AND a_fees_receivable.a_ledger_number_i = " + AGiftDetail.LedgerNumber;

            AMainDS.AFeesReceivable.Rows.Clear();

            // need to use a typed table to avoid problems with SQLite in the Merge
            AFeesReceivableTable tmpFeesReceivable = new AFeesReceivableTable();
            DBAccess.GDBAccessObj.SelectDT(tmpFeesReceivable, Query, ATransaction);
            AMainDS.AFeesReceivable.Merge(tmpFeesReceivable);

            #region Validate Data

            if ((AMainDS.AMotivationDetailFee != null) && (AMainDS.AMotivationDetailFee.Count > 0)
                && ((AMainDS.AFeesPayable == null) || (AMainDS.AFeesPayable.Rows.Count == 0))
                && ((AMainDS.AFeesReceivable == null) || (AMainDS.AFeesReceivable.Rows.Count == 0)))
            {
                throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString(
                            "Function:{0} - Admin fee data for Gift Detail {1}, from Gift {2} in Batch {3} and Ledger {4} does not exist or could not be accessed!"),
                        Utilities.GetMethodSignature(),
                        AGiftDetail.DetailNumber,
                        AGiftDetail.GiftTransactionNumber,
                        AGiftDetail.BatchNumber,
                        AGiftDetail.LedgerNumber));
            }

            #endregion Validate Data
        }
Example #25
0
        public static bool GiftRevertAdjust(
            Int32 ALedgerNumber,
            Int32 ABatchNumber,
            Int32 AGiftDetailNumber,
            bool ABatchSelected,
            Int32 ANewBatchNumber,
            DateTime?ANewGLDateEffective,
            GiftAdjustmentFunctionEnum AFunction,
            bool ANoReceipt,
            Decimal ANewPct,
            out int AAdjustmentBatchNumber)
        {
            AAdjustmentBatchNumber = 0;
            int AdjustmentBatchNo = AAdjustmentBatchNumber;

            GiftBatchTDS GiftDS = new GiftBatchTDS();

            decimal batchGiftTotal = 0;

            ANewBatchNumber = ABatchSelected ? ANewBatchNumber : 0;

            TDBTransaction Transaction  = new TDBTransaction();
            TDataBase      db           = DBAccess.Connect("GiftRevertAdjust");
            bool           SubmissionOK = false;

            try
            {
                db.WriteTransaction(
                    ref Transaction,
                    ref SubmissionOK,
                    delegate
                {
                    // load the original gifts and gift details
                    AGiftAccess.LoadViaAGiftBatch(GiftDS, ALedgerNumber, ABatchNumber, Transaction);
                    AGiftDetailAccess.LoadViaAGiftBatch(GiftDS, ALedgerNumber, ABatchNumber, Transaction);

                    ALedgerTable ledgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);

                    AGiftBatchRow giftBatch;

                    DateTime DateEffective;

                    if (ANewGLDateEffective.HasValue)
                    {
                        DateEffective = ANewGLDateEffective.Value;
                    }
                    else
                    {
                        AGiftBatchTable OriginalGiftBatch = AGiftBatchAccess.LoadByPrimaryKey(ALedgerNumber, ABatchNumber, Transaction);
                        DateEffective = OriginalGiftBatch[0].GlEffectiveDate;
                    }

                    // if we need to create a new gift batch
                    if (!ABatchSelected)
                    {
                        giftBatch = CreateNewGiftBatch(
                            ALedgerNumber,
                            ABatchNumber,
                            DateEffective,
                            AFunction,
                            ref GiftDS, ref ledgerTable, Transaction);
                    }
                    else     // using an existing gift batch
                    {
                        AGiftBatchAccess.LoadByPrimaryKey(GiftDS, ALedgerNumber, ANewBatchNumber, Transaction);

                        giftBatch     = GiftDS.AGiftBatch[0];
                        DateEffective = giftBatch.GlEffectiveDate;
                        //If into an existing batch, then retrieve the existing batch total
                        batchGiftTotal = giftBatch.BatchTotal;
                    }

                    AdjustmentBatchNo = giftBatch.BatchNumber;

                    //assuming new elements are added after these static borders

                    GiftDS.AGift.DefaultView.Sort = string.Format("{0}, {1}",
                                                                  AGiftTable.GetBatchNumberDBName(),
                                                                  AGiftTable.GetGiftTransactionNumberDBName());

                    GiftDS.AGiftDetail.DefaultView.Sort = string.Format("{0}, {1}, {2}",
                                                                        AGiftDetailTable.GetBatchNumberDBName(),
                                                                        AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                        AGiftDetailTable.GetDetailNumberDBName());

                    foreach (DataRowView giftRow in GiftDS.AGift.DefaultView)
                    {
                        int cycle = 0;

                        // first cycle creates gift reversal; second cycle creates new adjusted gift (if needed)
                        do
                        {
                            AGiftRow oldGift = (AGiftRow)giftRow.Row;

                            if (oldGift.RowState != DataRowState.Added)
                            {
                                AGiftRow gift = GiftDS.AGift.NewRowTyped(true);
                                DataUtilities.CopyAllColumnValuesWithoutPK(oldGift, gift);
                                gift.LedgerNumber = giftBatch.LedgerNumber;
                                gift.BatchNumber  = giftBatch.BatchNumber;
                                // keep the same DateEntered as in the original gift if it is in the same period as the batch
                                if ((gift.DateEntered.Year != DateEffective.Year) || (gift.DateEntered.Month != DateEffective.Month))
                                {
                                    gift.DateEntered = DateEffective;
                                }
                                gift.GiftTransactionNumber = giftBatch.LastGiftNumber + 1;
                                giftBatch.LastGiftNumber++;
                                gift.LinkToPreviousGift = (cycle != 0);
                                gift.LastDetailNumber   = 0;
                                gift.FirstTimeGift      = false;

                                // do not print a receipt for reversed gifts
                                if (cycle == 0)
                                {
                                    gift.ReceiptPrinted = true;
                                    gift.PrintReceipt   = false;
                                }
                                else
                                {
                                    gift.ReceiptPrinted = false;
                                    gift.PrintReceipt   = !ANoReceipt;
                                }

                                GiftDS.AGift.Rows.Add(gift);

                                foreach (DataRowView giftDetailRow in GiftDS.AGiftDetail.DefaultView)
                                {
                                    AGiftDetailRow oldGiftDetail = (AGiftDetailRow)giftDetailRow.Row;

                                    // if gift detail belongs to gift
                                    if ((oldGiftDetail.GiftTransactionNumber == oldGift.GiftTransactionNumber) &&
                                        (oldGiftDetail.BatchNumber == oldGift.BatchNumber) &&
                                        (AFunction != GiftAdjustmentFunctionEnum.ReverseGiftDetail) ||
                                        (oldGiftDetail.DetailNumber == AGiftDetailNumber))
                                    {
                                        AddDuplicateGiftDetailToGift(ref GiftDS, ref gift, oldGiftDetail, cycle == 0, Transaction,
                                                                     AFunction,
                                                                     ANewPct);

                                        batchGiftTotal += ((cycle == 0) ? 0 : oldGiftDetail.GiftTransactionAmount);

                                        // original gift also gets marked as a reversal
                                        oldGiftDetail.ModifiedDetail = true;
                                    }
                                }
                            }

                            cycle++;
                        } while ((cycle < 2) &&
                                 (AFunction.Equals(GiftAdjustmentFunctionEnum.AdjustGift) ||
                                  AFunction.Equals(GiftAdjustmentFunctionEnum.FieldAdjust) ||
                                  AFunction.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust)));
                    }

                    //When reversing into a new or existing batch, set batch total
                    giftBatch.BatchTotal = batchGiftTotal;

                    // save everything at the end
                    AGiftBatchAccess.SubmitChanges(GiftDS.AGiftBatch, Transaction);
                    ALedgerAccess.SubmitChanges(ledgerTable, Transaction);
                    AGiftAccess.SubmitChanges(GiftDS.AGift, Transaction);
                    AGiftDetailAccess.SubmitChanges(GiftDS.AGiftDetail, Transaction);

                    GiftDS.AGiftBatch.AcceptChanges();

                    SubmissionOK = true;
                });
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw new EOPAppException(Catalog.GetString("Gift Reverse/Adjust failed."), ex);
            }

            AAdjustmentBatchNumber = AdjustmentBatchNo;

            db.CloseDBConnection();

            return(SubmissionOK);
        }
        private void UpdateControlsProtection(AGiftDetailRow ARow)
        {
            bool firstIsEnabled = (ARow != null) && (ARow.DetailNumber == 1) && !ViewMode;
            bool pnlDetailsEnabledState = false;

            dtpDateEntered.Enabled = firstIsEnabled;
            txtDetailDonorKey.Enabled = firstIsEnabled;
            cmbDetailMethodOfGivingCode.Enabled = firstIsEnabled;

            cmbDetailMethodOfPaymentCode.Enabled = firstIsEnabled && !BatchHasMethodOfPayment();
            txtDetailReference.Enabled = firstIsEnabled;
            cmbDetailReceiptLetterCode.Enabled = firstIsEnabled;

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

            if (ARow == null)
            {
                PnlDetailsProtected = (ViewMode
                                       || !FBatchUnposted
                                       );
            }
            else
            {
                PnlDetailsProtected = (ViewMode
                                       || !FBatchUnposted
                                       || (ARow.GiftTransactionAmount < 0 && GetGiftRow(ARow.GiftTransactionNumber).ReceiptNumber != 0)
                                       );    // taken from old petra
            }

            pnlDetailsEnabledState = (!PnlDetailsProtected && grdDetails.Rows.Count > 1);
            pnlDetails.Enabled = pnlDetailsEnabledState;

            btnDelete.Enabled = pnlDetailsEnabledState;
            btnDeleteAll.Enabled = btnDelete.Enabled;
            btnNewDetail.Enabled = !PnlDetailsProtected;
            btnNewGift.Enabled = !PnlDetailsProtected;

            mniDonorFinanceDetails.Enabled = (ARow != null);

            // Only show the NoReceipt check box under special circumstances
            chkNoReceiptOnAdjustment.Visible = IsUnpostedReversedDetailAdjustment(ARow);
            chkNoReceiptOnAdjustment.Enabled = firstIsEnabled;
        }
Example #27
0
        public static void AddToFeeTotals(GiftBatchTDS AMainDS,
            AGiftDetailRow AGiftDetailRow,
            string AFeeCode,
            decimal AFeeAmount,
            int APostingPeriod)
        {
            #region Validate Arguments

            if (AMainDS == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Gift Batch dataset is null!"),
                        Utilities.GetMethodName(true)));
            }

            if (AGiftDetailRow == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString("Function:{0} - The Gift Detail row is null!"),
                        Utilities.GetMethodName(true)));
            }
            else if (AFeeCode.Length == 0)
            {
                throw new ArgumentException(String.Format(Catalog.GetString("Function:{0} - The Fee code is empty!"),
                        Utilities.GetMethodName(true)));
            }

            #endregion Validate Arguments

            try
            {
                /* Get the record for the totals of the processed fees. */
                AProcessedFeeTable ProcessedFeeDataTable = AMainDS.AProcessedFee;
                AProcessedFeeRow ProcessedFeeRow =
                    (AProcessedFeeRow)ProcessedFeeDataTable.Rows.Find(new object[] { AGiftDetailRow.LedgerNumber,
                                                                                     AGiftDetailRow.BatchNumber,
                                                                                     AGiftDetailRow.GiftTransactionNumber,
                                                                                     AGiftDetailRow.DetailNumber,
                                                                                     AFeeCode });

                if (ProcessedFeeRow == null)
                {
                    ProcessedFeeRow = (AProcessedFeeRow)ProcessedFeeDataTable.NewRowTyped(false);
                    ProcessedFeeRow.LedgerNumber = AGiftDetailRow.LedgerNumber;
                    ProcessedFeeRow.BatchNumber = AGiftDetailRow.BatchNumber;
                    ProcessedFeeRow.GiftTransactionNumber = AGiftDetailRow.GiftTransactionNumber;
                    ProcessedFeeRow.DetailNumber = AGiftDetailRow.DetailNumber;
                    ProcessedFeeRow.FeeCode = AFeeCode;
                    ProcessedFeeRow.PeriodicAmount = 0;

                    ProcessedFeeDataTable.Rows.Add(ProcessedFeeRow);
                }

                ProcessedFeeRow.CostCentreCode = AGiftDetailRow.CostCentreCode;
                ProcessedFeeRow.PeriodNumber = APostingPeriod;

                /* Add the amount to the existing total. */
                ProcessedFeeRow.PeriodicAmount += AFeeAmount;
            }
            catch (Exception ex)
            {
                TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}",
                        Utilities.GetMethodSignature(),
                        Environment.NewLine,
                        ex.Message));
                throw ex;
            }
        }
Example #28
0
        public static bool ReversedGiftReset(int ALedgerNumber, string AReversalIdentification)
        {
            bool           NewTransaction;
            TDBTransaction Transaction;
            int            BatchNo;
            int            GiftTransNo;
            int            DetailNo;

            TVerificationResultCollection Messages = new TVerificationResultCollection();

            int positionFirstNumber = 1;
            int positionSecondBar   = AReversalIdentification.IndexOf('|', positionFirstNumber);
            int positionThirdBar    = AReversalIdentification.LastIndexOf('|');
            int lenReversalDetails  = AReversalIdentification.Length;

            if (!Int32.TryParse(AReversalIdentification.Substring(positionFirstNumber, positionSecondBar - positionFirstNumber), out BatchNo) ||
                !Int32.TryParse(AReversalIdentification.Substring(positionSecondBar + 1,
                                                                  positionThirdBar - positionSecondBar - 1), out GiftTransNo) ||
                !Int32.TryParse(AReversalIdentification.Substring(positionThirdBar + 1, lenReversalDetails - positionThirdBar - 1), out DetailNo))
            {
                Messages.Add(new TVerificationResult(
                                 String.Format(Catalog.GetString("Cannot parse the Modified Detail Key: '{0}'"),
                                               AReversalIdentification),
                                 String.Format(Catalog.GetString("Unexpected error.")),
                                 TResultSeverity.Resv_Critical));

                return(false);
            }

            GiftBatchTDS MainDS = new GiftBatchTDS();

            Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.Serializable, out NewTransaction);

            try
            {
                TLogging.Log(BatchNo.ToString());
                TLogging.Log(GiftTransNo.ToString());
                TLogging.Log(DetailNo.ToString());

                AGiftDetailAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, BatchNo, GiftTransNo, DetailNo, Transaction);

                TLogging.Log("Count: " + MainDS.AGiftDetail.Count.ToString());

                AGiftDetailRow giftDetailRow = (AGiftDetailRow)MainDS.AGiftDetail.Rows[0];
                //Reset gift to not reversed
                giftDetailRow.ModifiedDetail = false;

                AGiftDetailAccess.SubmitChanges(MainDS.AGiftDetail, Transaction);

                MainDS.AGiftBatch.AcceptChanges();

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                }
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured in ReversedGiftReset:" + Environment.NewLine + Exc.ToString());

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }

                Messages.Add(new TVerificationResult(
                                 String.Format(Catalog.GetString("Cannot reset ModifiedDetail for Gift {0} Detail {1} in Batch {2}"),
                                               GiftTransNo, DetailNo, BatchNo),
                                 String.Format(Catalog.GetString("Unexpected error.")),
                                 TResultSeverity.Resv_Critical));

                throw;
            }

            return(true);
        }
        /// <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;
            }
        }
Example #30
0
        /// <summary>
        /// This "Einzahlungsschein mit Referenznummer" (ESR) input format is only used in Switzerland.
        /// This method could be pulled out of here, but sits here quite nicely.
        /// </summary>
        /// <param name="AImportLine"></param>
        /// <param name="AgiftBatch"></param>
        /// <param name="Agift"></param>
        /// <param name="AgiftDetails"></param>
        /// <param name="AIntlRateToBase"></param>
        /// <param name="AMotivationDetailTable"></param>
        /// <param name="ANeedRecipientLedgerNumber"></param>
        /// <param name="AMessages"></param>
        /// <returns></returns>
        private Boolean ParseEsrTransactionLine(
            String AImportLine,
            AGiftBatchRow AgiftBatch,
            AGiftRow Agift,
            AGiftDetailRow AgiftDetails,
            Decimal AIntlRateToBase,
            AMotivationDetailTable AMotivationDetailTable,
            GiftBatchTDSAGiftDetailTable ANeedRecipientLedgerNumber,
            TVerificationResultCollection AMessages
            )
        {
            Boolean NonNumericError = false;
            String Field = AImportLine.Substring(0, 3);

            Int32 FunctionType = 0;

            NonNumericError &= !Int32.TryParse(Field, out FunctionType);

            Int64 DonorKey = 0;
            Field = AImportLine.Substring(12, 10);
            NonNumericError &= !Int64.TryParse(Field, out DonorKey);

            Int64 RecipientKey = 0;
            Field = AImportLine.Substring(22, 10);
            NonNumericError &= !Int64.TryParse(Field, out RecipientKey);

            Int64 intAmount = 0;
            Field = AImportLine.Substring(39, 10);
            NonNumericError &= !Int64.TryParse(Field, out intAmount);

            Decimal Amount = intAmount / 100;

            if (NonNumericError)
            {
                return false;
            }

            String MotivGroup = "GIFT";
            String MotivDetail = "UNDESIG";
            TGuiTools.GetMotivationGroupAndDetail(RecipientKey, ref MotivGroup, ref MotivDetail);

            Agift.LedgerNumber = AgiftBatch.LedgerNumber;
            Agift.BatchNumber = AgiftBatch.BatchNumber;
            Agift.GiftTransactionNumber = AgiftBatch.LastGiftNumber + 1;
            AgiftBatch.LastGiftNumber++;
            AgiftBatch.BatchTotal += Amount;
            Agift.LastDetailNumber = 1;

            ExchangeFieldsInEsrTransaction(ref DonorKey, ref RecipientKey, AMessages, Agift.GiftTransactionNumber);

            Agift.DonorKey = DonorKey;
            Agift.MethodOfGivingCode = "DEFAULT";
            Agift.MethodOfPaymentCode = "ESR";
            FMainDS.AGift.Rows.Add(Agift);

            AgiftDetails.RecipientKey = RecipientKey;
            AgiftDetails.LedgerNumber = AgiftBatch.LedgerNumber;
            AgiftDetails.BatchNumber = AgiftBatch.BatchNumber;
            AgiftDetails.GiftTransactionNumber = Agift.GiftTransactionNumber;
            AgiftDetails.DetailNumber = 1;
            AgiftDetails.GiftTransactionAmount = Amount;
            AgiftDetails.GiftAmount = GLRoutines.Divide(Amount, AgiftBatch.ExchangeRateToBase);      // amount in ledger currency

            if (AIntlRateToBase > 0.0m)
            {
                AgiftDetails.GiftAmountIntl = GLRoutines.Divide(AgiftDetails.GiftAmount, AIntlRateToBase, 2);
            }

            AgiftDetails.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(AgiftDetails.RecipientKey,
                AgiftBatch.GlEffectiveDate);


            AgiftDetails.MotivationGroupCode = MotivGroup;
            AgiftDetails.MotivationDetailCode = MotivDetail;
            AgiftDetails.CostCentreCode = TGiftTransactionWebConnector.RetrieveCostCentreCodeForRecipient(
                AgiftDetails.LedgerNumber, AgiftDetails.RecipientKey, AgiftDetails.RecipientLedgerNumber,
                Agift.DateEntered, AgiftDetails.MotivationGroupCode, AgiftDetails.MotivationDetailCode);

            AMotivationDetailRow motivationDetailRow = (AMotivationDetailRow)AMotivationDetailTable.Rows.Find(
                new object[] { FLedgerNumber, AgiftDetails.MotivationGroupCode, AgiftDetails.MotivationDetailCode });

            // Account Code is inferred from the motivation detail.
            Boolean IsTaxDeductible = false;
            string NewAccountCode = null;
            string NewTaxDeductibleAccountCode = null;

            if (motivationDetailRow != null)
            {
                IsTaxDeductible = motivationDetailRow.TaxDeductible;
                NewAccountCode = motivationDetailRow.AccountCode;
                NewTaxDeductibleAccountCode = motivationDetailRow.TaxDeductibleAccountCode;
            }

            AgiftDetails.TaxDeductible = IsTaxDeductible;
            AgiftDetails.AccountCode = NewAccountCode;
            AgiftDetails.TaxDeductibleAccountCode = NewTaxDeductibleAccountCode;

            // If the gift has a recipient with no Gift Destination then the import will fail. Gift is added to a table and returned to client.
            if ((AgiftDetails.RecipientLedgerNumber == 0) && (AgiftDetails.MotivationGroupCode == MFinanceConstants.MOTIVATION_GROUP_GIFT))
            {
                ((GiftBatchTDSAGiftDetailRow)AgiftDetails).RecipientDescription = "Fault: RecipientLedger Not known";
                ANeedRecipientLedgerNumber.Rows.Add((object[])AgiftDetails.ItemArray.Clone());
            }

            FMainDS.AGiftDetail.Rows.Add(AgiftDetails);
            return true;
        }
Example #31
0
        void WriteGiftLine(AGiftRow gift, AGiftDetailRow giftDetails)
        {
            if (!FTransactionsOnly)
            {
                WriteStringQuoted("T");
            }

            if (TGift.GiftRestricted(gift, FTransaction))
            {
                WriteGeneralNumber(0);
                WriteStringQuoted("Confidential");
                ProcessConfidentialMessage();
            }
            else
            {
                WriteGeneralNumber(gift.DonorKey);
                WriteStringQuoted(PartnerShortName(gift.DonorKey));
            }

            WriteStringQuoted(gift.MethodOfGivingCode);
            WriteStringQuoted(gift.MethodOfPaymentCode);
            WriteStringQuoted(gift.Reference);
            WriteStringQuoted(gift.ReceiptLetterCode);

            if (FExtraColumns)
            {
                WriteGeneralNumber(gift.ReceiptNumber);
                WriteBoolean(gift.FirstTimeGift);
                WriteBoolean(gift.ReceiptPrinted);
            }

            WriteGeneralNumber(giftDetails.RecipientKey);
            WriteStringQuoted(PartnerShortName(giftDetails.RecipientKey));

            if (FExtraColumns)
            {
                WriteGeneralNumber(giftDetails.RecipientLedgerNumber);
            }

            if (FUseBaseCurrency)
            {
                WriteCurrency(giftDetails.GiftAmount);
            }
            else
            {
                WriteCurrency(giftDetails.GiftTransactionAmount);
            }

            if (FExtraColumns)
            {
                WriteCurrency(giftDetails.GiftAmountIntl);
            }

            WriteBoolean(giftDetails.ConfidentialGiftFlag);
            WriteStringQuoted(giftDetails.MotivationGroupCode);
            WriteStringQuoted(giftDetails.MotivationDetailCode);

            //
            // "In Petra Cost Centre is always inferred from recipient field and motivation detail so is not needed in the import."
            if (FExtraColumns)
            {
                WriteStringQuoted(giftDetails.CostCentreCode);
            }

            WriteStringQuoted(giftDetails.GiftCommentOne);
            WriteStringQuoted(giftDetails.CommentOneType);

            if (giftDetails.MailingCode.Equals("?"))
            {
                WriteStringQuoted("");
            }
            else
            {
                WriteStringQuoted(giftDetails.MailingCode);
            }

            WriteStringQuoted(giftDetails.GiftCommentTwo);
            WriteStringQuoted(giftDetails.CommentTwoType);
            WriteStringQuoted(giftDetails.GiftCommentThree);
            WriteStringQuoted(giftDetails.CommentThreeType);

            WriteBoolean(giftDetails.IsTaxDeductibleNull() ? false : giftDetails.TaxDeductible, true);

//          WriteLineDate(gift.DateEntered);  //Don't write this - it can't be used by import.
        }
        private static GiftBatchTDS CreateGiftBatches(SortedList <DateTime, List <XmlNode> > AGiftsPerDate, int APeriodNumber)
        {
            GiftBatchTDS MainDS      = new GiftBatchTDS();
            ALedgerTable LedgerTable = null;

            TDBTransaction ReadTransaction = new TDBTransaction();

            DBAccess.ReadTransaction(ref ReadTransaction,
                                     delegate
            {
                TDataBase db = ReadTransaction.DataBaseObj;

                // get a list of potential donors (all class FAMILY)
                string sqlGetFamilyPartnerKeys = "SELECT p_partner_key_n FROM PUB_p_family";
                DataTable FamilyKeys           = db.SelectDT(sqlGetFamilyPartnerKeys,
                                                             "keys",
                                                             ReadTransaction);

                // get a list of workers (all class FAMILY, with special type WORKER)
                string sqlGetWorkerPartnerKeys =
                    "SELECT PUB_p_family.p_partner_key_n FROM PUB_p_family, PUB_p_partner_type WHERE PUB_p_partner_type.p_partner_key_n = PUB_p_family.p_partner_key_n AND p_type_code_c = 'WORKER'";
                DataTable WorkerKeys = db.SelectDT(sqlGetWorkerPartnerKeys, "keys", ReadTransaction);

                // get a list of fields (all class UNIT, with unit type F)
                string sqlGetFieldPartnerKeys =
                    String.Format(
                        "SELECT U.p_partner_key_n FROM PUB_p_unit U WHERE u_unit_type_code_c = 'F' AND EXISTS (SELECT * FROM PUB_a_valid_ledger_number V WHERE V.a_ledger_number_i = {0} AND V.p_partner_key_n = U.p_partner_key_n)",
                        FLedgerNumber);
                DataTable FieldKeys = db.SelectDT(sqlGetFieldPartnerKeys, "keys", ReadTransaction);

                // get a list of key ministries (all class UNIT, with unit type KEY-MIN), and their field ledger number and cost centre code
                string sqlGetKeyMinPartnerKeys =
                    "SELECT u.p_partner_key_n, us.um_parent_unit_key_n, vl.a_cost_centre_code_c " +
                    "FROM PUB_p_unit u, PUB_um_unit_structure us, PUB_a_valid_ledger_number vl " +
                    "WHERE u.u_unit_type_code_c = 'KEY-MIN' " +
                    "AND us.um_child_unit_key_n = u.p_partner_key_n " +
                    "AND vl.p_partner_key_n = us.um_parent_unit_key_n " +
                    "AND vl.a_ledger_number_i = " + FLedgerNumber.ToString();
                DataTable KeyMinistries = db.SelectDT(sqlGetKeyMinPartnerKeys, "keys", ReadTransaction);

                LedgerTable = ALedgerAccess.LoadByPrimaryKey(FLedgerNumber, ReadTransaction);

                AAccountingPeriodRow AccountingPeriodRow = AAccountingPeriodAccess.LoadByPrimaryKey(FLedgerNumber,
                                                                                                    APeriodNumber,
                                                                                                    ReadTransaction)[0];

                // create a gift batch for each day.
                // TODO: could create one batch per month, if there are not so many gifts (less than 100 per month)
                foreach (DateTime GlEffectiveDate in AGiftsPerDate.Keys)
                {
                    if ((GlEffectiveDate.CompareTo(AccountingPeriodRow.PeriodStartDate) < 0) ||
                        (GlEffectiveDate.CompareTo(AccountingPeriodRow.PeriodEndDate) > 0))
                    {
                        // only create gifts in that period
                        continue;
                    }

                    AGiftBatchRow giftBatch = TGiftBatchFunctions.CreateANewGiftBatchRow(ref MainDS,
                                                                                         ref ReadTransaction,
                                                                                         ref LedgerTable,
                                                                                         FLedgerNumber,
                                                                                         GlEffectiveDate);

                    TLogging.LogAtLevel(1, "create gift batch for " + GlEffectiveDate.ToShortDateString());
                    giftBatch.BatchDescription = "Benerator Batch for " + GlEffectiveDate.ToShortDateString();
                    giftBatch.BatchTotal       = 0.0m;

                    foreach (XmlNode RecordNode in AGiftsPerDate[GlEffectiveDate])
                    {
                        AGiftRow gift              = MainDS.AGift.NewRowTyped();
                        gift.LedgerNumber          = giftBatch.LedgerNumber;
                        gift.BatchNumber           = giftBatch.BatchNumber;
                        gift.GiftTransactionNumber = giftBatch.LastGiftNumber + 1;
                        gift.DateEntered           = GlEffectiveDate;

                        // set donorKey
                        int donorID   = Convert.ToInt32(TXMLParser.GetAttribute(RecordNode, "donor")) % FamilyKeys.Rows.Count;
                        gift.DonorKey = Convert.ToInt64(FamilyKeys.Rows[donorID].ItemArray[0]);

                        // calculate gift detail information
                        int countDetails = Convert.ToInt32(TXMLParser.GetAttribute(RecordNode, "splitgift"));

                        for (int counter = 1; counter <= countDetails; counter++)
                        {
                            AGiftDetailRow giftDetail        = MainDS.AGiftDetail.NewRowTyped();
                            giftDetail.LedgerNumber          = gift.LedgerNumber;
                            giftDetail.BatchNumber           = gift.BatchNumber;
                            giftDetail.GiftTransactionNumber = gift.GiftTransactionNumber;

                            giftDetail.MotivationGroupCode   = "GIFT";
                            giftDetail.GiftTransactionAmount = Convert.ToDecimal(TXMLParser.GetAttribute(RecordNode, "amount_" + counter.ToString()));
                            giftDetail.GiftAmount            = giftDetail.GiftTransactionAmount;
                            giftBatch.BatchTotal            += giftDetail.GiftAmount;

                            string motivation = TXMLParser.GetAttribute(RecordNode, "motivation_" + counter.ToString());

                            if (motivation == "SUPPORT")
                            {
                                if (WorkerKeys.Rows.Count == 0)
                                {
                                    continue;
                                }

                                giftDetail.MotivationDetailCode = "SUPPORT";
                                int recipientID =
                                    Convert.ToInt32(TXMLParser.GetAttribute(RecordNode, "recipient_support_" +
                                                                            counter.ToString())) % WorkerKeys.Rows.Count;
                                giftDetail.RecipientKey = Convert.ToInt64(WorkerKeys.Rows[recipientID].ItemArray[0]);

                                giftDetail.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(giftDetail.RecipientKey,
                                                                                                                       giftBatch.GlEffectiveDate);

                                // ignore this gift detail, if there is no valid commitment period for the worker
                                if (giftDetail.RecipientLedgerNumber == 0)
                                {
                                    continue;
                                }
                            }
                            else if (motivation == "FIELD")
                            {
                                if (FieldKeys.Rows.Count == 0)
                                {
                                    continue;
                                }

                                giftDetail.MotivationDetailCode = "FIELD";
                                int recipientID =
                                    Convert.ToInt32(TXMLParser.GetAttribute(RecordNode, "recipient_field_" +
                                                                            counter.ToString())) % FieldKeys.Rows.Count;
                                giftDetail.RecipientKey          = Convert.ToInt64(FieldKeys.Rows[recipientID].ItemArray[0]);
                                giftDetail.RecipientLedgerNumber = giftDetail.RecipientKey;
                                giftDetail.CostCentreCode        = (giftDetail.RecipientKey / 10000).ToString("0000");
                            }
                            else if (motivation == "KEYMIN")
                            {
                                if (KeyMinistries.Rows.Count == 0)
                                {
                                    continue;
                                }

                                giftDetail.MotivationDetailCode = "KEYMIN";
                                int recipientID =
                                    Convert.ToInt32(TXMLParser.GetAttribute(RecordNode, "recipient_keymin_" +
                                                                            counter.ToString())) % KeyMinistries.Rows.Count;
                                giftDetail.RecipientKey = Convert.ToInt64(KeyMinistries.Rows[recipientID].ItemArray[0]);

                                giftDetail.RecipientLedgerNumber = Convert.ToInt64(KeyMinistries.Rows[recipientID].ItemArray[1]);
                                // TTransactionWebConnector.GetRecipientFundNumber(giftDetail.RecipientKey);
                                giftDetail.CostCentreCode = KeyMinistries.Rows[recipientID].ItemArray[2].ToString();
                                // TTransactionWebConnector.IdentifyPartnerCostCentre(FLedgerNumber, giftDetail.RecipientLedgerNumber);
                            }

                            giftDetail.DetailNumber = gift.LastDetailNumber + 1;
                            MainDS.AGiftDetail.Rows.Add(giftDetail);
                            gift.LastDetailNumber = giftDetail.DetailNumber;
                        }

                        if (gift.LastDetailNumber > 0)
                        {
                            MainDS.AGift.Rows.Add(gift);
                            giftBatch.LastGiftNumber = gift.GiftTransactionNumber;
                        }

                        if (giftBatch.LastGiftNumber >= MaxGiftsPerBatch)
                        {
                            break;
                        }
                    }

                    if (TLogging.DebugLevel > 0)
                    {
                        TLogging.Log(
                            GlEffectiveDate.ToShortDateString() + " " + giftBatch.LastGiftNumber.ToString());
                    }
                }
            });

            // need to save the last gift batch number in a_ledger
            if (LedgerTable != null)
            {
                TDBTransaction WriteTransaction = new TDBTransaction();
                bool           SubmissionOk     = false;
                DBAccess.WriteTransaction(ref WriteTransaction, ref SubmissionOk,
                                          delegate
                {
                    ALedgerAccess.SubmitChanges(LedgerTable, WriteTransaction);
                    SubmissionOk = true;
                });

                if (!SubmissionOk)
                {
                    TLogging.Log("An Exception occured during the creation of Gift Batches" + Environment.NewLine);
                }
            }

            return(MainDS);
        }
Example #33
0
        private void ParseTransactionLine(AGiftRow AGift,
            AGiftBatchRow AGiftBatch,
            ref AGiftRow APreviousGift,
            int ANumberOfColumns,
            ref decimal ATotalBatchAmount,
            ref string AImportMessage,
            int ARowNumber,
            decimal AIntlRateFromBase,
            TVerificationResultCollection AMessages,
            AMotivationDetailTable AMotivationDetailTable,
//            TValidationControlsDict AValidationControlsDictGift,
//            TValidationControlsDict AValidationControlsDictGiftDetail,
//            ACostCentreTable AValidationCostCentreTable,
//            AAccountTable AValidationAccountTable,
//            AMotivationGroupTable AValidationMotivationGroupTable,
//            AMethodOfGivingTable AValidationMethodOfGivingTable,
//            AMethodOfPaymentTable AValidationMethodOfPaymentTable,
//            PMailingTable AValidationMailingTable,
            GiftBatchTDSAGiftDetailTable ANeedRecipientLedgerNumber,
            AGiftDetailRow AGiftDetails)
        {
            // Start parsing
            int preParseMessageCount = AMessages.Count;

            // Is this the format with extra columns?
            // Actually if it has the extra columns but does not have the optional final 8 columns we cannot distiguish using this test...
            //   A file without extra columns will have between 13 and 21 columns - depending on whether some of the optional ones at the end are included.
            //   A file with extra columns will be between 19 and 27.
            //  So any count between 19 and 21 is ambiguous.  We will assume that if the file has extra columns it also has
            //   at least enough of the optional ones to exceed 21.
            bool HasExtraColumns = (ANumberOfColumns > 21);

            AImportMessage = Catalog.GetString("Importing the gift data");

            AGift.DonorKey = TCommonImport.ImportInt64(ref FImportLine, FDelimiter, Catalog.GetString("Donor key"),
                FMainDS.AGift.ColumnDonorKey, ARowNumber, AMessages, null);

            TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString(
                    "short name of donor (unused)"), null, ARowNumber, AMessages, null);                                                                   // unused

            // This group is optional and database NULL's are allowed
            AGift.MethodOfGivingCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Method of giving Code"),
                FMainDS.AGift.ColumnMethodOfGivingCode, ARowNumber, AMessages, null, false);
            AGift.MethodOfPaymentCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Method Of Payment Code"),
                FMainDS.AGift.ColumnMethodOfPaymentCode, ARowNumber, AMessages, null, false);
            AGift.Reference = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Reference"),
                FMainDS.AGift.ColumnReference, ARowNumber, AMessages, null, false);
            AGift.ReceiptLetterCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Receipt letter code"),
                FMainDS.AGift.ColumnReceiptLetterCode, ARowNumber, AMessages, null, false);

            if (AGift.MethodOfGivingCode != null)
            {
                AGift.MethodOfGivingCode = AGift.MethodOfGivingCode.ToUpper();
            }

            if (AGift.MethodOfPaymentCode != null)
            {
                AGift.MethodOfPaymentCode = AGift.MethodOfPaymentCode.ToUpper();
            }

            if (AGift.ReceiptLetterCode != null)
            {
                AGift.ReceiptLetterCode = AGift.ReceiptLetterCode.ToUpper();
            }

            if (HasExtraColumns)
            {
                TCommonImport.ImportInt32(ref FImportLine, FDelimiter, Catalog.GetString("Receipt number"),
                    FMainDS.AGift.ColumnReceiptNumber, ARowNumber, AMessages, null);
                TCommonImport.ImportBoolean(ref FImportLine, FDelimiter, Catalog.GetString("First time gift"),
                    FMainDS.AGift.ColumnFirstTimeGift, ARowNumber, AMessages, null);
                TCommonImport.ImportBoolean(ref FImportLine, FDelimiter, Catalog.GetString("Receipt printed"),
                    FMainDS.AGift.ColumnReceiptPrinted, ARowNumber, AMessages, null);
            }

            AImportMessage = Catalog.GetString("Importing the gift details");

            if ((APreviousGift != null) && (AGift.DonorKey == APreviousGift.DonorKey)
                && (AGift.MethodOfGivingCode == APreviousGift.MethodOfGivingCode)
                && (AGift.MethodOfPaymentCode == APreviousGift.MethodOfPaymentCode)
                && (AGift.Reference == APreviousGift.Reference)
                && (AGift.ReceiptLetterCode == APreviousGift.ReceiptLetterCode)
                && (AGift.ReceiptNumber == APreviousGift.ReceiptNumber)
                && (AGift.FirstTimeGift == APreviousGift.FirstTimeGift)
                && (AGift.ReceiptPrinted == APreviousGift.ReceiptPrinted))
            {
                // this row is a new detail for the previousGift
                AGift = APreviousGift;
                AGift.LastDetailNumber++;
                AGiftDetails.DetailNumber = AGift.LastDetailNumber;
            }
            else
            {
                APreviousGift = AGift;
                AGift.LedgerNumber = AGiftBatch.LedgerNumber;
                AGift.BatchNumber = AGiftBatch.BatchNumber;
                AGift.GiftTransactionNumber = AGiftBatch.LastGiftNumber + 1;
                AGiftBatch.LastGiftNumber++;
                AGift.LastDetailNumber = 1;
                FMainDS.AGift.Rows.Add(AGift);
                AGiftDetails.DetailNumber = 1;
            }

            AGiftDetails.LedgerNumber = AGift.LedgerNumber;
            AGiftDetails.BatchNumber = AGiftBatch.BatchNumber;
            AGiftDetails.GiftTransactionNumber = AGift.GiftTransactionNumber;
            FMainDS.AGiftDetail.Rows.Add(AGiftDetails);

            AGiftDetails.RecipientKey = TCommonImport.ImportInt64(ref FImportLine, FDelimiter, Catalog.GetString("Recipient key"),
                FMainDS.AGiftDetail.ColumnRecipientKey, ARowNumber, AMessages, null);

            TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString(
                    "short name of recipient (unused)"), null, ARowNumber, AMessages, null);                           // unused

            if (HasExtraColumns)
            {
                TCommonImport.ImportInt32(ref FImportLine, FDelimiter, Catalog.GetString("Recipient ledger number"),
                    FMainDS.AGiftDetail.ColumnRecipientLedgerNumber, ARowNumber, AMessages, null);
            }

            // we always calculate RecipientLedgerNumber
            AGiftDetails.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(
                AGiftDetails.RecipientKey, AGiftBatch.GlEffectiveDate);

            decimal currentGiftAmount =
                TCommonImport.ImportDecimal(ref FImportLine, FDelimiter, FCultureInfoNumberFormat, Catalog.GetString("Gift amount"),
                    FMainDS.AGiftDetail.ColumnGiftTransactionAmount, ARowNumber, AMessages, null);
            AGiftDetails.GiftTransactionAmount = currentGiftAmount;     // amount in batch currency
            ATotalBatchAmount += currentGiftAmount;

            AGiftDetails.GiftAmount = GLRoutines.Divide(currentGiftAmount, AGiftBatch.ExchangeRateToBase);      // amount in ledger currency

            if (HasExtraColumns)
            {
                // amount in international currency
                TCommonImport.ImportDecimal(ref FImportLine, FDelimiter, FCultureInfoNumberFormat, Catalog.GetString("Gift amount intl"),
                    FMainDS.AGiftDetail.ColumnGiftAmountIntl, ARowNumber, AMessages, null);
            }
            else if (AIntlRateFromBase > 0.0m)
            {
                AGiftDetails.GiftAmountIntl = GLRoutines.Divide(AGiftDetails.GiftAmount, AIntlRateFromBase, 2);
            }

            AGiftDetails.ConfidentialGiftFlag = TCommonImport.ImportBoolean(ref FImportLine, FDelimiter, Catalog.GetString("Confidential gift"),
                FMainDS.AGiftDetail.ColumnConfidentialGiftFlag, ARowNumber, AMessages, null);
            AGiftDetails.MotivationGroupCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Motivation group code"),
                FMainDS.AGiftDetail.ColumnMotivationGroupCode, ARowNumber, AMessages, null).ToUpper();
            AGiftDetails.MotivationDetailCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Motivation detail"),
                FMainDS.AGiftDetail.ColumnMotivationDetailCode, ARowNumber, AMessages, null).ToUpper();

            if (HasExtraColumns)
            {
                TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Cost centre code"),
                    FMainDS.AGiftDetail.ColumnCostCentreCode, ARowNumber, AMessages, null);
            }

            // "In Petra Cost Centre is always inferred from recipient field and motivation detail so is not needed in the import."
            AGiftDetails.CostCentreCode = TGiftTransactionWebConnector.RetrieveCostCentreCodeForRecipient(
                AGiftDetails.LedgerNumber, AGiftDetails.RecipientKey, AGiftDetails.RecipientLedgerNumber,
                AGift.DateEntered, AGiftDetails.MotivationGroupCode, AGiftDetails.MotivationDetailCode);

            // All the remaining columns are optional and can contain database NULL
            AGiftDetails.GiftCommentOne = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Gift comment one"),
                FMainDS.AGiftDetail.ColumnGiftCommentOne, ARowNumber, AMessages, null, false);
            string commentOneType = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Comment one type"),
                FMainDS.AGiftDetail.ColumnCommentOneType, ARowNumber, AMessages, null, false);

            AGiftDetails.MailingCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Mailing code"),
                FMainDS.AGiftDetail.ColumnMailingCode, ARowNumber, AMessages, null, false);

            AGiftDetails.GiftCommentTwo = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Gift comment two"),
                FMainDS.AGiftDetail.ColumnGiftCommentTwo, ARowNumber, AMessages, null, false);
            string commentTwoType = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Comment two type"),
                FMainDS.AGiftDetail.ColumnCommentTwoType, ARowNumber, AMessages, null, false);
            AGiftDetails.GiftCommentThree = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Gift comment three"),
                FMainDS.AGiftDetail.ColumnGiftCommentThree, ARowNumber, AMessages, null, false);
            string commentThreeType = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Comment three type"),
                FMainDS.AGiftDetail.ColumnCommentThreeType, ARowNumber, AMessages, null, false);

            SetCommentTypeCase(ref commentOneType);
            AGiftDetails.CommentOneType = commentOneType;

            SetCommentTypeCase(ref commentTwoType);
            AGiftDetails.CommentTwoType = commentTwoType;

            SetCommentTypeCase(ref commentThreeType);
            AGiftDetails.CommentThreeType = commentThreeType;

            if (AGiftDetails.MailingCode != null)
            {
                AGiftDetails.MailingCode = AGiftDetails.MailingCode.ToUpper();
            }

            // Find the default Tax deductabilty from the motivation detail. This ensures that the column can be missing.
            AMotivationDetailRow motivationDetailRow = (AMotivationDetailRow)AMotivationDetailTable.Rows.Find(
                new object[] { FLedgerNumber, AGiftDetails.MotivationGroupCode, AGiftDetails.MotivationDetailCode });
            string defaultTaxDeductible =
                ((motivationDetailRow != null) && !motivationDetailRow.IsTaxDeductibleAccountCodeNull()
                 && motivationDetailRow.TaxDeductible) ? "yes" : "no";

            AGiftDetails.TaxDeductible = TCommonImport.ImportBoolean(ref FImportLine, FDelimiter, Catalog.GetString("Tax deductible"),
                FMainDS.AGiftDetail.ColumnTaxDeductible, ARowNumber, AMessages, null, defaultTaxDeductible);

            // Account Codes are always inferred from the motivation detail and so is not needed in the import.
            string NewAccountCode = null;
            string NewTaxDeductibleAccountCode = null;

            // get up-to-date account codes
            if (motivationDetailRow != null)
            {
                NewAccountCode = motivationDetailRow.AccountCode;
                NewTaxDeductibleAccountCode = motivationDetailRow.TaxDeductibleAccountCode;
            }

            AGiftDetails.AccountCode = NewAccountCode;
            AGiftDetails.TaxDeductibleAccountCode = NewTaxDeductibleAccountCode;

            // Date entered cannot be imported although it can be modified in the GUI.
            // This is because it would have to be the last column in the import for compatibility
            // but it belongs with the gift and not the detail so it would need to go in an earlier column.
            // For now the import date entered is the effective date.
            AGift.DateEntered = AGiftBatch.GlEffectiveDate;

            // Enforce the correct case for our GIFT constant
            if (String.Compare(AGiftDetails.MotivationGroupCode, MFinanceConstants.MOTIVATION_GROUP_GIFT, true) == 0)
            {
                AGiftDetails.MotivationGroupCode = MFinanceConstants.MOTIVATION_GROUP_GIFT;
            }
        } // Parse TransactionLine
        public static Int32 CreateGiftBatch(
            Int32 ALedgerNumber,
            Int32 AStatementKey,
            Int32 AGiftBatchNumber,
            out TVerificationResultCollection AVerificationResult)
        {
            BankImportTDS MainDS = GetBankStatementTransactionsAndMatches(AStatementKey, ALedgerNumber);

            string MyClientID = DomainManager.GClientID.ToString();

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

            AVerificationResult = new TVerificationResultCollection();

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

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

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

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

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

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

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

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

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

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

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

            string MatchedGiftReference = stmt.Filename;

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

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

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

            DBAccess.GDBAccessObj.RollbackTransaction();

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

            AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];

            giftbatchRow.BankAccountCode = stmt.BankAccountCode;

            decimal HashTotal = 0.0M;

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

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

            int counter = 5;

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

                AEpTransactionRow transactionRow = (AEpTransactionRow)dv.Row;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            TProgressTracker.FinishJob(MyClientID);

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

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

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

            DataUtilities.CopyAllColumnValuesWithoutPK(AOldGiftDetail, giftDetail);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            AMainDS.AGiftDetail.Rows.Add(giftDetail);
        }
Example #36
0
        /// <summary>
        /// Adds a duplicate Gift Detail (or reversed duplicate GiftDetail) to Gift.
        /// </summary>
        /// <param name="AMainDS"></param>
        /// <param name="AGift"></param>
        /// <param name="AOldGiftDetail"></param>
        /// <param name="AReversal">True for reverse or false for straight duplicate</param>
        /// <param name="ATransaction"></param>
        /// <param name="ARequestParams"></param>
        private static void AddDuplicateGiftDetailToGift(ref GiftBatchTDS AMainDS,
            ref AGiftRow AGift,
            AGiftDetailRow AOldGiftDetail,
            bool AReversal,
            TDBTransaction ATransaction,
            Hashtable ARequestParams = null)
        {
            bool TaxDeductiblePercentageEnabled = Convert.ToBoolean(
                TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE"));

            GiftAdjustmentFunctionEnum Function = (GiftAdjustmentFunctionEnum)ARequestParams["Function"];

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

            DataUtilities.CopyAllColumnValuesWithoutPK(AOldGiftDetail, giftDetail);

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

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

            decimal signum = (AReversal) ? -1 : 1;
            giftDetail.GiftTransactionAmount = signum * AOldGiftDetail.GiftTransactionAmount;
            giftDetail.GiftAmount = signum * AOldGiftDetail.GiftAmount;
            giftDetail.GiftAmountIntl = signum * AOldGiftDetail.GiftAmountIntl;

            if (TaxDeductiblePercentageEnabled)
            {
                if (!AReversal && Function.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust))
                {
                    giftDetail.TaxDeductiblePct = Convert.ToDecimal(ARequestParams["NewPct"]);
                    TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetail);
                }
                else if (!AReversal)
                {
                    if (ARequestParams.ContainsKey("UpdateTaxDeductiblePct"))
                    {
                        List <string[]>UpdateTaxDeductiblePctRecipeints = (List <string[]> )ARequestParams["UpdateTaxDeductiblePct"];
                        string[] Result = UpdateTaxDeductiblePctRecipeints.Find(x => x[0] == giftDetail.RecipientKey.ToString());

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

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

                    giftDetail.GiftCommentThree = Catalog.GetString("Original gift date: " + OldGiftRow.DateEntered.ToString("dd-MMM-yyyy"));
                    giftDetail.CommentThreeType = "Both";
                }
                else // user defined
                {
                    giftDetail.GiftCommentOne = (String)ARequestParams["ReversalCommentOne"];
                    giftDetail.GiftCommentTwo = (String)ARequestParams["ReversalCommentTwo"];
                    giftDetail.GiftCommentThree = (String)ARequestParams["ReversalCommentThree"];
                    giftDetail.CommentOneType = (String)ARequestParams["ReversalCommentOneType"];
                    giftDetail.CommentTwoType = (String)ARequestParams["ReversalCommentTwoType"];
                    giftDetail.CommentThreeType = (String)ARequestParams["ReversalCommentThreeType"];
                }
            }

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

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

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

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

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

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

                // if the gift destination should be fixed
                if (ARequestParams.ContainsKey("FixedGiftDestination")
                    && (Function.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust) && (bool)ARequestParams["FixedGiftDestination"]
                        || (((List <string> )ARequestParams["FixedGiftDestination"]).Exists(x => x == giftDetail.RecipientKey.ToString()))))
                {
                    giftDetail.FixedGiftDestination = true;
                }
                else
                {
                    giftDetail.FixedGiftDestination = false;
                }
            }

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

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

                Boolean HasTaxDeductibleAccountCode = false;

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

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

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

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

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

            // if gift is not tax deductible or motivation detail does not hace a tax deductible account
            if (!AGiftDetail.TaxDeductible || !FoundTaxDeductiblePct)
            {
                AGiftDetail.TaxDeductiblePct = 0;
                AGiftDetail.NonDeductibleAmount = AGiftDetail.GiftTransactionAmount;
                AGiftDetail.NonDeductibleAmountBase = AGiftDetail.GiftAmount;
                AGiftDetail.NonDeductibleAmountIntl = AGiftDetail.GiftAmountIntl;
            }
        }
        private Boolean IsUnpostedReversedDetailAdjustment(AGiftDetailRow ARow)
        {
            // This method returns true if the gift detail row is an unposted adjustement to a reversed gift detail
            // We use the LinkToPreviousGift property to discover if this gift is associated with the previous gift row.
            // Then we check if that row has a modifiedDetail flag sets for its first detail.
            if ((ARow == null) || (FBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return false;
            }

            AGiftRow giftRow = GetGiftRow(ARow.GiftTransactionNumber);

            if ((giftRow != null) && (giftRow.LinkToPreviousGift == true))
            {
                if (ARow.GiftTransactionNumber > 1)
                {
                    AGiftDetailRow prevDetailRow = (AGiftDetailRow)FMainDS.AGiftDetail.Rows.Find(
                        new object[] { ARow.LedgerNumber, ARow.BatchNumber, ARow.GiftTransactionNumber - 1, 1 });
                    return prevDetailRow.ModifiedDetail == true;
                }
            }

            return false;
        }
Example #39
0
        private static void AddToFeeTotals(GiftBatchTDS AMainDS,
            AGiftDetailRow AGiftDetailRow,
            string AFeeCode,
            decimal AFeeAmount,
            int APostingPeriod)
        {
            // TODO CT
            // see Add_To_Fee_Totals in gr1210.p

            try
            {
                /* Get the record for the totals of the processed fees. */
                AProcessedFeeTable ProcessedFeeDataTable = AMainDS.AProcessedFee;
                AProcessedFeeRow ProcessedFeeRow =
                    (AProcessedFeeRow)ProcessedFeeDataTable.Rows.Find(new object[] { AGiftDetailRow.LedgerNumber,
                                                                                     AGiftDetailRow.BatchNumber,
                                                                                     AGiftDetailRow.GiftTransactionNumber,
                                                                                     AGiftDetailRow.DetailNumber,
                                                                                     AFeeCode });

                if (ProcessedFeeRow == null)
                {
                    ProcessedFeeRow = (AProcessedFeeRow)ProcessedFeeDataTable.NewRowTyped(false);
                    ProcessedFeeRow.LedgerNumber = AGiftDetailRow.LedgerNumber;
                    ProcessedFeeRow.BatchNumber = AGiftDetailRow.BatchNumber;
                    ProcessedFeeRow.GiftTransactionNumber = AGiftDetailRow.GiftTransactionNumber;
                    ProcessedFeeRow.DetailNumber = AGiftDetailRow.DetailNumber;
                    ProcessedFeeRow.FeeCode = AFeeCode;
                    ProcessedFeeRow.PeriodicAmount = 0;

                    ProcessedFeeDataTable.Rows.Add(ProcessedFeeRow);
                }

                ProcessedFeeRow.CostCentreCode = AGiftDetailRow.CostCentreCode;
                ProcessedFeeRow.PeriodNumber = APostingPeriod;

                /* Add the amount to the existing total. */
                ProcessedFeeRow.PeriodicAmount += AFeeAmount;
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <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);
        }
Example #41
0
        public void TestBatchPostingRecalculations()
        {
            TVerificationResultCollection VerificationResult;

            Int64        RecipientKey;
            Int64        RealRecipientLedgerNumber;
            Int64        FalseRecipientLedgerNumber;
            const string REALCOSTCENTRECODE  = "4300";
            const string FALSECOSTCENTRECODE = "3500";
            const string ACCOUNTCODE         = "0100";

            Int32 GiftBatchNumber;

            //
            // Arrange: Create all data needed for this test (Gift Details have 'fake' RecipientLedgerNumber and CostCentreCode)
            //
            TestBatchPostingRecalculations_Arrange(out RecipientKey, out RealRecipientLedgerNumber,
                                                   out FalseRecipientLedgerNumber, REALCOSTCENTRECODE, FALSECOSTCENTRECODE, out GiftBatchNumber);

            //
            // Act: Post the batch
            //
            bool result = TGiftTransactionWebConnector.PostGiftBatch(FLedgerNumber, GiftBatchNumber, out VerificationResult);

            //
            // Assert
            //

            // Initial Assert: Tests that the post returns positive
            Assert.AreEqual(true,
                            result,
                            "TestBatchPostingRecalculations fail: Posting GiftBatch failed: " + VerificationResult.BuildVerificationResultString());

            // Primary Assert: Chaeck that the gifts have the correct RecipientLedgerNumber, CostCentreCode and Account
            TDBTransaction  Transaction           = null;
            AGiftDetailRow  PositiveGiftDetailRow = null;
            AGiftDetailRow  NegativeGiftDetailRow = null;
            ATransactionRow TransactionRow        = null;
            Int32           GLBatchNumber         = -1;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                      TEnforceIsolationLevel.eilMinimum,
                                                                      ref Transaction,
                                                                      delegate
            {
                PositiveGiftDetailRow = AGiftDetailAccess.LoadByPrimaryKey(FLedgerNumber, GiftBatchNumber, 1, 1, Transaction)[0];
                NegativeGiftDetailRow = AGiftDetailAccess.LoadByPrimaryKey(FLedgerNumber, GiftBatchNumber, 2, 1, Transaction)[0];

                GLBatchNumber  = ALedgerAccess.LoadByPrimaryKey(FLedgerNumber, Transaction)[0].LastBatchNumber;
                TransactionRow = ATransactionAccess.LoadByPrimaryKey(FLedgerNumber, GLBatchNumber, 1, 1, Transaction)[0];
            });

            Assert.IsNotNull(PositiveGiftDetailRow, "TestBatchPostingRecalculations fail: Obtaining PositiveGiftDetailRow from database failed");
            Assert.IsNotNull(NegativeGiftDetailRow, "TestBatchPostingRecalculations fail: Obtaining NegativeGiftDetailRow from database failed");
            Assert.IsNotNull(TransactionRow, "TestBatchPostingRecalculations fail: Obtaining Transaction from database failed");

            Assert.AreEqual(RealRecipientLedgerNumber, PositiveGiftDetailRow.RecipientLedgerNumber,
                            "TestBatchPostingRecalculations fail: RecipientLedgerNumber for PositiveGiftDetailRow is incorrect");
            Assert.AreEqual(FalseRecipientLedgerNumber, NegativeGiftDetailRow.RecipientLedgerNumber,
                            "TestBatchPostingRecalculations fail: RecipientLedgerNumber for NegativeGiftDetailRow is incorrect");
            Assert.AreEqual(REALCOSTCENTRECODE, PositiveGiftDetailRow.CostCentreCode,
                            "TestBatchPostingRecalculations fail: CostCentreCode for PositiveGiftDetailRow is incorrect");
            Assert.AreEqual(FALSECOSTCENTRECODE, NegativeGiftDetailRow.CostCentreCode,
                            "TestBatchPostingRecalculations fail: CostCentreCode for NegativeGiftDetailRow is incorrect");
            Assert.AreEqual(ACCOUNTCODE, TransactionRow.AccountCode,
                            "TestBatchPostingRecalculations fail: AccountCode for PositiveGiftDetailRow is incorrect");

            // Cleanup: Delete test records

            bool SubmissionOK = true;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable,
                                                                  TEnforceIsolationLevel.eilMinimum,
                                                                  ref Transaction,
                                                                  ref SubmissionOK,
                                                                  delegate
            {
                AProcessedFeeAccess.DeleteUsingTemplate(
                    new TSearchCriteria[] { new TSearchCriteria("a_ledger_number_i", FLedgerNumber),
                                            new TSearchCriteria("a_batch_number_i", GiftBatchNumber) },
                    Transaction);

                AGiftDetailAccess.DeleteRow(AGiftDetailTable.TableId, PositiveGiftDetailRow, Transaction);
                AGiftDetailAccess.DeleteRow(AGiftDetailTable.TableId, NegativeGiftDetailRow, Transaction);
            });

            TPartnerWebConnector.DeletePartner(RecipientKey, out VerificationResult);
            TPartnerWebConnector.DeletePartner(RealRecipientLedgerNumber, out VerificationResult);
            TPartnerWebConnector.DeletePartner(FalseRecipientLedgerNumber, out VerificationResult);
        }
        private void UpdateControlsProtection(AGiftDetailRow ARow)
        {
            bool firstIsEnabled = (ARow != null) && (ARow.DetailNumber == 1) && !ViewMode;
            bool pnlDetailsEnabledState = false;

            dtpDateEntered.Enabled = firstIsEnabled;
            txtDetailDonorKey.Enabled = firstIsEnabled;
            cmbDetailMethodOfGivingCode.Enabled = firstIsEnabled;

            cmbDetailMethodOfPaymentCode.Enabled = firstIsEnabled && !BatchHasMethodOfPayment();
            txtDetailReference.Enabled = firstIsEnabled;
            cmbDetailReceiptLetterCode.Enabled = firstIsEnabled;

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

            if (ARow == null)
            {
                PnlDetailsProtected = (ViewMode
                                       || !FBatchUnposted
                                       );
            }
            else
            {
                PnlDetailsProtected = (ViewMode
                                       || !FBatchUnposted
                                       || (ARow.GiftTransactionAmount < 0 && GetGiftRow(ARow.GiftTransactionNumber).ReceiptNumber != 0)
                                       );    // taken from old petra
            }

            pnlDetailsEnabledState = (!PnlDetailsProtected && grdDetails.Rows.Count > 1);
            pnlDetails.Enabled = pnlDetailsEnabledState;

            btnDelete.Enabled = pnlDetailsEnabledState;
            btnDeleteAll.Enabled = btnDelete.Enabled;
            btnNewDetail.Enabled = !PnlDetailsProtected;
            btnNewGift.Enabled = !PnlDetailsProtected;
        }
Example #43
0
        public static bool GiftRevertAdjust(Hashtable requestParams, out TVerificationResultCollection AMessages)
        {
            AMessages = new TVerificationResultCollection();

            Int32   ALedgerNumber   = (Int32)requestParams["ALedgerNumber"];
            Boolean batchSelected   = (Boolean)requestParams["NewBatchSelected"];
            Int32   ANewBatchNumber = 0;

            bool TaxDeductiblePercentageEnabled = Convert.ToBoolean(
                TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE"));

            if (batchSelected)
            {
                ANewBatchNumber = (Int32)requestParams["NewBatchNumber"];
            }

            String Function          = (String)requestParams["Function"];
            Int32  AGiftDetailNumber = (Int32)requestParams["GiftDetailNumber"];
            Int32  AGiftNumber       = (Int32)requestParams["GiftNumber"];
            Int32  ABatchNumber      = (Int32)requestParams["BatchNumber"];

            //decimal batchHashTotal = 0;
            decimal batchGiftTotal = 0;

            GiftBatchTDS   MainDS      = new GiftBatchTDS();
            TDBTransaction Transaction = null;
            DateTime       ADateEffective;

            Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

            try
            {
                ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);

                AGiftBatchRow giftBatch;

                if (!batchSelected)
                {
                    ADateEffective = (DateTime)requestParams["GlEffectiveDate"];

                    AGiftBatchAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, Transaction);

                    AGiftBatchRow oldGiftBatch = MainDS.AGiftBatch[0];
                    TGiftBatchFunctions.CreateANewGiftBatchRow(ref MainDS, ref Transaction, ref LedgerTable, ALedgerNumber, ADateEffective);
                    giftBatch = MainDS.AGiftBatch[1];
                    giftBatch.BankAccountCode     = oldGiftBatch.BankAccountCode;
                    giftBatch.BankCostCentre      = oldGiftBatch.BankCostCentre;
                    giftBatch.CurrencyCode        = oldGiftBatch.CurrencyCode;
                    giftBatch.ExchangeRateToBase  = oldGiftBatch.ExchangeRateToBase;
                    giftBatch.MethodOfPaymentCode = oldGiftBatch.MethodOfPaymentCode;
                    giftBatch.HashTotal           = 0;

                    if (giftBatch.MethodOfPaymentCode.Length == 0)
                    {
                        giftBatch.SetMethodOfPaymentCodeNull();
                    }

                    giftBatch.BankCostCentre = oldGiftBatch.BankCostCentre;
                    giftBatch.GiftType       = oldGiftBatch.GiftType;

                    if (Function.Equals("AdjustGift"))
                    {
                        giftBatch.BatchDescription = Catalog.GetString("Gift Adjustment");
                    }
                    else
                    {
                        giftBatch.BatchDescription = Catalog.GetString("Reverse Gift");
                    }
                }
                else
                {
                    AGiftBatchAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ANewBatchNumber, Transaction);

                    giftBatch      = MainDS.AGiftBatch[0];
                    ADateEffective = giftBatch.GlEffectiveDate;
                    //If into an existing batch, then retrive the existing batch total
                    batchGiftTotal = giftBatch.BatchTotal;
                }

                if (Function.Equals("ReverseGiftBatch"))
                {
                    AGiftAccess.LoadViaAGiftBatch(MainDS, ALedgerNumber, ABatchNumber, Transaction);

                    foreach (AGiftRow gift in MainDS.AGift.Rows)
                    {
                        AGiftDetailAccess.LoadViaAGift(MainDS, ALedgerNumber, ABatchNumber, gift.GiftTransactionNumber, Transaction);
                    }
                }
                else
                {
                    AGiftAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, AGiftNumber, Transaction);

                    if (Function.Equals("ReverseGiftDetail"))
                    {
                        AGiftDetailAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, AGiftNumber, AGiftDetailNumber, Transaction);
                    }
                    else
                    {
                        AGiftDetailAccess.LoadViaAGift(MainDS, ALedgerNumber, ABatchNumber, AGiftNumber, Transaction);
                    }
                }

                //assuming new elements are added after these static borders

                int cycle = 0;

                MainDS.AGift.DefaultView.Sort = string.Format("{0}, {1}",
                                                              AGiftTable.GetBatchNumberDBName(),
                                                              AGiftTable.GetGiftTransactionNumberDBName());

                MainDS.AGiftDetail.DefaultView.Sort = string.Format("{0}, {1}, {2}",
                                                                    AGiftDetailTable.GetBatchNumberDBName(),
                                                                    AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                    AGiftDetailTable.GetDetailNumberDBName());

                do
                {
                    foreach (DataRowView giftRow in MainDS.AGift.DefaultView)
                    {
                        AGiftRow oldGift = (AGiftRow)giftRow.Row;

                        if ((oldGift.BatchNumber == ABatchNumber) && (oldGift.LedgerNumber == ALedgerNumber) &&
                            (Function.Equals("ReverseGiftBatch") || (oldGift.GiftTransactionNumber == AGiftNumber)))
                        {
                            AGiftRow gift = MainDS.AGift.NewRowTyped(true);
                            DataUtilities.CopyAllColumnValuesWithoutPK(oldGift, gift);
                            gift.LedgerNumber          = giftBatch.LedgerNumber;
                            gift.BatchNumber           = giftBatch.BatchNumber;
                            gift.DateEntered           = ADateEffective;
                            gift.GiftTransactionNumber = giftBatch.LastGiftNumber + 1;
                            giftBatch.LastGiftNumber++;
                            gift.LastDetailNumber = 0;

                            MainDS.AGift.Rows.Add(gift);

                            foreach (DataRowView giftDetailRow in MainDS.AGiftDetail.DefaultView)
                            {
                                AGiftDetailRow oldGiftDetail = (AGiftDetailRow)giftDetailRow.Row;

                                if ((oldGiftDetail.GiftTransactionNumber == oldGift.GiftTransactionNumber) &&
                                    (oldGiftDetail.BatchNumber == ABatchNumber) &&
                                    (oldGiftDetail.LedgerNumber == ALedgerNumber) &&
                                    (!Function.Equals("ReverseGiftDetail") || (oldGiftDetail.DetailNumber == AGiftDetailNumber)))
                                {
                                    if ((cycle == 0) && oldGiftDetail.ModifiedDetail)
                                    {
                                        AMessages.Add(new TVerificationResult(
                                                          String.Format(Catalog.GetString("Cannot reverse or adjust Gift {0} with Detail {1} in Batch {2}"),
                                                                        oldGiftDetail.GiftTransactionNumber, oldGiftDetail.DetailNumber, oldGiftDetail.BatchNumber),
                                                          String.Format(Catalog.GetString("It was already adjusted or reversed.")),
                                                          TResultSeverity.Resv_Critical));

                                        DBAccess.GDBAccessObj.RollbackTransaction();

                                        return(false);
                                    }

                                    AGiftDetailRow giftDetail = MainDS.AGiftDetail.NewRowTyped(true);
                                    DataUtilities.CopyAllColumnValuesWithoutPK(oldGiftDetail, giftDetail);

                                    giftDetail.DetailNumber = ++gift.LastDetailNumber;

                                    giftDetail.LedgerNumber          = gift.LedgerNumber;
                                    giftDetail.BatchNumber           = giftBatch.BatchNumber;
                                    giftDetail.GiftTransactionNumber = gift.GiftTransactionNumber;
                                    //Identify the reversal source
                                    giftDetail.ModifiedDetailKey = "|" + oldGiftDetail.BatchNumber.ToString() + "|" +
                                                                   oldGiftDetail.GiftTransactionNumber.ToString() + "|" +
                                                                   oldGiftDetail.DetailNumber.ToString();

                                    decimal signum = (cycle == 0) ? -1 : 1;
                                    giftDetail.GiftTransactionAmount = signum * oldGiftDetail.GiftTransactionAmount;
                                    batchGiftTotal           += giftDetail.GiftTransactionAmount;
                                    giftDetail.GiftAmount     = signum * oldGiftDetail.GiftAmount;
                                    giftDetail.GiftAmountIntl = signum * oldGiftDetail.GiftAmountIntl;

                                    if (TaxDeductiblePercentageEnabled)
                                    {
                                        giftDetail.TaxDeductibleAmount     = signum * oldGiftDetail.TaxDeductibleAmount;
                                        giftDetail.TaxDeductibleAmountBase = signum * oldGiftDetail.TaxDeductibleAmountBase;
                                        giftDetail.TaxDeductibleAmountIntl = signum * oldGiftDetail.TaxDeductibleAmountIntl;
                                        giftDetail.NonDeductibleAmount     = signum * oldGiftDetail.NonDeductibleAmount;
                                        giftDetail.NonDeductibleAmountBase = signum * oldGiftDetail.NonDeductibleAmountBase;
                                        giftDetail.NonDeductibleAmountIntl = signum * oldGiftDetail.NonDeductibleAmountIntl;
                                    }

                                    giftDetail.GiftCommentOne   = (String)requestParams["ReversalCommentOne"];
                                    giftDetail.GiftCommentTwo   = (String)requestParams["ReversalCommentTwo"];
                                    giftDetail.GiftCommentThree = (String)requestParams["ReversalCommentThree"];
                                    giftDetail.CommentOneType   = (String)requestParams["ReversalCommentOneType"];
                                    giftDetail.CommentTwoType   = (String)requestParams["ReversalCommentTwoType"];
                                    giftDetail.CommentThreeType = (String)requestParams["ReversalCommentThreeType"];

                                    // This is used to mark both as a Reverted giftDetails, except the adjusted (new) gift

                                    giftDetail.ModifiedDetail    = (cycle == 0);
                                    oldGiftDetail.ModifiedDetail = (cycle == 0);
                                    MainDS.AGiftDetail.Rows.Add(giftDetail);
                                }
                            }
                        }
                    }

                    cycle++;
                } while ((cycle < 2) && Function.Equals("AdjustGift"));

                //When reversing into a new or existing batch, set batch total
                if (!Function.Equals("AdjustGift"))
                {
                    giftBatch.BatchTotal = batchGiftTotal;
                }

                // save everything at the end
                AGiftBatchAccess.SubmitChanges(MainDS.AGiftBatch, Transaction);

                ALedgerAccess.SubmitChanges(LedgerTable, Transaction);

                AGiftAccess.SubmitChanges(MainDS.AGift, Transaction);

                AGiftDetailAccess.SubmitChanges(MainDS.AGiftDetail, Transaction);

                MainDS.AGiftBatch.AcceptChanges();

                DBAccess.GDBAccessObj.CommitTransaction();

                return(true);
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured while performing Gift Reverse/Adjust:" + Environment.NewLine + Exc.ToString());

                DBAccess.GDBAccessObj.RollbackTransaction();

                throw new EOPAppException(Catalog.GetString("Gift Reverse/Adjust failed."), Exc);
            }
        }
        /// <summary>
        /// Method to cancel a specified batch
        /// </summary>
        /// <param name="ACurrentBatchRow"></param>
        /// <returns></returns>
        public bool CancelBatch(AGiftBatchRow ACurrentBatchRow)
        {
            //Assign default value(s)
            bool CancellationSuccessful = false;

            string CancelMessage     = string.Empty;
            string CompletionMessage = string.Empty;

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

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

            int CurrentBatchNo = ACurrentBatchRow.BatchNumber;

            CancelMessage = String.Format(Catalog.GetString("Are you sure you want to cancel gift batch number: {0}?"),
                                          ACurrentBatchRow.BatchNumber);

            if ((MessageBox.Show(CancelMessage,
                                 "Cancel Batch",
                                 MessageBoxButtons.YesNo,
                                 MessageBoxIcon.Question,
                                 MessageBoxDefaultButton.Button2) != System.Windows.Forms.DialogResult.Yes))
            {
                return(CancellationSuccessful);
            }

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

            BackupMainDS.Merge(FMainDS);

            try
            {
                FMyForm.Cursor = Cursors.WaitCursor;

                //Normally need to set the message parameters before the delete is performed if requiring any of the row values
                CompletionMessage = String.Format(Catalog.GetString("Batch no.: {0} cancelled successfully."),
                                                  ACurrentBatchRow.BatchNumber);

                FMyForm.GetBatchControl().UndoModifiedBatchRow(ACurrentBatchRow, true);

                //Load all journals for current Batch
                //clear any transactions currently being editied in the Transaction Tab
                FMyForm.GetTransactionsControl().ClearCurrentSelection();

                //Delete transactions
                DataView GiftDV       = new DataView(FMainDS.AGift);
                DataView GiftDetailDV = new DataView(FMainDS.AGiftDetail);

                GiftDV.AllowDelete       = true;
                GiftDetailDV.AllowDelete = true;

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

                GiftDV.Sort = AGiftTable.GetGiftTransactionNumberDBName() + " DESC";

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

                GiftDetailDV.Sort = String.Format("{0} DESC, {1} DESC",
                                                  AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                  AGiftDetailTable.GetDetailNumberDBName());

                foreach (DataRowView drv in GiftDetailDV)
                {
                    AGiftDetailRow gdr = (AGiftDetailRow)drv.Row;

                    // if the gift detail being cancelled is a reversed gift
                    if (gdr.ModifiedDetail && !string.IsNullOrEmpty(gdr.ModifiedDetailKey))
                    {
                        ModifiedDetailKeys.Add(gdr.ModifiedDetailKey);
                    }

                    gdr.Delete();
                }

                for (int i = 0; i < GiftDV.Count; i++)
                {
                    GiftDV.Delete(i);
                }

                //Batch is only cancelled and never deleted
                ACurrentBatchRow.BatchTotal     = 0;
                ACurrentBatchRow.LastGiftNumber = 0;
                ACurrentBatchRow.BatchStatus    = MFinanceConstants.BATCH_CANCELLED;

                FPetraUtilsObject.SetChangedFlag();

                // save first
                if (FMyForm.SaveChanges())
                {
                    if (ModifiedDetailKeys.Count > 0)
                    {
                        TRemote.MFinance.Gift.WebConnectors.ReversedGiftReset(FLedgerNumber, ModifiedDetailKeys);
                    }

                    MessageBox.Show(CompletionMessage,
                                    "Batch Cancelled",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
                else
                {
                    throw new Exception(Catalog.GetString("The batch failed to save after being cancelled! Reopen the form and retry."));
                }

                CancellationSuccessful = true;
            }
            catch (Exception ex)
            {
                //Revert to previous state
                FMainDS.Merge(BackupMainDS);

                CompletionMessage = ex.Message;
                MessageBox.Show(CompletionMessage,
                                "Cancellation Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                FMyForm.Cursor = Cursors.Default;
            }

            return(CancellationSuccessful);
        }