示例#1
0
        /// <summary>
        /// Find the latest gift that was given by a donor
        /// </summary>
        /// <param name="AParameters">report parameter list</param>
        /// <param name="AResults">result list</param>
        /// <returns>DataTable with row for last gift by donor</returns>
        public static DataTable SelectLatestGiftRow(TParameterList AParameters, TResultList AResults)
        {
            Int64 DonorKey = AParameters.Get("PartnerKey").ToInt64();

            String StrSql = "SELECT DISTINCT " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetLedgerNumberDBName() + ", " +
                            AGiftTable.GetTableDBName() + "." + AGiftTable.GetBatchNumberDBName() + ", " +
                            AGiftTable.GetTableDBName() + "." + AGiftTable.GetGiftTransactionNumberDBName() + ", " +
                            AGiftTable.GetTableDBName() + "." + AGiftTable.GetDateEnteredDBName();

            StrSql = StrSql +
                     " FROM " + AGiftTable.GetTableDBName() +
                     " WHERE " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDonorKeyDBName() + " = " + DonorKey.ToString() +
                     " ORDER BY " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDateEnteredDBName() + " DESC";

            TDBTransaction Transaction = new TDBTransaction();
            DataTable      tempTbl     = new DataTable();

            DBAccess.ReadTransaction(
                ref Transaction,
                delegate
            {
                tempTbl = Transaction.DataBaseObj.SelectDT(StrSql, "result", Transaction);
            });

            DataTable resultTbl = tempTbl.Clone();

            resultTbl.Clear();

            if (tempTbl.Rows.Count > 0)
            {
                resultTbl.Rows.Add((object[])tempTbl.Rows[0].ItemArray.Clone());
            }

            return(resultTbl);
        }
示例#2
0
        private void DeleteCurrentBatchGiftData(Int32 ABatchNumber)
        {
            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)
            {
                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();
            }
        }
示例#3
0
        public static void MarkReceiptsPrinted(int ALedgerNumber, DataTable AGiftTbl)
        {
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);
            AGiftTable     Tbl         = new AGiftTable();

            foreach (DataRow Row in AGiftTbl.Rows)
            {
                Tbl.Merge(AGiftAccess.LoadByPrimaryKey(
                              ALedgerNumber,
                              Convert.ToInt32(Row["BatchNumber"]),
                              Convert.ToInt32(Row["TransactionNumber"]),
                              Transaction));
            }

            foreach (AGiftRow Row in Tbl.Rows)
            {
                Row.ReceiptPrinted = true;
            }

            try
            {
                AGiftAccess.SubmitChanges(Tbl, Transaction);

                DBAccess.GDBAccessObj.CommitTransaction();
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured while marking Receipts as printed:" + Environment.NewLine + Exc.ToString());

                DBAccess.GDBAccessObj.RollbackTransaction();

                throw;
            }
        }
示例#4
0
        public static string PrintGiftReceipt(
            String AGiftCurrency,
            String ADonorShortName,
            Int64 ADonorKey,
            TPartnerClass ADonorClass,
            AGiftTable GiftsThisDonor,
            string AHTMLTemplateFilename
            )
        {
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);
            string         HtmlDoc;

            try
            {
                string LocalCountryCode = TAddressTools.GetCountryCodeFromSiteLedger(Transaction);
                HtmlDoc = FormatHtmlReceipt(
                    ADonorShortName,
                    ADonorKey,
                    ADonorClass,
                    AGiftCurrency,
                    LocalCountryCode,
                    GiftsThisDonor,
                    AHTMLTemplateFilename,
                    Transaction);
            }
            finally
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
            }
            return(HtmlDoc);
        }
        /// <summary>
        /// Update all donor names in gift details table
        /// </summary>
        /// <param name="ABatchNumber"></param>
        private void UpdateAllDonorNames(Int32 ABatchNumber)
        {
            Dictionary <Int32, Int64>  GiftsDict  = new Dictionary <Int32, Int64>();
            Dictionary <Int64, string> DonorsDict = new Dictionary <Int64, string>();

            DataView GiftDV = new DataView(FMainDS.AGift);

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

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

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

                Int64 donorKey = gr.DonorKey;

                GiftsDict.Add(gr.GiftTransactionNumber, donorKey);

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

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

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

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

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

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

                Int64 donorKey = GiftsDict[giftDetail.GiftTransactionNumber];

                giftDetail.DonorKey  = donorKey;
                giftDetail.DonorName = DonorsDict[donorKey];
            }
        }
示例#6
0
        /// <summary>
        /// Select the last Gift and motivation details of the gifts that were given within the time period from one partner.
        /// </summary>
        /// <param name="ADonorKey">Partner key of the donor</param>
        /// <param name="ALedgerNumber">Ledger number</param>
        /// <param name="AStartDate">Start date of the period</param>
        /// <param name="AEndDate">End date of the period</param>
        /// <param name="ACurrency">Currency: Base or International</param>
        /// <returns>True if a gift was found; otherwise false</returns>
        private bool SelectLastGift(Int64 ADonorKey, Int64 ALedgerNumber, DateTime AStartDate, DateTime AEndDate, String ACurrency)
        {
            String StrSql = "SELECT " + AGiftTable.GetDateEnteredDBName() + ", " +
                            AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetMotivationGroupCodeDBName() + ", " +
                            AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetMotivationDetailCodeDBName();

            if (ACurrency == "Base")
            {
                StrSql = StrSql + ", " + AGiftDetailTable.GetGiftAmountDBName() + " AS CurrentAmount";
            }
            else
            {
                StrSql = StrSql + ", " + AGiftDetailTable.GetGiftAmountIntlDBName() + " AS CurrentAmount";
            }

            StrSql = StrSql +
                     " FROM " + AGiftTable.GetTableDBName() +
                     " , " + AGiftDetailTable.GetTableDBName() +
                     ", " + AGiftBatchTable.GetTableDBName() +

                     " WHERE " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetLedgerNumberDBName() + " = " + ALedgerNumber.ToString() +
                     " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetLedgerNumberDBName() + " = " +
                     ALedgerNumber.ToString() +
                     " AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetLedgerNumberDBName() + " = " + ALedgerNumber.ToString() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDonorKeyDBName() + " = " + ADonorKey.ToString() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetBatchNumberDBName() + " = " + AGiftDetailTable.GetTableDBName() +
                     "." + AGiftDetailTable.GetBatchNumberDBName() +
                     " AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchNumberDBName() + " = " +
                     AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetBatchNumberDBName() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetGiftTransactionNumberDBName() + " = " +
                     AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetGiftTransactionNumberDBName() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDateEnteredDBName() + " BETWEEN '" + AStartDate.ToString(
                "yyyy-MM-dd") + "' AND '" + AEndDate.ToString("yyyy-MM-dd") + "'" +
                     " AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchStatusDBName() + " = 'Posted'" +
                     " ORDER BY " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDateEnteredDBName() + " DESC LIMIT 1";

            DataTable Table = situation.GetDatabaseConnection().SelectDT(StrSql, "table",
                                                                         situation.GetDatabaseConnection().Transaction, new OdbcParameter[] { });

            if (Table.Rows.Count > 0)
            {
                DateTime DateEntered      = (DateTime)Table.Rows[0][AGiftTable.GetDateEnteredDBName()];
                decimal  CurrentAmount    = Convert.ToDecimal(Table.Rows[0]["CurrentAmount"]);
                String   MotivationDetail = (String)Table.Rows[0][AGiftDetailTable.GetMotivationDetailCodeDBName()];
                String   MotivationGroup  = (String)Table.Rows[0][AGiftDetailTable.GetMotivationGroupCodeDBName()];

                situation.GetParameters().Add("LastGiftDate", new TVariant(DateEntered));
                situation.GetParameters().Add("LastGiftAmount", new TVariant(CurrentAmount));
                situation.GetParameters().Add("MotivationDetail", new TVariant(MotivationDetail));
                situation.GetParameters().Add("MotivationGroup", new TVariant(MotivationGroup));

                return(true);
            }

            return(false);
        }
        private bool DonorIsAlreadyLoaded(Int64 ADonorKey, Int32 AGiftNumber)
        {
            //Check for Donor in loaded gift batches
            DataView giftDV = new DataView(FMainDS.AGift);

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

            return(giftDV != null && giftDV.Count > 0);
        }
        private void SetGiftDetailDefaultView()
        {
            if (FBatchNumber != -1)
            {
                string rowFilter = String.Format("{0}={1}",
                                                 AGiftDetailTable.GetBatchNumberDBName(),
                                                 FBatchNumber);
                FFilterAndFindObject.FilterPanelControls.SetBaseFilter(rowFilter, true);
                FMainDS.AGiftDetail.DefaultView.RowFilter = rowFilter;
                FFilterAndFindObject.CurrentActiveFilter  = rowFilter;
                // We don't apply the filter yet!

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

                FMainDS.AGift.DefaultView.RowFilter = String.Format("{0}={1}",
                                                                    AGiftTable.GetBatchNumberDBName(),
                                                                    FBatchNumber);
            }
        }
示例#9
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();
            }
        }
示例#10
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();
            }
        }
        private void SetBatchLastGiftNumber()
        {
            DataView dv = new DataView(FMainDS.AGift);

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

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

            dv.RowStateFilter = DataViewRowState.CurrentRows;

            if (dv.Count > 0)
            {
                AGiftRow transRow = (AGiftRow)dv[0].Row;
                FBatchRow.LastGiftNumber = transRow.GiftTransactionNumber;
            }
            else
            {
                FBatchRow.LastGiftNumber = 0;
            }
        }
