private Boolean IsAdjustmentToReversedDetail(AGiftDetailRow ARow) { // This method returns true if the gift detail row is an unposted adjustement to a reversed gift detail // We use the LinkToPreviousGift property to discover if this gift is associated with the previous gift row. // Then we check if that row has a modifiedDetail flag sets for its first detail. if ((ARow == null) || (FBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)) { return(false); } AGiftRow giftRow = GetGiftRow(ARow.GiftTransactionNumber); if ((giftRow != null) && (giftRow.LinkToPreviousGift == true)) { if (ARow.GiftTransactionNumber > 1) { AGiftDetailRow prevDetailRow = (AGiftDetailRow)FMainDS.AGiftDetail.Rows.Find( new object[] { ARow.LedgerNumber, ARow.BatchNumber, ARow.GiftTransactionNumber - 1, 1 }); return(prevDetailRow.ModifiedDetail == true); } } return(false); }
public void TestModifyGiftBatch() { TDataBase db = DBAccess.Connect("test"); TDBTransaction t = db.BeginTransaction(IsolationLevel.Serializable); GiftBatchTDS MainDS; ALedgerAccess.LoadAll(MainDS, t); MainDS.ALedger[0].LastGiftBatchNumber++; AGiftBatchRow batch = MainDS.AGiftBatch.NewRowTyped(); batch.LedgerNumber = MainDS.ALedger[0].LedgerNumber; batch.BatchNumber = MainDS.ALedger[0].LastGiftBatchNumber; batch.BankAccountCode = "6000"; batch.BatchYear = 1; batch.BatchPeriod = 1; batch.CurrencyCode = "EUR"; batch.BankCostCentre = MainDS.ALedger[0].LedgerNumber.ToString() + "00"; batch.LastGiftNumber = 2; MainDS.AGiftBatch.Rows.Add(batch); AGiftRow gift = MainDS.AGift.NewRowTyped(); gift.LedgerNumber = batch.LedgerNumber; gift.BatchNumber = batch.BatchNumber; gift.GiftTransactionNumber = 1; MainDS.AGift.Rows.Add(gift); gift = MainDS.AGift.NewRowTyped(); gift.LedgerNumber = batch.LedgerNumber; gift.BatchNumber = batch.BatchNumber; gift.GiftTransactionNumber = 2; gift.LastDetailNumber = 1; MainDS.AGift.Rows.Add(gift); AGiftDetailRow giftdetail = MainDS.AGiftDetail.NewRowTyped(); giftdetail.LedgerNumber = gift.LedgerNumber; giftdetail.BatchNumber = gift.BatchNumber; giftdetail.GiftTransactionNumber = gift.GiftTransactionNumber; giftdetail.DetailNumber = 1; giftdetail.MotivationGroupCode = "GIFT"; giftdetail.MotivationDetailCode = "SUPPORT"; MainDS.AGiftDetail.Rows.Add(giftdetail); MainDS.SubmitChanges(t); t.Commit(); // now delete the first gift, and fix the gift detail of the second gift t = db.BeginTransaction(IsolationLevel.Serializable); MainDS.AGift.Rows.RemoveAt(0); MainDS.AGift[0].GiftTransactionNumber = 1; MainDS.AGiftDetail[0].GiftTransactionNumber = 1; MainDS.AGiftBatch[0].LastGiftNumber = 1; MainDS.SubmitChanges(t); g.Commit(); }
private void NewGift(System.Object sender, EventArgs e) { string Reference = string.Empty; //Read currently selected gift's Reference if (FPreviouslySelectedDetailRow != null) { AGiftRow giftRow = GetGiftRow(FPreviouslySelectedDetailRow.GiftTransactionNumber); if (!giftRow.IsReferenceNull()) { if (giftRow.Reference == txtDetailReference.Text) { Reference = giftRow.Reference; } else { Reference = txtDetailReference.Text; } } } CreateANewGift(true); //Copy to new record txtDetailReference.Text = Reference; }
/// <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]; } }
public static bool GetGiftsForFieldChangeAdjustment(ref GiftBatchTDS AGiftDS, Int32 ALedgerNumber, Int64 ARecipientKey, DateTime AStartDate, DateTime AEndDate, Int64 AOldField, out TVerificationResultCollection AMessages) { TDBTransaction Transaction = new TDBTransaction(); TDataBase db = DBAccess.Connect("GetGiftsForFieldChangeAdjustment"); GiftBatchTDS MainDS = new GiftBatchTDS(); AMessages = new TVerificationResultCollection(); db.ReadTransaction( ref Transaction, delegate { string SqlStmt = TDataBase.ReadSqlFile("Gift.GetGiftsToAdjustField.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); db.Select(MainDS, SqlStmt, MainDS.AGiftDetail.TableName, Transaction, parameters.ToArray()); // get additional data foreach (GiftBatchTDSAGiftDetailRow Row in MainDS.AGiftDetail.Rows) { AGiftBatchAccess.LoadByPrimaryKey(MainDS, Row.LedgerNumber, Row.BatchNumber, Transaction); AGiftRow GiftRow = AGiftAccess.LoadByPrimaryKey(MainDS, Row.LedgerNumber, Row.BatchNumber, Row.GiftTransactionNumber, Transaction); Row.DateEntered = GiftRow.DateEntered; Row.DonorKey = GiftRow.DonorKey; Row.IchNumber = 0; Row.DonorName = PPartnerAccess.LoadByPrimaryKey(Row.DonorKey, Transaction)[0].PartnerShortName; } }); AGiftDS = MainDS; db.CloseDBConnection(); return(CheckGiftsNotPreviouslyReversed(AGiftDS, out AMessages)); }
/// create new gift info public static AGiftBatchRow CreateNewGiftInfo(Int64 APartnerKey, ref GiftBatchTDS AGiftDS, TDataBase ADataBase = null) { TDataBase db = DBAccess.Connect("CreateNewGiftInfo", ADataBase); bool NewTransaction; TDBTransaction Transaction = db.GetNewOrExistingTransaction(IsolationLevel.Serializable, out NewTransaction); ALedgerAccess.LoadAll(AGiftDS, Transaction); AGiftDS = TGiftTransactionWebConnector.CreateAGiftBatch(AGiftDS.ALedger[0].LedgerNumber, DateTime.Today, "Test batch", db); // Create a new GiftBatch AGiftBatchRow Batch = AGiftDS.AGiftBatch[0]; Batch.BankAccountCode = "6000"; Batch.BatchYear = 1; Batch.BatchPeriod = 1; Batch.CurrencyCode = "EUR"; Batch.BankCostCentre = Batch.LedgerNumber.ToString() + "00"; Batch.LastGiftNumber = 1; Batch.ExchangeRateToBase = 0.5M; // Create a new Gift record AGiftRow Gift = AGiftDS.AGift.NewRowTyped(); Gift.LedgerNumber = Batch.LedgerNumber; Gift.BatchNumber = Batch.BatchNumber; Gift.GiftTransactionNumber = 1; Gift.DonorKey = APartnerKey; AGiftDS.AGift.Rows.Add(Gift); // Create a new GiftDetail record AGiftDetailRow GiftDetail = AGiftDS.AGiftDetail.NewRowTyped(); GiftDetail.LedgerNumber = Gift.LedgerNumber; GiftDetail.BatchNumber = Gift.BatchNumber; GiftDetail.GiftTransactionNumber = Gift.GiftTransactionNumber; GiftDetail.DetailNumber = 1; GiftDetail.MotivationGroupCode = "GIFT"; GiftDetail.MotivationDetailCode = "SUPPORT"; // this won't work with RecipientKey 0 anymore. see https://github.com/openpetra/openpetra/issues/183 GiftDetail.RecipientKey = 43000000; GiftDetail.RecipientLedgerNumber = APartnerKey; GiftDetail.GiftTransactionAmount = 10; AGiftDS.AGiftDetail.Rows.Add(GiftDetail); if (NewTransaction) { Transaction.Rollback(); } return(Batch); }
public static bool GetGiftsForTaxDeductiblePctAdjustment(ref GiftBatchTDS AGiftDS, Int64 ARecipientKey, DateTime ADateFrom, decimal ANewPct, out TVerificationResultCollection AMessages) { TDBTransaction Transaction = new TDBTransaction(); TDataBase db = DBAccess.Connect("GetGiftsForTaxDeductiblePctAdjustment"); GiftBatchTDS MainDS = new GiftBatchTDS(); AMessages = new TVerificationResultCollection(); db.ReadTransaction(ref Transaction, delegate { string Query = "SELECT a_gift_detail.*" + " FROM a_gift_detail, a_gift_batch" + " WHERE a_gift_detail.p_recipient_key_n = " + ARecipientKey + " AND a_gift_detail.a_tax_deductible_pct_n <> " + ANewPct + " AND a_gift_detail.a_modified_detail_l <> true" + " AND a_gift_detail.a_tax_deductible_l = true" + " AND a_gift_batch.a_ledger_number_i = a_gift_detail.a_ledger_number_i" + " AND a_gift_batch.a_batch_number_i = a_gift_detail.a_batch_number_i" + " AND a_gift_batch.a_ledger_number_i = a_gift_detail.a_ledger_number_i" + " AND a_gift_batch.a_batch_status_c = 'Posted' " + " AND a_gift_batch.a_gl_effective_date_d >= '" + ADateFrom.ToString("yyyy-MM-dd") + "'"; db.Select(MainDS, Query, MainDS.AGiftDetail.TableName, Transaction); // get additional data foreach (GiftBatchTDSAGiftDetailRow Row in MainDS.AGiftDetail.Rows) { AGiftBatchAccess.LoadByPrimaryKey(MainDS, Row.LedgerNumber, Row.BatchNumber, Transaction); AGiftRow GiftRow = AGiftAccess.LoadByPrimaryKey(MainDS, Row.LedgerNumber, Row.BatchNumber, Row.GiftTransactionNumber, Transaction); Row.DateEntered = GiftRow.DateEntered; Row.DonorKey = GiftRow.DonorKey; Row.DonorName = PPartnerAccess.LoadByPrimaryKey(Row.DonorKey, Transaction)[0].PartnerShortName; } }); AGiftDS = MainDS; return(TAdjustmentWebConnector.CheckGiftsNotPreviouslyReversed(AGiftDS, out AMessages)); }
/// <summary> /// Check if a gift is really restricted or if the user belongs to the group that is allowed /// to access the gift /// </summary> /// <param name="gift">the gift we want to check for restriction</param> /// <param name="ATransaction">A TDBTransaction object for reuse</param> /// <returns>true if the user has no permission and the gift is restricted ///</returns> public static bool GiftRestricted(AGiftRow gift, TDBTransaction ATransaction) { SGroupGiftTable GroupGiftDT; SUserGroupTable UserGroupDT; Int16 Counter; DataRow[] FoundUserGroups; if (gift.Restricted) { GroupGiftDT = SGroupGiftAccess.LoadViaAGift( gift.LedgerNumber, gift.BatchNumber, gift.GiftTransactionNumber, ATransaction); UserGroupDT = SUserGroupAccess.LoadViaSUser(UserInfo.GUserInfo.UserID, ATransaction); // Loop over all rows of GroupGiftDT for (Counter = 0; Counter <= GroupGiftDT.Rows.Count - 1; Counter += 1) { // To be able to view a Gift, ReadAccess must be granted if (GroupGiftDT[Counter].ReadAccess) { // Find out whether the user has a row in s_user_group with the // GroupID of the GroupGift row FoundUserGroups = UserGroupDT.Select(SUserGroupTable.GetGroupIdDBName() + " = '" + GroupGiftDT[Counter].GroupId + "'"); if (FoundUserGroups.Length != 0) { // The gift is not restricted because there is a read access for the group return(false); // don't evaluate further GroupGiftDT rows } } } } else { return(false); } return(true); }
/// create new gift info public static AGiftBatchRow CreateNewGiftInfo(Int64 APartnerKey, ref GiftBatchTDS AGiftDS) { ALedgerAccess.LoadAll(AGiftDS, DBAccess.GDBAccessObj.Transaction); AGiftDS = TGiftTransactionWebConnector.CreateAGiftBatch(AGiftDS.ALedger[0].LedgerNumber, DateTime.Today, "Test batch"); // Create a new GiftBatch AGiftBatchRow Batch = AGiftDS.AGiftBatch[0]; Batch.BankAccountCode = "6000"; Batch.BatchYear = 1; Batch.BatchPeriod = 1; Batch.CurrencyCode = "EUR"; Batch.BankCostCentre = Batch.LedgerNumber.ToString() + "00"; Batch.LastGiftNumber = 1; Batch.ExchangeRateToBase = 0.5M; // Create a new Gift record AGiftRow Gift = AGiftDS.AGift.NewRowTyped(); Gift.LedgerNumber = Batch.LedgerNumber; Gift.BatchNumber = Batch.BatchNumber; Gift.GiftTransactionNumber = 1; Gift.DonorKey = APartnerKey; AGiftDS.AGift.Rows.Add(Gift); // Create a new GiftDetail record AGiftDetailRow GiftDetail = AGiftDS.AGiftDetail.NewRowTyped(); GiftDetail.LedgerNumber = Gift.LedgerNumber; GiftDetail.BatchNumber = Gift.BatchNumber; GiftDetail.GiftTransactionNumber = Gift.GiftTransactionNumber; GiftDetail.DetailNumber = 1; GiftDetail.MotivationGroupCode = "GIFT"; GiftDetail.MotivationDetailCode = "SUPPORT"; GiftDetail.RecipientKey = 0; GiftDetail.RecipientLedgerNumber = APartnerKey; AGiftDS.AGiftDetail.Rows.Add(GiftDetail); return(Batch); }
private void 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; } }
void WriteGiftLine(AGiftRow gift, AGiftDetailRow giftDetails) { if (!FTransactionsOnly) { WriteStringQuoted("T"); } if (TGift.GiftRestricted(gift, FTransaction)) { WriteGeneralNumber(0); WriteStringQuoted("Confidential"); ProcessConfidentialMessage(); } else { WriteGeneralNumber(gift.DonorKey); WriteStringQuoted(PartnerShortName(gift.DonorKey)); } WriteStringQuoted(gift.MethodOfGivingCode); WriteStringQuoted(gift.MethodOfPaymentCode); WriteStringQuoted(gift.Reference); WriteStringQuoted(gift.ReceiptLetterCode); if (FExtraColumns) { WriteGeneralNumber(gift.ReceiptNumber); WriteBoolean(gift.FirstTimeGift); WriteBoolean(gift.ReceiptPrinted); } WriteGeneralNumber(giftDetails.RecipientKey); WriteStringQuoted(PartnerShortName(giftDetails.RecipientKey)); if (FExtraColumns) { WriteGeneralNumber(giftDetails.RecipientLedgerNumber); } if (FUseBaseCurrency) { WriteCurrency(giftDetails.GiftAmount); } else { WriteCurrency(giftDetails.GiftTransactionAmount); } if (FExtraColumns) { WriteCurrency(giftDetails.GiftAmountIntl); } WriteBoolean(giftDetails.ConfidentialGiftFlag); WriteStringQuoted(giftDetails.MotivationGroupCode); WriteStringQuoted(giftDetails.MotivationDetailCode); // // "In Petra Cost Centre is always inferred from recipient field and motivation detail so is not needed in the import." if (FExtraColumns) { WriteStringQuoted(giftDetails.CostCentreCode); } WriteStringQuoted(giftDetails.GiftCommentOne); WriteStringQuoted(giftDetails.CommentOneType); if (giftDetails.MailingCode.Equals("?")) { WriteStringQuoted(""); } else { WriteStringQuoted(giftDetails.MailingCode); } WriteStringQuoted(giftDetails.GiftCommentTwo); WriteStringQuoted(giftDetails.CommentTwoType); WriteStringQuoted(giftDetails.GiftCommentThree); WriteStringQuoted(giftDetails.CommentThreeType); WriteBoolean(giftDetails.IsTaxDeductibleNull() ? false : giftDetails.TaxDeductible, true); // WriteLineDate(gift.DateEntered); //Don't write this - it can't be used by import. }
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> /// 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); }
/// <summary> /// Creates a new gift or gift detail depending upon the parameter /// </summary> /// <param name="ACompletelyNewGift"></param> private void CreateANewGift(bool ACompletelyNewGift) { AGiftRow CurrentGiftRow = null; bool IsEmptyGrid = (grdDetails.Rows.Count == 1); bool HasChanges = FPetraUtilsObject.HasChanges; bool SelectEndRow = false; bool FPrevRowIsNull = (FPreviouslySelectedDetailRow == null); bool CopyDetails = false; bool AutoSaveSuccessful = FAutoSave && HasChanges && ((TFrmGiftBatch)ParentForm).SaveChangesManual(); FCreatingNewGift = true; try { //May need to copy values down if a new detail row inside current gift int giftTransactionNumber = 0; string donorName = string.Empty; string donorClass = string.Empty; bool confidentialGiftFlag = false; bool chargeFlag = false; bool taxDeductible = false; string motivationGroupCode = string.Empty; string motivationDetailCode = string.Empty; if (AutoSaveSuccessful || ((!FAutoSave || !HasChanges) && ValidateAllData(true, TErrorProcessingMode.Epm_IgnoreNonCritical))) { if (!ACompletelyNewGift) //i.e. a gift detail { ACompletelyNewGift = IsEmptyGrid; } CopyDetails = (!ACompletelyNewGift && !FPrevRowIsNull); if (CopyDetails) { //Allow for possibility that FPrev... may have some null column values giftTransactionNumber = FPreviouslySelectedDetailRow.GiftTransactionNumber; donorName = FPreviouslySelectedDetailRow.IsDonorNameNull() ? string.Empty : FPreviouslySelectedDetailRow.DonorName; donorClass = FPreviouslySelectedDetailRow.IsDonorClassNull() ? string.Empty : FPreviouslySelectedDetailRow.DonorClass; confidentialGiftFlag = FPreviouslySelectedDetailRow.IsConfidentialGiftFlagNull() ? false : FPreviouslySelectedDetailRow.ConfidentialGiftFlag; chargeFlag = FPreviouslySelectedDetailRow.IsChargeFlagNull() ? true : FPreviouslySelectedDetailRow.ChargeFlag; taxDeductible = FPreviouslySelectedDetailRow.IsTaxDeductibleNull() ? true : FPreviouslySelectedDetailRow.TaxDeductible; motivationGroupCode = FPreviouslySelectedDetailRow.IsMotivationGroupCodeNull() ? string.Empty : FPreviouslySelectedDetailRow. MotivationGroupCode; motivationDetailCode = FPreviouslySelectedDetailRow.IsMotivationDetailCodeNull() ? string.Empty : FPreviouslySelectedDetailRow. MotivationDetailCode; } //Set previous row to Null. FPreviouslySelectedDetailRow = null; if (ACompletelyNewGift) { //Run this if a new gift is requested or required. SelectEndRow = true; // we create the row locally, no dataset AGiftRow giftRow = FMainDS.AGift.NewRowTyped(true); giftRow.LedgerNumber = FBatchRow.LedgerNumber; giftRow.BatchNumber = FBatchRow.BatchNumber; giftRow.GiftTransactionNumber = ++FBatchRow.LastGiftNumber; giftRow.MethodOfPaymentCode = FBatchRow.MethodOfPaymentCode; giftRow.LastDetailNumber = 1; giftRow.DateEntered = FBatchRow.GlEffectiveDate; FMainDS.AGift.Rows.Add(giftRow); CurrentGiftRow = giftRow; mniDonorHistory.Enabled = false; //Reset textboxes to zero txtGiftTotal.NumberValueDecimal = 0; } else { CurrentGiftRow = GetGiftRow(giftTransactionNumber); CurrentGiftRow.LastDetailNumber++; //If adding detail to current last gift, then new detail will be bottom row in grid if (FBatchRow.LastGiftNumber == giftTransactionNumber) { SelectEndRow = true; } } //New gifts will require a new detail anyway, so this code always runs GiftBatchTDSAGiftDetailRow newRow = FMainDS.AGiftDetail.NewRowTyped(true); newRow.LedgerNumber = FBatchRow.LedgerNumber; newRow.BatchNumber = FBatchRow.BatchNumber; newRow.GiftTransactionNumber = CurrentGiftRow.GiftTransactionNumber; newRow.DetailNumber = CurrentGiftRow.LastDetailNumber; newRow.MethodOfPaymentCode = CurrentGiftRow.MethodOfPaymentCode; newRow.MethodOfGivingCode = CurrentGiftRow.MethodOfGivingCode; newRow.DonorKey = CurrentGiftRow.DonorKey; if (CopyDetails) { newRow.DonorName = donorName; newRow.DonorClass = donorClass; newRow.ConfidentialGiftFlag = confidentialGiftFlag; newRow.ChargeFlag = chargeFlag; newRow.TaxDeductible = taxDeductible; newRow.MotivationGroupCode = motivationGroupCode; newRow.MotivationDetailCode = motivationDetailCode; // set the auto-populate comment if needed AMotivationDetailRow motivationDetail = (AMotivationDetailRow)FMainDS.AMotivationDetail.Rows.Find( new object[] { FLedgerNumber, newRow.MotivationGroupCode, newRow.MotivationDetailCode }); if ((motivationDetail != null) && motivationDetail.Autopopdesc) { newRow.GiftCommentOne = motivationDetail.MotivationDetailDesc; } } else { newRow.MotivationGroupCode = MFinanceConstants.MOTIVATION_GROUP_GIFT; newRow.MotivationDetailCode = MFinanceConstants.GROUP_DETAIL_SUPPORT; } newRow.DateEntered = CurrentGiftRow.DateEntered; newRow.ReceiptPrinted = false; newRow.ReceiptNumber = 0; if (FTaxDeductiblePercentageEnabled) { newRow.TaxDeductiblePct = newRow.TaxDeductible ? 100.0m : 0.0m; //Set unbound textboxes to 0 txtTaxDeductAmount.NumberValueDecimal = 0.0m; txtNonDeductAmount.NumberValueDecimal = 0.0m; } FMainDS.AGiftDetail.Rows.Add(newRow); FPetraUtilsObject.SetChangedFlag(); if (!SelectEndRow && !SelectDetailRowByDataTableIndex(FMainDS.AGiftDetail.Rows.Count - 1)) { if (!FFilterAndFindObject.IsActiveFilterEqualToBase) { MessageBox.Show( MCommonResourcestrings.StrNewRecordIsFiltered, MCommonResourcestrings.StrAddNewRecordTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); FFilterAndFindObject.FilterPanelControls.ClearAllDiscretionaryFilters(); if (FFilterAndFindObject.FilterFindPanel.ShowApplyFilterButton != TUcoFilterAndFind.FilterContext.None) { FFilterAndFindObject.ApplyFilter(); } SelectDetailRowByDataTableIndex(FMainDS.AGiftDetail.Rows.Count - 1); } } btnDeleteAll.Enabled = btnDelete.Enabled; UpdateRecordNumberDisplay(); FLastDonor = -1; //Select end row if (SelectEndRow) { grdDetails.SelectRowInGrid(grdDetails.Rows.Count - 1); } //Focus accordingly if (ACompletelyNewGift) { txtDetailDonorKey.Focus(); } else { txtDetailRecipientKey.Focus(); } //FPreviouslySelectedDetailRow should now be pointing to the newly added row TUC_GiftTransactions_Recipient.UpdateRecipientKeyText(0, FPreviouslySelectedDetailRow, cmbDetailMotivationGroupCode.GetSelectedString(), cmbDetailMotivationDetailCode.GetSelectedString()); cmbKeyMinistries.Clear(); mniRecipientHistory.Enabled = false; } } finally { FCreatingNewGift = false; if (AutoSaveSuccessful) { FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataSuccessful); } } }
private static GiftBatchTDS CreateGiftBatches(SortedList <DateTime, List <XmlNode> > AGiftsPerDate, int APeriodNumber) { GiftBatchTDS MainDS = new GiftBatchTDS(); ALedgerTable LedgerTable = null; TDBTransaction ReadTransaction = new TDBTransaction(); DBAccess.ReadTransaction(ref ReadTransaction, delegate { TDataBase db = ReadTransaction.DataBaseObj; // get a list of potential donors (all class FAMILY) string sqlGetFamilyPartnerKeys = "SELECT p_partner_key_n FROM PUB_p_family"; DataTable FamilyKeys = db.SelectDT(sqlGetFamilyPartnerKeys, "keys", ReadTransaction); // get a list of workers (all class FAMILY, with special type WORKER) string sqlGetWorkerPartnerKeys = "SELECT PUB_p_family.p_partner_key_n FROM PUB_p_family, PUB_p_partner_type WHERE PUB_p_partner_type.p_partner_key_n = PUB_p_family.p_partner_key_n AND p_type_code_c = 'WORKER'"; DataTable WorkerKeys = db.SelectDT(sqlGetWorkerPartnerKeys, "keys", ReadTransaction); // get a list of fields (all class UNIT, with unit type F) string sqlGetFieldPartnerKeys = String.Format( "SELECT U.p_partner_key_n FROM PUB_p_unit U WHERE u_unit_type_code_c = 'F' AND EXISTS (SELECT * FROM PUB_a_valid_ledger_number V WHERE V.a_ledger_number_i = {0} AND V.p_partner_key_n = U.p_partner_key_n)", FLedgerNumber); DataTable FieldKeys = db.SelectDT(sqlGetFieldPartnerKeys, "keys", ReadTransaction); // get a list of key ministries (all class UNIT, with unit type KEY-MIN), and their field ledger number and cost centre code string sqlGetKeyMinPartnerKeys = "SELECT u.p_partner_key_n, us.um_parent_unit_key_n, vl.a_cost_centre_code_c " + "FROM PUB_p_unit u, PUB_um_unit_structure us, PUB_a_valid_ledger_number vl " + "WHERE u.u_unit_type_code_c = 'KEY-MIN' " + "AND us.um_child_unit_key_n = u.p_partner_key_n " + "AND vl.p_partner_key_n = us.um_parent_unit_key_n " + "AND vl.a_ledger_number_i = " + FLedgerNumber.ToString(); DataTable KeyMinistries = db.SelectDT(sqlGetKeyMinPartnerKeys, "keys", ReadTransaction); LedgerTable = ALedgerAccess.LoadByPrimaryKey(FLedgerNumber, ReadTransaction); AAccountingPeriodRow AccountingPeriodRow = AAccountingPeriodAccess.LoadByPrimaryKey(FLedgerNumber, APeriodNumber, ReadTransaction)[0]; // create a gift batch for each day. // TODO: could create one batch per month, if there are not so many gifts (less than 100 per month) foreach (DateTime GlEffectiveDate in AGiftsPerDate.Keys) { if ((GlEffectiveDate.CompareTo(AccountingPeriodRow.PeriodStartDate) < 0) || (GlEffectiveDate.CompareTo(AccountingPeriodRow.PeriodEndDate) > 0)) { // only create gifts in that period continue; } AGiftBatchRow giftBatch = TGiftBatchFunctions.CreateANewGiftBatchRow(ref MainDS, ref ReadTransaction, ref LedgerTable, FLedgerNumber, GlEffectiveDate); TLogging.LogAtLevel(1, "create gift batch for " + GlEffectiveDate.ToShortDateString()); giftBatch.BatchDescription = "Benerator Batch for " + GlEffectiveDate.ToShortDateString(); giftBatch.BatchTotal = 0.0m; foreach (XmlNode RecordNode in AGiftsPerDate[GlEffectiveDate]) { AGiftRow gift = MainDS.AGift.NewRowTyped(); gift.LedgerNumber = giftBatch.LedgerNumber; gift.BatchNumber = giftBatch.BatchNumber; gift.GiftTransactionNumber = giftBatch.LastGiftNumber + 1; gift.DateEntered = GlEffectiveDate; // set donorKey int donorID = Convert.ToInt32(TXMLParser.GetAttribute(RecordNode, "donor")) % FamilyKeys.Rows.Count; gift.DonorKey = Convert.ToInt64(FamilyKeys.Rows[donorID].ItemArray[0]); // calculate gift detail information int countDetails = Convert.ToInt32(TXMLParser.GetAttribute(RecordNode, "splitgift")); for (int counter = 1; counter <= countDetails; counter++) { AGiftDetailRow giftDetail = MainDS.AGiftDetail.NewRowTyped(); giftDetail.LedgerNumber = gift.LedgerNumber; giftDetail.BatchNumber = gift.BatchNumber; giftDetail.GiftTransactionNumber = gift.GiftTransactionNumber; giftDetail.MotivationGroupCode = "GIFT"; giftDetail.GiftTransactionAmount = Convert.ToDecimal(TXMLParser.GetAttribute(RecordNode, "amount_" + counter.ToString())); giftDetail.GiftAmount = giftDetail.GiftTransactionAmount; giftBatch.BatchTotal += giftDetail.GiftAmount; string motivation = TXMLParser.GetAttribute(RecordNode, "motivation_" + counter.ToString()); if (motivation == "SUPPORT") { if (WorkerKeys.Rows.Count == 0) { continue; } giftDetail.MotivationDetailCode = "SUPPORT"; int recipientID = Convert.ToInt32(TXMLParser.GetAttribute(RecordNode, "recipient_support_" + counter.ToString())) % WorkerKeys.Rows.Count; giftDetail.RecipientKey = Convert.ToInt64(WorkerKeys.Rows[recipientID].ItemArray[0]); giftDetail.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(giftDetail.RecipientKey, giftBatch.GlEffectiveDate); // ignore this gift detail, if there is no valid commitment period for the worker if (giftDetail.RecipientLedgerNumber == 0) { continue; } } else if (motivation == "FIELD") { if (FieldKeys.Rows.Count == 0) { continue; } giftDetail.MotivationDetailCode = "FIELD"; int recipientID = Convert.ToInt32(TXMLParser.GetAttribute(RecordNode, "recipient_field_" + counter.ToString())) % FieldKeys.Rows.Count; giftDetail.RecipientKey = Convert.ToInt64(FieldKeys.Rows[recipientID].ItemArray[0]); giftDetail.RecipientLedgerNumber = giftDetail.RecipientKey; giftDetail.CostCentreCode = (giftDetail.RecipientKey / 10000).ToString("0000"); } else if (motivation == "KEYMIN") { if (KeyMinistries.Rows.Count == 0) { continue; } giftDetail.MotivationDetailCode = "KEYMIN"; int recipientID = Convert.ToInt32(TXMLParser.GetAttribute(RecordNode, "recipient_keymin_" + counter.ToString())) % KeyMinistries.Rows.Count; giftDetail.RecipientKey = Convert.ToInt64(KeyMinistries.Rows[recipientID].ItemArray[0]); giftDetail.RecipientLedgerNumber = Convert.ToInt64(KeyMinistries.Rows[recipientID].ItemArray[1]); // TTransactionWebConnector.GetRecipientFundNumber(giftDetail.RecipientKey); giftDetail.CostCentreCode = KeyMinistries.Rows[recipientID].ItemArray[2].ToString(); // TTransactionWebConnector.IdentifyPartnerCostCentre(FLedgerNumber, giftDetail.RecipientLedgerNumber); } giftDetail.DetailNumber = gift.LastDetailNumber + 1; MainDS.AGiftDetail.Rows.Add(giftDetail); gift.LastDetailNumber = giftDetail.DetailNumber; } if (gift.LastDetailNumber > 0) { MainDS.AGift.Rows.Add(gift); giftBatch.LastGiftNumber = gift.GiftTransactionNumber; } if (giftBatch.LastGiftNumber >= MaxGiftsPerBatch) { break; } } if (TLogging.DebugLevel > 0) { TLogging.Log( GlEffectiveDate.ToShortDateString() + " " + giftBatch.LastGiftNumber.ToString()); } } }); // need to save the last gift batch number in a_ledger if (LedgerTable != null) { TDBTransaction WriteTransaction = new TDBTransaction(); bool SubmissionOk = false; DBAccess.WriteTransaction(ref WriteTransaction, ref SubmissionOk, delegate { ALedgerAccess.SubmitChanges(LedgerTable, WriteTransaction); SubmissionOk = true; }); if (!SubmissionOk) { TLogging.Log("An Exception occured during the creation of Gift Batches" + Environment.NewLine); } } return(MainDS); }
/// <summary> /// Check if a gift is really restricted or if the user belongs to the group that is allowed /// to access the gift /// </summary> /// <param name="gift">the gift we want to check for restriction</param> /// <param name="ATransaction">A TDBTransaction object for reuse</param> /// <returns>true if the user has no permission and the gift is restricted ///</returns> public static bool GiftRestricted(AGiftRow gift, TDBTransaction ATransaction) { SGroupGiftTable GroupGiftDT; SUserGroupTable UserGroupDT; Int16 Counter; DataRow[] FoundUserGroups; if (gift.Restricted) { GroupGiftDT = SGroupGiftAccess.LoadViaAGift( gift.LedgerNumber, gift.BatchNumber, gift.GiftTransactionNumber, ATransaction); UserGroupDT = SUserGroupAccess.LoadViaSUser(UserInfo.GUserInfo.UserID, ATransaction); // Loop over all rows of GroupGiftDT for (Counter = 0; Counter <= GroupGiftDT.Rows.Count - 1; Counter += 1) { // To be able to view a Gift, ReadAccess must be granted if (GroupGiftDT[Counter].ReadAccess) { // Find out whether the user has a row in s_user_group with the // GroupID of the GroupGift row FoundUserGroups = UserGroupDT.Select(SUserGroupTable.GetGroupIdDBName() + " = '" + GroupGiftDT[Counter].GroupId + "'"); if (FoundUserGroups.Length != 0) { // The gift is not restricted because there is a read access for the group return false; // don't evaluate further GroupGiftDT rows } } } } else { return false; } return true; }
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); }
/// <summary> /// Update the transaction method payment from outside /// </summary> public void UpdateMethodOfPayment() { Int32 LedgerNumber; Int32 BatchNumber; if (!((TFrmGiftBatch)this.ParentForm).GetBatchControl().FBatchLoaded) { return; } FBatchRow = GetBatchRow(); if (FBatchRow == null) { FBatchRow = ((TFrmGiftBatch)this.ParentForm).GetBatchControl().GetSelectedDetailRow(); } FBatchMethodOfPayment = ((TFrmGiftBatch)this.ParentForm).GetBatchControl().MethodOfPaymentCode; LedgerNumber = FBatchRow.LedgerNumber; BatchNumber = FBatchRow.BatchNumber; if (!LoadGiftDataForBatch(LedgerNumber, BatchNumber)) { //No transactions exist to process or corporate exchange rate not found return; } if ((FLedgerNumber == LedgerNumber) && (FBatchNumber == BatchNumber)) { //Rows already active in transaction tab. Need to set current row ac code below will not update selected row if (FPreviouslySelectedDetailRow != null) { FPreviouslySelectedDetailRow.MethodOfPaymentCode = FBatchMethodOfPayment; cmbDetailMethodOfPaymentCode.SetSelectedString(FBatchMethodOfPayment); } } //Update all transactions DataView GiftView = new DataView(FMainDS.AGift); GiftView.RowStateFilter = DataViewRowState.CurrentRows; GiftView.RowFilter = String.Format("{0}={1}", AGiftTable.GetBatchNumberDBName(), BatchNumber); foreach (DataRowView drv in GiftView) { AGiftRow giftRow = (AGiftRow)drv.Row; giftRow.MethodOfPaymentCode = FBatchMethodOfPayment; } //Do same at detail level to update the grid DataView GiftDetailView = new DataView(FMainDS.AGiftDetail); GiftDetailView.RowStateFilter = DataViewRowState.CurrentRows; GiftDetailView.RowFilter = String.Format("{0}={1}", AGiftDetailTable.GetBatchNumberDBName(), BatchNumber); foreach (DataRowView drv in GiftDetailView) { GiftBatchTDSAGiftDetailRow giftDetailRow = (GiftBatchTDSAGiftDetailRow)drv.Row; giftDetailRow.MethodOfPaymentCode = FBatchMethodOfPayment; } }
/// <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; } }
/// <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(); }
private void ParseTransactionLine(AGiftRow AGift, AGiftBatchRow AGiftBatch, ref AGiftRow APreviousGift, int ANumberOfColumns, ref decimal ATotalBatchAmount, ref string AImportMessage, int ARowNumber, TVerificationResultCollection AMessages, TValidationControlsDict AValidationControlsDictGift, TValidationControlsDict AValidationControlsDictGiftDetail, ACostCentreTable AValidationCostCentreTable, AMotivationGroupTable AValidationMotivationGroupTable, AMotivationDetailTable AValidationMotivationDetailTable, AMethodOfGivingTable AValidationMethodOfGivingTable, AMethodOfPaymentTable AValidationMethodOfPaymentTable, ref GiftBatchTDSAGiftDetailTable ANeedRecipientLedgerNumber, out AGiftDetailRow AGiftDetails) { // Is this the format with extra columns? // Actually if it has the extra columns but does not have the optional final 8 columns we cannot distiguish using this test... // A file without extra columns will have between 13 and 21 columns - depending on whether some of the optional ones at the end are included. // A file with extra columns will be between 19 and 27. // So any count between 19 and 21 is ambiguous. We will assume that if the file has extra columns it also has // at least enough of the optional ones to exceed 21. bool HasExtraColumns = (ANumberOfColumns > 21); AImportMessage = Catalog.GetString("Importing the gift data"); AGift.DonorKey = ImportInt64(Catalog.GetString("Donor key"), FMainDS.AGift.ColumnDonorKey, ARowNumber, AMessages, AValidationControlsDictGift); ImportString(Catalog.GetString("short name of donor (unused)"), null, null); // unused // This group is optional and database NULL's are allowed AGift.MethodOfGivingCode = ImportString(Catalog.GetString("Method of giving Code"), FMainDS.AGift.ColumnMethodOfGivingCode, AValidationControlsDictGift, false); AGift.MethodOfPaymentCode = ImportString(Catalog.GetString("Method Of Payment Code"), FMainDS.AGift.ColumnMethodOfPaymentCode, AValidationControlsDictGift, false); AGift.Reference = ImportString(Catalog.GetString("Reference"), FMainDS.AGift.ColumnReference, AValidationControlsDictGift, false); AGift.ReceiptLetterCode = ImportString(Catalog.GetString("Receipt letter code"), FMainDS.AGift.ColumnReceiptLetterCode, AValidationControlsDictGift, false); if (HasExtraColumns) { ImportInt32(Catalog.GetString("Receipt number"), FMainDS.AGift.ColumnReceiptNumber, ARowNumber, AMessages, AValidationControlsDictGift); ImportBoolean(Catalog.GetString("First time gift"), FMainDS.AGift.ColumnFirstTimeGift, AValidationControlsDictGift); ImportBoolean(Catalog.GetString("Receipt printed"), FMainDS.AGift.ColumnReceiptPrinted, AValidationControlsDictGift); } AImportMessage = Catalog.GetString("Importing the gift details"); AGiftDetails = FMainDS.AGiftDetail.NewRowTyped(true); if ((APreviousGift != null) && (AGift.DonorKey == APreviousGift.DonorKey) && (AGift.MethodOfGivingCode == APreviousGift.MethodOfGivingCode) && (AGift.MethodOfPaymentCode == APreviousGift.MethodOfPaymentCode) && (AGift.Reference == APreviousGift.Reference) && (AGift.ReceiptLetterCode == APreviousGift.ReceiptLetterCode) && (AGift.ReceiptNumber == APreviousGift.ReceiptNumber) && (AGift.FirstTimeGift == APreviousGift.FirstTimeGift) && (AGift.ReceiptPrinted == APreviousGift.ReceiptPrinted)) { // this row is a new detail for the previousGift AGift = APreviousGift; AGift.LastDetailNumber++; AGiftDetails.DetailNumber = AGift.LastDetailNumber; } else { APreviousGift = AGift; AGift.LedgerNumber = AGiftBatch.LedgerNumber; AGift.BatchNumber = AGiftBatch.BatchNumber; AGift.GiftTransactionNumber = AGiftBatch.LastGiftNumber + 1; AGiftBatch.LastGiftNumber++; AGift.LastDetailNumber = 1; FMainDS.AGift.Rows.Add(AGift); AGiftDetails.DetailNumber = 1; } AGiftDetails.LedgerNumber = AGift.LedgerNumber; AGiftDetails.BatchNumber = AGiftBatch.BatchNumber; AGiftDetails.GiftTransactionNumber = AGift.GiftTransactionNumber; FMainDS.AGiftDetail.Rows.Add(AGiftDetails); AGiftDetails.RecipientKey = ImportInt64(Catalog.GetString("Recipient key"), FMainDS.AGiftDetail.ColumnRecipientKey, ARowNumber, AMessages, AValidationControlsDictGiftDetail); ImportString(Catalog.GetString("short name of recipient (unused)"), null, null); // unused if (HasExtraColumns) { ImportInt32(Catalog.GetString("Recipient ledger number"), FMainDS.AGiftDetail.ColumnRecipientLedgerNumber, ARowNumber, AMessages, AValidationControlsDictGiftDetail); } // we always calculate RecipientLedgerNumber AGiftDetails.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber( AGiftDetails.RecipientKey, AGiftBatch.GlEffectiveDate); decimal currentGiftAmount = ImportDecimal(Catalog.GetString("Gift amount"), FMainDS.AGiftDetail.ColumnGiftTransactionAmount, ARowNumber, AMessages, AValidationControlsDictGiftDetail); AGiftDetails.GiftTransactionAmount = currentGiftAmount; // amount in batch currency ATotalBatchAmount += currentGiftAmount; AGiftDetails.GiftAmount = GLRoutines.Divide(currentGiftAmount, AGiftBatch.ExchangeRateToBase); // amount in ledger currency if (HasExtraColumns) { // amount in international currency ImportDecimal(Catalog.GetString("Gift amount intl"), FMainDS.AGiftDetail.ColumnGiftAmountIntl, ARowNumber, AMessages, AValidationControlsDictGiftDetail); } AGiftDetails.ConfidentialGiftFlag = ImportBoolean(Catalog.GetString("Confidential gift"), FMainDS.AGiftDetail.ColumnConfidentialGiftFlag, AValidationControlsDictGiftDetail, "no"); AGiftDetails.MotivationGroupCode = ImportString(Catalog.GetString("Motivation group code"), FMainDS.AGiftDetail.ColumnMotivationGroupCode, AValidationControlsDictGiftDetail); AGiftDetails.MotivationDetailCode = ImportString(Catalog.GetString("Motivation detail"), FMainDS.AGiftDetail.ColumnMotivationDetailCode, AValidationControlsDictGiftDetail); if (HasExtraColumns) { ImportString(Catalog.GetString("Cost centre code"), FMainDS.AGiftDetail.ColumnCostCentreCode, AValidationControlsDictGiftDetail); } // "In Petra Cost Centre is always inferred from recipient field and motivation detail so is not needed in the import." AGiftDetails.CostCentreCode = InferCostCentre(AGiftDetails); // All the remaining columns are optional and can contain database NULL AGiftDetails.GiftCommentOne = ImportString(Catalog.GetString("Gift comment one"), FMainDS.AGiftDetail.ColumnGiftCommentOne, AValidationControlsDictGiftDetail, false); string commentOneType = ImportString(Catalog.GetString("Comment one type"), FMainDS.AGiftDetail.ColumnCommentOneType, AValidationControlsDictGiftDetail, false); AGiftDetails.MailingCode = ImportString(Catalog.GetString("Mailing code"), FMainDS.AGiftDetail.ColumnMailingCode, AValidationControlsDictGiftDetail, false); AGiftDetails.GiftCommentTwo = ImportString(Catalog.GetString("Gift comment two"), FMainDS.AGiftDetail.ColumnGiftCommentTwo, AValidationControlsDictGiftDetail, false); string commentTwoType = ImportString(Catalog.GetString("Comment two type"), FMainDS.AGiftDetail.ColumnCommentTwoType, AValidationControlsDictGiftDetail, false); AGiftDetails.GiftCommentThree = ImportString(Catalog.GetString("Gift comment three"), FMainDS.AGiftDetail.ColumnGiftCommentThree, AValidationControlsDictGiftDetail, false); string commentThreeType = ImportString(Catalog.GetString("Comment three type"), FMainDS.AGiftDetail.ColumnCommentThreeType, AValidationControlsDictGiftDetail, false); SetCommentTypeCase(ref commentOneType); AGiftDetails.CommentOneType = commentOneType; SetCommentTypeCase(ref commentTwoType); AGiftDetails.CommentOneType = commentTwoType; SetCommentTypeCase(ref commentThreeType); AGiftDetails.CommentOneType = commentThreeType; // Find the default Tax deductabilty from the motivation detail. This ensures that the column can be missing. AMotivationDetailRow motivationDetailRow = (AMotivationDetailRow)AValidationMotivationDetailTable.Rows.Find( new object[] { FLedgerNumber, AGiftDetails.MotivationGroupCode, AGiftDetails.MotivationDetailCode }); string defaultTaxDeductible = ((motivationDetailRow != null) && !motivationDetailRow.IsTaxDeductibleAccountNull() && motivationDetailRow.TaxDeductible) ? "yes" : "no"; AGiftDetails.TaxDeductible = ImportBoolean(Catalog.GetString("Tax deductible"), FMainDS.AGiftDetail.ColumnTaxDeductible, AValidationControlsDictGiftDetail, defaultTaxDeductible); // Date entered cannot be imported although it can be modified in the GUI. // This is because it would have to be the last column in the import for compatibility // but it belongs with the gift and not the detail so it would need to go in an earlier column. // For now the import date entered is the effective date. AGift.DateEntered = AGiftBatch.GlEffectiveDate; // Enforce the correct case for our GIFT constant if (String.Compare(AGiftDetails.MotivationGroupCode, MFinanceConstants.MOTIVATION_GROUP_GIFT, true) == 0) { AGiftDetails.MotivationGroupCode = MFinanceConstants.MOTIVATION_GROUP_GIFT; } TPartnerClass RecipientClass; string RecipientDescription; TPartnerServerLookups.GetPartnerShortName(AGiftDetails.RecipientKey, out RecipientDescription, out RecipientClass); // If the gift has a Family recipient with no Gift Destination then the import will fail. Gift is added to a table and returned to client. if ((AGiftDetails.RecipientLedgerNumber == 0) && (AGiftDetails.MotivationGroupCode == MFinanceConstants.MOTIVATION_GROUP_GIFT)) { if (RecipientClass == TPartnerClass.FAMILY) { ((GiftBatchTDSAGiftDetailRow)AGiftDetails).RecipientDescription = RecipientDescription; ANeedRecipientLedgerNumber.Rows.Add((object[])AGiftDetails.ItemArray.Clone()); } } AImportMessage = Catalog.GetString("Validating the gift data"); int messageCountBeforeValidate = AMessages.Count; // Do our standard validation on this gift AGiftValidation.Validate(this, AGift, ref AMessages, AValidationControlsDictGift); TSharedFinanceValidation_Gift.ValidateGiftManual(this, AGift, AGiftBatch.BatchYear, AGiftBatch.BatchPeriod, null, ref AMessages, AValidationControlsDictGift, AValidationMethodOfGivingTable, AValidationMethodOfPaymentTable); AImportMessage = Catalog.GetString("Validating the gift details data"); AGiftDetailValidation.Validate(this, AGiftDetails, ref AMessages, AValidationControlsDictGiftDetail); TSharedFinanceValidation_Gift.ValidateGiftDetailManual(this, (GiftBatchTDSAGiftDetailRow)AGiftDetails, ref AMessages, AValidationControlsDictGiftDetail, RecipientClass, AValidationCostCentreTable, AValidationMotivationGroupTable, AValidationMotivationDetailTable, AGiftDetails.RecipientKey); for (int i = messageCountBeforeValidate; i < AMessages.Count; i++) { ((TVerificationResult)AMessages[i]).OverrideResultContext(String.Format(MCommonConstants.StrValidationErrorInLine, ARowNumber)); if (AMessages[i] is TScreenVerificationResult) { TVerificationResult downgrade = new TVerificationResult((TScreenVerificationResult)AMessages[i]); AMessages.RemoveAt(i); AMessages.Insert(i, downgrade); } } }
private void ShowDetailsForGift(AGiftRow ACurrentGiftRow) { //Set GiftRow controls dtpDateEntered.Date = ACurrentGiftRow.DateEntered; txtDetailDonorKey.Text = ACurrentGiftRow.DonorKey.ToString(); if (ACurrentGiftRow.IsMethodOfGivingCodeNull()) { cmbDetailMethodOfGivingCode.SelectedIndex = -1; } else { cmbDetailMethodOfGivingCode.SetSelectedString(ACurrentGiftRow.MethodOfGivingCode); } if (ACurrentGiftRow.IsMethodOfPaymentCodeNull()) { cmbDetailMethodOfPaymentCode.SelectedIndex = -1; } else { cmbDetailMethodOfPaymentCode.SetSelectedString(ACurrentGiftRow.MethodOfPaymentCode); } if (ACurrentGiftRow.IsReferenceNull()) { txtDetailReference.Text = String.Empty; } else { txtDetailReference.Text = ACurrentGiftRow.Reference; } cmbDetailReceiptLetterCode.SetSelectedString(ACurrentGiftRow.ReceiptLetterCode, -1); chkNoReceiptOnAdjustment.Checked = !ACurrentGiftRow.PrintReceipt; }
/// <summary> /// Main method to post a specified batch /// </summary> /// <param name="ACurrentBatchRow">The batch row to post</param> /// <param name="ARefreshGUIAfterPosting">Will be set to true if the GUI should be updated. Can be true even if Posting fails /// <param name="AWarnOfInactiveValues">True means user is warned if inactive values exist</param> /// <param name="ADonorZeroIsValid"></param> /// <param name="ARecipientZeroIsValid"></param> /// <param name="APostingAlreadyConfirmed">True means ask user if they want to post</param> /// if the server gets a SerializableTransactionException</param> /// <returns>True if the batch was successfully posted</returns> public bool PostBatch(AGiftBatchRow ACurrentBatchRow, out bool ARefreshGUIAfterPosting, bool AWarnOfInactiveValues = true, bool ADonorZeroIsValid = false, bool ARecipientZeroIsValid = false, bool APostingAlreadyConfirmed = false) { ARefreshGUIAfterPosting = false; if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)) { return(false); } FSelectedBatchNumber = ACurrentBatchRow.BatchNumber; //Make sure that all control data is in dataset FMyForm.GetLatestControlData(); //Copy all batch data to new table GiftBatchTDSAGiftDetailTable BatchGiftDetails = new GiftBatchTDSAGiftDetailTable(); DataView BatchGiftDetailsDV = new DataView(FMainDS.AGiftDetail); BatchGiftDetailsDV.RowFilter = string.Format("{0}={1}", AGiftDetailTable.GetBatchNumberDBName(), FSelectedBatchNumber); BatchGiftDetailsDV.Sort = string.Format("{0} ASC, {1} ASC, {2} ASC", AGiftDetailTable.GetBatchNumberDBName(), AGiftDetailTable.GetGiftTransactionNumberDBName(), AGiftDetailTable.GetDetailNumberDBName()); foreach (DataRowView drv in BatchGiftDetailsDV) { GiftBatchTDSAGiftDetailRow gBRow = (GiftBatchTDSAGiftDetailRow)drv.Row; BatchGiftDetails.Rows.Add((object[])gBRow.ItemArray.Clone()); } //Save and check for inactive values and ex-workers and anonymous gifts if (FPetraUtilsObject.HasChanges) { //Keep this conditional check separate from the one above so that it only gets called // when necessary and doesn't result in the executon of the same method if (!FMyForm.SaveChangesForPosting(BatchGiftDetails)) { return(false); } else { APostingAlreadyConfirmed = true; } } else { //This has to be called here because if there are no changes then the DataSavingValidating // method which calls the method below, will not run. if (!FMyForm.GetBatchControl().AllowInactiveFieldValues(ref APostingAlreadyConfirmed, TExtraGiftBatchChecks.GiftBatchAction.POSTING) || FMyForm.GiftHasExWorkerOrAnon(BatchGiftDetails) ) { return(false); } } //Check hash total validity if ((ACurrentBatchRow.HashTotal != 0) && (ACurrentBatchRow.BatchTotal != ACurrentBatchRow.HashTotal)) { MessageBox.Show(String.Format(Catalog.GetString( "The gift batch total ({0}) for batch {1} does not equal the hash total ({2})!"), StringHelper.FormatUsingCurrencyCode(ACurrentBatchRow.BatchTotal, ACurrentBatchRow.CurrencyCode), ACurrentBatchRow.BatchNumber, StringHelper.FormatUsingCurrencyCode(ACurrentBatchRow.HashTotal, ACurrentBatchRow.CurrencyCode)), "Post Gift Batch"); return(false); } //Check for missing international exchange rate bool IsTransactionInIntlCurrency = false; FMyForm.WarnAboutMissingIntlExchangeRate = true; if (FMyForm.InternationalCurrencyExchangeRate(ACurrentBatchRow, out IsTransactionInIntlCurrency, true) == 0) { return(false); } //Check for zero Donors or Recipients if (!ADonorZeroIsValid) { DataView batchGiftDV = new DataView(FMainDS.AGift); batchGiftDV.RowFilter = string.Format("{0}={1} And {2}=0", AGiftTable.GetBatchNumberDBName(), FSelectedBatchNumber, AGiftTable.GetDonorKeyDBName()); int numDonorZeros = batchGiftDV.Count; if (numDonorZeros > 0) { string messageListOfOffendingGifts = String.Format(Catalog.GetString( "Gift Batch {0} contains {1} gift detail(s) with Donor 0000000. Please fix before posting!{2}{2}"), FSelectedBatchNumber, numDonorZeros, Environment.NewLine); string listOfOffendingRows = string.Empty; listOfOffendingRows += "Gift" + Environment.NewLine; listOfOffendingRows += "------------"; foreach (DataRowView drv in batchGiftDV) { AGiftRow giftRow = (AGiftRow)drv.Row; listOfOffendingRows += String.Format("{0}{1:0000}", Environment.NewLine, giftRow.GiftTransactionNumber); } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); return(false); } } if (!ARecipientZeroIsValid) { DataView batchGiftDetailsDV = new DataView(FMainDS.AGiftDetail); batchGiftDetailsDV.RowFilter = string.Format("{0}={1} And {2}=0", AGiftDetailTable.GetBatchNumberDBName(), FSelectedBatchNumber, AGiftDetailTable.GetRecipientKeyDBName()); int numRecipientZeros = batchGiftDetailsDV.Count; if (numRecipientZeros > 0) { string messageListOfOffendingGifts = String.Format(Catalog.GetString( "Gift Batch {0} contains {1} gift detail(s) with Recipient 0000000. Please fix before posting!{2}{2}"), FSelectedBatchNumber, numRecipientZeros, Environment.NewLine); string listOfOffendingRows = string.Empty; listOfOffendingRows += "Gift Detail" + Environment.NewLine; listOfOffendingRows += "-------------------"; foreach (DataRowView drv in batchGiftDetailsDV) { AGiftDetailRow giftDetailRow = (AGiftDetailRow)drv.Row; listOfOffendingRows += String.Format("{0}{1:0000} {2:00}", Environment.NewLine, giftDetailRow.GiftTransactionNumber, giftDetailRow.DetailNumber); } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); return(false); } } //Check for inactive KeyMinistries DataTable GiftsWithInactiveKeyMinistries; bool ModifiedDetails = false; if (AWarnOfInactiveValues && TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber, out GiftsWithInactiveKeyMinistries, false)) { int numInactiveValues = GiftsWithInactiveKeyMinistries.Rows.Count; string messageNonModifiedBatch = String.Format(Catalog.GetString("Gift Batch {0} contains {1} inactive key ministries. Please fix before posting!{2}{2}"), FSelectedBatchNumber, numInactiveValues, Environment.NewLine); string messageModifiedBatch = String.Format(Catalog.GetString( "Reversal/Adjustment Gift Batch {0} contains {1} inactive key ministries. Do you still want to post?{2}{2}"), FSelectedBatchNumber, numInactiveValues, Environment.NewLine); string listOfOffendingRows = string.Empty; listOfOffendingRows += "Gift Detail Recipient KeyMinistry" + Environment.NewLine; listOfOffendingRows += "-------------------------------------------------------------------------------"; foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows) { listOfOffendingRows += String.Format("{0}{1:0000} {2:00} {3:00000000000} {4}", Environment.NewLine, dr[0], dr[1], dr[2], dr[3]); bool isModified = Convert.ToBoolean(dr[4]); if (isModified) { ModifiedDetails = true; } } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); if (ModifiedDetails) { if (extendedMessageBox.ShowDialog((messageModifiedBatch + listOfOffendingRows), Catalog.GetString("Post Batch"), string.Empty, TFrmExtendedMessageBox.TButtons.embbYesNo, TFrmExtendedMessageBox.TIcon.embiWarning) == TFrmExtendedMessageBox.TResult.embrYes) { APostingAlreadyConfirmed = true; } else { return(false); } } else { extendedMessageBox.ShowDialog((messageNonModifiedBatch + listOfOffendingRows), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); return(false); } } // ask if the user really wants to post the batch if (!APostingAlreadyConfirmed && (MessageBox.Show(String.Format(Catalog.GetString("Do you really want to post gift batch {0}?"), FSelectedBatchNumber), Catalog.GetString("Confirm posting of Gift Batch"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)) { return(false); } TVerificationResultCollection Verifications = new TVerificationResultCollection(); try { FPostingInProgress = true; Thread postingThread = new Thread(() => PostGiftBatch(out Verifications)); postingThread.SetApartmentState(ApartmentState.STA); using (TProgressDialog dialog = new TProgressDialog(postingThread)) { dialog.ShowDialog(); } if (TVerificationHelper.ResultsContainErrorCode(Verifications, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION)) { TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog(); ARefreshGUIAfterPosting = true; return(false); } else if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications)) { TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); StringBuilder errorMessages = new StringBuilder(); int counter = 0; errorMessages.AppendLine(Catalog.GetString("________________________Gift Posting Errors________________________")); errorMessages.AppendLine(); foreach (TVerificationResult verif in Verifications) { counter++; errorMessages.AppendLine(counter.ToString("000") + " - " + verif.ResultText); errorMessages.AppendLine(); } extendedMessageBox.ShowDialog(errorMessages.ToString(), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); } else { MessageBox.Show(Catalog.GetString("The batch has been posted successfully!")); ARefreshGUIAfterPosting = true; } } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { FPostingInProgress = false; } return(true); }
/// <summary> /// This "Einzahlungsschein mit Referenznummer" (ESR) input format is only used in Switzerland. /// This method could be pulled out of here, but sits here quite nicely. /// </summary> /// <param name="AImportLine"></param> /// <param name="AgiftBatch"></param> /// <param name="Agift"></param> /// <param name="AgiftDetails"></param> /// <param name="AIntlRateToBase"></param> /// <param name="AMotivationDetailTable"></param> /// <param name="ANeedRecipientLedgerNumber"></param> /// <param name="AMessages"></param> /// <returns></returns> private Boolean ParseEsrTransactionLine( String AImportLine, AGiftBatchRow AgiftBatch, AGiftRow Agift, AGiftDetailRow AgiftDetails, Decimal AIntlRateToBase, AMotivationDetailTable AMotivationDetailTable, GiftBatchTDSAGiftDetailTable ANeedRecipientLedgerNumber, TVerificationResultCollection AMessages ) { Boolean NonNumericError = false; String Field = AImportLine.Substring(0, 3); Int32 FunctionType = 0; NonNumericError &= !Int32.TryParse(Field, out FunctionType); Int64 DonorKey = 0; Field = AImportLine.Substring(12, 10); NonNumericError &= !Int64.TryParse(Field, out DonorKey); Int64 RecipientKey = 0; Field = AImportLine.Substring(22, 10); NonNumericError &= !Int64.TryParse(Field, out RecipientKey); Int64 intAmount = 0; Field = AImportLine.Substring(39, 10); NonNumericError &= !Int64.TryParse(Field, out intAmount); Decimal Amount = intAmount / 100; if (NonNumericError) { return false; } String MotivGroup = "GIFT"; String MotivDetail = "UNDESIG"; TGuiTools.GetMotivationGroupAndDetail(RecipientKey, ref MotivGroup, ref MotivDetail); Agift.LedgerNumber = AgiftBatch.LedgerNumber; Agift.BatchNumber = AgiftBatch.BatchNumber; Agift.GiftTransactionNumber = AgiftBatch.LastGiftNumber + 1; AgiftBatch.LastGiftNumber++; AgiftBatch.BatchTotal += Amount; Agift.LastDetailNumber = 1; ExchangeFieldsInEsrTransaction(ref DonorKey, ref RecipientKey, AMessages, Agift.GiftTransactionNumber); Agift.DonorKey = DonorKey; Agift.MethodOfGivingCode = "DEFAULT"; Agift.MethodOfPaymentCode = "ESR"; FMainDS.AGift.Rows.Add(Agift); AgiftDetails.RecipientKey = RecipientKey; AgiftDetails.LedgerNumber = AgiftBatch.LedgerNumber; AgiftDetails.BatchNumber = AgiftBatch.BatchNumber; AgiftDetails.GiftTransactionNumber = Agift.GiftTransactionNumber; AgiftDetails.DetailNumber = 1; AgiftDetails.GiftTransactionAmount = Amount; AgiftDetails.GiftAmount = GLRoutines.Divide(Amount, AgiftBatch.ExchangeRateToBase); // amount in ledger currency if (AIntlRateToBase > 0.0m) { AgiftDetails.GiftAmountIntl = GLRoutines.Divide(AgiftDetails.GiftAmount, AIntlRateToBase, 2); } AgiftDetails.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(AgiftDetails.RecipientKey, AgiftBatch.GlEffectiveDate); AgiftDetails.MotivationGroupCode = MotivGroup; AgiftDetails.MotivationDetailCode = MotivDetail; AgiftDetails.CostCentreCode = TGiftTransactionWebConnector.RetrieveCostCentreCodeForRecipient( AgiftDetails.LedgerNumber, AgiftDetails.RecipientKey, AgiftDetails.RecipientLedgerNumber, Agift.DateEntered, AgiftDetails.MotivationGroupCode, AgiftDetails.MotivationDetailCode); AMotivationDetailRow motivationDetailRow = (AMotivationDetailRow)AMotivationDetailTable.Rows.Find( new object[] { FLedgerNumber, AgiftDetails.MotivationGroupCode, AgiftDetails.MotivationDetailCode }); // Account Code is inferred from the motivation detail. Boolean IsTaxDeductible = false; string NewAccountCode = null; string NewTaxDeductibleAccountCode = null; if (motivationDetailRow != null) { IsTaxDeductible = motivationDetailRow.TaxDeductible; NewAccountCode = motivationDetailRow.AccountCode; NewTaxDeductibleAccountCode = motivationDetailRow.TaxDeductibleAccountCode; } AgiftDetails.TaxDeductible = IsTaxDeductible; AgiftDetails.AccountCode = NewAccountCode; AgiftDetails.TaxDeductibleAccountCode = NewTaxDeductibleAccountCode; // If the gift has a recipient with no Gift Destination then the import will fail. Gift is added to a table and returned to client. if ((AgiftDetails.RecipientLedgerNumber == 0) && (AgiftDetails.MotivationGroupCode == MFinanceConstants.MOTIVATION_GROUP_GIFT)) { ((GiftBatchTDSAGiftDetailRow)AgiftDetails).RecipientDescription = "Fault: RecipientLedger Not known"; ANeedRecipientLedgerNumber.Rows.Add((object[])AgiftDetails.ItemArray.Clone()); } FMainDS.AGiftDetail.Rows.Add(AgiftDetails); return true; }
/// <summary> /// Creates a new gift or gift detail depending upon the parameter /// </summary> /// <param name="ACompletelyNewGift"></param> private void CreateANewGift(bool ACompletelyNewGift) { AGiftRow CurrentGiftRow = null; bool IsEmptyGrid = (grdDetails.Rows.Count == 1); FCreatingNewGift = true; try { if (ValidateAllData(true, true)) { if (!ACompletelyNewGift) //i.e. a gift detail { ACompletelyNewGift = IsEmptyGrid; } if (ACompletelyNewGift) { //Run this if a new gift is requested or required. // we create the table locally, no dataset AGiftRow giftRow = FMainDS.AGift.NewRowTyped(true); giftRow.DateEntered = FBatchRow.GlEffectiveDate; giftRow.LedgerNumber = FBatchRow.LedgerNumber; giftRow.BatchNumber = FBatchRow.BatchNumber; giftRow.GiftTransactionNumber = ++FBatchRow.LastGiftNumber; giftRow.MethodOfPaymentCode = FBatchRow.MethodOfPaymentCode; giftRow.LastDetailNumber = 1; FMainDS.AGift.Rows.Add(giftRow); CurrentGiftRow = giftRow; mniDonorHistory.Enabled = false; } else { CurrentGiftRow = GetGiftRow(FPreviouslySelectedDetailRow.GiftTransactionNumber); CurrentGiftRow.LastDetailNumber++; } //New gifts will require a new detail anyway, so this code always runs GiftBatchTDSAGiftDetailRow newRow = FMainDS.AGiftDetail.NewRowTyped(true); newRow.LedgerNumber = FBatchRow.LedgerNumber; newRow.BatchNumber = FBatchRow.BatchNumber; newRow.GiftTransactionNumber = CurrentGiftRow.GiftTransactionNumber; newRow.DetailNumber = CurrentGiftRow.LastDetailNumber; newRow.MethodOfPaymentCode = CurrentGiftRow.MethodOfPaymentCode; newRow.MethodOfGivingCode = CurrentGiftRow.MethodOfGivingCode; newRow.DonorKey = CurrentGiftRow.DonorKey; if (!ACompletelyNewGift && (FPreviouslySelectedDetailRow != null)) { newRow.DonorName = FPreviouslySelectedDetailRow.DonorName; newRow.ConfidentialGiftFlag = FPreviouslySelectedDetailRow.ConfidentialGiftFlag; newRow.ChargeFlag = FPreviouslySelectedDetailRow.ChargeFlag; newRow.TaxDeductible = FPreviouslySelectedDetailRow.TaxDeductible; newRow.MotivationGroupCode = FPreviouslySelectedDetailRow.MotivationGroupCode; newRow.MotivationDetailCode = FPreviouslySelectedDetailRow.MotivationDetailCode; } else { newRow.MotivationGroupCode = MFinanceConstants.MOTIVATION_GROUP_GIFT; newRow.MotivationDetailCode = MFinanceConstants.GROUP_DETAIL_SUPPORT; } newRow.DateEntered = CurrentGiftRow.DateEntered; if (FTaxDeductiblePercentageEnabled) { newRow.TaxDeductiblePct = 100; } FMainDS.AGiftDetail.Rows.Add(newRow); FPetraUtilsObject.SetChangedFlag(); if (!SelectDetailRowByDataTableIndex(FMainDS.AGiftDetail.Rows.Count - 1)) { if (!FFilterAndFindObject.IsActiveFilterEqualToBase) { MessageBox.Show( MCommonResourcestrings.StrNewRecordIsFiltered, MCommonResourcestrings.StrAddNewRecordTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); FFilterAndFindObject.FilterPanelControls.ClearAllDiscretionaryFilters(); if (FFilterAndFindObject.FilterFindPanel.ShowApplyFilterButton != TUcoFilterAndFind.FilterContext.None) { FFilterAndFindObject.ApplyFilter(); } SelectDetailRowByDataTableIndex(FMainDS.AGiftDetail.Rows.Count - 1); } } btnDeleteAll.Enabled = btnDelete.Enabled && (FFilterAndFindObject.IsActiveFilterEqualToBase); UpdateRecordNumberDisplay(); FLastDonor = -1; //Focus accordingly if (ACompletelyNewGift) { txtDetailDonorKey.Focus(); } else { txtDetailRecipientKey.Focus(); } TUC_GiftTransactions_Recipient.UpdateRecipientKeyText(0, FPreviouslySelectedDetailRow, cmbDetailMotivationGroupCode.GetSelectedString(), cmbDetailMotivationDetailCode.GetSelectedString()); cmbKeyMinistries.Clear(); mniRecipientHistory.Enabled = false; } } finally { FCreatingNewGift = false; } }
/// <summary> /// Adds a duplicate Gift Detail (or reversed duplicate GiftDetail) to Gift. /// </summary> /// <param name="AMainDS"></param> /// <param name="AGift"></param> /// <param name="AOldGiftDetail"></param> /// <param name="AReversal">True for reverse or false for straight duplicate</param> /// <param name="ATransaction"></param> /// <param name="AFunction"></param> /// <param name="ANewPct"></param> /// <param name="AAutoCompleteComments"></param> /// <param name="AReversalCommentOne"></param> /// <param name="AReversalCommentTwo"></param> /// <param name="AReversalCommentThree"></param> /// <param name="AReversalCommentOneType"></param> /// <param name="AReversalCommentTwoType"></param> /// <param name="AReversalCommentThreeType"></param> /// <param name="AUpdateTaxDeductiblePctRecipients"></param> /// <param name="AGeneralFixedGiftDestination"></param> /// <param name="AFixedGiftDestination"></param> private static void AddDuplicateGiftDetailToGift(ref GiftBatchTDS AMainDS, ref AGiftRow AGift, AGiftDetailRow AOldGiftDetail, bool AReversal, TDBTransaction ATransaction, GiftAdjustmentFunctionEnum AFunction, Decimal ANewPct, bool AAutoCompleteComments = false, string AReversalCommentOne = "", string AReversalCommentTwo = "", string AReversalCommentThree = "", string AReversalCommentOneType = "", string AReversalCommentTwoType = "", string AReversalCommentThreeType = "", List <string[]> AUpdateTaxDeductiblePctRecipients = null, bool AGeneralFixedGiftDestination = false, List <string> AFixedGiftDestination = null ) { bool TaxDeductiblePercentageEnabled = new TSystemDefaults(ATransaction.DataBaseObj).GetBooleanDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, false); AGiftDetailRow giftDetail = AMainDS.AGiftDetail.NewRowTyped(true); DataUtilities.CopyAllColumnValuesWithoutPK(AOldGiftDetail, giftDetail); giftDetail.DetailNumber = AGift.LastDetailNumber + 1; AGift.LastDetailNumber++; giftDetail.LedgerNumber = AGift.LedgerNumber; giftDetail.BatchNumber = AGift.BatchNumber; giftDetail.GiftTransactionNumber = AGift.GiftTransactionNumber; giftDetail.IchNumber = 0; decimal signum = (AReversal) ? -1 : 1; giftDetail.GiftTransactionAmount = signum * AOldGiftDetail.GiftTransactionAmount; giftDetail.GiftAmount = signum * AOldGiftDetail.GiftAmount; giftDetail.GiftAmountIntl = signum * AOldGiftDetail.GiftAmountIntl; if (TaxDeductiblePercentageEnabled) { if (!AReversal && AFunction.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust)) { giftDetail.TaxDeductiblePct = ANewPct; TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetail); } else if (!AReversal) { if (AUpdateTaxDeductiblePctRecipients != null) { string[] Result = AUpdateTaxDeductiblePctRecipients.Find(x => x[0] == giftDetail.RecipientKey.ToString()); // true if a new percentage is available and the user wants to use it if (Result != null) { giftDetail.TaxDeductiblePct = Convert.ToDecimal(Result[1]); TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetail); } } } else { giftDetail.TaxDeductibleAmount = signum * AOldGiftDetail.TaxDeductibleAmount; giftDetail.TaxDeductibleAmountBase = signum * AOldGiftDetail.TaxDeductibleAmountBase; giftDetail.TaxDeductibleAmountIntl = signum * AOldGiftDetail.TaxDeductibleAmountIntl; giftDetail.NonDeductibleAmount = signum * AOldGiftDetail.NonDeductibleAmount; giftDetail.NonDeductibleAmountBase = signum * AOldGiftDetail.NonDeductibleAmountBase; giftDetail.NonDeductibleAmountIntl = signum * AOldGiftDetail.NonDeductibleAmountIntl; } } if (AAutoCompleteComments) // only used for tax deductible pct gift adjustments { AGiftRow OldGiftRow = (AGiftRow)AMainDS.AGift.Rows.Find( new object[] { AOldGiftDetail.LedgerNumber, AOldGiftDetail.BatchNumber, AOldGiftDetail.GiftTransactionNumber }); giftDetail.GiftCommentThree = Catalog.GetString("Original gift date: " + OldGiftRow.DateEntered.ToString("dd-MMM-yyyy")); giftDetail.CommentThreeType = "Both"; } else // user defined { giftDetail.GiftCommentOne = AReversalCommentOne; giftDetail.GiftCommentTwo = AReversalCommentTwo; giftDetail.GiftCommentThree = AReversalCommentThree; giftDetail.CommentOneType = AReversalCommentOneType; giftDetail.CommentTwoType = AReversalCommentTwoType; giftDetail.CommentThreeType = AReversalCommentThreeType; } // If reversal: mark the new gift as a reversal if (AReversal) { giftDetail.ModifiedDetail = true; //Identify the reversal source giftDetail.ModifiedDetailKey = "|" + AOldGiftDetail.BatchNumber.ToString() + "|" + AOldGiftDetail.GiftTransactionNumber.ToString() + "|" + AOldGiftDetail.DetailNumber.ToString(); } else { giftDetail.ModifiedDetail = false; // Make sure the motivation detail is still active. If not then we need a new one. AMotivationDetailTable MotivationDetailTable = AMotivationDetailAccess.LoadViaAMotivationGroup( giftDetail.LedgerNumber, giftDetail.MotivationGroupCode, ATransaction); DataRow CurrentMotivationDetail = MotivationDetailTable.Rows.Find( new object[] { giftDetail.LedgerNumber, giftDetail.MotivationGroupCode, giftDetail.MotivationDetailCode }); // Motivation detail has been made inactive (or doesn't exist) then use default if (!((MotivationDetailTable != null) && (MotivationDetailTable.Rows.Count > 0) && (CurrentMotivationDetail != null)) || !Convert.ToBoolean(CurrentMotivationDetail[AMotivationDetailTable.GetMotivationStatusDBName()])) { bool ActiveRowFound = false; // search for first alternative active detail that is part of the same group foreach (AMotivationDetailRow Row in MotivationDetailTable.Rows) { if ((Row.MotivationDetailCode != giftDetail.MotivationDetailCode) && Row.MotivationStatus) { ActiveRowFound = true; giftDetail.MotivationGroupCode = Row.MotivationGroupCode; giftDetail.MotivationDetailCode = Row.MotivationDetailCode; break; } } // if none found then use default group and detail if (!ActiveRowFound) { giftDetail.MotivationGroupCode = MFinanceConstants.MOTIVATION_GROUP_GIFT; giftDetail.MotivationDetailCode = MFinanceConstants.GROUP_DETAIL_SUPPORT; } } // if the gift destination should be fixed if ((AFunction.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust) && AGeneralFixedGiftDestination) || ((AFixedGiftDestination != null) && (AFixedGiftDestination.Exists(x => x == giftDetail.RecipientKey.ToString())))) { giftDetail.FixedGiftDestination = true; } else { giftDetail.FixedGiftDestination = false; } } AMainDS.AGiftDetail.Rows.Add(giftDetail); }
/// <summary> /// Validation for Gift table /// </summary> /// <param name="AContext"></param> /// <param name="ARow"></param> /// <param name="AYear"></param> /// <param name="APeriod"></param> /// <param name="AControl">Need to pass the validation control because it is not a bound control</param> /// <param name="AVerificationResultCollection"></param> /// <param name="AValidationControlsDict"></param> /// <param name="AMethodOfGivingRef">Required for import validation</param> /// <param name="AMethodOfPaymentRef">Required for</param> /// <param name="AFormLetterCodeTbl">Supplied in import validation</param> /// <returns></returns> public static bool ValidateGiftManual(object AContext, AGiftRow ARow, Int32 AYear, Int32 APeriod, Control AControl, ref TVerificationResultCollection AVerificationResultCollection, TValidationControlsDict AValidationControlsDict, AMethodOfGivingTable AMethodOfGivingRef = null, AMethodOfPaymentTable AMethodOfPaymentRef = null, PFormTable AFormLetterCodeTbl = null) { DataColumn ValidationColumn; //TValidationControlsData ValidationControlsData; TVerificationResult VerificationResult = null; object ValidationContext; int VerifResultCollAddedCount = 0; // Don't validate deleted DataRows if (ARow.RowState == DataRowState.Deleted) { return true; } bool isImporting = AContext.ToString().Contains("Importing"); // Check if valid donor ValidationColumn = ARow.Table.Columns[AGiftTable.ColumnDonorKeyId]; ValidationContext = String.Format("Batch no. {0}, gift no. {1}", ARow.BatchNumber, ARow.GiftTransactionNumber); VerificationResult = TSharedPartnerValidation_Partner.IsValidPartner( ARow.DonorKey, new TPartnerClass[] { }, true, (isImporting) ? String.Empty : "Donor of " + THelper.NiceValueDescription(ValidationContext.ToString()), AContext, ValidationColumn, null); if (VerificationResult != null) { AVerificationResultCollection.Remove(ValidationColumn); AVerificationResultCollection.AddAndIgnoreNullValue(VerificationResult); } // 'Entered From Date' must be valid // But we do not test for this when importing because the date is tested for the batch rather than the individual gift(s) if (!isImporting) { ValidationColumn = ARow.Table.Columns[AGiftTable.ColumnDateEnteredId]; ValidationContext = String.Format("Gift No.: {0}", ARow.GiftTransactionNumber); DateTime StartDateCurrentPeriod; DateTime EndDateCurrentPeriod; TSharedFinanceValidationHelper.GetValidPeriodDates(ARow.LedgerNumber, AYear, 0, APeriod, out StartDateCurrentPeriod, out EndDateCurrentPeriod); VerificationResult = (TScreenVerificationResult)TDateChecks.IsDateBetweenDates(ARow.DateEntered, StartDateCurrentPeriod, EndDateCurrentPeriod, (isImporting) ? String.Empty : "Gift Date for " + ValidationContext.ToString(), TDateBetweenDatesCheckType.dbdctUnspecific, TDateBetweenDatesCheckType.dbdctUnspecific, AContext, ValidationColumn, AControl); //ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } } // A method of giving must be valid ValidationColumn = ARow.Table.Columns[AGiftTable.ColumnMethodOfGivingCodeId]; ValidationContext = String.Format("Batch no. {0}, gift no. {1}", ARow.BatchNumber, ARow.GiftTransactionNumber); if (!ARow.IsMethodOfGivingCodeNull() && (AMethodOfGivingRef != null)) { AMethodOfGivingRow foundRow = (AMethodOfGivingRow)AMethodOfGivingRef.Rows.Find(ARow.MethodOfGivingCode); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Unknown method of giving code '{0}'."), ARow.MethodOfGivingCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } // A method of payment must be valid ValidationColumn = ARow.Table.Columns[AGiftTable.ColumnMethodOfPaymentCodeId]; ValidationContext = String.Format("Batch no. {0}, gift no. {1}", ARow.BatchNumber, ARow.GiftTransactionNumber); if (!ARow.IsMethodOfPaymentCodeNull() && (AMethodOfPaymentRef != null)) { AMethodOfPaymentRow foundRow = (AMethodOfPaymentRow)AMethodOfPaymentRef.Rows.Find(ARow.MethodOfPaymentCode); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Unknown method of payment code '{0}'."), ARow.MethodOfPaymentCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } // If supplied, Receipt Letter Code must be a name specified in PForm. if (!ARow.IsReceiptLetterCodeNull() && (AFormLetterCodeTbl != null)) { AFormLetterCodeTbl.DefaultView.RowFilter = String.Format("p_form_name_c='{0}'", ARow.ReceiptLetterCode); if ((AFormLetterCodeTbl.DefaultView.Count == 0) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Unknown Letter Code '{0}'."), ARow.ReceiptLetterCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } return VerifResultCollAddedCount == 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); }
/// <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); } } } }
private void ParseTransactionLine(AGiftRow AGift, AGiftBatchRow AGiftBatch, ref AGiftRow APreviousGift, int ANumberOfColumns, ref decimal ATotalBatchAmount, ref string AImportMessage, int ARowNumber, decimal AIntlRateFromBase, TVerificationResultCollection AMessages, AMotivationDetailTable AMotivationDetailTable, // TValidationControlsDict AValidationControlsDictGift, // TValidationControlsDict AValidationControlsDictGiftDetail, // ACostCentreTable AValidationCostCentreTable, // AAccountTable AValidationAccountTable, // AMotivationGroupTable AValidationMotivationGroupTable, // AMethodOfGivingTable AValidationMethodOfGivingTable, // AMethodOfPaymentTable AValidationMethodOfPaymentTable, // PMailingTable AValidationMailingTable, GiftBatchTDSAGiftDetailTable ANeedRecipientLedgerNumber, AGiftDetailRow AGiftDetails) { // Start parsing int preParseMessageCount = AMessages.Count; // Is this the format with extra columns? // Actually if it has the extra columns but does not have the optional final 8 columns we cannot distiguish using this test... // A file without extra columns will have between 13 and 21 columns - depending on whether some of the optional ones at the end are included. // A file with extra columns will be between 19 and 27. // So any count between 19 and 21 is ambiguous. We will assume that if the file has extra columns it also has // at least enough of the optional ones to exceed 21. bool HasExtraColumns = (ANumberOfColumns > 21); AImportMessage = Catalog.GetString("Importing the gift data"); AGift.DonorKey = TCommonImport.ImportInt64(ref FImportLine, FDelimiter, Catalog.GetString("Donor key"), FMainDS.AGift.ColumnDonorKey, ARowNumber, AMessages, null); TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString( "short name of donor (unused)"), null, ARowNumber, AMessages, null); // unused // This group is optional and database NULL's are allowed AGift.MethodOfGivingCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Method of giving Code"), FMainDS.AGift.ColumnMethodOfGivingCode, ARowNumber, AMessages, null, false); AGift.MethodOfPaymentCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Method Of Payment Code"), FMainDS.AGift.ColumnMethodOfPaymentCode, ARowNumber, AMessages, null, false); AGift.Reference = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Reference"), FMainDS.AGift.ColumnReference, ARowNumber, AMessages, null, false); AGift.ReceiptLetterCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Receipt letter code"), FMainDS.AGift.ColumnReceiptLetterCode, ARowNumber, AMessages, null, false); if (AGift.MethodOfGivingCode != null) { AGift.MethodOfGivingCode = AGift.MethodOfGivingCode.ToUpper(); } if (AGift.MethodOfPaymentCode != null) { AGift.MethodOfPaymentCode = AGift.MethodOfPaymentCode.ToUpper(); } if (AGift.ReceiptLetterCode != null) { AGift.ReceiptLetterCode = AGift.ReceiptLetterCode.ToUpper(); } if (HasExtraColumns) { TCommonImport.ImportInt32(ref FImportLine, FDelimiter, Catalog.GetString("Receipt number"), FMainDS.AGift.ColumnReceiptNumber, ARowNumber, AMessages, null); TCommonImport.ImportBoolean(ref FImportLine, FDelimiter, Catalog.GetString("First time gift"), FMainDS.AGift.ColumnFirstTimeGift, ARowNumber, AMessages, null); TCommonImport.ImportBoolean(ref FImportLine, FDelimiter, Catalog.GetString("Receipt printed"), FMainDS.AGift.ColumnReceiptPrinted, ARowNumber, AMessages, null); } AImportMessage = Catalog.GetString("Importing the gift details"); if ((APreviousGift != null) && (AGift.DonorKey == APreviousGift.DonorKey) && (AGift.MethodOfGivingCode == APreviousGift.MethodOfGivingCode) && (AGift.MethodOfPaymentCode == APreviousGift.MethodOfPaymentCode) && (AGift.Reference == APreviousGift.Reference) && (AGift.ReceiptLetterCode == APreviousGift.ReceiptLetterCode) && (AGift.ReceiptNumber == APreviousGift.ReceiptNumber) && (AGift.FirstTimeGift == APreviousGift.FirstTimeGift) && (AGift.ReceiptPrinted == APreviousGift.ReceiptPrinted)) { // this row is a new detail for the previousGift AGift = APreviousGift; AGift.LastDetailNumber++; AGiftDetails.DetailNumber = AGift.LastDetailNumber; } else { APreviousGift = AGift; AGift.LedgerNumber = AGiftBatch.LedgerNumber; AGift.BatchNumber = AGiftBatch.BatchNumber; AGift.GiftTransactionNumber = AGiftBatch.LastGiftNumber + 1; AGiftBatch.LastGiftNumber++; AGift.LastDetailNumber = 1; FMainDS.AGift.Rows.Add(AGift); AGiftDetails.DetailNumber = 1; } AGiftDetails.LedgerNumber = AGift.LedgerNumber; AGiftDetails.BatchNumber = AGiftBatch.BatchNumber; AGiftDetails.GiftTransactionNumber = AGift.GiftTransactionNumber; FMainDS.AGiftDetail.Rows.Add(AGiftDetails); AGiftDetails.RecipientKey = TCommonImport.ImportInt64(ref FImportLine, FDelimiter, Catalog.GetString("Recipient key"), FMainDS.AGiftDetail.ColumnRecipientKey, ARowNumber, AMessages, null); TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString( "short name of recipient (unused)"), null, ARowNumber, AMessages, null); // unused if (HasExtraColumns) { TCommonImport.ImportInt32(ref FImportLine, FDelimiter, Catalog.GetString("Recipient ledger number"), FMainDS.AGiftDetail.ColumnRecipientLedgerNumber, ARowNumber, AMessages, null); } // we always calculate RecipientLedgerNumber AGiftDetails.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber( AGiftDetails.RecipientKey, AGiftBatch.GlEffectiveDate); decimal currentGiftAmount = TCommonImport.ImportDecimal(ref FImportLine, FDelimiter, FCultureInfoNumberFormat, Catalog.GetString("Gift amount"), FMainDS.AGiftDetail.ColumnGiftTransactionAmount, ARowNumber, AMessages, null); AGiftDetails.GiftTransactionAmount = currentGiftAmount; // amount in batch currency ATotalBatchAmount += currentGiftAmount; AGiftDetails.GiftAmount = GLRoutines.Divide(currentGiftAmount, AGiftBatch.ExchangeRateToBase); // amount in ledger currency if (HasExtraColumns) { // amount in international currency TCommonImport.ImportDecimal(ref FImportLine, FDelimiter, FCultureInfoNumberFormat, Catalog.GetString("Gift amount intl"), FMainDS.AGiftDetail.ColumnGiftAmountIntl, ARowNumber, AMessages, null); } else if (AIntlRateFromBase > 0.0m) { AGiftDetails.GiftAmountIntl = GLRoutines.Divide(AGiftDetails.GiftAmount, AIntlRateFromBase, 2); } AGiftDetails.ConfidentialGiftFlag = TCommonImport.ImportBoolean(ref FImportLine, FDelimiter, Catalog.GetString("Confidential gift"), FMainDS.AGiftDetail.ColumnConfidentialGiftFlag, ARowNumber, AMessages, null); AGiftDetails.MotivationGroupCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Motivation group code"), FMainDS.AGiftDetail.ColumnMotivationGroupCode, ARowNumber, AMessages, null).ToUpper(); AGiftDetails.MotivationDetailCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Motivation detail"), FMainDS.AGiftDetail.ColumnMotivationDetailCode, ARowNumber, AMessages, null).ToUpper(); if (HasExtraColumns) { TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Cost centre code"), FMainDS.AGiftDetail.ColumnCostCentreCode, ARowNumber, AMessages, null); } // "In Petra Cost Centre is always inferred from recipient field and motivation detail so is not needed in the import." AGiftDetails.CostCentreCode = TGiftTransactionWebConnector.RetrieveCostCentreCodeForRecipient( AGiftDetails.LedgerNumber, AGiftDetails.RecipientKey, AGiftDetails.RecipientLedgerNumber, AGift.DateEntered, AGiftDetails.MotivationGroupCode, AGiftDetails.MotivationDetailCode); // All the remaining columns are optional and can contain database NULL AGiftDetails.GiftCommentOne = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Gift comment one"), FMainDS.AGiftDetail.ColumnGiftCommentOne, ARowNumber, AMessages, null, false); string commentOneType = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Comment one type"), FMainDS.AGiftDetail.ColumnCommentOneType, ARowNumber, AMessages, null, false); AGiftDetails.MailingCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Mailing code"), FMainDS.AGiftDetail.ColumnMailingCode, ARowNumber, AMessages, null, false); AGiftDetails.GiftCommentTwo = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Gift comment two"), FMainDS.AGiftDetail.ColumnGiftCommentTwo, ARowNumber, AMessages, null, false); string commentTwoType = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Comment two type"), FMainDS.AGiftDetail.ColumnCommentTwoType, ARowNumber, AMessages, null, false); AGiftDetails.GiftCommentThree = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Gift comment three"), FMainDS.AGiftDetail.ColumnGiftCommentThree, ARowNumber, AMessages, null, false); string commentThreeType = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Comment three type"), FMainDS.AGiftDetail.ColumnCommentThreeType, ARowNumber, AMessages, null, false); SetCommentTypeCase(ref commentOneType); AGiftDetails.CommentOneType = commentOneType; SetCommentTypeCase(ref commentTwoType); AGiftDetails.CommentTwoType = commentTwoType; SetCommentTypeCase(ref commentThreeType); AGiftDetails.CommentThreeType = commentThreeType; if (AGiftDetails.MailingCode != null) { AGiftDetails.MailingCode = AGiftDetails.MailingCode.ToUpper(); } // Find the default Tax deductabilty from the motivation detail. This ensures that the column can be missing. AMotivationDetailRow motivationDetailRow = (AMotivationDetailRow)AMotivationDetailTable.Rows.Find( new object[] { FLedgerNumber, AGiftDetails.MotivationGroupCode, AGiftDetails.MotivationDetailCode }); string defaultTaxDeductible = ((motivationDetailRow != null) && !motivationDetailRow.IsTaxDeductibleAccountCodeNull() && motivationDetailRow.TaxDeductible) ? "yes" : "no"; AGiftDetails.TaxDeductible = TCommonImport.ImportBoolean(ref FImportLine, FDelimiter, Catalog.GetString("Tax deductible"), FMainDS.AGiftDetail.ColumnTaxDeductible, ARowNumber, AMessages, null, defaultTaxDeductible); // Account Codes are always inferred from the motivation detail and so is not needed in the import. string NewAccountCode = null; string NewTaxDeductibleAccountCode = null; // get up-to-date account codes if (motivationDetailRow != null) { NewAccountCode = motivationDetailRow.AccountCode; NewTaxDeductibleAccountCode = motivationDetailRow.TaxDeductibleAccountCode; } AGiftDetails.AccountCode = NewAccountCode; AGiftDetails.TaxDeductibleAccountCode = NewTaxDeductibleAccountCode; // Date entered cannot be imported although it can be modified in the GUI. // This is because it would have to be the last column in the import for compatibility // but it belongs with the gift and not the detail so it would need to go in an earlier column. // For now the import date entered is the effective date. AGift.DateEntered = AGiftBatch.GlEffectiveDate; // Enforce the correct case for our GIFT constant if (String.Compare(AGiftDetails.MotivationGroupCode, MFinanceConstants.MOTIVATION_GROUP_GIFT, true) == 0) { AGiftDetails.MotivationGroupCode = MFinanceConstants.MOTIVATION_GROUP_GIFT; } } // Parse TransactionLine
/// <summary> /// Adds a duplicate Gift Detail (or reversed duplicate GiftDetail) to Gift. /// </summary> /// <param name="AMainDS"></param> /// <param name="AGift"></param> /// <param name="AOldGiftDetail"></param> /// <param name="AReversal">True for reverse or false for straight duplicate</param> /// <param name="ATransaction"></param> /// <param name="ARequestParams"></param> private static void AddDuplicateGiftDetailToGift(ref GiftBatchTDS AMainDS, ref AGiftRow AGift, AGiftDetailRow AOldGiftDetail, bool AReversal, TDBTransaction ATransaction, Hashtable ARequestParams = null) { bool TaxDeductiblePercentageEnabled = Convert.ToBoolean( TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE")); GiftAdjustmentFunctionEnum Function = (GiftAdjustmentFunctionEnum)ARequestParams["Function"]; AGiftDetailRow giftDetail = AMainDS.AGiftDetail.NewRowTyped(true); DataUtilities.CopyAllColumnValuesWithoutPK(AOldGiftDetail, giftDetail); giftDetail.DetailNumber = AGift.LastDetailNumber + 1; AGift.LastDetailNumber++; giftDetail.LedgerNumber = AGift.LedgerNumber; giftDetail.BatchNumber = AGift.BatchNumber; giftDetail.GiftTransactionNumber = AGift.GiftTransactionNumber; decimal signum = (AReversal) ? -1 : 1; giftDetail.GiftTransactionAmount = signum * AOldGiftDetail.GiftTransactionAmount; giftDetail.GiftAmount = signum * AOldGiftDetail.GiftAmount; giftDetail.GiftAmountIntl = signum * AOldGiftDetail.GiftAmountIntl; if (TaxDeductiblePercentageEnabled) { if (!AReversal && Function.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust)) { giftDetail.TaxDeductiblePct = Convert.ToDecimal(ARequestParams["NewPct"]); TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetail); } else if (!AReversal) { if (ARequestParams.ContainsKey("UpdateTaxDeductiblePct")) { List <string[]>UpdateTaxDeductiblePctRecipeints = (List <string[]> )ARequestParams["UpdateTaxDeductiblePct"]; string[] Result = UpdateTaxDeductiblePctRecipeints.Find(x => x[0] == giftDetail.RecipientKey.ToString()); // true if a new percentage is available and the user wants to use it if (Result != null) { giftDetail.TaxDeductiblePct = Convert.ToDecimal(Result[1]); TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetail); } } } else { giftDetail.TaxDeductibleAmount = signum * AOldGiftDetail.TaxDeductibleAmount; giftDetail.TaxDeductibleAmountBase = signum * AOldGiftDetail.TaxDeductibleAmountBase; giftDetail.TaxDeductibleAmountIntl = signum * AOldGiftDetail.TaxDeductibleAmountIntl; giftDetail.NonDeductibleAmount = signum * AOldGiftDetail.NonDeductibleAmount; giftDetail.NonDeductibleAmountBase = signum * AOldGiftDetail.NonDeductibleAmountBase; giftDetail.NonDeductibleAmountIntl = signum * AOldGiftDetail.NonDeductibleAmountIntl; } } if (ARequestParams != null) { if ((bool)ARequestParams["AutoCompleteComments"]) // only used for tax deductible pct gift adjustments { AGiftRow OldGiftRow = (AGiftRow)AMainDS.AGift.Rows.Find( new object[] { AOldGiftDetail.LedgerNumber, AOldGiftDetail.BatchNumber, AOldGiftDetail.GiftTransactionNumber }); giftDetail.GiftCommentThree = Catalog.GetString("Original gift date: " + OldGiftRow.DateEntered.ToString("dd-MMM-yyyy")); giftDetail.CommentThreeType = "Both"; } else // user defined { giftDetail.GiftCommentOne = (String)ARequestParams["ReversalCommentOne"]; giftDetail.GiftCommentTwo = (String)ARequestParams["ReversalCommentTwo"]; giftDetail.GiftCommentThree = (String)ARequestParams["ReversalCommentThree"]; giftDetail.CommentOneType = (String)ARequestParams["ReversalCommentOneType"]; giftDetail.CommentTwoType = (String)ARequestParams["ReversalCommentTwoType"]; giftDetail.CommentThreeType = (String)ARequestParams["ReversalCommentThreeType"]; } } // If reversal: mark the new gift as a reversal if (AReversal) { giftDetail.ModifiedDetail = true; //Identify the reversal source giftDetail.ModifiedDetailKey = "|" + AOldGiftDetail.BatchNumber.ToString() + "|" + AOldGiftDetail.GiftTransactionNumber.ToString() + "|" + AOldGiftDetail.DetailNumber.ToString(); } else { giftDetail.ModifiedDetail = false; // Make sure the motivation detail is still active. If not then we need a new one. AMotivationDetailTable MotivationDetailTable = AMotivationDetailAccess.LoadViaAMotivationGroup( giftDetail.LedgerNumber, giftDetail.MotivationGroupCode, ATransaction); DataRow CurrentMotivationDetail = MotivationDetailTable.Rows.Find( new object[] { giftDetail.LedgerNumber, giftDetail.MotivationGroupCode, giftDetail.MotivationDetailCode }); // Motivation detail has been made inactive (or doesn't exist) then use default if (!((MotivationDetailTable != null) && (MotivationDetailTable.Rows.Count > 0) && (CurrentMotivationDetail != null)) || !Convert.ToBoolean(CurrentMotivationDetail[AMotivationDetailTable.GetMotivationStatusDBName()])) { bool ActiveRowFound = false; // search for first alternative active detail that is part of the same group foreach (AMotivationDetailRow Row in MotivationDetailTable.Rows) { if ((Row.MotivationDetailCode != giftDetail.MotivationDetailCode) && Row.MotivationStatus) { ActiveRowFound = true; giftDetail.MotivationGroupCode = Row.MotivationGroupCode; giftDetail.MotivationDetailCode = Row.MotivationDetailCode; break; } } // if none found then use default group and detail if (!ActiveRowFound) { giftDetail.MotivationGroupCode = MFinanceConstants.MOTIVATION_GROUP_GIFT; giftDetail.MotivationDetailCode = MFinanceConstants.GROUP_DETAIL_SUPPORT; } } // if the gift destination should be fixed if (ARequestParams.ContainsKey("FixedGiftDestination") && (Function.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust) && (bool)ARequestParams["FixedGiftDestination"] || (((List <string> )ARequestParams["FixedGiftDestination"]).Exists(x => x == giftDetail.RecipientKey.ToString())))) { giftDetail.FixedGiftDestination = true; } else { giftDetail.FixedGiftDestination = false; } } AMainDS.AGiftDetail.Rows.Add(giftDetail); }
public static Int32 CreateGiftBatch( Int32 ALedgerNumber, Int32 AStatementKey, Int32 AGiftBatchNumber, out TVerificationResultCollection AVerificationResult) { BankImportTDS MainDS = GetBankStatementTransactionsAndMatches(AStatementKey, ALedgerNumber); string MyClientID = DomainManager.GClientID.ToString(); TProgressTracker.InitProgressTracker(MyClientID, Catalog.GetString("Creating gift batch"), MainDS.AEpTransaction.DefaultView.Count + 10); AVerificationResult = new TVerificationResultCollection(); MainDS.AEpTransaction.DefaultView.RowFilter = String.Format("{0}={1}", AEpTransactionTable.GetStatementKeyDBName(), AStatementKey); MainDS.AEpStatement.DefaultView.RowFilter = String.Format("{0}={1}", AEpStatementTable.GetStatementKeyDBName(), AStatementKey); AEpStatementRow stmt = (AEpStatementRow)MainDS.AEpStatement.DefaultView[0].Row; // TODO: optional: use the preselected gift batch, AGiftBatchNumber Int32 DateEffectivePeriodNumber, DateEffectiveYearNumber; DateTime BatchDateEffective = stmt.Date; TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted); if (!TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber, ref BatchDateEffective, out DateEffectiveYearNumber, out DateEffectivePeriodNumber, Transaction, true)) { // just use the latest possible date string msg = String.Format(Catalog.GetString("Date {0} is not in an open period of the ledger, using date {1} instead for the gift batch."), stmt.Date.ToShortDateString(), BatchDateEffective.ToShortDateString()); AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating Gift Batch"), msg, TResultSeverity.Resv_Info)); } ACostCentreAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction); AMotivationDetailAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction); MainDS.AEpMatch.DefaultView.Sort = AEpMatchTable.GetActionDBName() + ", " + AEpMatchTable.GetMatchTextDBName(); if (MainDS.AEpTransaction.DefaultView.Count == 0) { AVerificationResult.Add(new TVerificationResult( Catalog.GetString("Creating Gift Batch"), String.Format(Catalog.GetString("There are no transactions for statement #{0}."), AStatementKey), TResultSeverity.Resv_Info)); return(-1); } foreach (DataRowView dv in MainDS.AEpTransaction.DefaultView) { AEpTransactionRow transactionRow = (AEpTransactionRow)dv.Row; DataRowView[] matches = MainDS.AEpMatch.DefaultView.FindRows(new object[] { MFinanceConstants.BANK_STMT_STATUS_MATCHED_GIFT, transactionRow.MatchText }); if (matches.Length > 0) { AEpMatchRow match = (AEpMatchRow)matches[0].Row; if (match.IsDonorKeyNull() || (match.DonorKey == 0)) { string msg = String.Format(Catalog.GetString("Cannot create a gift for transaction {0} since there is no valid donor."), transactionRow.Description); AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating Gift Batch"), msg, TResultSeverity.Resv_Critical)); DBAccess.GDBAccessObj.RollbackTransaction(); return(-1); } } } string MatchedGiftReference = stmt.Filename; if (!stmt.IsBankAccountKeyNull()) { string sqlGetBankSortCode = "SELECT bank.p_branch_code_c " + "FROM PUB_p_banking_details details, PUB_p_bank bank " + "WHERE details.p_banking_details_key_i = ?" + "AND details.p_bank_key_n = bank.p_partner_key_n"; OdbcParameter param = new OdbcParameter("detailkey", OdbcType.Int); param.Value = stmt.BankAccountKey; PBankTable bankTable = new PBankTable(); DBAccess.GDBAccessObj.SelectDT(bankTable, sqlGetBankSortCode, Transaction, new OdbcParameter[] { param }, 0, 0); MatchedGiftReference = bankTable[0].BranchCode + " " + stmt.Date.Day.ToString(); } DBAccess.GDBAccessObj.RollbackTransaction(); GiftBatchTDS GiftDS = TGiftTransactionWebConnector.CreateAGiftBatch( ALedgerNumber, BatchDateEffective, String.Format(Catalog.GetString("bank import for date {0}"), stmt.Date.ToShortDateString())); AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0]; giftbatchRow.BankAccountCode = stmt.BankAccountCode; decimal HashTotal = 0.0M; MainDS.AEpTransaction.DefaultView.Sort = AEpTransactionTable.GetNumberOnPaperStatementDBName(); MainDS.AEpMatch.DefaultView.RowFilter = String.Empty; MainDS.AEpMatch.DefaultView.Sort = AEpMatchTable.GetActionDBName() + ", " + AEpMatchTable.GetMatchTextDBName(); int counter = 5; foreach (DataRowView dv in MainDS.AEpTransaction.DefaultView) { TProgressTracker.SetCurrentState(MyClientID, Catalog.GetString("Preparing the gifts"), counter++); AEpTransactionRow transactionRow = (AEpTransactionRow)dv.Row; DataRowView[] matches = MainDS.AEpMatch.DefaultView.FindRows(new object[] { MFinanceConstants.BANK_STMT_STATUS_MATCHED_GIFT, transactionRow.MatchText }); if (matches.Length > 0) { AEpMatchRow match = (AEpMatchRow)matches[0].Row; AGiftRow gift = GiftDS.AGift.NewRowTyped(); gift.LedgerNumber = giftbatchRow.LedgerNumber; gift.BatchNumber = giftbatchRow.BatchNumber; gift.GiftTransactionNumber = giftbatchRow.LastGiftNumber + 1; gift.DonorKey = match.DonorKey; gift.DateEntered = transactionRow.DateEffective; gift.Reference = MatchedGiftReference; GiftDS.AGift.Rows.Add(gift); giftbatchRow.LastGiftNumber++; foreach (DataRowView r in matches) { match = (AEpMatchRow)r.Row; AGiftDetailRow detail = GiftDS.AGiftDetail.NewRowTyped(); detail.LedgerNumber = gift.LedgerNumber; detail.BatchNumber = gift.BatchNumber; detail.GiftTransactionNumber = gift.GiftTransactionNumber; detail.DetailNumber = gift.LastDetailNumber + 1; gift.LastDetailNumber++; detail.GiftTransactionAmount = match.GiftTransactionAmount; detail.GiftAmount = match.GiftTransactionAmount; HashTotal += match.GiftTransactionAmount; detail.MotivationGroupCode = match.MotivationGroupCode; detail.MotivationDetailCode = match.MotivationDetailCode; // do not use the description in comment one, because that could show up on the gift receipt??? // detail.GiftCommentOne = transactionRow.Description; detail.CommentOneType = MFinanceConstants.GIFT_COMMENT_TYPE_BOTH; detail.CostCentreCode = match.CostCentreCode; detail.RecipientKey = match.RecipientKey; detail.RecipientLedgerNumber = match.RecipientLedgerNumber; AMotivationDetailRow motivation = (AMotivationDetailRow)MainDS.AMotivationDetail.Rows.Find( new object[] { ALedgerNumber, detail.MotivationGroupCode, detail.MotivationDetailCode }); if (motivation == null) { AVerificationResult.Add(new TVerificationResult( String.Format(Catalog.GetString("creating gift for match {0}"), transactionRow.Description), String.Format(Catalog.GetString("Cannot find motivation group '{0}' and motivation detail '{1}'"), detail.MotivationGroupCode, detail.MotivationDetailCode), TResultSeverity.Resv_Critical)); } if (detail.CostCentreCode.Length == 0) { // try to retrieve the current costcentre for this recipient if (detail.RecipientKey != 0) { detail.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(detail.RecipientKey); detail.CostCentreCode = TGiftTransactionWebConnector.IdentifyPartnerCostCentre(detail.LedgerNumber, detail.RecipientLedgerNumber); } else { if (motivation != null) { detail.CostCentreCode = motivation.CostCentreCode; } } } // check for active cost centre ACostCentreRow costcentre = (ACostCentreRow)MainDS.ACostCentre.Rows.Find(new object[] { ALedgerNumber, detail.CostCentreCode }); if ((costcentre == null) || !costcentre.CostCentreActiveFlag) { AVerificationResult.Add(new TVerificationResult( String.Format(Catalog.GetString("creating gift for match {0}"), transactionRow.Description), Catalog.GetString("Invalid or inactive cost centre"), TResultSeverity.Resv_Critical)); } GiftDS.AGiftDetail.Rows.Add(detail); } } } TProgressTracker.SetCurrentState(MyClientID, Catalog.GetString("Submit to database"), counter++); if (AVerificationResult.HasCriticalErrors) { return(-1); } giftbatchRow.HashTotal = HashTotal; giftbatchRow.BatchTotal = HashTotal; // do not overwrite the parameter, because there might be the hint for a different gift batch date TVerificationResultCollection VerificationResultSubmitChanges; TSubmitChangesResult result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref GiftDS, out VerificationResultSubmitChanges); TProgressTracker.FinishJob(MyClientID); if (result == TSubmitChangesResult.scrOK) { return(giftbatchRow.BatchNumber); } return(-1); }
/// <summary> /// Main method to post a specified batch /// </summary> /// <param name="ACurrentBatchRow">The batch row to post</param> /// <param name="APostingAlreadyConfirmed">True means ask user if they want to post</param> /// <param name="AWarnOfInactiveValues">True means user is warned if inactive values exist</param> /// <param name="ADonorZeroIsValid"></param> /// <param name="ARecipientZeroIsValid"></param> /// <returns>True if the batch was successfully posted</returns> public bool PostBatch(AGiftBatchRow ACurrentBatchRow, bool APostingAlreadyConfirmed = false, bool AWarnOfInactiveValues = true, bool ADonorZeroIsValid = false, bool ARecipientZeroIsValid = false) { //This assumes that all gift data etc is loaded into the batch before arriving here bool RetVal = false; if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)) { return(RetVal); } FSelectedBatchNumber = ACurrentBatchRow.BatchNumber; TVerificationResultCollection Verifications; try { //Make sure that all control data is in dataset FMyForm.GetControlDataForPosting(); GiftBatchTDSAGiftDetailTable batchGiftDetails = new GiftBatchTDSAGiftDetailTable(); DataView batchGiftDetailsDV = new DataView(FMainDS.AGiftDetail); batchGiftDetailsDV.RowFilter = string.Format("{0}={1}", AGiftDetailTable.GetBatchNumberDBName(), FSelectedBatchNumber); batchGiftDetailsDV.Sort = string.Format("{0} ASC, {1} ASC, {2} ASC", AGiftDetailTable.GetBatchNumberDBName(), AGiftDetailTable.GetGiftTransactionNumberDBName(), AGiftDetailTable.GetDetailNumberDBName()); foreach (DataRowView drv in batchGiftDetailsDV) { GiftBatchTDSAGiftDetailRow gBRow = (GiftBatchTDSAGiftDetailRow)drv.Row; batchGiftDetails.Rows.Add((object[])gBRow.ItemArray.Clone()); } bool CancelledDueToExWorkerOrAnonDonor; // save first, then post if (!FMyForm.SaveChangesForPosting(batchGiftDetails, out CancelledDueToExWorkerOrAnonDonor)) { FMyForm.Cursor = Cursors.Default; if (!CancelledDueToExWorkerOrAnonDonor) { // saving failed, therefore do not try to post MessageBox.Show(Catalog.GetString("The batch was not posted due to problems during saving; ") + Environment.NewLine + Catalog.GetString("Please first correct and save the batch, and then post it!")); } return(RetVal); } } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } //Check for missing international exchange rate bool IsTransactionInIntlCurrency = false; FMyForm.WarnAboutMissingIntlExchangeRate = true; if (FMyForm.InternationalCurrencyExchangeRate(ACurrentBatchRow, out IsTransactionInIntlCurrency, true) == 0) { return(RetVal); } //Check for zero Donors or Recipients if (!ADonorZeroIsValid) { DataView batchGiftDV = new DataView(FMainDS.AGift); batchGiftDV.RowFilter = string.Format("{0}={1} And {2}=0", AGiftTable.GetBatchNumberDBName(), FSelectedBatchNumber, AGiftTable.GetDonorKeyDBName()); int numDonorZeros = batchGiftDV.Count; if (numDonorZeros > 0) { string messageListOfOffendingGifts = String.Format(Catalog.GetString( "Gift Batch {0} contains {1} gift detail(s) with Donor 0000000. Please fix before posting!{2}{2}"), FSelectedBatchNumber, numDonorZeros, Environment.NewLine); string listOfOffendingRows = string.Empty; listOfOffendingRows += "Gift" + Environment.NewLine; listOfOffendingRows += "------------"; foreach (DataRowView drv in batchGiftDV) { AGiftRow giftRow = (AGiftRow)drv.Row; listOfOffendingRows += String.Format("{0}{1:0000}", Environment.NewLine, giftRow.GiftTransactionNumber); } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); return(RetVal); } } if (!ARecipientZeroIsValid) { DataView batchGiftDetailsDV = new DataView(FMainDS.AGiftDetail); batchGiftDetailsDV.RowFilter = string.Format("{0}={1} And {2}=0", AGiftDetailTable.GetBatchNumberDBName(), FSelectedBatchNumber, AGiftDetailTable.GetRecipientKeyDBName()); int numRecipientZeros = batchGiftDetailsDV.Count; if (numRecipientZeros > 0) { string messageListOfOffendingGifts = String.Format(Catalog.GetString( "Gift Batch {0} contains {1} gift detail(s) with Recipient 0000000. Please fix before posting!{2}{2}"), FSelectedBatchNumber, numRecipientZeros, Environment.NewLine); string listOfOffendingRows = string.Empty; listOfOffendingRows += "Gift Detail" + Environment.NewLine; listOfOffendingRows += "-------------------"; foreach (DataRowView drv in batchGiftDetailsDV) { AGiftDetailRow giftDetailRow = (AGiftDetailRow)drv.Row; listOfOffendingRows += String.Format("{0}{1:0000} {2:00}", Environment.NewLine, giftDetailRow.GiftTransactionNumber, giftDetailRow.DetailNumber); } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); return(RetVal); } } //Check for inactive KeyMinistries DataTable GiftsWithInactiveKeyMinistries; bool ModifiedDetails = false; if (AWarnOfInactiveValues && TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber, out GiftsWithInactiveKeyMinistries, false)) { int numInactiveValues = GiftsWithInactiveKeyMinistries.Rows.Count; string messageNonModifiedBatch = String.Format(Catalog.GetString("Gift Batch {0} contains {1} inactive key ministries. Please fix before posting!{2}{2}"), FSelectedBatchNumber, numInactiveValues, Environment.NewLine); string messageModifiedBatch = String.Format(Catalog.GetString( "Reversal/Adjustment Gift Batch {0} contains {1} inactive key ministries. Do you still want to post?{2}{2}"), FSelectedBatchNumber, numInactiveValues, Environment.NewLine); string listOfOffendingRows = string.Empty; listOfOffendingRows += "Gift Detail Recipient KeyMinistry" + Environment.NewLine; listOfOffendingRows += "-------------------------------------------------------------------------------"; foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows) { listOfOffendingRows += String.Format("{0}{1:0000} {2:00} {3:00000000000} {4}", Environment.NewLine, dr[0], dr[1], dr[2], dr[3]); bool isModified = Convert.ToBoolean(dr[4]); if (isModified) { ModifiedDetails = true; } } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); if (ModifiedDetails) { if (extendedMessageBox.ShowDialog((messageModifiedBatch + listOfOffendingRows), Catalog.GetString("Post Batch"), string.Empty, TFrmExtendedMessageBox.TButtons.embbYesNo, TFrmExtendedMessageBox.TIcon.embiWarning) == TFrmExtendedMessageBox.TResult.embrYes) { APostingAlreadyConfirmed = true; } else { return(RetVal); } } else { extendedMessageBox.ShowDialog((messageNonModifiedBatch + listOfOffendingRows), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); return(RetVal); } } // ask if the user really wants to post the batch if (!APostingAlreadyConfirmed && (MessageBox.Show(String.Format(Catalog.GetString("Do you really want to post gift batch {0}?"), FSelectedBatchNumber), Catalog.GetString("Confirm posting of Gift Batch"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)) { return(RetVal); } Verifications = new TVerificationResultCollection(); try { FPostingInProgress = true; Thread postingThread = new Thread(() => PostGiftBatch(out Verifications)); using (TProgressDialog dialog = new TProgressDialog(postingThread)) { dialog.ShowDialog(); } if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications)) { TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); StringBuilder errorMessages = new StringBuilder(); int counter = 0; errorMessages.AppendLine(Catalog.GetString("________________________Gift Posting Errors________________________")); errorMessages.AppendLine(); foreach (TVerificationResult verif in Verifications) { counter++; errorMessages.AppendLine(counter.ToString("000") + " - " + verif.ResultText); errorMessages.AppendLine(); } extendedMessageBox.ShowDialog(errorMessages.ToString(), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); } else { MessageBox.Show(Catalog.GetString("The batch has been posted successfully!")); RetVal = true; } } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { FPostingInProgress = false; } return(RetVal); }
private bool OnDeleteRowManual(GiftBatchTDSAGiftDetailRow ARowToDelete, ref string ACompletionMessage) { bool DeletionSuccessful = false; List <string> OriginatingDetailRef = new List <string>(); ACompletionMessage = string.Empty; if (ARowToDelete == null) { return(DeletionSuccessful); } bool RowToDeleteIsNew = (ARowToDelete.RowState == DataRowState.Added); if (!RowToDeleteIsNew) { try { // temporarily disable New Donor Warning ((TFrmGiftBatch)this.ParentForm).NewDonorWarning = false; //Return modified row to last saved state to avoid validation failures ARowToDelete.RejectChanges(); ShowDetails(ARowToDelete); if (!((TFrmGiftBatch)this.ParentForm).SaveChanges()) { MessageBox.Show(Catalog.GetString("Error in trying to save prior to deleting current gift detail!"), Catalog.GetString("Deletion Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(DeletionSuccessful); } } finally { ((TFrmGiftBatch)this.ParentForm).NewDonorWarning = true; } } //Backup the Dataset for reversion purposes GiftBatchTDS BackupMainDS = (GiftBatchTDS)FMainDS.Copy(); BackupMainDS.Merge(FMainDS); //To be used later....Pass copy to delete method. //GiftBatchTDS TempDS = (GiftBatchTDS)FMainDS.Copy(); //TempDS.Merge(FMainDS); int SelectedDetailNumber = ARowToDelete.DetailNumber; int GiftToDeleteTransNo = 0; string FilterAllGiftsOfBatch = String.Empty; string FilterAllGiftDetailsOfBatch = String.Empty; int DetailRowCount = FGiftDetailView.Count; try { this.Cursor = Cursors.WaitCursor; //Speeds up deletion of larger gift sets FMainDS.EnforceConstraints = false; if ((ARowToDelete.ModifiedDetailKey != null) && (ARowToDelete.ModifiedDetailKey.Length > 0)) { OriginatingDetailRef.Add(ARowToDelete.ModifiedDetailKey); } //Delete current detail row ARowToDelete.Delete(); //If there existed (before the delete row above) more than one detail row, then no need to delete gift header row if (DetailRowCount > 1) { ACompletionMessage = Catalog.GetString("Gift Detail row deleted successfully!"); FGiftSelectedForDeletion = false; foreach (DataRowView rv in FGiftDetailView) { GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row; if (row.DetailNumber > SelectedDetailNumber) { row.DetailNumber--; } } FGift.LastDetailNumber--; FPetraUtilsObject.SetChangedFlag(); } else { ACompletionMessage = Catalog.GetString("Gift deleted successfully!"); GiftToDeleteTransNo = FGift.GiftTransactionNumber; // Reduce all Gift Detail row Transaction numbers by 1 if they are greater then gift to be deleted FilterAllGiftDetailsOfBatch = String.Format("{0}={1} And {2}>{3}", AGiftDetailTable.GetBatchNumberDBName(), FBatchNumber, AGiftDetailTable.GetGiftTransactionNumberDBName(), GiftToDeleteTransNo); DataView giftDetailView = new DataView(FMainDS.AGiftDetail); giftDetailView.RowFilter = FilterAllGiftDetailsOfBatch; giftDetailView.Sort = String.Format("{0} ASC", AGiftDetailTable.GetGiftTransactionNumberDBName()); foreach (DataRowView rv in giftDetailView) { GiftBatchTDSAGiftDetailRow row = (GiftBatchTDSAGiftDetailRow)rv.Row; row.GiftTransactionNumber--; } //Cannot delete the gift row, just copy the data of rows above down by 1 row // and then mark the top row for deletion //In other words, bubble the gift row to be deleted to the top FilterAllGiftsOfBatch = String.Format("{0}={1} And {2}>={3}", AGiftTable.GetBatchNumberDBName(), FBatchNumber, AGiftTable.GetGiftTransactionNumberDBName(), GiftToDeleteTransNo); DataView giftView = new DataView(FMainDS.AGift); giftView.RowFilter = FilterAllGiftsOfBatch; giftView.Sort = String.Format("{0} ASC", AGiftTable.GetGiftTransactionNumberDBName()); AGiftRow giftRowToReceive = null; AGiftRow giftRowToCopyDown = null; AGiftRow giftRowCurrent = null; int currentGiftTransNo = 0; foreach (DataRowView gv in giftView) { giftRowCurrent = (AGiftRow)gv.Row; currentGiftTransNo = giftRowCurrent.GiftTransactionNumber; if (currentGiftTransNo > GiftToDeleteTransNo) { giftRowToCopyDown = giftRowCurrent; //Copy column values down for (int j = 3; j < giftRowToCopyDown.Table.Columns.Count; j++) { //Update all columns except the pk fields that remain the same if (!giftRowToCopyDown.Table.Columns[j].ColumnName.EndsWith("_text")) { giftRowToReceive[j] = giftRowToCopyDown[j]; } } } if (currentGiftTransNo == FBatchRow.LastGiftNumber) { //Mark last record for deletion giftRowCurrent.GiftStatus = MFinanceConstants.MARKED_FOR_DELETION; } //Will always be previous row giftRowToReceive = giftRowCurrent; } FPreviouslySelectedDetailRow = null; FPetraUtilsObject.SetChangedFlag(); FGiftSelectedForDeletion = true; FBatchRow.LastGiftNumber--; } //Try to save changes if (((TFrmGiftBatch)this.ParentForm).SaveChangesManual()) { //Check if have deleted a reversing gift detail if (OriginatingDetailRef.Count > 0) { TRemote.MFinance.Gift.WebConnectors.ReversedGiftReset(FLedgerNumber, OriginatingDetailRef); } //Clear current batch's gift data and reload from server RefreshCurrentBatchGiftData(FBatchNumber, true); } else { throw new Exception("Unable to save after deleting a gift!"); } DeletionSuccessful = true; } catch (Exception ex) { //Revert to previous state RevertDataSet(FMainDS, BackupMainDS); TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { FMainDS.EnforceConstraints = true; SetGiftDetailDefaultView(); FFilterAndFindObject.ApplyFilter(); this.Cursor = Cursors.Default; } UpdateRecordNumberDisplay(); return(DeletionSuccessful); }
/// <summary> /// Creates data needed to test posting recalculations /// </summary> /// <param name="ARecipientKey">Partner Key of the recipient.</param> /// <param name="ARealRecipientLedgerNumber">What the RecipientLedgerNumber should be.</param> /// <param name="AFalseRecipientLedgerNumber">What the RecipientLedgerNumber is.</param> /// <param name="ARealCostCentreCode">What the CostCentreCode should be.</param> /// <param name="AFalseCostCentreCode">What the CostCentreCode is.</param> /// <param name="AGiftBatchNumber">Batch Number.</param> private void TestBatchPostingRecalculations_Arrange(out long ARecipientKey, out long ARealRecipientLedgerNumber, out long AFalseRecipientLedgerNumber, string ARealCostCentreCode, string AFalseCostCentreCode, out Int32 AGiftBatchNumber) { TVerificationResultCollection VerificationResult; TSubmitChangesResult Result; DataSet ResponseDS; TPartnerEditUIConnector PartnerEditUIUIConnector = new TPartnerEditUIConnector(); GiftBatchTDS MainDS = new GiftBatchTDS(); PartnerEditTDS PartnerEditDS = new PartnerEditTDS(); //GLSetupTDS GLSetupDS = new GLSetupTDS(); // this is a family partner in the test database const Int64 DONORKEY = 43005001; // create a new recipient TCreateTestPartnerData.CreateNewFamilyPartner(PartnerEditDS); ARecipientKey = PartnerEditDS.PFamily[0].PartnerKey; // create two new Unit partners TCreateTestPartnerData.CreateNewUnitPartner(PartnerEditDS); TCreateTestPartnerData.CreateNewUnitPartner(PartnerEditDS); AFalseRecipientLedgerNumber = PartnerEditDS.PPartner[0].PartnerKey; ARealRecipientLedgerNumber = PartnerEditDS.PPartner[1].PartnerKey; // create a Gift Destination for family PPartnerGiftDestinationRow GiftDestination = PartnerEditDS.PPartnerGiftDestination.NewRowTyped(true); GiftDestination.Key = TPartnerDataReaderWebConnector.GetNewKeyForPartnerGiftDestination(); GiftDestination.PartnerKey = ARecipientKey; GiftDestination.DateEffective = new DateTime(2011, 01, 01); GiftDestination.FieldKey = ARealRecipientLedgerNumber; PartnerEditDS.PPartnerGiftDestination.Rows.Add(GiftDestination); // Guard Assertions Assert.That(PartnerEditDS.PFamily[0], Is.Not.Null); Assert.That(PartnerEditDS.PPartner[0], Is.Not.Null); Assert.That(PartnerEditDS.PPartner[1], Is.Not.Null); // Submit the new PartnerEditTDS records to the database ResponseDS = new PartnerEditTDS(); Result = PartnerEditUIUIConnector.SubmitChanges(ref PartnerEditDS, ref ResponseDS, out VerificationResult); // Guard Assertion Assert.That(Result, Is.EqualTo( TSubmitChangesResult.scrOK), "SubmitChanges for PartnerEditDS failed: " + VerificationResult.BuildVerificationResultString()); // link unit to Cost Centre DataTable PartnerCostCentreTbl = TGLSetupWebConnector.LoadCostCentrePartnerLinks(FLedgerNumber, 0); DataRow PartnerCostCentreRow = PartnerCostCentreTbl.NewRow(); PartnerCostCentreRow["PartnerKey"] = ARealRecipientLedgerNumber; PartnerCostCentreRow["IsLinked"] = ARealCostCentreCode; PartnerCostCentreTbl.Rows.Add(PartnerCostCentreRow); TGLSetupWebConnector.SaveCostCentrePartnerLinks(FLedgerNumber, PartnerCostCentreTbl); // create a new Gift Batch MainDS = TGiftTransactionWebConnector.CreateAGiftBatch(FLedgerNumber); AGiftBatchNumber = MainDS.AGiftBatch[0].BatchNumber; // create two new gifts AGiftRow GiftRow = MainDS.AGift.NewRowTyped(true); GiftRow.LedgerNumber = FLedgerNumber; GiftRow.BatchNumber = AGiftBatchNumber; GiftRow.DonorKey = DONORKEY; GiftRow.GiftTransactionNumber = 1; GiftRow.LastDetailNumber = 1; MainDS.AGift.Rows.Add(GiftRow); GiftRow = MainDS.AGift.NewRowTyped(true); GiftRow.LedgerNumber = FLedgerNumber; GiftRow.BatchNumber = AGiftBatchNumber; GiftRow.DonorKey = DONORKEY; GiftRow.GiftTransactionNumber = 2; GiftRow.LastDetailNumber = 1; MainDS.AGift.Rows.Add(GiftRow); // create a new GiftDetail with a positive amount AGiftDetailRow GiftDetail = MainDS.AGiftDetail.NewRowTyped(true); GiftDetail.LedgerNumber = FLedgerNumber; GiftDetail.BatchNumber = AGiftBatchNumber; GiftDetail.GiftTransactionNumber = 1; GiftDetail.DetailNumber = 1; GiftDetail.RecipientLedgerNumber = AFalseRecipientLedgerNumber; GiftDetail.GiftAmount = 100; GiftDetail.MotivationGroupCode = "GIFT"; GiftDetail.MotivationDetailCode = "SUPPORT"; GiftDetail.RecipientKey = ARecipientKey; GiftDetail.CostCentreCode = AFalseCostCentreCode; GiftDetail.GiftTransactionAmount = 100; MainDS.AGiftDetail.Rows.Add(GiftDetail); // create a new GiftDetail with a negative amount GiftDetail = MainDS.AGiftDetail.NewRowTyped(true); GiftDetail.LedgerNumber = FLedgerNumber; GiftDetail.BatchNumber = AGiftBatchNumber; GiftDetail.GiftTransactionNumber = 2; GiftDetail.DetailNumber = 1; GiftDetail.RecipientLedgerNumber = AFalseRecipientLedgerNumber; GiftDetail.GiftAmount = -100; GiftDetail.MotivationGroupCode = "GIFT"; GiftDetail.MotivationDetailCode = "SUPPORT"; GiftDetail.RecipientKey = ARecipientKey; GiftDetail.CostCentreCode = AFalseCostCentreCode; GiftDetail.GiftTransactionAmount = -100; MainDS.AGiftDetail.Rows.Add(GiftDetail); // Submit the new GiftBatchTDS records to the database Result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref MainDS, out VerificationResult); // Guard Assertion Assert.That(Result, Is.EqualTo( TSubmitChangesResult.scrOK), "SaveGiftBatchTDS failed: " + VerificationResult.BuildVerificationResultString()); }
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> /// 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(); } }