public static GiftBatchTDS LoadMotivationDetails(Int32 ALedgerNumber) { GiftBatchTDS MainDS = new GiftBatchTDS(); TDBTransaction Transaction = null; DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); AMotivationGroupAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction); AMotivationDetailAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction); AMotivationDetailFeeAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction); }); // Accept row changes here so that the Client gets 'unmodified' rows MainDS.AcceptChanges(); // Remove all Tables that were not filled with data before remoting them. MainDS.RemoveEmptyTables(); return(MainDS); }
public static GiftBatchTDS LoadMotivationDetails(Int32 ALedgerNumber, string AMotivationGroupCode) { GiftBatchTDS MainDS = new GiftBatchTDS(); TDBTransaction Transaction = new TDBTransaction(); TDataBase db = DBAccess.Connect("LoadMotivationDetails"); db.ReadTransaction( ref Transaction, delegate { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); if (AMotivationGroupCode.Length > 0) { AMotivationGroupAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, AMotivationGroupCode, Transaction); AMotivationDetailAccess.LoadViaAMotivationGroup(MainDS, ALedgerNumber, AMotivationGroupCode, Transaction); } else { AMotivationGroupAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction); AMotivationDetailAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction); } AMotivationDetailFeeAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction); }); // Accept row changes here so that the Client gets 'unmodified' rows MainDS.AcceptChanges(); // Remove all Tables that were not filled with data before remoting them. MainDS.RemoveEmptyTables(); return(MainDS); }
public static GiftBatchTDS LoadMotivationDetails(Int32 ALedgerNumber) { GiftBatchTDS MainDS = new GiftBatchTDS(); TDBTransaction Transaction = null; DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); AMotivationGroupAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction); AMotivationDetailAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction); AMotivationDetailFeeAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction); }); // Accept row changes here so that the Client gets 'unmodified' rows MainDS.AcceptChanges(); // Remove all Tables that were not filled with data before remoting them. MainDS.RemoveEmptyTables(); return MainDS; }
public void UpdateRecord() { TDBTransaction ReadTransaction = new TDBTransaction(); GiftBatchTDS MainDS = new GiftBatchTDS(); TDataBase db = DBAccess.Connect("test"); db.ReadTransaction(ref ReadTransaction, delegate { ALedgerAccess.LoadAll(MainDS, ReadTransaction); }); ReadTransaction.Rollback(); MainDS.ALedger[0].LastGiftBatchNumber++; AGiftBatchRow batch = MainDS.AGiftBatch.NewRowTyped(); batch.LedgerNumber = MainDS.ALedger[0].LedgerNumber; batch.BatchNumber = MainDS.ALedger[0].LastGiftBatchNumber; batch.BankAccountCode = "6000"; batch.BatchYear = 0; batch.BatchPeriod = 1; batch.CurrencyCode = "EUR"; batch.BatchDescription = "test"; batch.BankCostCentre = (MainDS.ALedger[0].LedgerNumber * 100).ToString("0000"); batch.LastGiftNumber = 0; batch.HashTotal = 83; MainDS.AGiftBatch.Rows.Add(batch); GiftBatchTDSAccess.SubmitChanges(MainDS); MainDS.AcceptChanges(); MainDS.AGiftBatch[0].BatchDescription = "test2"; GiftBatchTDSAccess.SubmitChanges(MainDS); TDBTransaction transaction = new TDBTransaction(); AGiftBatchTable batches = null; db.ReadTransaction( ref transaction, delegate { batches = AGiftBatchAccess.LoadByPrimaryKey(batch.LedgerNumber, batch.BatchNumber, transaction); }); // some problems with sqlite and datagrid Assert.AreEqual(typeof(decimal), batches[0][AGiftBatchTable.ColumnHashTotalId].GetType(), "type decimal"); Assert.AreEqual(83.0m, batches[0].HashTotal, "gift batch hashtotal does not equal"); }
public static GiftBatchTDS LoadALedgerTable(Int32 ALedgerNumber) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } #endregion Validate Arguments GiftBatchTDS MainDS = new GiftBatchTDS(); TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); #region Validate Data if ((MainDS.ALedger == null) || (MainDS.ALedger.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Details for Ledger {1} could not be accessed!"), Utilities.GetMethodSignature(), ALedgerNumber)); } #endregion Validate Data }); // Remove all Tables that were not filled with data before remoting them. MainDS.RemoveEmptyTables(); // Accept row changes here so that the Client gets 'unmodified' rows MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
public static GiftBatchTDS LoadARecurringGiftBatchAndRelatedData(Int32 ALedgerNumber, Int32 ABatchNumber, bool AExcludeBatchRow = false) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } #endregion Validate Arguments bool ChangesToCommit = false; GiftBatchTDS MainDS = new GiftBatchTDS(); TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { MainDS = LoadARecurringGiftBatchAndRelatedData(ALedgerNumber, ABatchNumber, Transaction, out ChangesToCommit, AExcludeBatchRow); }); if (ChangesToCommit) { // if RecipientLedgerNumber has been updated then this should immediately be saved to the database GiftBatchTDSAccess.SubmitChanges(MainDS); } MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
public static void SubmitRecurringGiftBatch(Hashtable requestParams) { Int32 ALedgerNumber; Int32 ABatchNumber; DateTime AEffectiveDate; Decimal AExchangeRateToBase; Decimal AExchangeRateIntlToBase; #region Validate Parameter Arguments try { ALedgerNumber = (Int32)requestParams["ALedgerNumber"]; ABatchNumber = (Int32)requestParams["ABatchNumber"]; AEffectiveDate = (DateTime)requestParams["AEffectiveDate"]; AExchangeRateToBase = (Decimal)requestParams["AExchangeRateToBase"]; AExchangeRateIntlToBase = (Decimal)requestParams["AExchangeRateIntlToBase"]; } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } else if (AExchangeRateToBase <= 0) { throw new ArgumentException(String.Format(Catalog.GetString( "Function:{0} - The exchange rate to base parameter must be greater than 0!"), Utilities.GetMethodName(true))); } else if (AExchangeRateIntlToBase <= 0) { throw new ArgumentException(String.Format(Catalog.GetString( "Function:{0} - The international exchange rate parameter must be greater than 0!"), Utilities.GetMethodName(true))); } #endregion Validate Parameter Arguments bool TaxDeductiblePercentageEnabled = Convert.ToBoolean( TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE")); bool TransactionInIntlCurrency = false; int NewGiftBatchNumber = -1; GiftBatchTDS MainDS = new GiftBatchTDS(); GiftBatchTDS MainRecurringDS = LoadRecurringGiftTransactionsForBatch(ALedgerNumber, ABatchNumber); TDBTransaction Transaction = null; bool SubmissionOK = false; try { DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref SubmissionOK, delegate { ALedgerTable ledgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction); #region Validate Data if ((ledgerTable == null) || (ledgerTable.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Details for Ledger {1} could not be accessed!"), Utilities.GetMethodSignature(), ALedgerNumber)); } #endregion Validate Data ARecurringGiftBatchAccess.LoadByPrimaryKey(MainRecurringDS, ALedgerNumber, ABatchNumber, Transaction); // Assuming all relevant data is loaded in RMainDS foreach (ARecurringGiftBatchRow recBatch in MainRecurringDS.ARecurringGiftBatch.Rows) { if ((recBatch.BatchNumber == ABatchNumber) && (recBatch.LedgerNumber == ALedgerNumber)) { Decimal batchTotal = 0; AGiftBatchRow batch = TGiftBatchFunctions.CreateANewGiftBatchRow(ref MainDS, ref Transaction, ref ledgerTable, ALedgerNumber, AEffectiveDate); NewGiftBatchNumber = batch.BatchNumber; batch.BatchDescription = recBatch.BatchDescription; batch.BankCostCentre = recBatch.BankCostCentre; batch.BankAccountCode = recBatch.BankAccountCode; batch.ExchangeRateToBase = AExchangeRateToBase; batch.MethodOfPaymentCode = recBatch.MethodOfPaymentCode; batch.GiftType = recBatch.GiftType; batch.HashTotal = recBatch.HashTotal; batch.CurrencyCode = recBatch.CurrencyCode; TransactionInIntlCurrency = (batch.CurrencyCode == ledgerTable[0].IntlCurrency); foreach (ARecurringGiftRow recGift in MainRecurringDS.ARecurringGift.Rows) { if ((recGift.BatchNumber == ABatchNumber) && (recGift.LedgerNumber == ALedgerNumber) && recGift.Active) { //Look if there is a detail which is in the donation period (else continue) bool foundDetail = false; foreach (ARecurringGiftDetailRow recGiftDetail in MainRecurringDS.ARecurringGiftDetail.Rows) { if ((recGiftDetail.GiftTransactionNumber == recGift.GiftTransactionNumber) && (recGiftDetail.BatchNumber == ABatchNumber) && (recGiftDetail.LedgerNumber == ALedgerNumber) && ((recGiftDetail.StartDonations == null) || (AEffectiveDate >= recGiftDetail.StartDonations)) && ((recGiftDetail.EndDonations == null) || (AEffectiveDate <= recGiftDetail.EndDonations)) ) { foundDetail = true; break; } } if (!foundDetail) { continue; } // make the gift from recGift AGiftRow gift = MainDS.AGift.NewRowTyped(); gift.LedgerNumber = batch.LedgerNumber; gift.BatchNumber = batch.BatchNumber; gift.GiftTransactionNumber = ++batch.LastGiftNumber; gift.DonorKey = recGift.DonorKey; gift.MethodOfGivingCode = recGift.MethodOfGivingCode; gift.DateEntered = AEffectiveDate; if (gift.MethodOfGivingCode.Length == 0) { gift.SetMethodOfGivingCodeNull(); } gift.MethodOfPaymentCode = recGift.MethodOfPaymentCode; if (gift.MethodOfPaymentCode.Length == 0) { gift.SetMethodOfPaymentCodeNull(); } gift.Reference = recGift.Reference; gift.ReceiptLetterCode = recGift.ReceiptLetterCode; MainDS.AGift.Rows.Add(gift); //TODO (not here, but in the client or while posting) Check for Ex-OM Partner //TODO (not here, but in the client or while posting) Check for expired key ministry (while Posting) foreach (ARecurringGiftDetailRow recGiftDetail in MainRecurringDS.ARecurringGiftDetail.Rows) { //decimal amtIntl = 0M; decimal amtBase = 0M; decimal amtTrans = 0M; if ((recGiftDetail.GiftTransactionNumber == recGift.GiftTransactionNumber) && (recGiftDetail.BatchNumber == ABatchNumber) && (recGiftDetail.LedgerNumber == ALedgerNumber) && ((recGiftDetail.StartDonations == null) || (recGiftDetail.StartDonations <= AEffectiveDate)) && ((recGiftDetail.EndDonations == null) || (recGiftDetail.EndDonations >= AEffectiveDate)) ) { AGiftDetailRow detail = MainDS.AGiftDetail.NewRowTyped(); detail.LedgerNumber = gift.LedgerNumber; detail.BatchNumber = gift.BatchNumber; detail.GiftTransactionNumber = gift.GiftTransactionNumber; detail.DetailNumber = ++gift.LastDetailNumber; amtTrans = recGiftDetail.GiftAmount; detail.GiftTransactionAmount = amtTrans; batchTotal += amtTrans; amtBase = GLRoutines.Divide((decimal)amtTrans, AExchangeRateToBase); detail.GiftAmount = amtBase; if (!TransactionInIntlCurrency) { detail.GiftAmountIntl = GLRoutines.Divide((decimal)amtBase, AExchangeRateIntlToBase); } else { detail.GiftAmountIntl = amtTrans; } detail.RecipientKey = recGiftDetail.RecipientKey; detail.RecipientLedgerNumber = recGiftDetail.RecipientLedgerNumber; detail.ChargeFlag = recGiftDetail.ChargeFlag; detail.ConfidentialGiftFlag = recGiftDetail.ConfidentialGiftFlag; detail.TaxDeductible = recGiftDetail.TaxDeductible; detail.MailingCode = recGiftDetail.MailingCode; if (detail.MailingCode.Length == 0) { detail.SetMailingCodeNull(); } detail.MotivationGroupCode = recGiftDetail.MotivationGroupCode; detail.MotivationDetailCode = recGiftDetail.MotivationDetailCode; detail.GiftCommentOne = recGiftDetail.GiftCommentOne; detail.CommentOneType = recGiftDetail.CommentOneType; detail.GiftCommentTwo = recGiftDetail.GiftCommentTwo; detail.CommentTwoType = recGiftDetail.CommentTwoType; detail.GiftCommentThree = recGiftDetail.GiftCommentThree; detail.CommentThreeType = recGiftDetail.CommentThreeType; if (TaxDeductiblePercentageEnabled) { // Sets TaxDeductiblePct and uses it to calculate the tax deductibility amounts for a Gift Detail TGift.SetDefaultTaxDeductibilityData(ref detail, gift.DateEntered, Transaction); } MainDS.AGiftDetail.Rows.Add(detail); } } batch.BatchTotal = batchTotal; } } } } ALedgerAccess.SubmitChanges(ledgerTable, Transaction); AGiftBatchAccess.SubmitChanges(MainDS.AGiftBatch, Transaction); AGiftAccess.SubmitChanges(MainDS.AGift, Transaction); AGiftDetailAccess.SubmitChanges(MainDS.AGiftDetail, Transaction); MainDS.AcceptChanges(); SubmissionOK = true; }); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } }
public static GiftBatchTDS LoadDonorRecipientHistory(Hashtable requestParams, out TVerificationResultCollection AMessages) { GiftBatchTDS MainDS = new GiftBatchTDS(); TDBTransaction Transaction = null; AMessages = new TVerificationResultCollection(); string tempTableName = (string)requestParams["TempTable"]; Int32 ledgerNumber = (Int32)requestParams["Ledger"]; long recipientKey = (Int64)requestParams["Recipient"]; long donorKey = (Int64)requestParams["Donor"]; string dateFrom = (string)requestParams["DateFrom"]; string dateTo = (string)requestParams["DateTo"]; DateTime startDate; DateTime endDate; bool noDates = (dateFrom.Length == 0 && dateTo.Length == 0); string sqlStmt = string.Empty; try { sqlStmt = TDataBase.ReadSqlFile("Gift.GetDonationsOfDonorAndOrRecipientTemplate.sql"); OdbcParameter param; List <OdbcParameter>parameters = new List <OdbcParameter>(); param = new OdbcParameter("LedgerNumber", OdbcType.Int); param.Value = ledgerNumber; parameters.Add(param); param = new OdbcParameter("DonorAny", OdbcType.Bit); param.Value = (donorKey == 0); parameters.Add(param); param = new OdbcParameter("DonorKey", OdbcType.BigInt); param.Value = donorKey; parameters.Add(param); param = new OdbcParameter("RecipientAny", OdbcType.Bit); param.Value = (recipientKey == 0); parameters.Add(param); param = new OdbcParameter("RecipientKey", OdbcType.BigInt); param.Value = recipientKey; parameters.Add(param); noDates = (dateFrom.Length == 0 && dateTo.Length == 0); param = new OdbcParameter("DateAny", OdbcType.Bit); param.Value = noDates; parameters.Add(param); if (noDates) { //These values don't matter because of the value of noDate startDate = new DateTime(2000, 1, 1); endDate = new DateTime(2000, 1, 1); } else if ((dateFrom.Length > 0) && (dateTo.Length > 0)) { startDate = Convert.ToDateTime(dateFrom); //, new CultureInfo("en-US")); endDate = Convert.ToDateTime(dateTo); //, new CultureInfo("en-US")); } else if (dateFrom.Length > 0) { startDate = Convert.ToDateTime(dateFrom); endDate = new DateTime(2050, 1, 1); } else { startDate = new DateTime(1965, 1, 1); endDate = Convert.ToDateTime(dateTo); } param = new OdbcParameter("DateFrom", OdbcType.Date); param.Value = startDate; parameters.Add(param); param = new OdbcParameter("DateTo", OdbcType.Date); param.Value = endDate; parameters.Add(param); DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, ref Transaction, delegate { //Load Ledger Table ALedgerAccess.LoadByPrimaryKey(MainDS, ledgerNumber, Transaction); //Can do this if needed: MainDS.DisableConstraints(); DBAccess.GDBAccessObj.SelectToTempTable(MainDS, sqlStmt, tempTableName, Transaction, parameters.ToArray(), 0, 0); MainDS.Tables[tempTableName].Columns.Add("DonorDescription"); PPartnerTable Tbl = null; // Two scenarios. 1. The donor key is not set which means the Donor Description could be different for every record. if (donorKey == 0) { Tbl = PPartnerAccess.LoadAll(Transaction); foreach (DataRow Row in MainDS.Tables[tempTableName].Rows) { Row["DonorDescription"] = ((PPartnerRow)Tbl.Rows.Find(new object[] { Convert.ToInt64( Row["DonorKey"]) })).PartnerShortName; } } // 2. The donor key is set which means the Donor Description will be the same for every record. (Less calculations this way.) else { Tbl = PPartnerAccess.LoadByPrimaryKey(donorKey, Transaction); foreach (DataRow Row in MainDS.Tables[tempTableName].Rows) { Row["DonorDescription"] = Tbl[0].PartnerShortName; } } }); } catch (Exception e) { TLogging.Log("Error in LoadDonorRecipientHistory: " + e.Message); throw e; } MainDS.AcceptChanges(); return MainDS; }
public static GiftBatchTDS LoadAGiftBatchesForCurrentYear(Int32 ALedgerNumber) { GiftBatchTDS MainDS = new GiftBatchTDS(); TDBTransaction Transaction = null; DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, ref Transaction, delegate { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); string SelectClause = String.Format("SELECT * FROM PUB_{0} WHERE {1} = {2} AND PUB_{0}.{3} = {4}", AGiftBatchTable.GetTableDBName(), AGiftBatchTable.GetLedgerNumberDBName(), ALedgerNumber, AGiftBatchTable.GetBatchYearDBName(), MainDS.ALedger[0].CurrentFinancialYear); DBAccess.GDBAccessObj.Select(MainDS, SelectClause, MainDS.AGiftBatch.TableName, Transaction); }); MainDS.AcceptChanges(); return MainDS; }
public static GiftBatchTDS LoadAGiftSingle(Int32 ALedgerNumber, Int32 ABatchNumber, Int32 AGiftTransactionNumber) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } else if (AGiftTransactionNumber <= 0) { throw new ArgumentException(String.Format(Catalog.GetString( "Function:{0} - The Gift Transaction number in Ledger {1}, Batch {2} must be greater than 0!"), Utilities.GetMethodName(true), ALedgerNumber, ABatchNumber)); } #endregion Validate Arguments GiftBatchTDS MainDS = new GiftBatchTDS(); TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); AGiftBatchAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, Transaction); AGiftAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, AGiftTransactionNumber, Transaction); AGiftDetailAccess.LoadViaAGift(MainDS, ALedgerNumber, ABatchNumber, AGiftTransactionNumber, Transaction); #region Validate Data if ((MainDS.ALedger == null) || (MainDS.ALedger.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } else if ((MainDS.AGiftBatch == null) || (MainDS.AGiftBatch.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Batch data for Gift Batch number {1} in Ledger number {2} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ABatchNumber, ALedgerNumber)); } else if ((MainDS.AGift == null) || (MainDS.AGift.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Gift data for Gift {1} in Batch number {2} in Ledger number {3} does not exist or could not be accessed!"), Utilities.GetMethodName(true), AGiftTransactionNumber, ABatchNumber, ALedgerNumber)); } else if ((MainDS.AGiftDetail == null) || (MainDS.AGiftDetail.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Gift Details for Gift {1} in Batch number {2} in Ledger number {3} do not exist or could not be accessed!"), Utilities.GetMethodName(true), AGiftTransactionNumber, ABatchNumber, ALedgerNumber)); } #endregion Validate Data }); MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
/// <summary> /// Import Gift Transactions from a file /// </summary> /// <param name="ARequestParams"></param> /// <param name="AImportString"></param> /// <param name="AGiftBatchNumber"></param> /// <param name="ANeedRecipientLedgerNumber"></param> /// <param name="AMessages"></param> /// <returns></returns> public bool ImportGiftTransactions( Hashtable ARequestParams, String AImportString, Int32 AGiftBatchNumber, out GiftBatchTDSAGiftDetailTable ANeedRecipientLedgerNumber, out TVerificationResultCollection AMessages ) { TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(), Catalog.GetString("Importing Gift Batches"), 100); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Initialising"), 5); AMessages = new TVerificationResultCollection(); FMainDS = new GiftBatchTDS(); StringReader sr = new StringReader(AImportString); ANeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable(); // Parse the supplied parameters FDelimiter = (String)ARequestParams["Delimiter"]; FLedgerNumber = (Int32)ARequestParams["ALedgerNumber"]; FDateFormatString = (String)ARequestParams["DateFormatString"]; String NumberFormat = (String)ARequestParams["NumberFormat"]; FNewLine = (String)ARequestParams["NewLine"]; // Set culture from parameters FCultureInfoNumberFormat = new CultureInfo(NumberFormat.Equals("American") ? "en-US" : "de-DE"); FCultureInfoDate = new CultureInfo("en-GB"); FCultureInfoDate.DateTimeFormat.ShortDatePattern = FDateFormatString; bool TaxDeductiblePercentageEnabled = Convert.ToBoolean( TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE")); // Initialise our working variables TDBTransaction Transaction = null; decimal totalBatchAmount = 0; Int32 RowNumber = 0; Int32 InitialTextLength = AImportString.Length; Int32 TextProcessedLength = 0; Int32 PercentDone = 10; Int32 PreviousPercentDone = 0; bool ok = false; string ImportMessage = Catalog.GetString("Initialising"); // Create some validation dictionaries TValidationControlsDict ValidationControlsDictGift = new TValidationControlsDict(); TValidationControlsDict ValidationControlsDictGiftDetail = new TValidationControlsDict(); try { // This needs to be initialised because we will be calling the method TSharedFinanceValidationHelper.GetValidPeriodDatesDelegate = @TAccountingPeriodsWebConnector.GetPeriodDates; TSharedFinanceValidationHelper.GetFirstDayOfAccountingPeriodDelegate = @TAccountingPeriodsWebConnector.GetFirstDayOfAccountingPeriod; // Get a new transaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable); // If we did not succeed there is something wrong (a transaction is already dangling somewhere?) if (Transaction == null) { throw new Exception(Catalog.GetString( "Could not create a new import transaction because an existing transaction has not completed.")); } // Load supplementary tables that we are going to need for validation ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(FLedgerNumber, Transaction); ACostCentreTable CostCentreTable = ACostCentreAccess.LoadViaALedger(FLedgerNumber, Transaction); AMotivationGroupTable MotivationGroupTable = AMotivationGroupAccess.LoadViaALedger(FLedgerNumber, Transaction); AMotivationDetailTable MotivationDetailTable = AMotivationDetailAccess.LoadViaALedger(FLedgerNumber, Transaction); AMethodOfGivingTable MethodOfGivingTable = AMethodOfGivingAccess.LoadAll(Transaction); AMethodOfPaymentTable MethodOfPaymentTable = AMethodOfPaymentAccess.LoadAll(Transaction); AGiftBatchTable giftBatchTable = AGiftBatchAccess.LoadViaALedger(FLedgerNumber, Transaction); DataView giftBatchDV = new DataView(giftBatchTable, String.Format("{0}={1}", AGiftBatchTable.GetBatchNumberDBName(), AGiftBatchNumber), "", DataViewRowState.CurrentRows); FMainDS.AGiftBatch.ImportRow(giftBatchDV[0].Row); FMainDS.AcceptChanges(); AGiftBatchRow giftBatch = (AGiftBatchRow)FMainDS.AGiftBatch.Rows.Find(new object[] { FLedgerNumber, AGiftBatchNumber }); if (LedgerTable.Rows.Count == 0) { throw new Exception(String.Format(Catalog.GetString("Ledger {0} doesn't exist."), FLedgerNumber)); } ImportMessage = Catalog.GetString("Parsing first line"); AGiftRow previousGift = null; // Go round a loop reading the file line by line FImportLine = sr.ReadLine(); while (FImportLine != null) { RowNumber++; TextProcessedLength += (FImportLine.Length + FNewLine.Length); PercentDone = 10 + ((TextProcessedLength * 90) / InitialTextLength); // skip empty lines and commented lines if ((FImportLine.Trim().Length > 0) && !FImportLine.StartsWith("/*") && !FImportLine.StartsWith("#")) { // number of elements is incremented by 1 as though the line started with 'T' int numberOfElements = StringHelper.GetCSVList(FImportLine, FDelimiter).Count + 1; // It is a Transaction row if (numberOfElements < 13) // Perhaps this CSV file is a summary, and can't be imported? { AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, RowNumber), Catalog.GetString("Wrong number of gift columns. Expected at least 13 columns. (This may be a summary?)"), TResultSeverity.Resv_Critical)); FImportLine = sr.ReadLine(); if (FImportLine != null) { TextProcessedLength += (FImportLine.Length + FNewLine.Length); } continue; } // Parse the line into a new row ImportMessage = Catalog.GetString("Parsing transaction line"); AGiftRow gift = FMainDS.AGift.NewRowTyped(true); AGiftDetailRow giftDetails; ParseTransactionLine(gift, giftBatch, ref previousGift, numberOfElements, ref totalBatchAmount, ref ImportMessage, RowNumber, AMessages, ValidationControlsDictGift, ValidationControlsDictGiftDetail, CostCentreTable, MotivationGroupTable, MotivationDetailTable, MethodOfGivingTable, MethodOfPaymentTable, ref ANeedRecipientLedgerNumber, out giftDetails); if (TaxDeductiblePercentageEnabled) { // Sets TaxDeductiblePct and uses it to calculate the tax deductibility amounts for a Gift Detail TGift.SetDefaultTaxDeductibilityData(ref giftDetails, gift.DateEntered, Transaction); } } if (AMessages.Count > 100) { // This probably means that it is a big file and the user has made the same mistake many times over break; } // Update progress tracker every few percent if ((PercentDone - PreviousPercentDone) > 3) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), String.Format(Catalog.GetString("Importing row {0}"), RowNumber), (PercentDone > 98) ? 98 : PercentDone); PreviousPercentDone = PercentDone; } // Read the next line FImportLine = sr.ReadLine(); if (FImportLine != null) { TextProcessedLength += (FImportLine.Length + FNewLine.Length); } } // while CSV lines // Finished reading the file - did we have critical errors? if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages)) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Batch has critical errors"), 100); // Record error count AMessages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, String.Format(Catalog.GetString("{0} messages reported."), AMessages.Count), TResultSeverity.Resv_Info)); if (FImportLine == null) { // We did reach the end of the file AMessages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, Catalog.GetString( "Reached the end of file but errors occurred. When these errors are fixed the batch will import successfully."), TResultSeverity.Resv_Info)); } else { // We gave up before the end AMessages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, Catalog.GetString( "Stopped reading the file after generating more than 100 messages. The file may contian more errors beyond the ones listed here."), TResultSeverity.Resv_Info)); } TLogging.Log("Return from here!"); // we do not want to think about Gift Destination problems if the import has failed for another reason ANeedRecipientLedgerNumber.Clear(); // Do the 'finally' actions and return false return false; } // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination then the import will fail if (ANeedRecipientLedgerNumber.Rows.Count > 0) { // Do the 'finally' actions and return false return false; } // Everything is ok, so we can do our finish actions //Update batch total for the last batch entered. if (giftBatch != null) { giftBatch.BatchTotal = totalBatchAmount; } TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Saving all data into the database"), 100); //Finally save pending changes (the last number is updated !) ImportMessage = Catalog.GetString("Saving gift batch"); AGiftBatchAccess.SubmitChanges(FMainDS.AGiftBatch, Transaction); FMainDS.AGiftBatch.AcceptChanges(); ImportMessage = Catalog.GetString("Saving gifts"); AGiftAccess.SubmitChanges(FMainDS.AGift, Transaction); FMainDS.AGift.AcceptChanges(); ImportMessage = Catalog.GetString("Saving giftdetails"); AGiftDetailAccess.SubmitChanges(FMainDS.AGiftDetail, Transaction); FMainDS.AGiftDetail.AcceptChanges(); ImportMessage = Catalog.GetString("Saving ledger"); ALedgerAccess.SubmitChanges(LedgerTable, Transaction); LedgerTable.AcceptChanges(); // Commit the transaction (we know that we got a new one and can control it) DBAccess.GDBAccessObj.CommitTransaction(); ok = true; } catch (Exception ex) { // Parse the exception text for possible references to database foreign keys // Make the message more friendly in that case string friendlyExceptionText = MakeFriendlyFKExceptions(ex); if (AMessages == null) { AMessages = new TVerificationResultCollection(); } if (RowNumber > 0) { // At least we made a start string msg = ImportMessage; if (friendlyExceptionText.Length > 0) { msg += FNewLine + friendlyExceptionText; } if (ImportMessage.StartsWith(Catalog.GetString("Saving "))) { // Do not display any specific line number because these errors occur outside the parsing loop AMessages.Add(new TVerificationResult(MCommonConstants.StrExceptionWhileSavingTransactions, msg, TResultSeverity.Resv_Critical)); } else { AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrExceptionWhileParsingLine, RowNumber), msg, TResultSeverity.Resv_Critical)); } } else { // We got an exception before we even started parsing the rows (getting a transaction?) AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrExceptionWhileParsingLine, RowNumber), friendlyExceptionText, TResultSeverity.Resv_Critical)); } TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Exception Occurred"), 0); ok = false; } finally { try { sr.Close(); } catch (Exception Exc) { TLogging.Log("An Exception occured while closing the Import File:" + Environment.NewLine + Exc.ToString()); if (AMessages == null) { AMessages = new TVerificationResultCollection(); } AMessages.Add(new TVerificationResult(Catalog.GetString("Import exception"), Catalog.GetString("A problem was encountered while closing the Import File:"), TResultSeverity.Resv_Critical)); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Exception Occurred"), 0); TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); throw; } if (ok) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Gift batch import successful"), 100); } else { DBAccess.GDBAccessObj.RollbackTransaction(); if (AMessages == null) { AMessages = new TVerificationResultCollection(); } AMessages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, Catalog.GetString("None of the data from the import was saved."), TResultSeverity.Resv_Critical)); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Data could not be saved."), 0); } TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); } // end of 'finally' return ok; }
/// <summary> /// Clear the gift data of the current batch without marking records for delete /// </summary> private bool RefreshBatchGiftData(Int32 ABatchNumber, bool AAcceptChanges = false, bool AHandleDataSetBackup = false) { bool RetVal = false; //Copy and backup the current dataset GiftBatchTDS BackupDS = null; GiftBatchTDS TempDS = (GiftBatchTDS)FMainDS.Copy(); TempDS.Merge(FMainDS); if (AHandleDataSetBackup) { BackupDS = (GiftBatchTDS)FMainDS.GetChangesTyped(false); } try { this.Cursor = Cursors.WaitCursor; //Remove current batch gift data DataView giftDetailView = new DataView(TempDS.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(TempDS.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(); } TempDS.AcceptChanges(); //Clear all gift data from Main dataset gift tables FMainDS.AGiftDetail.Clear(); FMainDS.AGift.Clear(); //Bring data back in from other batches if it exists if (TempDS.AGift.Count > 0) { FMainDS.AGift.Merge(TempDS.AGift); FMainDS.AGiftDetail.Merge(TempDS.AGiftDetail); } //TODO: Confirm I need to AcceptChanges FMainDS.Merge(TRemote.MFinance.Gift.WebConnectors.LoadGiftTransactionsForBatch(FLedgerNumber, ABatchNumber)); if (AAcceptChanges) { FMainDS.AcceptChanges(); } RetVal = true; } catch (Exception ex) { //If not revert on error then calling method will if (AHandleDataSetBackup) { RevertDataSet(FMainDS, BackupDS); } TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { this.Cursor = Cursors.Default; } return(RetVal); }
public void UpdateRecord() { TDBTransaction ReadTransaction = null; GiftBatchTDS MainDS = new GiftBatchTDS(); DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction( IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref ReadTransaction, delegate { ALedgerAccess.LoadAll(MainDS, ReadTransaction); }); MainDS.ALedger[0].LastGiftBatchNumber++; AGiftBatchRow batch = MainDS.AGiftBatch.NewRowTyped(); batch.LedgerNumber = MainDS.ALedger[0].LedgerNumber; batch.BatchNumber = MainDS.ALedger[0].LastGiftBatchNumber; batch.BankAccountCode = "6000"; batch.BatchYear = 0; batch.BatchPeriod = 1; batch.CurrencyCode = "EUR"; batch.BatchDescription = "test"; batch.BankCostCentre = (MainDS.ALedger[0].LedgerNumber * 100).ToString("0000"); batch.LastGiftNumber = 0; batch.HashTotal = 83; MainDS.AGiftBatch.Rows.Add(batch); GiftBatchTDSAccess.SubmitChanges(MainDS); MainDS.AcceptChanges(); MainDS.AGiftBatch[0].BatchDescription = "test2"; GiftBatchTDSAccess.SubmitChanges(MainDS); TDBTransaction transaction = DBAccess.GDBAccessObj.BeginTransaction(); AGiftBatchTable batches = AGiftBatchAccess.LoadByPrimaryKey(batch.LedgerNumber, batch.BatchNumber, transaction); DBAccess.GDBAccessObj.RollbackTransaction(); // some problems with sqlite and datagrid Assert.AreEqual(typeof(decimal), batches[0][AGiftBatchTable.ColumnHashTotalId].GetType(), "type decimal"); Assert.AreEqual(83.0m, batches[0].HashTotal, "gift batch hashtotal does not equal"); }
public void TestDeleteSavedGiftBatch() { Int64 donorKey = 43005001; Int64 recipKey = 43000000; int giftTransNumber = 1; int giftTranDetailNumber = 1; decimal giftAmount = 100.50M; string motivationGroupCode = "GIFT"; string motivationDetailCode = "SUPPORT"; //Create the recurring gift batch FMainDS = TGiftTransactionWebConnector.CreateARecurringGiftBatch(FLedgerNumber); FRecurringBatchNumberToDelete = FMainDS.ARecurringGiftBatch[0].BatchNumber; //Create the recurring gift batch's single gift header ARecurringGiftRow newRow = FMainDS.ARecurringGift.NewRowTyped(true); newRow.LedgerNumber = FLedgerNumber; newRow.BatchNumber = FRecurringBatchNumberToDelete; newRow.DonorKey = donorKey; newRow.GiftTransactionNumber = giftTransNumber; newRow.LastDetailNumber = giftTransNumber; FMainDS.ARecurringGift.Rows.Add(newRow); //Create the recurring gift batch's single gift detail ARecurringGiftDetailRow newDetailRow = FMainDS.ARecurringGiftDetail.NewRowTyped(true); newDetailRow = FMainDS.ARecurringGiftDetail.NewRowTyped(true); newDetailRow.LedgerNumber = FLedgerNumber; newDetailRow.BatchNumber = FRecurringBatchNumberToDelete; newDetailRow.GiftTransactionNumber = giftTransNumber; newDetailRow.DetailNumber = giftTranDetailNumber; newDetailRow.RecipientKey = recipKey; newDetailRow.GiftAmount = giftAmount; newDetailRow.MotivationGroupCode = motivationGroupCode; newDetailRow.MotivationDetailCode = motivationDetailCode; FMainDS.ARecurringGiftDetail.Rows.Add(newDetailRow); //Save changes GiftBatchTDSAccess.SubmitChanges(FMainDS); FMainDS.AcceptChanges(); // Delete the associated recurring gift detail rows. DataView viewGiftDetail = new DataView(FMainDS.ARecurringGiftDetail); viewGiftDetail.RowFilter = string.Empty; foreach (DataRowView row in viewGiftDetail) { row.Delete(); } Assert.AreNotEqual(0, FMainDS.ARecurringGiftDetail.Rows.Count, "after deletion the row should still exist"); // Delete the associated recurring gift rows. DataView viewGift = new DataView(FMainDS.ARecurringGift); viewGift.RowFilter = string.Empty; foreach (DataRowView row in viewGift) { row.Delete(); } Assert.AreNotEqual(0, FMainDS.ARecurringGiftBatch.Rows.Count, "after deletion the batch row should still exist"); // Delete the recurring batch row. FMainDS.ARecurringGiftBatch.Rows[0].Delete(); Assert.AreNotEqual(0, FMainDS.ARecurringGiftBatch.Rows.Count, "after deletion the batch row should still exist"); //Save changes GiftBatchTDSAccess.SubmitChanges(FMainDS); }
/// <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); } 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(); //Clear gifts and details etc for current and any other loaded batches FMainDS.AGiftDetail.Clear(); FMainDS.AGift.Clear(); //Load tables afresh FMainDS.Merge(TRemote.MFinance.Gift.WebConnectors.LoadGiftTransactionsForBatch(FLedgerNumber, ACurrentBatchRow.BatchNumber)); FMainDS.AcceptChanges(); //Delete gift details for (int i = FMainDS.AGiftDetail.Count - 1; i >= 0; i--) { // if the gift detail being cancelled is a reversed gift if (FMainDS.AGiftDetail[i].ModifiedDetail && !string.IsNullOrEmpty(FMainDS.AGiftDetail[i].ModifiedDetailKey)) { ModifiedDetailKeys.Add(FMainDS.AGiftDetail[i].ModifiedDetailKey); } FMainDS.AGiftDetail[i].Delete(); } //Delete gifts for (int i = FMainDS.AGift.Count - 1; i >= 0; i--) { FMainDS.AGift[i].Delete(); } //Batch is only cancelled and never deleted ACurrentBatchRow.BatchTotal = 0; ACurrentBatchRow.BatchStatus = MFinanceConstants.BATCH_CANCELLED; // save first if (FMyForm.SaveChanges()) { TRemote.MFinance.Gift.WebConnectors.RemoveModifiedDetailOnCancel(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) { CompletionMessage = ex.Message; MessageBox.Show(CompletionMessage, "Cancellation Error", MessageBoxButtons.OK, MessageBoxIcon.Error); //Revert to previous state FMainDS.Merge(BackupMainDS); } finally { FMyForm.Cursor = Cursors.Default; } return(CancellationSuccessful); }
/// <summary> /// Import Gift Transactions from a file /// </summary> /// <param name="ARequestParams"></param> /// <param name="AImportString"></param> /// <param name="AGiftBatchNumber"></param> /// <param name="ANeedRecipientLedgerNumber"></param> /// <param name="AMessages"></param> /// <returns></returns> public bool ImportGiftTransactions( Hashtable ARequestParams, String AImportString, Int32 AGiftBatchNumber, out GiftBatchTDSAGiftDetailTable ANeedRecipientLedgerNumber, out TVerificationResultCollection AMessages ) { TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(), Catalog.GetString("Importing Gift Batches"), 100); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Initialising"), 5); GiftBatchTDSAGiftDetailTable NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable(); TVerificationResultCollection Messages = new TVerificationResultCollection(); // fix for Mono issue with out parameter: https://bugzilla.xamarin.com/show_bug.cgi?id=28196 AMessages = Messages; FMainDS = new GiftBatchTDS(); StringReader sr = new StringReader(AImportString); // Parse the supplied parameters FDelimiter = (String)ARequestParams["Delimiter"]; FLedgerNumber = (Int32)ARequestParams["ALedgerNumber"]; FDateFormatString = (String)ARequestParams["DateFormatString"]; String NumberFormat = (String)ARequestParams["NumberFormat"]; FNewLine = (String)ARequestParams["NewLine"]; // Set culture from parameters FCultureInfoNumberFormat = new CultureInfo(NumberFormat.Equals("American") ? "en-US" : "de-DE"); FCultureInfoDate = new CultureInfo("en-GB"); FCultureInfoDate.DateTimeFormat.ShortDatePattern = FDateFormatString; bool TaxDeductiblePercentageEnabled = Convert.ToBoolean( TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE")); // Initialise our working variables decimal totalBatchAmount = 0; Boolean CancelledByUser = false; string ImportMessage = Catalog.GetString("Initialising"); // This needs to be initialised because we will be calling the method TSharedFinanceValidationHelper.GetValidPeriodDatesDelegate = @TAccountingPeriodsWebConnector.GetPeriodDates; TSharedFinanceValidationHelper.GetFirstDayOfAccountingPeriodDelegate = @TAccountingPeriodsWebConnector.GetFirstDayOfAccountingPeriod; TDBTransaction Transaction = null; bool SubmissionOK = false; Int32 RowNumber = 0; DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref SubmissionOK, delegate { try { // Load supplementary tables that we are going to need for validation ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(FLedgerNumber, Transaction); ACostCentreTable CostCentreTable = ACostCentreAccess.LoadViaALedger(FLedgerNumber, Transaction); AAccountTable AccountTable = AAccountAccess.LoadViaALedger(FLedgerNumber, Transaction); AMotivationGroupTable MotivationGroupTable = AMotivationGroupAccess.LoadViaALedger(FLedgerNumber, Transaction); AMotivationDetailTable MotivationDetailTable = AMotivationDetailAccess.LoadViaALedger(FLedgerNumber, Transaction); AMethodOfGivingTable MethodOfGivingTable = AMethodOfGivingAccess.LoadAll(Transaction); AMethodOfPaymentTable MethodOfPaymentTable = AMethodOfPaymentAccess.LoadAll(Transaction); PMailingTable MailingTable = PMailingAccess.LoadAll(Transaction); PFormTable MailingFormTable = TFormTemplatesWebConnector.GetPartnerForms(); AGiftBatchTable giftBatchTable = AGiftBatchAccess.LoadByPrimaryKey(FLedgerNumber, AGiftBatchNumber, Transaction); FMainDS.AGiftBatch.ImportRow(giftBatchTable[0]); FMainDS.AcceptChanges(); AGiftBatchRow giftBatch = FMainDS.AGiftBatch[0]; if (LedgerTable.Rows.Count == 0) { throw new Exception(String.Format(Catalog.GetString("Ledger {0} doesn't exist."), FLedgerNumber)); } string LedgerBaseCurrency = ((ALedgerRow)LedgerTable.Rows[0]).BaseCurrency; string LedgerIntlCurrency = ((ALedgerRow)LedgerTable.Rows[0]).IntlCurrency; decimal intlRateFromBase = -1.0m; DateTime firstOfMonth; if (TSharedFinanceValidationHelper.GetFirstDayOfAccountingPeriod(FLedgerNumber, giftBatch.GlEffectiveDate, out firstOfMonth)) { intlRateFromBase = TExchangeRateTools.GetCorporateExchangeRate(LedgerBaseCurrency, LedgerIntlCurrency, firstOfMonth, giftBatch.GlEffectiveDate); } ImportMessage = Catalog.GetString("Parsing first line"); AGiftRow previousGift = null; // Go round a loop reading the file line by line FImportLine = sr.ReadLine(); Boolean ImportingEsr = false; Int32 PercentDone = 10; Int32 PreviousPercentDone = 0; Int32 InitialTextLength = AImportString.Length; Int32 totalRows = AImportString.Split('\n').Length; TValidationControlsDict EmptyControlsDict = new TValidationControlsDict(); while (FImportLine != null) { RowNumber++; PercentDone = 10 + ((RowNumber * 90) / totalRows); // skip empty lines and commented lines if ((FImportLine.Trim().Length > 0) && !FImportLine.StartsWith("/*") && !FImportLine.StartsWith("#")) { // number of elements is incremented by 1 as though the line started with 'T' int numberOfElements = StringHelper.GetCSVList(FImportLine, FDelimiter).Count + 1; Boolean IsEsrString = false; if (numberOfElements == 2) { IsEsrString = ((FImportLine.Trim().Length == 100) && (FImportLine.Substring(53, 2) == " ")); } if (ImportingEsr && !IsEsrString) // I did previously succeed with ESR, but now not so much - { // I'm probably at the last line of the file. FImportLine = sr.ReadLine(); continue; } if (!IsEsrString) { // It is a Transaction row if (numberOfElements < 13) // Perhaps this CSV file is a summary, and can't be imported? { Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, RowNumber), Catalog.GetString( "Wrong number of gift columns. Expected at least 13 columns. (This may be a summary?)"), TResultSeverity.Resv_Critical)); FImportLine = sr.ReadLine(); continue; } } // Parse the line into a new row ImportMessage = Catalog.GetString("Parsing transaction line"); Int32 preParseMessageCount = Messages.Count; AGiftRow gift = FMainDS.AGift.NewRowTyped(true); AGiftDetailRow giftDetails = FMainDS.AGiftDetail.NewRowTyped(true); if (IsEsrString) { ImportingEsr = ParseEsrTransactionLine( FImportLine, giftBatch, gift, giftDetails, intlRateFromBase, MotivationDetailTable, NeedRecipientLedgerNumber, Messages ); } else { ParseTransactionLine(gift, giftBatch, ref previousGift, numberOfElements, ref totalBatchAmount, ref ImportMessage, RowNumber, intlRateFromBase, Messages, MotivationDetailTable, NeedRecipientLedgerNumber, giftDetails); } if (Messages.Count == preParseMessageCount) // No parsing errors so we can validate { // (parsing errors will have assumed, probably invalid, values) ImportMessage = Catalog.GetString("Validating the gift data"); int messageCountBeforeValidate = preParseMessageCount; TPartnerClass RecipientClass; string RecipientDescription; TPartnerServerLookups.GetPartnerShortName(giftDetails.RecipientKey, out RecipientDescription, out RecipientClass); // Do our standard validation on this gift AGiftValidation.Validate(this, gift, ref Messages, EmptyControlsDict); TSharedFinanceValidation_Gift.ValidateGiftManual(this, gift, giftBatch.BatchYear, giftBatch.BatchPeriod, null, ref Messages, EmptyControlsDict, MethodOfGivingTable, MethodOfPaymentTable, MailingFormTable); ImportMessage = Catalog.GetString("Validating the gift details data"); AGiftDetailValidation.Validate(this, giftDetails, ref Messages, EmptyControlsDict); TSharedFinanceValidation_Gift.ValidateGiftDetailManual(this, (GiftBatchTDSAGiftDetailRow)giftDetails, ref Messages, EmptyControlsDict, RecipientClass, null, CostCentreTable, AccountTable, MotivationGroupTable, MotivationDetailTable, MailingTable, giftDetails.RecipientKey); // Fix up the messages for (int i = messageCountBeforeValidate; i < Messages.Count; i++) { ((TVerificationResult)Messages[i]).OverrideResultContext(String.Format(MCommonConstants. StrValidationErrorInLine, RowNumber)); if (Messages[i] is TScreenVerificationResult) { TVerificationResult downgrade = new TVerificationResult((TScreenVerificationResult)Messages[i]); Messages.RemoveAt(i); Messages.Insert(i, downgrade); } } } if (TaxDeductiblePercentageEnabled) { // Sets TaxDeductiblePct and uses it to calculate the tax deductibility amounts for a Gift Detail TGift.SetDefaultTaxDeductibilityData(ref giftDetails, gift.DateEntered, Transaction); } } if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true) { CancelledByUser = true; break; } if (Messages.HasCriticalErrors && (Messages.Count > 100)) { // This probably means that it is a big file and the user has made the same mistake many times over break; } // Update progress tracker every few percent if ((PercentDone - PreviousPercentDone) > 3) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), String.Format(Catalog.GetString("Importing row {0}"), RowNumber), (PercentDone > 98) ? 98 : PercentDone); PreviousPercentDone = PercentDone; } // Read the next line FImportLine = sr.ReadLine(); } // while CSV lines if (CancelledByUser) { Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, String.Format(Catalog.GetString("{0} messages reported."), Messages.Count), TResultSeverity.Resv_Info)); Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, "The import was cancelled by the user.", TResultSeverity.Resv_Info)); return; } // Finished reading the file - did we have critical errors? if (!TVerificationHelper.IsNullOrOnlyNonCritical(Messages)) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Batch has critical errors"), 100); // Record error count Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, String.Format(Catalog.GetString("{0} messages reported."), Messages.Count), TResultSeverity.Resv_Info)); if (FImportLine == null) { // We did reach the end of the file Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, Catalog.GetString( "Reached the end of file but errors occurred. When these errors are fixed the batch will import successfully."), TResultSeverity.Resv_Info)); } else { // We gave up before the end Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, Catalog.GetString( "Stopped reading the file after generating more than 100 messages. The file may contian more errors beyond the ones listed here."), TResultSeverity.Resv_Info)); } // we do not want to think about Gift Destination problems if the import has failed for another reason NeedRecipientLedgerNumber.Clear(); // Do the 'finally' actions and return false return; } // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination then the import will fail if (NeedRecipientLedgerNumber.Rows.Count > 0) { // Do the 'finally' actions and return false return; } // Everything is ok, so we can do our finish actions //Update batch total for the last batch entered. if ((giftBatch != null) && !ImportingEsr) { giftBatch.BatchTotal = totalBatchAmount; } TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Saving all data into the database"), 100); //Finally save pending changes (the last number is updated !) ImportMessage = Catalog.GetString("Saving gift batch"); AGiftBatchAccess.SubmitChanges(FMainDS.AGiftBatch, Transaction); FMainDS.AGiftBatch.AcceptChanges(); ImportMessage = Catalog.GetString("Saving gifts"); AGiftAccess.SubmitChanges(FMainDS.AGift, Transaction); FMainDS.AGift.AcceptChanges(); ImportMessage = Catalog.GetString("Saving giftdetails"); AGiftDetailAccess.SubmitChanges(FMainDS.AGiftDetail, Transaction); FMainDS.AGiftDetail.AcceptChanges(); ImportMessage = Catalog.GetString("Saving ledger"); ALedgerAccess.SubmitChanges(LedgerTable, Transaction); LedgerTable.AcceptChanges(); // Commit the transaction (we know that we got a new one and can control it) SubmissionOK = true; } catch (Exception ex) { // Parse the exception text for possible references to database foreign keys // Make the message more friendly in that case string friendlyExceptionText = MakeFriendlyFKExceptions(ex); if (RowNumber > 0) { // At least we made a start string msg = ImportMessage; if (friendlyExceptionText.Length > 0) { msg += FNewLine + friendlyExceptionText; } if (ImportMessage.StartsWith(Catalog.GetString("Saving "))) { // Do not display any specific line number because these errors occur outside the parsing loop Messages.Add(new TVerificationResult(MCommonConstants.StrExceptionWhileSavingTransactions, msg, TResultSeverity.Resv_Critical)); } else { Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrExceptionWhileParsingLine, RowNumber), msg, TResultSeverity.Resv_Critical)); } } else { // We got an exception before we even started parsing the rows (getting a transaction?) Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrExceptionWhileParsingLine, RowNumber), friendlyExceptionText, TResultSeverity.Resv_Critical)); } TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Exception Occurred"), 0); SubmissionOK = false; } finally { sr.Close(); if (SubmissionOK) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Gift batch import successful"), 100); } else { Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, Catalog.GetString("None of the data from the import was saved."), TResultSeverity.Resv_Critical)); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Data could not be saved."), 0); } TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); } // end of 'finally' }); // Set our 'out' parameters ANeedRecipientLedgerNumber = NeedRecipientLedgerNumber; AMessages = Messages; return SubmissionOK; }
public static GiftBatchTDS LoadAGiftBatchForYearPeriod(Int32 ALedgerNumber, Int32 AYear, Int32 APeriod) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } #endregion Validate Arguments string FilterByPeriod = string.Empty; GiftBatchTDS MainDS = new GiftBatchTDS(); TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { //Load Ledger table ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); #region Validate Data if ((MainDS.ALedger == null) || (MainDS.ALedger.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Details for Ledger {1} could not be accessed!"), Utilities.GetMethodSignature(), ALedgerNumber)); } #endregion Validate Data if (AYear > -1) { FilterByPeriod = String.Format(" AND PUB_{0}.{1} = {2}", AGiftBatchTable.GetTableDBName(), AGiftBatchTable.GetBatchYearDBName(), AYear); if ((APeriod == 0) && (AYear == MainDS.ALedger[0].CurrentFinancialYear)) { //Return current and forwarding periods FilterByPeriod += String.Format(" AND PUB_{0}.{1} >= {2}", AGiftBatchTable.GetTableDBName(), AGiftBatchTable.GetBatchPeriodDBName(), MainDS.ALedger[0].CurrentPeriod); } else if (APeriod > 0) { //Return only specified period FilterByPeriod += String.Format(" AND PUB_{0}.{1} = {2}", AGiftBatchTable.GetTableDBName(), AGiftBatchTable.GetBatchPeriodDBName(), APeriod); } else { //Nothing to add, returns all periods } } string SelectClause = String.Format("SELECT * FROM PUB_{0} WHERE {1} = {2}", AGiftBatchTable.GetTableDBName(), AGiftBatchTable.GetLedgerNumberDBName(), ALedgerNumber); DBAccess.GDBAccessObj.Select(MainDS, SelectClause + FilterByPeriod, MainDS.AGiftBatch.TableName, Transaction); }); MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
public static GiftBatchTDS LoadAGiftBatchSingle(Int32 ALedgerNumber, Int32 ABatchNumber) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } #endregion Validate Arguments GiftBatchTDS MainDS = new GiftBatchTDS(); TDBTransaction Transaction = null; DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { MainDS = LoadAGiftBatchSingle(ALedgerNumber, ABatchNumber, ref Transaction); }); MainDS.AcceptChanges(); return MainDS; }
public static GiftBatchTDS LoadAGiftBatchesForCurrentYearPeriod(Int32 ALedgerNumber) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } #endregion Validate Arguments GiftBatchTDS MainDS = new GiftBatchTDS(); TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); #region Validate Data if ((MainDS.ALedger == null) || (MainDS.ALedger.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } #endregion Validate Data string SelectClause = String.Format("SELECT * FROM PUB_{0} WHERE {1} = {2} AND PUB_{0}.{3} = {4} AND PUB_{0}.{5} >= {6}", AGiftBatchTable.GetTableDBName(), AGiftBatchTable.GetLedgerNumberDBName(), ALedgerNumber, AGiftBatchTable.GetBatchYearDBName(), MainDS.ALedger[0].CurrentFinancialYear, AGiftBatchTable.GetBatchPeriodDBName(), MainDS.ALedger[0].CurrentPeriod); DBAccess.GDBAccessObj.Select(MainDS, SelectClause, MainDS.AGiftBatch.TableName, Transaction); }); MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
public static void SubmitRecurringGiftBatch(Hashtable requestParams) { GiftBatchTDS GMainDS = new GiftBatchTDS(); Int32 ALedgerNumber = (Int32)requestParams["ALedgerNumber"]; Int32 ABatchNumber = (Int32)requestParams["ABatchNumber"]; DateTime AEffectiveDate = (DateTime)requestParams["AEffectiveDate"]; Decimal AExchangeRateToBase = (Decimal)requestParams["AExchangeRateToBase"]; Decimal AExchangeRateIntlToBase = (Decimal)requestParams["AExchangeRateIntlToBase"]; bool TaxDeductiblePercentageEnabled = Convert.ToBoolean( TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE")); bool TransactionInIntlCurrency = false; int NewGiftBatchNumber = -1; GiftBatchTDS RMainDS = LoadRecurringGiftTransactionsForBatch(ALedgerNumber, ABatchNumber); TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable); try { ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction); ARecurringGiftBatchAccess.LoadByPrimaryKey(RMainDS, ALedgerNumber, ABatchNumber, Transaction); // Assuming all relevant data is loaded in RMainDS foreach (ARecurringGiftBatchRow recBatch in RMainDS.ARecurringGiftBatch.Rows) { if ((recBatch.BatchNumber == ABatchNumber) && (recBatch.LedgerNumber == ALedgerNumber)) { Decimal batchTotal = 0; AGiftBatchRow batch = TGiftBatchFunctions.CreateANewGiftBatchRow(ref GMainDS, ref Transaction, ref LedgerTable, ALedgerNumber, AEffectiveDate); NewGiftBatchNumber = batch.BatchNumber; batch.BatchDescription = recBatch.BatchDescription; batch.BankCostCentre = recBatch.BankCostCentre; batch.BankAccountCode = recBatch.BankAccountCode; batch.ExchangeRateToBase = AExchangeRateToBase; batch.MethodOfPaymentCode = recBatch.MethodOfPaymentCode; batch.GiftType = recBatch.GiftType; batch.HashTotal = recBatch.HashTotal; batch.CurrencyCode = recBatch.CurrencyCode; TransactionInIntlCurrency = (batch.CurrencyCode == LedgerTable[0].IntlCurrency); foreach (ARecurringGiftRow recGift in RMainDS.ARecurringGift.Rows) { if ((recGift.BatchNumber == ABatchNumber) && (recGift.LedgerNumber == ALedgerNumber) && recGift.Active) { //Look if there is a detail which is in the donation period (else continue) bool foundDetail = false; foreach (ARecurringGiftDetailRow recGiftDetail in RMainDS.ARecurringGiftDetail.Rows) { if ((recGiftDetail.GiftTransactionNumber == recGift.GiftTransactionNumber) && (recGiftDetail.BatchNumber == ABatchNumber) && (recGiftDetail.LedgerNumber == ALedgerNumber) && ((recGiftDetail.StartDonations == null) || (AEffectiveDate >= recGiftDetail.StartDonations)) && ((recGiftDetail.EndDonations == null) || (AEffectiveDate <= recGiftDetail.EndDonations)) ) { foundDetail = true; break; } } if (!foundDetail) { continue; } // make the gift from recGift AGiftRow gift = GMainDS.AGift.NewRowTyped(); gift.LedgerNumber = batch.LedgerNumber; gift.BatchNumber = batch.BatchNumber; gift.GiftTransactionNumber = ++batch.LastGiftNumber; gift.DonorKey = recGift.DonorKey; gift.MethodOfGivingCode = recGift.MethodOfGivingCode; gift.DateEntered = AEffectiveDate; if (gift.MethodOfGivingCode.Length == 0) { gift.SetMethodOfGivingCodeNull(); } gift.MethodOfPaymentCode = recGift.MethodOfPaymentCode; if (gift.MethodOfPaymentCode.Length == 0) { gift.SetMethodOfPaymentCodeNull(); } gift.Reference = recGift.Reference; gift.ReceiptLetterCode = recGift.ReceiptLetterCode; GMainDS.AGift.Rows.Add(gift); //TODO (not here, but in the client or while posting) Check for Ex-OM Partner //TODO (not here, but in the client or while posting) Check for expired key ministry (while Posting) foreach (ARecurringGiftDetailRow recGiftDetail in RMainDS.ARecurringGiftDetail.Rows) { //decimal amtIntl = 0M; decimal amtBase = 0M; decimal amtTrans = 0M; if ((recGiftDetail.GiftTransactionNumber == recGift.GiftTransactionNumber) && (recGiftDetail.BatchNumber == ABatchNumber) && (recGiftDetail.LedgerNumber == ALedgerNumber) && ((recGiftDetail.StartDonations == null) || (recGiftDetail.StartDonations <= AEffectiveDate)) && ((recGiftDetail.EndDonations == null) || (recGiftDetail.EndDonations >= AEffectiveDate)) ) { AGiftDetailRow detail = GMainDS.AGiftDetail.NewRowTyped(); detail.LedgerNumber = gift.LedgerNumber; detail.BatchNumber = gift.BatchNumber; detail.GiftTransactionNumber = gift.GiftTransactionNumber; detail.DetailNumber = ++gift.LastDetailNumber; amtTrans = recGiftDetail.GiftAmount; detail.GiftTransactionAmount = amtTrans; batchTotal += amtTrans; amtBase = GLRoutines.Divide((decimal)amtTrans, AExchangeRateToBase); detail.GiftAmount = amtBase; if (!TransactionInIntlCurrency) { detail.GiftAmountIntl = GLRoutines.Divide((decimal)amtBase, AExchangeRateIntlToBase); } else { detail.GiftAmountIntl = amtTrans; } detail.RecipientKey = recGiftDetail.RecipientKey; detail.RecipientLedgerNumber = recGiftDetail.RecipientLedgerNumber; detail.ChargeFlag = recGiftDetail.ChargeFlag; detail.ConfidentialGiftFlag = recGiftDetail.ConfidentialGiftFlag; detail.TaxDeductible = recGiftDetail.TaxDeductible; detail.MailingCode = recGiftDetail.MailingCode; if (detail.MailingCode.Length == 0) { detail.SetMailingCodeNull(); } detail.MotivationGroupCode = recGiftDetail.MotivationGroupCode; detail.MotivationDetailCode = recGiftDetail.MotivationDetailCode; detail.GiftCommentOne = recGiftDetail.GiftCommentOne; detail.CommentOneType = recGiftDetail.CommentOneType; detail.GiftCommentTwo = recGiftDetail.GiftCommentTwo; detail.CommentTwoType = recGiftDetail.CommentTwoType; detail.GiftCommentThree = recGiftDetail.GiftCommentThree; detail.CommentThreeType = recGiftDetail.CommentThreeType; if (TaxDeductiblePercentageEnabled) { // Sets TaxDeductiblePct and uses it to calculate the tax deductibility amounts for a Gift Detail TGift.SetDefaultTaxDeductibilityData(ref detail, gift.DateEntered, Transaction); } GMainDS.AGiftDetail.Rows.Add(detail); } } batch.BatchTotal = batchTotal; } } } } AGiftBatchAccess.SubmitChanges(GMainDS.AGiftBatch, Transaction); ALedgerAccess.SubmitChanges(LedgerTable, Transaction); AGiftAccess.SubmitChanges(GMainDS.AGift, Transaction); AGiftDetailAccess.SubmitChanges(GMainDS.AGiftDetail, Transaction); DBAccess.GDBAccessObj.CommitTransaction(); GMainDS.AcceptChanges(); } catch (Exception Exc) { TLogging.Log("An Exception occured during the submission of a Recurring Gift Batch:" + Environment.NewLine + Exc.ToString()); DBAccess.GDBAccessObj.RollbackTransaction(); GMainDS.RejectChanges(); throw; } }
/// <summary> /// Method to cancel a specified batch /// </summary> /// <param name="ACurrentBatchRow"></param> /// <returns></returns> public bool CancelBatch(AGiftBatchRow ACurrentBatchRow) { string CancelMessage = string.Empty; string CompletionMessage = string.Empty; string ExistingBatchStatus = string.Empty; decimal ExistingBatchTotal = 0; List <string> ModifiedDetailKeys = new List <string>(); if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)) { return(false); } 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(false); } // first save any changes if (!FMyForm.SaveChangesManual(TExtraGiftBatchChecks.GiftBatchAction.CANCELLING)) { return(false); } try { //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); ExistingBatchTotal = ACurrentBatchRow.BatchTotal; ExistingBatchStatus = ACurrentBatchRow.BatchStatus; //Load all journals for current Batch //clear any transactions currently being editied in the Transaction Tab FMyForm.GetTransactionsControl().ClearCurrentSelection(); //Clear gifts and details etc for current Batch FMainDS.AGiftDetail.Clear(); FMainDS.AGift.Clear(); //Load tables afresh FMainDS.Merge(TRemote.MFinance.Gift.WebConnectors.LoadGiftTransactionsForBatch(FLedgerNumber, ACurrentBatchRow.BatchNumber)); FMainDS.AcceptChanges(); //Delete gift details for (int i = FMainDS.AGiftDetail.Count - 1; i >= 0; i--) { // if the gift detail being cancelled is a reversed gift if (FMainDS.AGiftDetail[i].ModifiedDetail && !string.IsNullOrEmpty(FMainDS.AGiftDetail[i].ModifiedDetailKey)) { ModifiedDetailKeys.Add(FMainDS.AGiftDetail[i].ModifiedDetailKey); } FMainDS.AGiftDetail[i].Delete(); } //Delete gifts for (int i = FMainDS.AGift.Count - 1; i >= 0; i--) { FMainDS.AGift[i].Delete(); } //Batch is only cancelled and never deleted ACurrentBatchRow.BeginEdit(); ACurrentBatchRow.BatchTotal = 0; ACurrentBatchRow.BatchStatus = MFinanceConstants.BATCH_CANCELLED; ACurrentBatchRow.EndEdit(); FPetraUtilsObject.HasChanges = true; // save first, then post if (!FMyForm.SaveChanges()) { ACurrentBatchRow.BeginEdit(); //Should normally be Unposted, but allow for other status values in future ACurrentBatchRow.BatchTotal = ExistingBatchTotal; ACurrentBatchRow.BatchStatus = ExistingBatchStatus; ACurrentBatchRow.EndEdit(); // saving failed, therefore do not try to cancel MessageBox.Show(Catalog.GetString("The cancelled batch failed to save!")); } else { TRemote.MFinance.Gift.WebConnectors.RemoveModifiedDetailOnCancel(FLedgerNumber, ModifiedDetailKeys); MessageBox.Show(CompletionMessage, "Batch Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { CompletionMessage = ex.Message; MessageBox.Show(ex.Message, "Cancellation Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(false); }
public static GiftBatchTDS LoadRecurringGiftTransactionsForBatch(Int32 ALedgerNumber, Int32 ABatchNumber) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } #endregion Validate Arguments GiftBatchTDS MainDS = new GiftBatchTDS(); try { MainDS = LoadARecurringGiftBatchAndRelatedData(ALedgerNumber, ABatchNumber); #region Validate Data if ((MainDS == null) || (MainDS.Tables.Count == 0)) { throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString( "Function:{0} - Dataset MainDS is NULL or has no tables!"), Utilities.GetMethodName(true), ALedgerNumber)); } #endregion Validate Data // drop all tables apart from ARecurringGift and ARecurringGiftDetail foreach (DataTable table in MainDS.Tables) { if ((table.TableName != MainDS.ARecurringGift.TableName) && (table.TableName != MainDS.ARecurringGiftDetail.TableName)) { table.Clear(); } } MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
private static GiftBatchTDS LoadAGiftBatchSingle(Int32 ALedgerNumber, Int32 ABatchNumber, ref TDBTransaction ATransaction) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } else if (ATransaction == null) { throw new EFinanceSystemDBTransactionNullException(String.Format(Catalog.GetString( "Function:{0} - Database Transaction must not be NULL!"), Utilities.GetMethodName(true))); } #endregion Validate Arguments GiftBatchTDS MainDS = new GiftBatchTDS(); try { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ATransaction); AGiftBatchAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, ATransaction); #region Validate Data if ((MainDS.ALedger == null) || (MainDS.ALedger.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } else if ((MainDS.AGiftBatch == null) || (MainDS.AGiftBatch.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Gift Batch data for Batch {1} in Ledger number {2} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ABatchNumber, ALedgerNumber)); } #endregion Validate Data MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
public static GiftBatchTDS LoadAGiftBatchForYearPeriod(Int32 ALedgerNumber, Int32 AYear, Int32 APeriod) { GiftBatchTDS MainDS = new GiftBatchTDS(); string FilterByPeriod = string.Empty; TDBTransaction Transaction = null; DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, ref Transaction, delegate { //Load Ledger table ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); if (AYear > -1) { FilterByPeriod = String.Format(" AND PUB_{0}.{1} = {2}", AGiftBatchTable.GetTableDBName(), AGiftBatchTable.GetBatchYearDBName(), AYear); if ((APeriod == 0) && (AYear == MainDS.ALedger[0].CurrentFinancialYear)) { //Return current and forwarding periods FilterByPeriod += String.Format(" AND PUB_{0}.{1} >= {2}", AGiftBatchTable.GetTableDBName(), AGiftBatchTable.GetBatchPeriodDBName(), MainDS.ALedger[0].CurrentPeriod); } else if (APeriod > 0) { //Return only specified period FilterByPeriod += String.Format(" AND PUB_{0}.{1} = {2}", AGiftBatchTable.GetTableDBName(), AGiftBatchTable.GetBatchPeriodDBName(), APeriod); } else { //Nothing to add, returns all periods } } string SelectClause = String.Format("SELECT * FROM PUB_{0} WHERE {1} = {2}", AGiftBatchTable.GetTableDBName(), AGiftBatchTable.GetLedgerNumberDBName(), ALedgerNumber); DBAccess.GDBAccessObj.Select(MainDS, SelectClause + FilterByPeriod, MainDS.AGiftBatch.TableName, Transaction); }); MainDS.AcceptChanges(); return MainDS; }