示例#12
0
        /// <summary>
        /// export all the Data of the batches matching the parameters to a String
        /// </summary>
        /// <param name="ARequestParams">Hashtable containing the given params </param>
        /// <param name="AExportString">Big parts of the export file as a simple String</param>
        /// <param name="AVerificationMessages">Additional messages to display in a messagebox</param>
        /// <returns>number of exported batches, -1 if cancelled, -2 if error</returns>
        public Int32 ExportAllGiftBatchData(
            Hashtable ARequestParams,
            out String AExportString,
            out TVerificationResultCollection AVerificationMessages)
        {
            //Return number of exported batches, -1 if cancelled, -2 if error
            int ReturnGiftBatchCount = 0;

            FStringWriter     = new StringWriter();
            FMainDS           = new GiftBatchTDS();
            FDelimiter        = (String)ARequestParams["Delimiter"];
            FLedgerNumber     = (Int32)ARequestParams["ALedgerNumber"];
            FDateFormatString = (String)ARequestParams["DateFormatString"];
            bool Summary = (bool)ARequestParams["Summary"];

            FUseBaseCurrency = (bool)ARequestParams["bUseBaseCurrency"];
            FDateForSummary  = (DateTime)ARequestParams["DateForSummary"];
            String NumberFormat = (String)ARequestParams["NumberFormat"];

            FCultureInfo      = new CultureInfo(NumberFormat.Equals("American") ? "en-US" : "de-DE");
            FTransactionsOnly = (bool)ARequestParams["TransactionsOnly"];
            FExtraColumns     = (bool)ARequestParams["ExtraColumns"];

            try
            {
                DBAccess.GDBAccessObj.BeginAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                               ref FTransaction,
                                                               delegate
                {
                    try
                    {
                        ALedgerAccess.LoadByPrimaryKey(FMainDS, FLedgerNumber, FTransaction);

                        List <OdbcParameter> parameters = new List <OdbcParameter>();

                        SortedList <String, String> SQLCommandDefines = new SortedList <string, string>();

                        if ((bool)ARequestParams["IncludeUnposted"])
                        {
                            SQLCommandDefines.Add("INCLUDEUNPOSTED", string.Empty);
                        }

                        OdbcParameter param = new OdbcParameter("LedgerNumber", OdbcType.Int);
                        param.Value         = FLedgerNumber;
                        parameters.Add(param);

                        Int64 recipientNumber = (Int64)ARequestParams["RecipientNumber"];
                        Int64 fieldNumber     = (Int64)ARequestParams["FieldNumber"];

                        if (recipientNumber != 0)
                        {
                            SQLCommandDefines.Add("BYRECIPIENT", string.Empty);
                            param       = new OdbcParameter("RecipientNumber", OdbcType.Int);
                            param.Value = recipientNumber;
                            parameters.Add(param);
                        }

                        if (fieldNumber != 0)
                        {
                            SQLCommandDefines.Add("BYFIELD", string.Empty);
                            param       = new OdbcParameter("fieldNumber", OdbcType.Int);
                            param.Value = fieldNumber;
                            parameters.Add(param);
                        }

                        if (ARequestParams.ContainsKey("BatchNumberStart"))
                        {
                            SQLCommandDefines.Add("BYBATCHNUMBER", string.Empty);
                            param       = new OdbcParameter("BatchNumberStart", OdbcType.Int);
                            param.Value = (Int32)ARequestParams["BatchNumberStart"];
                            parameters.Add(param);
                            param       = new OdbcParameter("BatchNumberEnd", OdbcType.Int);
                            param.Value = (Int32)ARequestParams["BatchNumberEnd"];
                            parameters.Add(param);
                        }
                        else
                        {
                            SQLCommandDefines.Add("BYDATERANGE", string.Empty);
                            param       = new OdbcParameter("BatchDateFrom", OdbcType.DateTime);
                            param.Value = (DateTime)ARequestParams["BatchDateFrom"];
                            parameters.Add(param);
                            param       = new OdbcParameter("BatchDateTo", OdbcType.DateTime);
                            param.Value = (DateTime)ARequestParams["BatchDateTo"];
                            parameters.Add(param);
                        }

                        string sqlStatement = TDataBase.ReadSqlFile("Gift.GetGiftsToExport.sql", SQLCommandDefines);

                        TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                         Catalog.GetString("Retrieving gift batch records"),
                                                         5);

                        if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                            throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                        }

                        DBAccess.GDBAccessObj.Select(FMainDS,
                                                     "SELECT DISTINCT PUB_a_gift_batch.* " + sqlStatement + " ORDER BY " + AGiftBatchTable.GetBatchNumberDBName(),
                                                     FMainDS.AGiftBatch.TableName,
                                                     FTransaction,
                                                     parameters.ToArray());


                        TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                         Catalog.GetString("Retrieving gift records"),
                                                         10);

                        if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                            throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                        }

                        DBAccess.GDBAccessObj.Select(FMainDS,
                                                     "SELECT DISTINCT PUB_a_gift.* " + sqlStatement + " ORDER BY " + AGiftBatchTable.GetBatchNumberDBName() + ", " +
                                                     AGiftTable.GetGiftTransactionNumberDBName(),
                                                     FMainDS.AGift.TableName,
                                                     FTransaction,
                                                     parameters.ToArray());


                        TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                         Catalog.GetString("Retrieving gift detail records"),
                                                         15);

                        if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                            throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                        }

                        DBAccess.GDBAccessObj.Select(FMainDS,
                                                     "SELECT DISTINCT PUB_a_gift_detail.* " + sqlStatement,
                                                     FMainDS.AGiftDetail.TableName,
                                                     FTransaction,
                                                     parameters.ToArray());
                    }
                    catch (ApplicationException ex)
                    {
                        throw ex;
                    }
                    catch (Exception ex)
                    {
                        TLogging.Log("Error in ExportAllGiftBatchData: " + ex.Message);
                        throw ex;
                    }
                });

                TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(),
                                                     Catalog.GetString("Exporting Gift Batches"), 100);

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("Retrieving records"),
                                                 5);

                string BaseCurrency = FMainDS.ALedger[0].BaseCurrency;
                FCurrencyCode = BaseCurrency; // Depending on FUseBaseCurrency, this will be overwritten for each gift.

                SortedDictionary <String, AGiftSummaryRow> sdSummary = new SortedDictionary <String, AGiftSummaryRow>();

                UInt32 counter = 0;

                // TProgressTracker Variables
                UInt32 GiftCounter = 0;

                AGiftSummaryRow giftSummary = null;

                FMainDS.AGiftDetail.DefaultView.Sort =
                    AGiftDetailTable.GetLedgerNumberDBName() + "," +
                    AGiftDetailTable.GetBatchNumberDBName() + "," +
                    AGiftDetailTable.GetGiftTransactionNumberDBName();

                foreach (AGiftBatchRow giftBatch in FMainDS.AGiftBatch.Rows)
                {
                    if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                    {
                        TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                        throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                    }

                    ReturnGiftBatchCount++;

                    TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                     string.Format(Catalog.GetString("Batch {0}"), giftBatch.BatchNumber),
                                                     20);
                    GiftCounter = 0;

                    if (!FTransactionsOnly & !Summary)
                    {
                        WriteGiftBatchLine(giftBatch);
                    }

                    foreach (AGiftRow gift in FMainDS.AGift.Rows)
                    {
                        if (gift.BatchNumber.Equals(giftBatch.BatchNumber) && gift.LedgerNumber.Equals(giftBatch.LedgerNumber))
                        {
                            if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                            {
                                TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                                throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user"));
                            }

                            // Update progress tracker every 25 records
                            if (++GiftCounter % 25 == 0)
                            {
                                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                                 string.Format(Catalog.GetString("Batch {0} - Exporting gifts"), giftBatch.BatchNumber),
                                                                 (GiftCounter / 25 + 4) * 5 > 90 ? 90 : (GiftCounter / 25 + 4) * 5);
                            }

                            DataRowView[] selectedRowViews = FMainDS.AGiftDetail.DefaultView.FindRows(
                                new object[] { gift.LedgerNumber, gift.BatchNumber, gift.GiftTransactionNumber });

                            foreach (DataRowView rv in selectedRowViews)
                            {
                                AGiftDetailRow giftDetail = (AGiftDetailRow)rv.Row;

                                if (Summary)
                                {
                                    FCurrencyCode = FUseBaseCurrency ? BaseCurrency : giftBatch.CurrencyCode;
                                    decimal mapExchangeRateToBase = FUseBaseCurrency ? 1 : giftBatch.ExchangeRateToBase;


                                    counter++;
                                    String DictionaryKey = FCurrencyCode + ";" + giftBatch.BankCostCentre + ";" + giftBatch.BankAccountCode + ";" +
                                                           giftDetail.RecipientKey + ";" + giftDetail.MotivationGroupCode + ";" +
                                                           giftDetail.MotivationDetailCode;

                                    if (sdSummary.TryGetValue(DictionaryKey, out giftSummary))
                                    {
                                        giftSummary.GiftTransactionAmount += giftDetail.GiftTransactionAmount;
                                        giftSummary.GiftAmount            += giftDetail.GiftAmount;
                                    }
                                    else
                                    {
                                        giftSummary = new AGiftSummaryRow();

                                        /*
                                         * summary_data.a_transaction_currency_c = lv_stored_currency_c
                                         * summary_data.a_bank_cost_centre_c = a_gift_batch.a_bank_cost_centre_c
                                         * summary_data.a_bank_account_code_c = a_gift_batch.a_bank_account_code_c
                                         * summary_data.a_recipient_key_n = a_gift_detail.p_recipient_key_n
                                         * summary_data.a_motivation_group_code_c = a_gift_detail.a_motivation_group_code_c
                                         * summary_data.a_motivation_detail_code_c = a_gift_detail.a_motivation_detail_code_c
                                         * summary_data.a_exchange_rate_to_base_n = lv_exchange_rate_n
                                         * summary_data.a_gift_type_c = a_gift_batch.a_gift_type_c */
                                        giftSummary.CurrencyCode          = FCurrencyCode;
                                        giftSummary.BankCostCentre        = giftBatch.BankCostCentre;
                                        giftSummary.BankAccountCode       = giftBatch.BankAccountCode;
                                        giftSummary.RecipientKey          = giftDetail.RecipientKey;
                                        giftSummary.MotivationGroupCode   = giftDetail.MotivationGroupCode;
                                        giftSummary.MotivationDetailCode  = giftDetail.MotivationDetailCode;
                                        giftSummary.GiftTransactionAmount = giftDetail.GiftTransactionAmount;
                                        giftSummary.GiftAmount            = giftDetail.GiftAmount;

                                        sdSummary.Add(DictionaryKey, giftSummary);
                                    }

                                    //overwrite always because we want to have the last
                                    giftSummary.ExchangeRateToBase = mapExchangeRateToBase;
                                }
                                else  // not summary
                                {
                                    WriteGiftLine(gift, giftDetail);
                                }
                            }
                        }
                    }
                }

                if (Summary)
                {
                    TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                     Catalog.GetString("Export Summary"),
                                                     95);

                    bool first = true;

                    foreach (KeyValuePair <string, AGiftSummaryRow> kvp in sdSummary)
                    {
                        if (!FTransactionsOnly && first)
                        {
                            WriteGiftBatchSummaryLine(kvp.Value);
                            first = false;
                        }

                        WriteGiftSummaryLine(kvp.Value);
                    }
                }

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("Gift batch export successful"),
                                                 100);

                TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
            }
            catch (ApplicationException)
            {
                //Show cancel condition
                ReturnGiftBatchCount = -1;
                TProgressTracker.CancelJob(DomainManager.GClientID.ToString());
            }
            catch (Exception ex)
            {
                TLogging.Log(ex.ToString());

                //Show error condition
                ReturnGiftBatchCount = -2;

                FMessages.Add(new TVerificationResult(
                                  "Exporting Gift Batches Terminated Unexpectedly",
                                  ex.Message,
                                  "An unexpected error occurred during the export of gift batches",
                                  string.Empty,
                                  TResultSeverity.Resv_Critical,
                                  Guid.Empty));

                TProgressTracker.CancelJob(DomainManager.GClientID.ToString());
            }

            if (ReturnGiftBatchCount > 0)
            {
                AExportString = FStringWriter.ToString();
            }
            else
            {
                AExportString = string.Empty;
            }

            AVerificationMessages = FMessages;

            return(ReturnGiftBatchCount);
        }
示例#13
0
        /// <summary>
        /// This report considers gifts given between the two specified dates, and can include all gifts or, if
        /// selected, those to a particular motivation, motivation detail or recipient. For the defined set of gifts
        /// and its total value, the donors are sorted into a list, starting with those who gave most, and showing
        /// the percentage that their gifts contributed to the total received (for this motivation or recipient, if
        /// specified) and the cumulative percentage, moving down the list starting with the top donor.
        /// </summary>
        /// <param name="ATotalAmount">Pre calculated value of the total gifts given with these parameters</param>
        /// <param name="ATopXPercent">Upper limit of the percentage to show in the report</param>
        /// <param name="ABottomXPercent">Lower limit of the percentage to show in the report</param>
        /// <param name="AExtract">true to use only partners from an extract</param>
        /// <param name="AExtractName">extract name</param>
        /// <param name="AStartDate">Start date of the gifts given</param>
        /// <param name="AEndDate">End date of the gifts given</param>
        /// <param name="ARecipientKey">Partner key of a specific recipient. If 0 then use all recipients</param>
        /// <param name="AMotivationGroup">Limit gifts to this motivation group. If % use all motivation groups</param>
        /// <param name="AMotivationDetail">Limit gifts to this motivation detail. If % use all motivation details</param>
        /// <returns></returns>
        private bool MakeTopDonor(decimal ATotalAmount, decimal ATopXPercent, decimal ABottomXPercent,
                                  bool AExtract, String AExtractName, DateTime AStartDate, DateTime AEndDate,
                                  Int64 ARecipientKey, String AMotivationGroup, String AMotivationDetail)
        {
            Int64         LedgerNumber = situation.GetParameters().Get("param_ledger_number_i").ToInt64();
            String        CurrencyType = situation.GetParameters().Get("param_currency").ToString();
            StringBuilder SqlString    = new StringBuilder();

            SqlString.Append("SELECT DISTINCT ");
            SqlString.Append("gift.p_donor_key_n AS DonorKey, ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerShortNameDBName() + " AS ShortName, ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerClassDBName() + " AS PartnerClass, ");

            if (CurrencyType == "Base")
            {
                SqlString.Append("SUM(detail." + AGiftDetailTable.GetGiftAmountDBName() + ") AS Amount ");
            }
            else
            {
                SqlString.Append("SUM(detail." + AGiftDetailTable.GetGiftAmountIntlDBName() + ") AS Amount ");
            }

            SqlString.Append(
                " FROM " + AGiftTable.GetTableDBName() + " as gift, " + AGiftDetailTable.GetTableDBName() + " as detail, " +
                PPartnerTable.GetTableDBName() + ", " + AGiftBatchTable.GetTableDBName() + " ");

            if (AExtract)
            {
                SqlString.Append(", " + MExtractTable.GetTableDBName() + ", " + MExtractMasterTable.GetTableDBName());
                SqlString.Append(
                    " WHERE gift." + AGiftTable.GetDonorKeyDBName() + " = " + MExtractTable.GetTableDBName() + "." +
                    MExtractTable.GetPartnerKeyDBName());
                SqlString.Append(
                    " AND " + MExtractTable.GetTableDBName() + "." + MExtractTable.GetExtractIdDBName() + " = " +
                    MExtractMasterTable.GetTableDBName() +
                    "." + MExtractMasterTable.GetExtractIdDBName());
                SqlString.Append(" AND " + MExtractMasterTable.GetTableDBName() + "." + MExtractMasterTable.GetExtractNameDBName() + " = '");
                SqlString.Append(AExtractName);
                SqlString.Append("' AND ");
            }
            else
            {
                SqlString.Append(" WHERE ");
            }

            SqlString.Append(" detail." + AGiftDetailTable.GetLedgerNumberDBName() + " = gift." + AGiftTable.GetLedgerNumberDBName());
            SqlString.Append(" AND detail." + AGiftDetailTable.GetBatchNumberDBName() + " = gift." + AGiftTable.GetBatchNumberDBName());
            SqlString.Append(
                " AND detail." + AGiftDetailTable.GetGiftTransactionNumberDBName() + " = gift." + AGiftTable.GetGiftTransactionNumberDBName());
            SqlString.Append(" AND gift." + AGiftTable.GetDateEnteredDBName() + " BETWEEN '");
            SqlString.Append(AStartDate.ToString("yyyy-MM-dd"));
            SqlString.Append("' AND '");
            SqlString.Append(AEndDate.ToString("yyyy-MM-dd"));
            SqlString.Append("' AND gift." + AGiftTable.GetLedgerNumberDBName() + " = ");
            SqlString.Append(LedgerNumber.ToString());
            SqlString.Append(" AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetLedgerNumberDBName() + " = ");
            SqlString.Append(LedgerNumber.ToString());
            SqlString.Append(
                " AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchNumberDBName() + " = gift." +
                AGiftTable.GetBatchNumberDBName());
            SqlString.Append(" AND ( " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchStatusDBName() + " = 'Posted' OR ");
            SqlString.Append(AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchStatusDBName() + " = 'posted' ) ");
            SqlString.Append(
                " AND " + PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = gift." + AGiftTable.GetDonorKeyDBName());

            if (ARecipientKey != 0)
            {
                SqlString.Append(" AND detail." + AGiftDetailTable.GetRecipientKeyDBName() + " = ");
                SqlString.Append(ARecipientKey.ToString());
            }

            if (AMotivationGroup != "%")
            {
                SqlString.Append(" AND  detail." + AGiftDetailTable.GetMotivationGroupCodeDBName() + " LIKE '");
                SqlString.Append(AMotivationGroup);
                SqlString.Append("' ");
            }

            if (AMotivationDetail != "%")
            {
                SqlString.Append(" AND  detail." + AGiftDetailTable.GetMotivationDetailCodeDBName() + " LIKE '");
                SqlString.Append(AMotivationDetail);
                SqlString.Append("' ");
            }

            SqlString.Append(" GROUP BY gift." + AGiftTable.GetDonorKeyDBName() + ", ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerShortNameDBName() + ", ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerClassDBName());
            SqlString.Append(" ORDER BY Amount DESC");

            DataTable Table = situation.GetDatabaseConnection().SelectDT(SqlString.ToString(), "table",
                                                                         situation.GetDatabaseConnection().Transaction, new OdbcParameter[] { });

            decimal CummulativeAmount = 0;
            decimal TopAmount         = ATotalAmount * ATopXPercent / 100;
            decimal BottomAmount      = ATotalAmount * ABottomXPercent / 100;

            int NumColumns = 7;
            int ChildRow   = 1;

            situation.GetResults().Clear();

            for (int Counter = 0; Counter < Table.Rows.Count; ++Counter)
            {
                decimal CurrentAmount = Convert.ToDecimal(Table.Rows[Counter]["Amount"]);

                if (CurrentAmount < 0)
                {
                    continue;
                }

                if ((CummulativeAmount <= TopAmount) &&
                    (CummulativeAmount >= BottomAmount))
                {
                    Int64  DonorKey     = Convert.ToInt64(Table.Rows[Counter]["DonorKey"]);
                    String ShortName    = (String)Table.Rows[Counter]["ShortName"];
                    String PartnerClass = (String)Table.Rows[Counter]["PartnerClass"];

                    CummulativeAmount += CurrentAmount;

                    // Transfer to results
                    TVariant[] Header      = new TVariant[NumColumns];
                    TVariant[] Description =
                    {
                        new TVariant(), new TVariant()
                    };
                    TVariant[] Columns = new TVariant[NumColumns];

                    for (int Counter2 = 0; Counter2 < NumColumns; ++Counter2)
                    {
                        Header[Counter2]  = new TVariant();
                        Columns[Counter2] = new TVariant();
                    }

                    StringBuilder       PartnerAddress = new StringBuilder();
                    PPartnerLocationRow AddressRow;

                    if (Ict.Petra.Server.MReporting.MPartner.TRptUserFunctionsPartner.GetPartnerBestAddressRow(DonorKey, situation, out AddressRow))
                    {
                        PLocationTable LocationTable = PLocationAccess.LoadByPrimaryKey(AddressRow.SiteKey,
                                                                                        AddressRow.LocationKey, situation.GetDatabaseConnection().Transaction);

                        if (LocationTable.Rows.Count > 0)
                        {
                            PLocationRow LocationRow = (PLocationRow)LocationTable.Rows[0];

                            PartnerAddress.Append(LocationRow.Locality);

                            if (LocationRow.Locality.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                            }

                            PartnerAddress.Append(LocationRow.StreetName);

                            if (PartnerAddress.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                            }

                            PartnerAddress.Append(LocationRow.Address3);

                            if (PartnerAddress.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                            }

                            PartnerAddress.Append(LocationRow.PostalCode);
                            PartnerAddress.Append(" ");
                            PartnerAddress.Append(LocationRow.City);

                            if (LocationRow.County.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                                PartnerAddress.Append(LocationRow.County);
                            }

                            PartnerAddress.Append(", ");
                            PartnerAddress.Append(LocationRow.CountryCode);
                        }
                    }

                    Columns[0] = new TVariant(DonorKey.ToString("0000000000"));
                    Columns[1] = new TVariant(PartnerClass);
                    Columns[2] = new TVariant(ShortName);
                    Columns[3] = new TVariant(CurrentAmount, "-#,##0.00;#,##0.00");
                    Columns[4] = new TVariant((CurrentAmount * 100 / ATotalAmount), "-#,##0.00;#,##0.00");
                    Columns[5] = new TVariant((CummulativeAmount * 100 / ATotalAmount), "-#,##0.00;#,##0.00");
                    Columns[6] = new TVariant(PartnerAddress.ToString());

                    situation.GetResults().AddRow(0, ChildRow++, true, 2, "", "", false,
                                                  Header, Description, Columns);
                }
                else
                {
                    CummulativeAmount += CurrentAmount;
                }
            }

            return(true);
        }
示例#14
0
        /// <summary>
        /// Used internally to build a SQL WHERE criteria from the AFindCriteria HashTable.
        ///
        /// </summary>
        /// <param name="ACriteriaData">HashTable containing non-empty Partner Find parameters</param>
        /// <param name="AParametersArray">An array holding 1..n instantiated OdbcParameters
        /// (including parameter Value)</param>
        /// <returns>SQL WHERE criteria
        /// </returns>
        private static String BuildCustomWhereCriteria(DataTable ACriteriaData, out OdbcParameter[] AParametersArray)
        {
            String    CustomWhereCriteria = "";
            DataTable CriteriaDataTable;
            DataRow   CriteriaRow;
            ArrayList InternalParameters;

            CriteriaDataTable  = ACriteriaData;
            CriteriaRow        = CriteriaDataTable.Rows[0];
            InternalParameters = new ArrayList();

            if (CriteriaRow["Ledger"].ToString().Length > 0)
            {
                // Searched DB Field: 'a_ledger_number_i'
                new TDynamicSearchHelper(AGiftDetailTable.TableId,
                                         AGiftDetailTable.ColumnLedgerNumberId, CriteriaRow, "Ledger", "",
                                         ref CustomWhereCriteria, ref InternalParameters);
            }

            // Searched DB Field: 'a_batch_number_i'
            if ((CriteriaRow["Batch"] != null) && (CriteriaRow["Batch"] != System.DBNull.Value))
            {
                // do manually otherwise 0 gets changed to a string and we get a crash
                CustomWhereCriteria = String.Format("{0} AND {1} = ?", CustomWhereCriteria,
                                                    "PUB_" + TTypedDataTable.GetTableNameSQL(AGiftDetailTable.TableId) + "." + AGiftDetailTable.GetBatchNumberDBName());
                OdbcParameter miParam = new OdbcParameter("", OdbcType.Int, 10);
                miParam.Value = (object)(CriteriaRow["Batch"]);
                InternalParameters.Add(miParam);
            }

            // Searched DB Field: 'a_gift_transaction_number_i'
            if ((CriteriaRow["Transaction"] != null) && (CriteriaRow["Transaction"] != System.DBNull.Value))
            {
                // do manually otherwise 0 gets changed to a string and we get a crash
                CustomWhereCriteria = String.Format("{0} AND {1} = ?", CustomWhereCriteria,
                                                    "PUB_" + TTypedDataTable.GetTableNameSQL(AGiftDetailTable.TableId) + "." + AGiftDetailTable.GetGiftTransactionNumberDBName());
                OdbcParameter miParam = new OdbcParameter("", OdbcType.Int, 10);
                miParam.Value = (object)(CriteriaRow["Transaction"]);
                InternalParameters.Add(miParam);
            }

            // Searched DB Field: 'a_receipt_number_i'
            if ((CriteriaRow["Receipt"] != null) && (CriteriaRow["Receipt"] != System.DBNull.Value))
            {
                // do manually otherwise 0 gets changed to a string and we get a crash
                CustomWhereCriteria = String.Format("{0} AND {1} = ?", CustomWhereCriteria,
                                                    "PUB_" + TTypedDataTable.GetTableNameSQL(AGiftTable.TableId) + "." + AGiftTable.GetReceiptNumberDBName());
                OdbcParameter miParam = new OdbcParameter("", OdbcType.Int, 10);
                miParam.Value = (object)(CriteriaRow["Receipt"]);
                InternalParameters.Add(miParam);
            }

            // Searched DB Field: 'a_motivation_group_code_c'
            if (CriteriaRow["MotivationGroup"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(AGiftDetailTable.TableId,
                                         AGiftDetailTable.ColumnMotivationGroupCodeId, CriteriaRow, "MotivationGroup", "",
                                         ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            // Searched DB Field: 'a_motivation_detail_code_c'
            if (CriteriaRow["MotivationDetail"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(AGiftDetailTable.TableId,
                                         AGiftDetailTable.ColumnMotivationDetailCodeId, CriteriaRow, "MotivationDetail", "",
                                         ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            // Searched DB Field: 'a_gift_comment_one_c'
            if (CriteriaRow["Comment1"].ToString().Length > 0)
            {
                CriteriaRow.Table.Columns.Add(new DataColumn("Comment1Match"));
                CriteriaRow["Comment1Match"] = "CONTAINS";

                new TDynamicSearchHelper(AGiftDetailTable.TableId,
                                         AGiftDetailTable.ColumnGiftCommentOneId, CriteriaRow, "Comment1", "Comment1Match",
                                         ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            // Searched DB Field: 'p_donor_key_n'
            if (((Int64)CriteriaRow["Donor"]) > 0)
            {
                new TDynamicSearchHelper(AGiftTable.TableId,
                                         AGiftTable.ColumnDonorKeyId, CriteriaRow, "Donor", "",
                                         ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            // Searched DB Field: 'p_recipient_key_n'
            if (((Int64)CriteriaRow["Recipient"]) > 0)
            {
                new TDynamicSearchHelper(AGiftDetailTable.TableId,
                                         AGiftDetailTable.ColumnRecipientKeyId, CriteriaRow, "Recipient", "",
                                         ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            // Searched DB Field: 'a_date_entered_d'
            if ((CriteriaRow["From"] != System.DBNull.Value) && (CriteriaRow["To"] != System.DBNull.Value) &&
                (CriteriaRow["From"] == CriteriaRow["To"]))
            {
                CustomWhereCriteria = String.Format("{0} AND {1} = ?", CustomWhereCriteria,
                                                    AGiftTable.GetDateEnteredDBName());
                OdbcParameter miParam = new OdbcParameter("", OdbcType.DateTime, 10);
                miParam.Value = (object)(CriteriaRow["From"]);
                InternalParameters.Add(miParam);
            }
            else
            {
                if (CriteriaRow["From"] != System.DBNull.Value)
                {
                    CustomWhereCriteria = String.Format("{0} AND {1} >= ?", CustomWhereCriteria,
                                                        AGiftTable.GetDateEnteredDBName());
                    OdbcParameter miParam = new OdbcParameter("", OdbcType.DateTime, 10);
                    miParam.Value = (object)(CriteriaRow["From"]);
                    InternalParameters.Add(miParam);
                }

                if (CriteriaRow["To"] != System.DBNull.Value)
                {
                    CustomWhereCriteria = String.Format("{0} AND {1} <= ?", CustomWhereCriteria,
                                                        AGiftTable.GetDateEnteredDBName());
                    OdbcParameter miParam = new OdbcParameter("", OdbcType.DateTime, 10);
                    miParam.Value = (object)(CriteriaRow["To"]);
                    InternalParameters.Add(miParam);
                }
            }

            // Searched DB Field: 'a_gift_amount_n'
            if ((CriteriaRow["MinAmount"].ToString().Length > 0) && (CriteriaRow["MaxAmount"].ToString().Length > 0) &&
                (CriteriaRow["MinAmount"] == CriteriaRow["MaxAmount"]))
            {
                CustomWhereCriteria = String.Format("{0} AND {1} = ?", CustomWhereCriteria,
                                                    AGiftDetailTable.GetGiftAmountDBName());
                OdbcParameter miParam = new OdbcParameter("", OdbcType.Int, 10);
                miParam.Value = (object)(CriteriaRow["MinAmount"]);
                InternalParameters.Add(miParam);
            }
            else
            {
                if (CriteriaRow["MinAmount"].ToString().Length > 0)
                {
                    CustomWhereCriteria = String.Format("{0} AND {1} >= ?", CustomWhereCriteria,
                                                        AGiftDetailTable.GetGiftAmountDBName());
                    OdbcParameter miParam = new OdbcParameter("", OdbcType.Int, 10);
                    miParam.Value = (object)(CriteriaRow["MinAmount"]);
                    InternalParameters.Add(miParam);
                }

                if (CriteriaRow["MaxAmount"].ToString().Length > 0)
                {
                    CustomWhereCriteria = String.Format("{0} AND {1} <= ?", CustomWhereCriteria,
                                                        AGiftDetailTable.GetGiftAmountDBName());
                    OdbcParameter miParam = new OdbcParameter("", OdbcType.Int, 10);
                    miParam.Value = (object)(CriteriaRow["MaxAmount"]);
                    InternalParameters.Add(miParam);
                }
            }

//           TLogging.LogAtLevel(7, "CustomWhereCriteria: " + CustomWhereCriteria);

            /* Convert ArrayList to a array of ODBCParameters
             * seem to need to declare a type first
             */
            AParametersArray   = ((OdbcParameter[])(InternalParameters.ToArray(typeof(OdbcParameter))));
            InternalParameters = null;             // ensure this is GC'd

            return(CustomWhereCriteria);
        }
示例#15
0
        public static void MarkReceiptsPrinted(int ALedgerNumber, DataTable AGiftTbl)
        {
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);
            AGiftTable Tbl = new AGiftTable();

            foreach (DataRow Row in AGiftTbl.Rows)
            {
                Tbl.Merge(AGiftAccess.LoadByPrimaryKey(
                        ALedgerNumber,
                        Convert.ToInt32(Row["BatchNumber"]),
                        Convert.ToInt32(Row["TransactionNumber"]),
                        Transaction));
            }

            foreach (AGiftRow Row in Tbl.Rows)
            {
                Row.ReceiptPrinted = true;
            }

            try
            {
                AGiftAccess.SubmitChanges(Tbl, Transaction);

                DBAccess.GDBAccessObj.CommitTransaction();
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured while marking Receipts as printed:" + Environment.NewLine + Exc.ToString());

                DBAccess.GDBAccessObj.RollbackTransaction();

                throw;
            }
        }
        /// <summary>
        /// update the transaction DateEntered from outside
        /// </summary>
        /// <param name="ABatchRow"></param>
        public void UpdateDateEntered(AGiftBatchRow ABatchRow)
        {
            Int32    ledgerNumber;
            Int32    batchNumber;
            DateTime batchEffectiveDate;

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

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

            DataView giftDataView = new DataView(FMainDS.AGift);

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

            DataView giftDetailDataView = new DataView(FMainDS.AGiftDetail);

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

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

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

            TFrmGiftBatch ParentGiftBatchForm = (TFrmGiftBatch)ParentForm;

            ParentGiftBatchForm.Cursor = Cursors.WaitCursor;

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

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

            ParentGiftBatchForm.Cursor = Cursors.Default;

            //If current row exists then refresh details
            if (FGLEffectivePeriodHasChangedFlag)
            {
                ShowDetails();
            }
        }
示例#17
0
        /// <summary>
        /// there are several gift batches that might fit this bank statement. find the right one!
        /// simple matching; no split gifts, bank account number fits and amount fits
        /// </summary>
        private static int FindGiftBatch(BankImportTDS AMainDS, AEpStatementRow AStmt)
        {
            SortedList <Int32, Int32> MatchedGiftBatches = new SortedList <int, int>();

            // create the dataview only after loading, otherwise loading is much slower
            DataView GiftDetailByAmountAndDonor = new DataView(AMainDS.AGiftDetail,
                                                               string.Empty,
                                                               AGiftDetailTable.GetGiftAmountDBName() + "," +
                                                               BankImportTDSAGiftDetailTable.GetDonorKeyDBName(),
                                                               DataViewRowState.CurrentRows);

            DataView GiftByAmountAndDonor = new DataView(AMainDS.AGift,
                                                         string.Empty,
                                                         BankImportTDSAGiftTable.GetTotalAmountDBName() + "," +
                                                         AGiftTable.GetDonorKeyDBName(),
                                                         DataViewRowState.CurrentRows);

            AMainDS.PBankingDetails.DefaultView.Sort = BankImportTDSPBankingDetailsTable.GetBankSortCodeDBName() + "," +
                                                       BankImportTDSPBankingDetailsTable.GetBankAccountNumberDBName();

            foreach (BankImportTDSAEpTransactionRow transaction in AMainDS.AEpTransaction.Rows)
            {
                // find the donor for this transaction, by his bank account number
                Int64 DonorKey = GetDonorByBankAccountNumber(AMainDS, transaction.BranchCode, transaction.BankAccountNumber);

                if (transaction.BankAccountNumber.Length == 0)
                {
                    // useful for NUnit testing for csv import: partnerkey in description
                    try
                    {
                        DonorKey = Convert.ToInt64(transaction.Description);
                    }
                    catch (Exception)
                    {
                        DonorKey = -1;
                    }
                }

                BankImportTDSAGiftDetailRow detailrow = null;

                if (DonorKey != -1)
                {
                    DataRowView[] giftDetails = GiftDetailByAmountAndDonor.FindRows(new object[] { transaction.TransactionAmount, DonorKey });

                    if (giftDetails.Length == 1)
                    {
                        // found a possible match
                        detailrow = (BankImportTDSAGiftDetailRow)giftDetails[0].Row;
                    }
                    else
                    {
                        // check if we can find a gift with several gift details, that would match this transaction amount
                        DataRowView[] gifts = GiftByAmountAndDonor.FindRows(new object[] { transaction.TransactionAmount, DonorKey });

                        if (gifts.Length >= 1)
                        {
                            AGiftRow gift = (AGiftRow)gifts[0].Row;
                            detailrow =
                                (BankImportTDSAGiftDetailRow)AMainDS.AGiftDetail.Rows.Find(new object[] { gift.LedgerNumber, gift.BatchNumber,
                                                                                                          gift.GiftTransactionNumber,
                                                                                                          1 });
                        }
                    }
                }

                if (detailrow != null)
                {
                    if (MatchedGiftBatches.ContainsKey(detailrow.BatchNumber))
                    {
                        MatchedGiftBatches[detailrow.BatchNumber]++;
                    }
                    else
                    {
                        MatchedGiftBatches.Add(detailrow.BatchNumber, 1);
                    }
                }
            }

            int SelectedGiftBatch = -1;
            int maxMatches        = 0;

            foreach (int GiftBatchNumber in MatchedGiftBatches.Keys)
            {
                if (MatchedGiftBatches[GiftBatchNumber] > maxMatches)
                {
                    maxMatches        = MatchedGiftBatches[GiftBatchNumber];
                    SelectedGiftBatch = GiftBatchNumber;
                }
            }

            if ((SelectedGiftBatch != -1) &&
                ((AMainDS.AEpTransaction.Rows.Count > 2) &&
                 (MatchedGiftBatches[SelectedGiftBatch] < AMainDS.AEpTransaction.Rows.Count / 2)))
            {
                TLogging.Log(
                    "cannot find enough gifts that look the same, for statement " + AStmt.Filename +
                    ". CountMatches for batch " + SelectedGiftBatch.ToString() + ": " +
                    MatchedGiftBatches[SelectedGiftBatch].ToString());

                SelectedGiftBatch = -1;
            }

            return(SelectedGiftBatch);
        }
示例#18
0
        private bool OnDeleteRowManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ACompletionMessage)
        {
            bool DeletionSuccessful = false;

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

            ACompletionMessage = string.Empty;

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

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

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

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

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

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

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

            BackupMainDS.Merge(FMainDS);

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

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

            int DetailRowCount = FGiftDetailView.Count;

            try
            {
                this.Cursor = Cursors.WaitCursor;

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

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

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

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

                    FGiftSelectedForDeletion = false;

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

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

                    FGift.LastDetailNumber--;

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

                    GiftToDeleteTransNo = FGift.GiftTransactionNumber;

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

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

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

                        row.GiftTransactionNumber--;
                    }

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

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

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

                    int currentGiftTransNo = 0;

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

                        currentGiftTransNo = giftRowCurrent.GiftTransactionNumber;

                        if (currentGiftTransNo > GiftToDeleteTransNo)
                        {
                            giftRowToCopyDown = giftRowCurrent;

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

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

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

                    FPreviouslySelectedDetailRow = null;

                    FPetraUtilsObject.SetChangedFlag();

                    FGiftSelectedForDeletion = true;

                    FBatchRow.LastGiftNumber--;
                }

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

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

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

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

            UpdateRecordNumberDisplay();

            return(DeletionSuccessful);
        }
示例#19
0
        private bool OnDeleteRowManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ACompletionMessage)
        {
            bool   deletionSuccessful   = false;
            string originatingDetailRef = string.Empty;

            ACompletionMessage = string.Empty;

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

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

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

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

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

            FTempDS.Merge(FMainDS);

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

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

            int detailRowCount = FGiftDetailView.Count;

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

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

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

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

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

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

                    FGift.LastDetailNumber--;

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

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

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

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

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

                        row.GiftTransactionNumber--;
                    }

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

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

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

                    int currentGiftTransNo = 0;

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

                        currentGiftTransNo = giftRowCurrent.GiftTransactionNumber;

                        if (currentGiftTransNo > giftToDeleteTransNo)
                        {
                            giftRowToCopyDown = giftRowCurrent;

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

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

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

                    FPreviouslySelectedDetailRow = null;

                    FPetraUtilsObject.SetChangedFlag();

                    FGiftSelectedForDeletion = true;

                    FBatchRow.LastGiftNumber--;
                }

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

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

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

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

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

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

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

            UpdateRecordNumberDisplay();

            return(deletionSuccessful);
        }
示例#20
0
        public static string PrintGiftReceipt(
            String AGiftCurrency,
            String ADonorShortName,
            Int64 ADonorKey,
            TPartnerClass ADonorClass,
            AGiftTable GiftsThisDonor,
            string AHTMLTemplateFilename
            )
        {
            string HtmlDoc = string.Empty;

            TDBTransaction Transaction = null;

            try
            {
                DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                    ref Transaction,
                    delegate
                    {
                        string LocalCountryCode = TAddressTools.GetCountryCodeFromSiteLedger(Transaction);
                        HtmlDoc = FormatHtmlReceipt(
                            ADonorShortName,
                            ADonorKey,
                            ADonorClass,
                            AGiftCurrency,
                            LocalCountryCode,
                            GiftsThisDonor,
                            AHTMLTemplateFilename,
                            Transaction);
                    });
            }
            catch (Exception ex)
            {
                TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}",
                        Utilities.GetMethodSignature(),
                        Environment.NewLine,
                        ex.Message));
                throw ex;
            }

            return HtmlDoc;
        }
        /// <summary>
        /// Main method to post a specified batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch row to post</param>
        /// <param name="ARefreshGUIAfterPosting">Will be set to true if the GUI should be updated.  Can be true even if Posting fails
        /// <param name="AWarnOfInactiveValues">True means user is warned if inactive values exist</param>
        /// <param name="ADonorZeroIsValid"></param>
        /// <param name="ARecipientZeroIsValid"></param>
        /// <param name="APostingAlreadyConfirmed">True means ask user if they want to post</param>
        /// if the server gets a SerializableTransactionException</param>
        /// <returns>True if the batch was successfully posted</returns>
        public bool PostBatch(AGiftBatchRow ACurrentBatchRow,
                              out bool ARefreshGUIAfterPosting,
                              bool AWarnOfInactiveValues    = true,
                              bool ADonorZeroIsValid        = false,
                              bool ARecipientZeroIsValid    = false,
                              bool APostingAlreadyConfirmed = false)
        {
            ARefreshGUIAfterPosting = false;

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

            FSelectedBatchNumber = ACurrentBatchRow.BatchNumber;

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

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

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

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

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

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

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

                return(false);
            }

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

            FMyForm.WarnAboutMissingIntlExchangeRate = true;

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

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

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

                int numDonorZeros = batchGiftDV.Count;

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

                    string listOfOffendingRows = string.Empty;

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

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

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

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

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

                    return(false);
                }
            }

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

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

                int numRecipientZeros = batchGiftDetailsDV.Count;

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

                    string listOfOffendingRows = string.Empty;

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

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

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

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

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

                    return(false);
                }
            }

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

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

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

                string listOfOffendingRows = string.Empty;

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

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

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

                    if (isModified)
                    {
                        ModifiedDetails = true;
                    }
                }

                TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

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

                    return(false);
                }
            }

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

            TVerificationResultCollection Verifications = new TVerificationResultCollection();

            try
            {
                FPostingInProgress = true;

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

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

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

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

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

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

            return(true);
        }
示例#22
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>
        /// Print a receipt for each gift (one page for each donor) in the batch
        /// </summary>
        /// <param name="AGiftTDS"></param>
        public void PrintGiftBatchReceipts(GiftBatchTDS AGiftTDS)
        {
            AGiftBatchRow GiftBatchRow = AGiftTDS.AGiftBatch[0];

            DataView GiftView = new DataView(AGiftTDS.AGift);

            //AGiftTDS.AGift.DefaultView.RowFilter
            GiftView.RowFilter = String.Format("{0}={1} and {2}={3}",
                                               AGiftTable.GetLedgerNumberDBName(), GiftBatchRow.LedgerNumber,
                                               AGiftTable.GetBatchNumberDBName(), GiftBatchRow.BatchNumber);
            String       ReceiptedDonorsList             = "";
            List <Int32> ReceiptedGiftTransactions       = new List <Int32>();
            SortedList <Int64, AGiftTable> GiftsPerDonor = new SortedList <Int64, AGiftTable>();

            foreach (DataRowView rv in GiftView)
            {
                AGiftRow GiftRow = (AGiftRow)rv.Row;
                bool     ReceiptEachGift;
                String   ReceiptLetterFrequency;
                bool     EmailGiftStatement;
                bool     AnonymousDonor;

                TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetPartnerReceiptingInfo(
                    GiftRow.DonorKey,
                    out ReceiptEachGift,
                    out ReceiptLetterFrequency,
                    out EmailGiftStatement,
                    out AnonymousDonor);

                if (ReceiptEachGift)
                {
                    // I want to print a receipt for this gift,
                    // but if there's already one queued for this donor,
                    // I'll add this gift onto the existing receipt.

                    if (!GiftsPerDonor.ContainsKey(GiftRow.DonorKey))
                    {
                        GiftsPerDonor.Add(GiftRow.DonorKey, new AGiftTable());
                    }

                    AGiftRow NewRow = GiftsPerDonor[GiftRow.DonorKey].NewRowTyped();
                    DataUtilities.CopyAllColumnValues(GiftRow, NewRow);
                    GiftsPerDonor[GiftRow.DonorKey].Rows.Add(NewRow);
                } // if receipt required
            }     // foreach gift

            String HtmlDoc = "";

            OpenFileDialog DialogOpen = new OpenFileDialog();

            if (Directory.Exists(TAppSettingsManager.GetValue("Formletters.Path")))
            {
                DialogOpen.InitialDirectory = TAppSettingsManager.GetValue("Formletters.Path");
            }

            DialogOpen.Filter           = Catalog.GetString("HTML file (*.html)|*.html;*.htm");
            DialogOpen.RestoreDirectory = true;
            DialogOpen.Title            = Catalog.GetString("Select the template for the gift receipt");

            if (DialogOpen.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            string HTMLTemplateFilename = DialogOpen.FileName;

            foreach (Int64 DonorKey in GiftsPerDonor.Keys)
            {
                String        DonorShortName;
                TPartnerClass DonorClass;
                TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetPartnerShortName(DonorKey, out DonorShortName, out DonorClass);
                DonorShortName = Calculations.FormatShortName(DonorShortName, eShortNameFormat.eReverseShortname);

                string HtmlPage = TRemote.MFinance.Gift.WebConnectors.PrintGiftReceipt(
                    GiftBatchRow.CurrencyCode,
                    DonorShortName,
                    DonorKey,
                    DonorClass,
                    GiftsPerDonor[DonorKey],
                    HTMLTemplateFilename
                    );

                TFormLettersTools.AttachNextPage(ref HtmlDoc, HtmlPage);
                ReceiptedDonorsList += (DonorShortName + "\r\n");

                foreach (AGiftRow GiftRow in GiftsPerDonor[DonorKey].Rows)
                {
                    ReceiptedGiftTransactions.Add(GiftRow.GiftTransactionNumber);
                }
            }

            TFormLettersTools.CloseDocument(ref HtmlDoc);

            if (ReceiptedGiftTransactions.Count > 0)
            {
                TFrmReceiptControl.PreviewOrPrint(HtmlDoc);

                if (MessageBox.Show(
                        Catalog.GetString(
                            "Press OK if receipts to these recipients were printed correctly.\r\nThe gifts will be marked as receipted.\r\n") +
                        ReceiptedDonorsList,

                        Catalog.GetString("Receipt Printing"),
                        MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    foreach (Int32 Trans in ReceiptedGiftTransactions)
                    {
                        TRemote.MFinance.Gift.WebConnectors.MarkReceiptsPrinted(
                            GiftBatchRow.LedgerNumber,
                            GiftBatchRow.BatchNumber,
                            Trans);
                    }
                }
            }
        }
        /// <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);
        }
        /// <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;
            }
        }
示例#26
0
        /// <summary>
        /// export all posted invoices for conference and seminar participants in this year
        /// </summary>
        public static void Export(string AOutputPath,
                                  char ACSVSeparator,
                                  string ANewLine,
                                  Int32 ALedgerNumber,
                                  Int32 AFinancialYear,
                                  string ACostCentres)
        {
            string filename = Path.GetFullPath(Path.Combine(AOutputPath, "participants.csv"));

            Console.WriteLine("Writing file: " + filename);

            TDBTransaction   Transaction = new TDBTransaction();
            AGiftDetailTable giftdetails = new AGiftDetailTable();
            AGiftTable       gifts       = new AGiftTable();
            AGiftBatchTable  batches     = new AGiftBatchTable();
            PPersonTable     persons     = new PPersonTable();

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

                // all gift details towards a costcentre that needs to be exported
                string sql =
                    String.Format("SELECT DISTINCT D.* " +
                                  "FROM PUB_{0} AS B, PUB_{1} AS G, PUB_{2} AS D " +
                                  "WHERE B.{3} = {4} AND B.{5} = {6} AND B.{7}='{8}' " +
                                  "AND G.{3} = B.{3} AND G.{9} = B.{9} " +
                                  "AND D.{3} = G.{3} AND D.{9} = G.{9} AND D.{10} = G.{10} " +
                                  "AND D.{11} IN ({12}) " +
                                  "AND NOT D.{13} = '{14}'",
                                  AGiftBatchTable.GetTableDBName(),
                                  AGiftTable.GetTableDBName(),
                                  AGiftDetailTable.GetTableDBName(),
                                  AGiftBatchTable.GetLedgerNumberDBName(),
                                  ALedgerNumber,
                                  AGiftBatchTable.GetBatchYearDBName(),
                                  AFinancialYear,
                                  AGiftBatchTable.GetBatchStatusDBName(),
                                  MFinanceConstants.BATCH_POSTED,
                                  AGiftBatchTable.GetBatchNumberDBName(),
                                  AGiftTable.GetGiftTransactionNumberDBName(),
                                  AGiftDetailTable.GetCostCentreCodeDBName(),
                                  "'" + ACostCentres.Replace(",", "','") + "'",
                                  AGiftDetailTable.GetMotivationGroupCodeDBName(),
                                  "GIFT");

                db.SelectDT(giftdetails, sql, Transaction, null, 0, 0);

                sql = sql.Replace("SELECT DISTINCT D.*", "SELECT DISTINCT G.*");

                db.SelectDT(gifts, sql, Transaction, null, 0, 0);

                gifts.DefaultView.Sort =
                    AGiftTable.GetBatchNumberDBName() + "," +
                    AGiftTable.GetGiftTransactionNumberDBName();

                sql = sql.Replace("SELECT DISTINCT G.*", "SELECT DISTINCT B.*");

                db.SelectDT(batches, sql, Transaction, null, 0, 0);
                batches.DefaultView.Sort = AGiftTable.GetBatchNumberDBName();

                sql =
                    String.Format("SELECT DISTINCT P.* " +
                                  "FROM PUB_{0} AS B, PUB_{1} AS G, PUB_{2} AS D, PUB.{15} AS P " +
                                  "WHERE B.{3} = {4} AND B.{5} = {6} AND B.{7}='{8}' " +
                                  "AND G.{3} = B.{3} AND G.{9} = B.{9} " +
                                  "AND D.{3} = G.{3} AND D.{9} = G.{9} AND D.{10} = G.{10} " +
                                  "AND D.{11} IN ({12}) " +
                                  "AND NOT D.{13} = '{14}' " +
                                  "AND P.{16} = G.{17}",
                                  AGiftBatchTable.GetTableDBName(),
                                  AGiftTable.GetTableDBName(),
                                  AGiftDetailTable.GetTableDBName(),
                                  AGiftBatchTable.GetLedgerNumberDBName(),
                                  ALedgerNumber,
                                  AGiftBatchTable.GetBatchYearDBName(),
                                  AFinancialYear,
                                  AGiftBatchTable.GetBatchStatusDBName(),
                                  MFinanceConstants.BATCH_POSTED,
                                  AGiftBatchTable.GetBatchNumberDBName(),
                                  AGiftTable.GetGiftTransactionNumberDBName(),
                                  AGiftDetailTable.GetCostCentreCodeDBName(),
                                  "'" + ACostCentres.Replace(",", "','") + "'",
                                  AGiftDetailTable.GetMotivationGroupCodeDBName(),
                                  "GIFT",
                                  PPersonTable.GetTableDBName(),
                                  PPersonTable.GetPartnerKeyDBName(),
                                  AGiftTable.GetDonorKeyDBName());

                db.SelectDT(persons, sql, Transaction, null, 0, 0);
                persons.DefaultView.Sort = PPersonTable.GetPartnerKeyDBName();
            });

            StringBuilder sb = new StringBuilder();

            foreach (AGiftDetailRow detail in giftdetails.Rows)
            {
                AGiftRow      gift  = (AGiftRow)gifts.DefaultView.FindRows(new object[] { detail.BatchNumber, detail.GiftTransactionNumber })[0].Row;
                AGiftBatchRow batch = (AGiftBatchRow)batches.DefaultView.FindRows(detail.BatchNumber)[0].Row;

                DataRowView[] personList = persons.DefaultView.FindRows(gift.DonorKey);
                PPersonRow    person     = (personList.Length > 0 ? (PPersonRow)personList[0].Row : null);

                sb.Append(StringHelper.StrMerge(
                              new string[] {
                    "GB" + detail.BatchNumber.ToString() + "_G" + detail.GiftTransactionNumber.ToString() +
                    "_D" + detail.DetailNumber.ToString(),
                    String.Format("{0:N}", detail.GiftTransactionAmount),
                    batch.GlEffectiveDate.ToString("yyyyMMdd"),
                    gift.DonorKey.ToString(),
                    person !=
                    null ? (person.DateOfBirth.HasValue ? person.DateOfBirth.Value.ToString("yyyyMMdd") : string.Empty) : string.Empty,
                    detail.CostCentreCode,
                    batch.BatchDescription,
                    detail.GiftCommentOne,
                    detail.GiftCommentTwo
                }, ACSVSeparator));
                sb.Append(ANewLine);
            }

            StreamWriter sw = new StreamWriter(filename, false, Encoding.GetEncoding(1252));

            sw.Write(sb.ToString());
            sw.Close();
        }
        // auto populate recipient info using the donor's last gift
        private void AutoPopulateGiftDetail(Int64 ADonorKey)
        {
            FAutoPopulatingGift = true;

            try
            {
                AGiftTable GiftTable = new AGiftTable();
                GiftBatchTDSAGiftDetailTable GiftDetailTable = new GiftBatchTDSAGiftDetailTable();

                // check if the donor has another gift in this same batch
                foreach (AGiftRow GiftRow in FMainDS.AGift.Rows)
                {
                    if ((GiftRow.RowState != DataRowState.Deleted) && (GiftRow.DonorKey == ADonorKey)
                        && (GiftRow.GiftTransactionNumber != GetSelectedDetailRow().GiftTransactionNumber))
                    {
                        GiftTable.Rows.Add((object[])GiftRow.ItemArray.Clone());
                    }
                }

                // if the donor does have another gift then get the AGiftDetail records for the most recent gift
                if (GiftTable.Rows.Count > 0)
                {
                    // find the most recent gift (probably the last gift in the table)
                    AGiftRow LatestGiftRow = (AGiftRow)GiftTable.Rows[GiftTable.Rows.Count - 1];

                    for (int i = GiftTable.Rows.Count - 2; i >= 0; i--)
                    {
                        if (LatestGiftRow.DateEntered < ((AGiftRow)GiftTable.Rows[i]).DateEntered)
                        {
                            LatestGiftRow = (AGiftRow)GiftTable.Rows[i];
                        }
                    }

                    foreach (AGiftDetailRow GiftDetailRow in FMainDS.AGiftDetail.Rows)
                    {
                        if ((GiftDetailRow.LedgerNumber == LatestGiftRow.LedgerNumber)
                            && (GiftDetailRow.BatchNumber == LatestGiftRow.BatchNumber)
                            && (GiftDetailRow.GiftTransactionNumber == LatestGiftRow.GiftTransactionNumber))
                        {
                            GiftDetailTable.Rows.Add((object[])GiftDetailRow.ItemArray.Clone());
                        }
                    }
                }
                else
                {
                    // if the donor does not have another gift in this gift batch then search the database for
                    // the last gift from this donor
                    GiftDetailTable = TRemote.MFinance.Gift.WebConnectors.LoadDonorLastGift(ADonorKey, FLedgerNumber);
                }

                // if this is the donor's first ever gift
                if ((GiftDetailTable == null) || (GiftDetailTable.Rows.Count == 0))
                {
                    // set FirstTimeGift field in AGift to true
                    GiftBatchTDSAGiftDetailRow CurrentDetail = GetSelectedDetailRow();
                    AGiftRow CurrentGift = (AGiftRow)FMainDS.AGift.Rows.Find(
                        new object[] { CurrentDetail.LedgerNumber, CurrentDetail.BatchNumber, CurrentDetail.GiftTransactionNumber });
                    CurrentGift.FirstTimeGift = true;

                    // add donor key to list so that new donor warning can be shown
                    if (!FNewDonorsList.Contains(ADonorKey))
                    {
                        FNewDonorsList.Add(ADonorKey);
                    }
                }

                bool SplitGift = false;

                // 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 ((GiftDetailTable != null) && (GiftDetailTable.Rows.Count > 1))
                {
                    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?");

                    SplitGift = MessageBox.Show(Message, Catalog.GetString("Create Split Gift"), MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                                == DialogResult.Yes;
                }

                if ((GiftDetailTable != null) && (GiftDetailTable.Rows.Count > 0))
                {
                    int CurrentTransaction = 0;

                    while (true)
                    {
                        GiftBatchTDSAGiftDetailRow Row = (GiftBatchTDSAGiftDetailRow)GiftDetailTable.DefaultView[CurrentTransaction].Row;

                        // populate gift detail
                        txtDetailDonorKey.Text = String.Format("{0:0000000000}", ADonorKey);
                        txtDetailRecipientKey.Text = String.Format("{0:0000000000}", Row.RecipientKey);
                        cmbDetailMotivationGroupCode.SetSelectedString(Row.MotivationGroupCode);
                        cmbDetailMotivationDetailCode.SetSelectedString(Row.MotivationDetailCode);
                        chkDetailConfidentialGiftFlag.Checked = Row.ConfidentialGiftFlag;
                        chkDetailChargeFlag.Checked = Row.ChargeFlag;
                        chkDetailTaxDeductible.Checked = Row.TaxDeductible;
                        ToggleTaxDeductible(this, null);
                        cmbDetailMailingCode.SetSelectedString(Row.MailingCode, -1);

                        if (SplitGift)
                        {
                            // only populate amount if a split gift
                            txtDetailGiftTransactionAmount.NumberValueDecimal = Row.GiftTransactionAmount;
                            CurrentTransaction++;

                            // if there are more details that are part of this gift
                            if (CurrentTransaction < GiftDetailTable.Rows.Count)
                            {
                                // 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();

                                // create a new gift detail
                                CreateANewGift(false);
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            finally
            {
                FAutoPopulatingGift = false;
            }
        }
示例#28
0
        public static string FormatHtmlReceipt(
            String ADonorShortName,
            Int64 ADonorKey,
            TPartnerClass ADonorClass,
            String AGiftCurrency,
            string ALocalCountryCode,
            AGiftTable AGiftsThisDonor,
            string AHTMLTemplateFilename,
            TDBTransaction ATransaction)
        {
            SortedList <string, List <string>>FormValues = new SortedList <string, List <string>>();

            // These are the fields that can be printed in the letter:
            FormValues.Add("AdresseeShortName", new List <string>());
            FormValues.Add("AdresseeTitle", new List <string>());
            FormValues.Add("AdresseeFirstName", new List <string>());
            FormValues.Add("AdresseeFamilyName", new List <string>());
            FormValues.Add("AdresseeStreetAddress", new List <string>());
            FormValues.Add("AdresseeAddress3", new List <string>());
            FormValues.Add("AdresseeCity", new List <string>());
            FormValues.Add("AdresseePostCode", new List <string>());
            FormValues.Add("AdresseeCountry", new List <string>());
            FormValues.Add("FormattedAddress", new List <string>());

            FormValues.Add("DateToday", new List <string>());

            FormValues.Add("DateEntered", new List <string>());
            FormValues.Add("GiftAmount", new List <string>());
            FormValues.Add("GiftCurrency", new List <string>());
            FormValues.Add("GiftTxd", new List <string>());
            FormValues.Add("RecipientShortName", new List <string>());
            FormValues.Add("MotivationDetail", new List <string>());
            FormValues.Add("Reference", new List <string>());
            FormValues.Add("DonorComment", new List <string>());

            FormValues.Add("GiftTotalAmount", new List <string>());
            FormValues.Add("GiftTotalCurrency", new List <string>());
            FormValues.Add("TxdTotal", new List <string>());
            FormValues.Add("NonTxdTotal", new List <string>());


            // Donor Name:
            FormValues["AdresseeShortName"].Add(ADonorShortName);

            if (ADonorClass == TPartnerClass.PERSON)
            {
                PPersonTable Tbl = PPersonAccess.LoadByPrimaryKey(ADonorKey, ATransaction);

                if (Tbl.Rows.Count > 0)
                {
                    FormValues["AdresseeTitle"].Add(Tbl[0].Title);
                    FormValues["AdresseeFirstName"].Add(Tbl[0].FirstName);
                    FormValues["AdresseeFamilyName"].Add(Tbl[0].FamilyName);
                }
            }
            else if (ADonorClass == TPartnerClass.FAMILY)
            {
                PFamilyTable Tbl = PFamilyAccess.LoadByPrimaryKey(ADonorKey, ATransaction);

                if (Tbl.Rows.Count > 0)
                {
                    FormValues["AdresseeTitle"].Add(Tbl[0].Title);
                    FormValues["AdresseeFirstName"].Add(Tbl[0].FirstName);
                    FormValues["AdresseeFamilyName"].Add(Tbl[0].FamilyName);
                }
            }
            else
            {
                FormValues["AdresseeFamilyName"].Add(ADonorShortName);
            }

            FormValues["DateToday"].Add(DateTime.Now.ToString("dd MMMM yyyy"));

            // Donor Adress:
            PLocationTable Location;
            string CountryName;

            if (TAddressTools.GetBestAddress(ADonorKey, out Location, out CountryName, ATransaction))
            {
                PLocationRow LocRow = Location[0];
                FormValues["AdresseeStreetAddress"].Add(LocRow.StreetName);
                FormValues["AdresseeAddress3"].Add(LocRow.Address3);
                FormValues["AdresseeCity"].Add(LocRow.City);
                FormValues["AdresseePostCode"].Add(LocRow.PostalCode);

                if (LocRow.CountryCode != ALocalCountryCode)  // Don't add the Donor's country if it's also my country:
                {
                    FormValues["AdresseeCountry"].Add(CountryName);
                }
                else
                {
                    LocRow.CountryCode = "";
                }

                FormValues["FormattedAddress"].Add(Calculations.DetermineLocationString(LocRow,
                        Calculations.TPartnerLocationFormatEnum.plfHtmlLineBreak));
            }

            decimal GiftTotal = 0;
            decimal TxdTotal = 0;
            decimal NonTxdTotal = 0;

            // Details per gift:
            foreach (AGiftRow GiftRow in AGiftsThisDonor.Rows)
            {
                String DateEntered = GiftRow.DateEntered.ToString("dd MMM yyyy");
                String GiftReference = GiftRow.Reference;
                AGiftDetailTable DetailTbl = AGiftDetailAccess.LoadViaAGift(
                    GiftRow.LedgerNumber, GiftRow.BatchNumber, GiftRow.GiftTransactionNumber, ATransaction);

                foreach (AGiftDetailRow DetailRow in DetailTbl.Rows)
                {
                    FormValues["Reference"].Add(GiftReference);
                    FormValues["DateEntered"].Add(DateEntered);
                    GiftReference = "";                         // Date and Reference are one-per-gift, not per detail
                    DateEntered = "";                           // so if this gift has several details, I'll blank the subsequent lines.

                    string DonorComment = "";
                    FormValues["GiftAmount"].Add(StringHelper.FormatUsingCurrencyCode(DetailRow.GiftTransactionAmount, AGiftCurrency));
                    FormValues["GiftCurrency"].Add(AGiftCurrency);
                    FormValues["MotivationDetail"].Add(DetailRow.MotivationDetailCode);
                    GiftTotal += DetailRow.GiftTransactionAmount;

                    if (DetailRow.TaxDeductible)
                    {
                        FormValues["GiftTxd"].Add("Y");
                        TxdTotal += DetailRow.GiftTransactionAmount;
                    }
                    else
                    {
                        FormValues["GiftTxd"].Add(" ");
                        NonTxdTotal += DetailRow.GiftTransactionAmount;
                    }

                    // Recipient Short Name:
                    PPartnerTable RecipientTbl = PPartnerAccess.LoadByPrimaryKey(DetailRow.RecipientKey, ATransaction);

                    if (RecipientTbl.Rows.Count > 0)
                    {
                        String ShortName = Calculations.FormatShortName(RecipientTbl[0].PartnerShortName, eShortNameFormat.eReverseShortname);
                        FormValues["RecipientShortName"].Add(ShortName);
                    }

                    if (DetailRow.CommentOneType == "Donor")
                    {
                        DonorComment += DetailRow.GiftCommentOne;
                    }

                    if (DetailRow.CommentTwoType == "Donor")
                    {
                        if (DonorComment != "")
                        {
                            DonorComment += "\r\n";
                        }

                        DonorComment += DetailRow.GiftCommentTwo;
                    }

                    if (DetailRow.CommentThreeType == "Donor")
                    {
                        if (DonorComment != "")
                        {
                            DonorComment += "\r\n";
                        }

                        DonorComment += DetailRow.GiftCommentThree;
                    }

                    if (DonorComment != "")
                    {
                        DonorComment = "Comment: " + DonorComment;
                    }

                    FormValues["DonorComment"].Add(DonorComment);
                } // foreach GiftDetail
            } // foreach Gift

            FormValues["GiftTotalAmount"].Add(StringHelper.FormatUsingCurrencyCode(GiftTotal, AGiftCurrency));
            FormValues["GiftTotalCurrency"].Add(AGiftCurrency);
            FormValues["TxdTotal"].Add(StringHelper.FormatUsingCurrencyCode(TxdTotal, AGiftCurrency));
            FormValues["NonTxdTotal"].Add(StringHelper.FormatUsingCurrencyCode(NonTxdTotal, AGiftCurrency));

            return TFormLettersTools.PrintSimpleHTMLLetter(AHTMLTemplateFilename, FormValues);
        }
示例#29
0
        private int GetChangedRecordCountManual(out string AMessage)
        {
            //For Gift Batch we will get a mix of some batches, gifts and gift details.
            // Only check relevant tables.
            List <string> TablesToCheck = new List <string>();

            TablesToCheck.Add(FMainDS.AGiftBatch.TableName);
            TablesToCheck.Add(FMainDS.AGift.TableName);
            TablesToCheck.Add(FMainDS.AGiftDetail.TableName);

            List <Tuple <string, int> > TableAndCountList = new List <Tuple <string, int> >();
            int AllChangesCount = 0;

            if (FMainDS.HasChanges())
            {
                foreach (DataTable dt in FMainDS.GetChanges().Tables)
                {
                    string currentTableName = dt.TableName;

                    if ((dt != null) &&
                        TablesToCheck.Contains(currentTableName) &&
                        (dt.Rows.Count > 0))
                    {
                        int tableChangesCount = 0;

                        DataTable dtChanges = dt.GetChanges();

                        foreach (DataRow dr in dtChanges.Rows)
                        {
                            if (DataUtilities.DataRowColumnsHaveChanged(dr))
                            {
                                tableChangesCount++;
                                AllChangesCount++;
                            }
                        }

                        if (tableChangesCount > 0)
                        {
                            TableAndCountList.Add(new Tuple <string, int>(currentTableName, tableChangesCount));
                        }
                    }
                }
            }

            // Now build up a sensible message
            AMessage = String.Empty;

            if (TableAndCountList.Count > 0)
            {
                if (TableAndCountList.Count == 1)
                {
                    Tuple <string, int> TableAndCount = TableAndCountList[0];

                    string tableName = TableAndCount.Item1;

                    if (TableAndCount.Item1.Equals(AGiftBatchTable.GetTableName()))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to the details of {0} {1}.{2}"),
                                                 TableAndCount.Item2,
                                                 Catalog.GetPluralString("batch", "batches", TableAndCount.Item2),
                                                 Environment.NewLine);
                    }
                    else if (TableAndCount.Item1.Equals(AGiftTable.GetTableName()))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to the details of {0} {1}.{2}"),
                                                 TableAndCount.Item2,
                                                 Catalog.GetPluralString("gift", "gifts", TableAndCount.Item2),
                                                 Environment.NewLine);
                    }
                    else //if (TableAndCount.Item1.Equals(AGiftDetailTable.GetTableName()))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1}.{2}"),
                                                 TableAndCount.Item2,
                                                 Catalog.GetPluralString("gift detail", "gift details", TableAndCount.Item2),
                                                 Environment.NewLine);
                    }
                }
                else
                {
                    int nBatches     = 0;
                    int nGifts       = 0;
                    int nGiftDetails = 0;

                    foreach (Tuple <string, int> TableAndCount in TableAndCountList)
                    {
                        if (TableAndCount.Item1.Equals(AGiftBatchTable.GetTableName()))
                        {
                            nBatches = TableAndCount.Item2;
                        }
                        else if (TableAndCount.Item1.Equals(AGiftTable.GetTableName()))
                        {
                            nGifts = TableAndCount.Item2;
                        }
                        else //if (TableAndCount.Item1.Equals(AGiftDetailTable.GetTableName()))
                        {
                            nGiftDetails = TableAndCount.Item2;
                        }
                    }

                    if ((nBatches > 0) && (nGifts > 0) && (nGiftDetails > 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1}, {2} {3} and {4} {5}.{6}"),
                                                 nBatches,
                                                 Catalog.GetPluralString("batch", "batches", nBatches),
                                                 nGifts,
                                                 Catalog.GetPluralString("gift", "gifts", nGifts),
                                                 nGiftDetails,
                                                 Catalog.GetPluralString("gift detail", "gift details", nGiftDetails),
                                                 Environment.NewLine);
                    }
                    else if ((nBatches > 0) && (nGifts > 0) && (nGiftDetails == 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1} and {2} {3}.{4}"),
                                                 nBatches,
                                                 Catalog.GetPluralString("batch", "batches", nBatches),
                                                 nGifts,
                                                 Catalog.GetPluralString("gift", "gifts", nGifts),
                                                 Environment.NewLine);
                    }
                    else if ((nBatches > 0) && (nGifts == 0) && (nGiftDetails > 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1} and {2} {3}.{4}"),
                                                 nBatches,
                                                 Catalog.GetPluralString("batch", "batches", nBatches),
                                                 nGiftDetails,
                                                 Catalog.GetPluralString("gift detail", "gift details", nGiftDetails),
                                                 Environment.NewLine);
                    }
                    else if ((nBatches > 0) && (nGifts == 0) && (nGiftDetails == 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1}.{2}"),
                                                 nBatches,
                                                 Catalog.GetPluralString("batch", "batches", nBatches),
                                                 Environment.NewLine);
                    }
                    else if ((nBatches == 0) && (nGifts > 0) && (nGiftDetails > 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1} and {2} {3}.{4}"),
                                                 nGifts,
                                                 Catalog.GetPluralString("gift", "gifts", nGifts),
                                                 nGiftDetails,
                                                 Catalog.GetPluralString("gift detail", "gift details", nGiftDetails),
                                                 Environment.NewLine);
                    }
                    else if ((nBatches == 0) && (nGifts > 0) && (nGiftDetails == 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1}.{2}"),
                                                 nGifts,
                                                 Catalog.GetPluralString("gift", "gifts", nGiftDetails),
                                                 Environment.NewLine);
                    }
                    else if ((nBatches == 0) && (nGifts == 0) && (nGiftDetails > 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1}.{2}"),
                                                 nGiftDetails,
                                                 Catalog.GetPluralString("gift detail", "gift details", nGiftDetails),
                                                 Environment.NewLine);
                    }
                }

                AMessage += Catalog.GetString("(some of the changes may include related background items)");
                AMessage += Environment.NewLine;
                AMessage += String.Format(TFrmPetraEditUtils.StrConsequenceIfNotSaved, Environment.NewLine);
            }

            return(AllChangesCount);
        }
示例#30
0
        public static void MarkReceiptsPrinted(int ALedgerNumber, DataTable AGiftTbl)
        {
            AGiftTable Tbl = new AGiftTable();

            TDBTransaction Transaction = null;
            bool SubmissionOK = false;

            DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable,
                ref Transaction,
                ref SubmissionOK,
                delegate
                {
                    try
                    {
                        foreach (DataRow Row in AGiftTbl.Rows)
                        {
                            Tbl.Merge(AGiftAccess.LoadByPrimaryKey(
                                    ALedgerNumber,
                                    Convert.ToInt32(Row["BatchNumber"]),
                                    Convert.ToInt32(Row["TransactionNumber"]),
                                    Transaction));
                        }

                        foreach (AGiftRow Row in Tbl.Rows)
                        {
                            Row.ReceiptPrinted = true;
                        }

                        AGiftAccess.SubmitChanges(Tbl, Transaction);

                        SubmissionOK = true;
                    }
                    catch (Exception e)
                    {
                        TLogging.Log("Error in MarkReceiptsPrinted: " + e.Message);
                        throw e;
                    }
                });
        }
示例#31
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);
        }
示例#32
0
        /// <summary>
        /// Checks if the donor is a lapsed donor according to the parameters supplied
        /// </summary>
        /// <param name="ADonorKey">Partner Key of the donor</param>
        /// <param name="ARecipientKey">Partner Key of the gift recipient</param>
        /// <param name="AStartDate">Date of the first gift</param>
        /// <param name="AEndDate">Date until the gift must occure regularly</param>
        /// <param name="AFrequency">How often the gift must come</param>
        /// <param name="ATolerance">How much tolerance (in days) the gift can vary</param>
        /// <param name="ALedgerNumber">The ledger number</param>
        /// <param name="AMotivationGroup">A matching string for the gift motivation group.</param>
        /// <param name="AMotivationDetail">A matching string for the gift motivation detail</param>
        /// <param name="AIgnoreBetween">True: If this donor gave a gift in between the frequency pattern, then return false</param>
        /// <returns>True if donor is still active</returns>
        private bool IsLapsedDonor(Int64 ADonorKey, Int64 ARecipientKey, DateTime AStartDate, DateTime AEndDate, String AFrequency,
                                   int ATolerance, int ALedgerNumber,
                                   String AMotivationGroup, String AMotivationDetail, bool AIgnoreBetween)
        {
            bool ReturnValue = false;
            bool FirstTime   = true;

            DateTime StartDate = AEndDate.AddDays(-ATolerance);
            DateTime EndDate   = AEndDate.AddDays(ATolerance);

            int YearFrequency;
            int MonthFrequency;
            int DayFrequency;

            GetTimeFrequency(AFrequency, out YearFrequency, out MonthFrequency, out DayFrequency);

            DataTable Table;

            String StrSql = "SELECT " + AGiftTable.GetDateEnteredDBName() +
                            " FROM " + AGiftTable.GetTableDBName() +
                            " , " + AGiftDetailTable.GetTableDBName() +
                            " WHERE " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetLedgerNumberDBName() + " = " + ALedgerNumber.ToString() +
                            " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetLedgerNumberDBName() + " = " +
                            ALedgerNumber.ToString() +
                            " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDonorKeyDBName() + " = " + ADonorKey.ToString() +
                            " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetBatchNumberDBName() + " = " +
                            AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetBatchNumberDBName() +
                            " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetGiftTransactionNumberDBName() + " = " +
                            AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetGiftTransactionNumberDBName();

            if (ARecipientKey != 0)
            {
                StrSql = StrSql +
                         " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetRecipientKeyDBName() + " = " +
                         ARecipientKey.ToString();
            }

            if (AMotivationDetail != "%")
            {
                StrSql = StrSql +
                         " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetMotivationDetailCodeDBName() + " LIKE '" +
                         AMotivationDetail + "'";
            }

            if (AMotivationGroup != "%")
            {
                StrSql = StrSql +
                         " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetMotivationGroupCodeDBName() + " LIKE '" +
                         AMotivationGroup + "'";
            }

            StrSql = StrSql +
                     " ORDER BY " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDateEnteredDBName() + " DESC ";

            Table = situation.GetDatabaseConnection().SelectDT(StrSql, "table", situation.GetDatabaseConnection().Transaction, new OdbcParameter[] { });

            foreach (DataRow Row in Table.Rows)
            {
                DateTime DateEntered = (DateTime)Row[AGiftTable.GetDateEnteredDBName()];

                // Ok they gave a gift during this period but check that it was the last gift.
                if (FirstTime)
                {
                    if (DateEntered > EndDate)
                    {
                        break;
                    }

                    FirstTime = false;
                }

                // If the date is not within the date range then
                // check the flag to see if gifts are allowed between gifts.
                // otherwise ignore.
                if (DateEntered > EndDate)
                {
                    if (AIgnoreBetween)
                    {
                        break;
                    }

                    continue;
                }

                // If we are passed the start date and have not found a gift then this
                // donor does not have the right pattern of giving */
                if (DateEntered < StartDate)
                {
                    break;
                }

                // we have found a gift and it is within the dates we are interested in.
                // now go back to the next set of dates.
                StartDate = StartDate.AddDays(-DayFrequency);
                StartDate = StartDate.AddMonths(-MonthFrequency);
                StartDate = StartDate.AddYears(-YearFrequency);
                EndDate   = EndDate.AddDays(-DayFrequency);
                EndDate   = EndDate.AddMonths(-MonthFrequency);
                EndDate   = EndDate.AddYears(-YearFrequency);

                // we are now beyond the first gift date so stop.
                if (EndDate < AStartDate)
                {
                    ReturnValue = true;
                    break;
                }
            }

            if (!ReturnValue)
            {
                // clear this row, we don't want to display it
                // set all parameters of this row to NULL
                situation.GetParameters().Add("DONTDISPLAYROW", new TVariant(true));
            }
            else
            {
                // show this row
                situation.GetParameters().Add("DONTDISPLAYROW", new TVariant(false), -1, -1, null, null, ReportingConsts.CALCULATIONPARAMETERS);

                String Currency     = situation.GetParameters().Get("param_currency").ToString();
                bool   BaseCurrency = false;

                if (Currency == "Base")
                {
                    BaseCurrency = true;
                }

                CalculatePrviousYearsGift(AEndDate, ADonorKey, ALedgerNumber, ARecipientKey, AMotivationDetail, AMotivationGroup, BaseCurrency);
            }

            return(ReturnValue);
        }
示例#33
0
        /// <summary>
        /// Calculate the gift amount for this year and the previous two years given from this donor to this recipient.
        /// </summary>
        /// <param name="ALastGiftDate">defines the last year of the calculation</param>
        /// <param name="ADonorKey">Partner Key of the donor</param>
        /// <param name="ALedgerNumber">The ledger number</param>
        /// <param name="ARecipientKey">Partner Key of the gift recipient</param>
        /// <param name="AMotivationDetail">A matching string for the gift motivation detail</param>
        /// <param name="AMotivationGroup">A matching string for the gift motivation group.</param>
        /// <param name="ABaseCurrency">Defines if we sum up the base currency or international currency</param>
        private void CalculatePrviousYearsGift(DateTime ALastGiftDate,
                                               Int64 ADonorKey,
                                               int ALedgerNumber,
                                               Int64 ARecipientKey,
                                               String AMotivationDetail,
                                               String AMotivationGroup,
                                               bool ABaseCurrency)
        {
            DateTime SelectionEndDate   = new DateTime(ALastGiftDate.Year, 12, 31);
            DateTime SelectionStartDate = new DateTime(ALastGiftDate.Year - 2, 1, 1);

            String StrSql = "SELECT " + AGiftTable.GetDateEnteredDBName();

            if (ABaseCurrency)
            {
                StrSql = StrSql + ", " + AGiftDetailTable.GetGiftAmountDBName() + " AS CurrentAmount";
            }
            else
            {
                StrSql = StrSql + ", " + AGiftDetailTable.GetGiftAmountIntlDBName() + " AS CurrentAmount";
            }

            StrSql = StrSql +
                     " FROM " + AGiftTable.GetTableDBName() +
                     " , " + AGiftDetailTable.GetTableDBName() +
                     " WHERE " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetLedgerNumberDBName() + " = " + ALedgerNumber.ToString() +
                     " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetLedgerNumberDBName() + " = " +
                     ALedgerNumber.ToString() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDonorKeyDBName() + " = " + ADonorKey.ToString() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetBatchNumberDBName() + " = " + AGiftDetailTable.GetTableDBName() +
                     "." + AGiftDetailTable.GetBatchNumberDBName() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetGiftTransactionNumberDBName() + " = " +
                     AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetGiftTransactionNumberDBName() +
                     " AND " + AGiftTable.GetTableDBName() + "." + AGiftTable.GetDateEnteredDBName() + " BETWEEN '" + SelectionStartDate.ToString(
                "yyyy-MM-dd") + "' AND '" + SelectionEndDate.ToString("yyyy-MM-dd") + "'";

            if (ARecipientKey != 0)
            {
                StrSql = StrSql +
                         " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetRecipientKeyDBName() + " = " +
                         ARecipientKey.ToString();
            }

            if (AMotivationDetail != "%")
            {
                StrSql = StrSql +
                         " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetMotivationDetailCodeDBName() + " LIKE '" +
                         AMotivationDetail + "'";
            }

            if (AMotivationGroup != "%")
            {
                StrSql = StrSql +
                         " AND " + AGiftDetailTable.GetTableDBName() + "." + AGiftDetailTable.GetMotivationGroupCodeDBName() + " LIKE '" +
                         AMotivationGroup + "'";
            }

            DataTable Table = situation.GetDatabaseConnection().SelectDT(StrSql, "table",
                                                                         situation.GetDatabaseConnection().Transaction, new OdbcParameter[] { });

            decimal TotalYear_0 = 0.0M;
            decimal TotalYear_1 = 0.0M;
            decimal TotalYear_2 = 0.0M;

            foreach (DataRow Row in Table.Rows)
            {
                DateTime DateEntered   = (DateTime)Row[AGiftTable.GetDateEnteredDBName()];
                decimal  CurrentAmount = Convert.ToDecimal(Row["CurrentAmount"]);

                if (DateEntered.Year == ALastGiftDate.Year)
                {
                    TotalYear_0 += CurrentAmount;
                }
                else if (DateEntered.Year == ALastGiftDate.Year - 1)
                {
                    TotalYear_1 += CurrentAmount;
                }
                else if (DateEntered.Year == ALastGiftDate.Year - 2)
                {
                    TotalYear_2 += CurrentAmount;
                }
            }

            situation.GetParameters().Add("TotalYear_0", new TVariant(TotalYear_0));
            situation.GetParameters().Add("TotalYear_1", new TVariant(TotalYear_1));
            situation.GetParameters().Add("TotalYear_2", new TVariant(TotalYear_2));
        }
示例#34
0
        /// <summary>
        /// export all posted invoices for conference and seminar participants in this year
        /// </summary>
        public static void Export(string AOutputPath,
            char ACSVSeparator,
            string ANewLine,
            Int32 ALedgerNumber,
            Int32 AFinancialYear,
            string ACostCentres)
        {
            string filename = Path.GetFullPath(Path.Combine(AOutputPath, "participants.csv"));

            Console.WriteLine("Writing file: " + filename);

            TDBTransaction Transaction = null;
            AGiftDetailTable giftdetails = new AGiftDetailTable();
            AGiftTable gifts = new AGiftTable();
            AGiftBatchTable batches = new AGiftBatchTable();
            PPersonTable persons = new PPersonTable();
            DBAccess.GDBAccessObj.BeginAutoReadTransaction(IsolationLevel.ReadCommitted, ref Transaction,
                delegate
                {
                    // all gift details towards a costcentre that needs to be exported
                    string sql =
                        String.Format("SELECT DISTINCT D.* " +
                            "FROM PUB_{0} AS B, PUB_{1} AS G, PUB_{2} AS D " +
                            "WHERE B.{3} = {4} AND B.{5} = {6} AND B.{7}='{8}' " +
                            "AND G.{3} = B.{3} AND G.{9} = B.{9} " +
                            "AND D.{3} = G.{3} AND D.{9} = G.{9} AND D.{10} = G.{10} " +
                            "AND D.{11} IN ({12}) " +
                            "AND NOT D.{13} = '{14}'",
                            AGiftBatchTable.GetTableDBName(),
                            AGiftTable.GetTableDBName(),
                            AGiftDetailTable.GetTableDBName(),
                            AGiftBatchTable.GetLedgerNumberDBName(),
                            ALedgerNumber,
                            AGiftBatchTable.GetBatchYearDBName(),
                            AFinancialYear,
                            AGiftBatchTable.GetBatchStatusDBName(),
                            MFinanceConstants.BATCH_POSTED,
                            AGiftBatchTable.GetBatchNumberDBName(),
                            AGiftTable.GetGiftTransactionNumberDBName(),
                            AGiftDetailTable.GetCostCentreCodeDBName(),
                            "'" + ACostCentres.Replace(",", "','") + "'",
                            AGiftDetailTable.GetMotivationGroupCodeDBName(),
                            "GIFT");

                    DBAccess.GDBAccessObj.SelectDT(giftdetails, sql, Transaction, null, 0, 0);

                    sql = sql.Replace("SELECT DISTINCT D.*", "SELECT DISTINCT G.*");

                    DBAccess.GDBAccessObj.SelectDT(gifts, sql, Transaction, null, 0, 0);

                    gifts.DefaultView.Sort =
                        AGiftTable.GetBatchNumberDBName() + "," +
                        AGiftTable.GetGiftTransactionNumberDBName();

                    sql = sql.Replace("SELECT DISTINCT G.*", "SELECT DISTINCT B.*");

                    DBAccess.GDBAccessObj.SelectDT(batches, sql, Transaction, null, 0, 0);
                    batches.DefaultView.Sort = AGiftTable.GetBatchNumberDBName();

                    sql =
                        String.Format("SELECT DISTINCT P.* " +
                            "FROM PUB_{0} AS B, PUB_{1} AS G, PUB_{2} AS D, PUB.{15} AS P " +
                            "WHERE B.{3} = {4} AND B.{5} = {6} AND B.{7}='{8}' " +
                            "AND G.{3} = B.{3} AND G.{9} = B.{9} " +
                            "AND D.{3} = G.{3} AND D.{9} = G.{9} AND D.{10} = G.{10} " +
                            "AND D.{11} IN ({12}) " +
                            "AND NOT D.{13} = '{14}' " +
                            "AND P.{16} = G.{17}",
                            AGiftBatchTable.GetTableDBName(),
                            AGiftTable.GetTableDBName(),
                            AGiftDetailTable.GetTableDBName(),
                            AGiftBatchTable.GetLedgerNumberDBName(),
                            ALedgerNumber,
                            AGiftBatchTable.GetBatchYearDBName(),
                            AFinancialYear,
                            AGiftBatchTable.GetBatchStatusDBName(),
                            MFinanceConstants.BATCH_POSTED,
                            AGiftBatchTable.GetBatchNumberDBName(),
                            AGiftTable.GetGiftTransactionNumberDBName(),
                            AGiftDetailTable.GetCostCentreCodeDBName(),
                            "'" + ACostCentres.Replace(",", "','") + "'",
                            AGiftDetailTable.GetMotivationGroupCodeDBName(),
                            "GIFT",
                            PPersonTable.GetTableDBName(),
                            PPersonTable.GetPartnerKeyDBName(),
                            AGiftTable.GetDonorKeyDBName());

                    DBAccess.GDBAccessObj.SelectDT(persons, sql, Transaction, null, 0, 0);
                    persons.DefaultView.Sort = PPersonTable.GetPartnerKeyDBName();
                });

            StringBuilder sb = new StringBuilder();

            foreach (AGiftDetailRow detail in giftdetails.Rows)
            {
                AGiftRow gift = (AGiftRow)gifts.DefaultView.FindRows(new object[] { detail.BatchNumber, detail.GiftTransactionNumber })[0].Row;
                AGiftBatchRow batch = (AGiftBatchRow)batches.DefaultView.FindRows(detail.BatchNumber)[0].Row;

                DataRowView[] personList = persons.DefaultView.FindRows(gift.DonorKey);
                PPersonRow person = (personList.Length > 0 ? (PPersonRow)personList[0].Row : null);

                sb.Append(StringHelper.StrMerge(
                        new string[] {
                            "GB" + detail.BatchNumber.ToString() + "_G" + detail.GiftTransactionNumber.ToString() +
                            "_D" + detail.DetailNumber.ToString(),
                            String.Format("{0:N}", detail.GiftTransactionAmount),
                            batch.GlEffectiveDate.ToString("yyyyMMdd"),
                            gift.DonorKey.ToString(),
                            person !=
                            null ? (person.DateOfBirth.HasValue ? person.DateOfBirth.Value.ToString("yyyyMMdd") : string.Empty) : string.Empty,
                            detail.CostCentreCode,
                            batch.BatchDescription,
                            detail.GiftCommentOne,
                            detail.GiftCommentTwo
                        }, ACSVSeparator));
                sb.Append(ANewLine);
            }

            StreamWriter sw = new StreamWriter(filename, false, Encoding.GetEncoding(1252));
            sw.Write(sb.ToString());
            sw.Close();
        }
示例#35
0
        public static string PrintGiftReceipt(
            String AGiftCurrency,
            String ADonorShortName,
            Int64 ADonorKey,
            TPartnerClass ADonorClass,
            AGiftTable GiftsThisDonor,
            string AHTMLTemplateFilename
            )
        {
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);
            string HtmlDoc;

            try
            {
                string LocalCountryCode = TAddressTools.GetCountryCodeFromSiteLedger(Transaction);
                HtmlDoc = FormatHtmlReceipt(
                    ADonorShortName,
                    ADonorKey,
                    ADonorClass,
                    AGiftCurrency,
                    LocalCountryCode,
                    GiftsThisDonor,
                    AHTMLTemplateFilename,
                    Transaction);
            }
            finally
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
            }
            return HtmlDoc;
        }
示例#36
0
        public static Int32 FieldChangeAdjustment(Int32 ALedgerNumber,
                                                  Int64 ARecipientKey,
                                                  DateTime AStartDate,
                                                  DateTime AEndDate,
                                                  Int64 AOldField,
                                                  DateTime ADateCorrection,
                                                  bool AWithReceipt)
        {
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);
            GiftBatchTDS   oldGiftDS   = new GiftBatchTDS();

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

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

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

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

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

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

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

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

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

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

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

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

                AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];

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

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

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

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

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

                DataUtilities.CopyAllColumnValues(oldGiftDetail, detail);

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

                GiftDS.AGiftDetail.Rows.Add(detail);

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

                DataUtilities.CopyAllColumnValues(oldGiftDetail, detail);

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

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

                GiftDS.AGiftDetail.Rows.Add(detail);

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

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

            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = TSubmitChangesResult.scrOK;

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

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

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

            return(-1);
        }
        /// <summary>
        /// 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);
        }