/// <summary> /// Export the cost centres /// </summary> public static void ExportCostCentres(string AOutputPath, char ACSVSeparator, string ANewLine, Int32 ALedgerNumber, List <string> ACostCentres) { string filename = Path.GetFullPath(Path.Combine(AOutputPath, "costcentre.csv")); Console.WriteLine("Writing file: " + filename); StringBuilder sb = new StringBuilder(); ACostCentreTable costcentres = ACostCentreAccess.LoadViaALedger(ALedgerNumber, null); costcentres.DefaultView.Sort = ACostCentreTable.GetCostCentreCodeDBName(); foreach (ACostCentreRow row in costcentres.Rows) { if (ACostCentres.Contains(row.CostCentreCode)) { ACostCentreRow departmentRow = GetDepartmentCostCentre(costcentres, row, StringHelper.StrSplit(TAppSettingsManager.GetValue("SummaryCostCentres", "4300S"), ",")); sb.Append(StringHelper.StrMerge(new string[] { row.CostCentreCode, row.CostCentreName, departmentRow.CostCentreName }, ACSVSeparator)); sb.Append(ANewLine); } } StreamWriter sw = new StreamWriter(filename, false, Encoding.GetEncoding(1252)); sw.Write(sb.ToString()); sw.Close(); }
private void InsertNodeIntoTreeView(TreeNode AParent, DataView view, ACostCentreRow ADetailRow) { TreeNode newNode = new TreeNode(""); CostCentreNodeDetails NewNodeDetails = CostCentreNodeDetails.AddNewCostCentre(newNode, ADetailRow); NewNodeDetails.IsNew = false; SetNodeLabel(ADetailRow, newNode); if (AParent == null) { trvCostCentres.Nodes.Add(newNode); } else { InsertInOrder(AParent, newNode); } view.RowFilter = ACostCentreTable.GetCostCentreToReportToDBName() + " = '" + ADetailRow.CostCentreCode + "'"; if (view.Count > 0) { // A cost centre cannot be deleted if it has children. NewNodeDetails.CanDelete = false; NewNodeDetails.Msg = Catalog.GetString("Child Cost Centres must be deleted first."); NewNodeDetails.CanHaveChildren = true; foreach (DataRowView rowView in view) { InsertNodeIntoTreeView(newNode, view, (ACostCentreRow)rowView.Row); } } }
/// <summary> /// Load CostCentre hierarchy from the dataset into the tree view /// </summary> public void PopulateTreeView(GLSetupTDS MainDS) { FDuringInitialisation = true; trvCostCentres.BeginUpdate(); trvCostCentres.Nodes.Clear(); // find the root cost centre MainDS.ACostCentre.DefaultView.RowFilter = ACostCentreTable.GetCostCentreToReportToDBName() + " IS NULL"; DataView view = new DataView(MainDS.ACostCentre); view.Sort = ACostCentreTable.GetCostCentreCodeDBName(); InsertNodeIntoTreeView(null, view, (ACostCentreRow)MainDS.ACostCentre.DefaultView[0].Row); MainDS.ACostCentre.DefaultView.RowFilter = ""; trvCostCentres.EndUpdate(); this.trvCostCentres.BeforeSelect += TreeViewBeforeSelect; this.trvCostCentres.AfterSelect += TreeViewAfterSelect; trvCostCentres.EndUpdate(); FDuringInitialisation = false; if (trvCostCentres.Nodes.Count > 0) { SelectNodeByName(trvCostCentres.Nodes[0].Name); // Select the first item } }
void CheckGLMPeriodEntry(int ALedgerNumber, int AYear, int APeriodNr, string AAccount, decimal cc1Base, decimal cc2Base, decimal cc3Base) { TGlmInfo glmInfo = new TGlmInfo(ALedgerNumber, AYear, AAccount); glmInfo.Reset(); int intCnt = 0; bool blnFnd1 = false; bool blnFnd2 = false; bool blnFnd3 = false; TCacheable cache = new Ict.Petra.Server.MFinance.Cacheable.TCacheable(); Type dummy; ACostCentreTable costcentres = (ACostCentreTable)cache.GetCacheableTable(TCacheableFinanceTablesEnum.CostCentreList, string.Empty, false, ALedgerNumber, out dummy); while (glmInfo.MoveNext()) { // TLogging.Log("glmInfo.CostCentreCode: " + glmInfo.CostCentreCode); TGlmpInfo glmpInfo = new TGlmpInfo(-1, -1, glmInfo.GlmSequence, APeriodNr); Assert.AreEqual(true, glmpInfo.RowExists, "we cannot find a glm period record for " + glmInfo.AccountCode + " / " + glmInfo.CostCentreCode); if (glmInfo.CostCentreCode.Equals("4301")) { Assert.AreEqual(cc1Base, glmpInfo.ActualBase); blnFnd1 = true; } if (glmInfo.CostCentreCode.Equals("4302")) { Assert.AreEqual(cc2Base, glmpInfo.ActualBase); blnFnd2 = true; } if (glmInfo.CostCentreCode.Equals("4303")) { Assert.AreEqual(cc3Base, glmpInfo.ActualBase); blnFnd3 = true; } if (((ACostCentreRow)costcentres.Rows.Find(new object[] { ALedgerNumber, glmInfo.CostCentreCode })).PostingCostCentreFlag) { ++intCnt; } } Assert.AreEqual(3, intCnt, "3 posting cost centres ..."); Assert.IsTrue(blnFnd1); Assert.IsTrue(blnFnd2); Assert.IsTrue(blnFnd3); }
private void SetAccountCostCentreTableVariables() { //Populate CostCentreList variable DataTable CostCentreListTable = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.CostCentreList, FLedgerNumber); ACostCentreTable tmpCostCentreTable = new ACostCentreTable(); FMainDS.Tables.Add(tmpCostCentreTable); DataUtilities.ChangeDataTableToTypedDataTable(ref CostCentreListTable, FMainDS.Tables[tmpCostCentreTable.TableName].GetType(), ""); FMainDS.RemoveTable(tmpCostCentreTable.TableName); FCostCentreTable = (ACostCentreTable)CostCentreListTable; //Populate AccountList variable DataTable AccountListTable = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.AccountList, FLedgerNumber); AAccountTable tmpAccountTable = new AAccountTable(); FMainDS.Tables.Add(tmpAccountTable); DataUtilities.ChangeDataTableToTypedDataTable(ref AccountListTable, FMainDS.Tables[tmpAccountTable.TableName].GetType(), ""); FMainDS.RemoveTable(tmpAccountTable.TableName); FAccountTable = (AAccountTable)AccountListTable; }
/// <summary> /// Helper method that we can call to initialise each of the filter/find comboBoxes /// </summary> private void InitFilterFindComboBox(TCmbAutoPopulated AClonedFromComboBox, TCmbAutoComplete AFFInstance) { AFFInstance.DisplayMember = AClonedFromComboBox.DisplayMember; AFFInstance.ValueMember = AClonedFromComboBox.ValueMember; if (AClonedFromComboBox.Name.Contains("Account")) { // This is quicker than getting the cached table again DataView dv = new DataView(FAccountTable.Copy()); dv.RowFilter = TFinanceControls.PrepareAccountFilter(true, false, false, false, ""); dv.Sort = String.Format("{0}", AAccountTable.GetAccountCodeDBName()); AFFInstance.DataSource = dv; } else if (AClonedFromComboBox.Name.Contains("CostCentre")) { // This is quicker than getting the cached table again DataView dv = new DataView(FCostCentreTable.Copy()); dv.RowFilter = TFinanceControls.PrepareCostCentreFilter(true, false, false, false); dv.Sort = String.Format("{0}", ACostCentreTable.GetCostCentreCodeDBName()); AFFInstance.DataSource = dv; } else { throw new Exception("Unexpected ComboBox name"); } AFFInstance.DrawMode = DrawMode.OwnerDrawFixed; AFFInstance.DrawItem += new DrawItemEventHandler(DrawComboBoxItem); }
/// <summary> /// Call this to initialise the 'Lists' (tables) for the ComboBoxes /// </summary> /// <param name="ALoadAndFilterLogicObject">Supply a reference to the Filter Logic object because it needs a reference to the same Lists</param> /// <param name="ACostCentreTab"></param> /// <param name="AAccountTab"></param> public void RefreshBankAccountAndCostCentreData(TUC_RecurringGiftBatches_LoadAndFilter ALoadAndFilterLogicObject, out ACostCentreTable ACostCentreTab, out AAccountTable AAccountTab) { //Populate CostCentreList variable DataTable CostCentreList = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.CostCentreList, FLedgerNumber); ACostCentreTable TmpCostCentreTable = new ACostCentreTable(); FMainDS.Tables.Add(TmpCostCentreTable); DataUtilities.ChangeDataTableToTypedDataTable(ref CostCentreList, FMainDS.Tables[TmpCostCentreTable.TableName].GetType(), ""); FMainDS.RemoveTable(TmpCostCentreTable.TableName); FCostCentreTable = (ACostCentreTable)CostCentreList; ALoadAndFilterLogicObject.CostCentreTable = FCostCentreTable; ACostCentreTab = FCostCentreTable; //Populate AccountList variable DataTable AccountList = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.AccountList, FLedgerNumber); AAccountTable TmpAccountTable = new AAccountTable(); FMainDS.Tables.Add(TmpAccountTable); DataUtilities.ChangeDataTableToTypedDataTable(ref AccountList, FMainDS.Tables[TmpAccountTable.TableName].GetType(), ""); FMainDS.RemoveTable(TmpAccountTable.TableName); FAccountTable = (AAccountTable)AccountList; ALoadAndFilterLogicObject.AccountTable = FAccountTable; AAccountTab = FAccountTable; }
private void RefreshBankAccountAndCostCentreData() { //Populate CostCentreList variable DataTable costCentreList = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.CostCentreList, FLedgerNumber); ACostCentreTable tmpCostCentreTable = new ACostCentreTable(); FMainDS.Tables.Add(tmpCostCentreTable); DataUtilities.ChangeDataTableToTypedDataTable(ref costCentreList, FMainDS.Tables[tmpCostCentreTable.TableName].GetType(), ""); FMainDS.RemoveTable(tmpCostCentreTable.TableName); FCostCentreTable = (ACostCentreTable)costCentreList; //Populate AccountList variable DataTable accountList = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.AccountList, FLedgerNumber); AAccountTable tmpAccountTable = new AAccountTable(); FMainDS.Tables.Add(tmpAccountTable); DataUtilities.ChangeDataTableToTypedDataTable(ref accountList, FMainDS.Tables[tmpAccountTable.TableName].GetType(), ""); FMainDS.RemoveTable(tmpAccountTable.TableName); FAccountTable = (AAccountTable)accountList; }
private static ACostCentreRow GetDepartmentCostCentre(ACostCentreTable ACostCentres, ACostCentreRow ACostCentreToInvestigate, StringCollection ADepartmentCodes) { if (ADepartmentCodes.Contains(ACostCentreToInvestigate.CostCentreCode)) { return ACostCentreToInvestigate; } ACostCentreRow row = (ACostCentreRow)ACostCentres.DefaultView.FindRows(ACostCentreToInvestigate.CostCentreToReportTo)[0].Row; return GetDepartmentCostCentre(ACostCentres, row, ADepartmentCodes); }
private DataTable GetCostCentreListTable(TDBTransaction AReadTransaction, System.Int32 ALedgerNumber, string ATableName) { StringCollection FieldList = new StringCollection(); FieldList.Add(ACostCentreTable.GetLedgerNumberDBName()); FieldList.Add(ACostCentreTable.GetCostCentreCodeDBName()); FieldList.Add(ACostCentreTable.GetCostCentreNameDBName()); FieldList.Add(ACostCentreTable.GetCostCentreToReportToDBName()); FieldList.Add(ACostCentreTable.GetPostingCostCentreFlagDBName()); FieldList.Add(ACostCentreTable.GetCostCentreActiveFlagDBName()); FieldList.Add(ACostCentreTable.GetCostCentreTypeDBName()); return(ACostCentreAccess.LoadViaALedger(ALedgerNumber, FieldList, AReadTransaction)); }
private static ACostCentreRow GetDepartmentCostCentre(ACostCentreTable ACostCentres, ACostCentreRow ACostCentreToInvestigate, StringCollection ADepartmentCodes) { if (ADepartmentCodes.Contains(ACostCentreToInvestigate.CostCentreCode)) { return(ACostCentreToInvestigate); } ACostCentreRow row = (ACostCentreRow)ACostCentres.DefaultView.FindRows(ACostCentreToInvestigate.CostCentreToReportTo)[0].Row; return(GetDepartmentCostCentre(ACostCentres, row, ADepartmentCodes)); }
/// <summary> /// Populates the Cost Centre, Account Code and DR Account Code ComboBoxes. /// </summary> /// <param name="ACostCentreComboBox">Cost Centre ComboBox Control</param> /// <param name="AAccountCodeComboBox">Account Code ComboBox Control</param> /// <param name="ADrAccountCodeComboBox">DR Account Code ComboBox Control</param> /// <param name="ALedgerNumber">Ledger Number</param> /// <param name="ACalledByReceivableScreen">Set this to true if the 'Admin Grants Receivable' screen is calling this Method.</param> public static void PopulateComboBoxes(TCmbAutoPopulated ACostCentreComboBox, TCmbAutoPopulated AAccountCodeComboBox, TCmbAutoPopulated ADrAccountCodeComboBox, Int32 ALedgerNumber, bool ACalledByReceivableScreen) { string filter = String.Empty; DataTable CostCentreListTable = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.CostCentreList, ALedgerNumber); CostCentreListTable.DefaultView.Sort = ACostCentreTable.GetCostCentreNameDBName() + " ASC"; if (ACalledByReceivableScreen) { filter = ACostCentreTable.GetPostingCostCentreFlagDBName() + " = true AND " + ACostCentreTable.GetCostCentreTypeDBName() + " = 'Local'"; } else { filter = ACostCentreTable.GetPostingCostCentreFlagDBName() + " = true"; } ACostCentreComboBox.InitialiseUserControl(CostCentreListTable, ACostCentreTable.GetCostCentreCodeDBName(), ACostCentreTable.GetCostCentreNameDBName(), null); ACostCentreComboBox.AppearanceSetup(new int[] { -1, 300 }, 20); ACostCentreComboBox.Filter = filter; DataTable AccountListTable = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.AccountList, ALedgerNumber); AccountListTable.DefaultView.Sort = AAccountTable.GetAccountCodeDBName() + " ASC"; filter = AAccountTable.GetPostingStatusDBName() + " = true AND " + AAccountTable.GetAccountTypeDBName().ToUpper() + " = 'INCOME'"; AAccountCodeComboBox.InitialiseUserControl(AccountListTable, AAccountTable.GetAccountCodeDBName(), AAccountTable.GetAccountCodeShortDescDBName(), null); AAccountCodeComboBox.AppearanceSetup(new int[] { -1, 300 }, 20); AAccountCodeComboBox.Filter = filter; DataTable DrAccountListTable = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.AccountList, ALedgerNumber); DrAccountListTable.DefaultView.Sort = AAccountTable.GetAccountCodeDBName() + " ASC"; filter = AAccountTable.GetPostingStatusDBName() + " = true AND " + AAccountTable.GetAccountTypeDBName().ToUpper() + " = 'EXPENSE'"; ADrAccountCodeComboBox.InitialiseUserControl(DrAccountListTable, AAccountTable.GetAccountCodeDBName(), AAccountTable.GetAccountCodeShortDescDBName(), null); ADrAccountCodeComboBox.AppearanceSetup(new int[] { -1, 300 }, 20); ADrAccountCodeComboBox.Filter = filter; }
/// <summary> /// Method to check and, if possible fix, codes that have had leading zeros removed by Excel for example. /// </summary> /// <param name="ALedgerNumber">The ledger number</param> /// <param name="ARowNumber">The current row number</param> /// <param name="AAccountCode">The account code that may get changed</param> /// <param name="AAccountTableRef">The account table that will be checked for valid codes</param> /// <param name="ACostCentreCode">The cost centre code that may get changed</param> /// <param name="ACostCentreTableRef">The cost centre table that will be checked for valid codes</param> /// <param name="AMessages">A message collection. If a change is made a 'Information' (non-critical) message will be added to the collection</param> public static void FixAccountCodes(int ALedgerNumber, int ARowNumber, ref string AAccountCode, AAccountTable AAccountTableRef, ref string ACostCentreCode, ACostCentreTable ACostCentreTableRef, TVerificationResultCollection AMessages) { // Start with the Account code string code = ConvertTo4DigitCode(AAccountCode); if (code != AAccountCode) { // Maybe it is wrong? if (AAccountTableRef.Rows.Find(new object[] { ALedgerNumber, AAccountCode }) == null) { // That one does not exist, so try our new 4 digit one if (AAccountTableRef.Rows.Find(new object[] { ALedgerNumber, code }) != null) { // Swap the short code for the longer one AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationWarningInLine, ARowNumber), String.Format(Catalog.GetString( "The account code '{0}' does not exist. The code has been converted to '{1}' (which does exist). Please check that this is what you intended."), AAccountCode, code), TResultSeverity.Resv_Noncritical)); AAccountCode = code; } } } // Do the same for the cost centre code code = ConvertTo4DigitCode(ACostCentreCode); if (code != ACostCentreCode) { // Maybe it is wrong? if (ACostCentreTableRef.Rows.Find(new object[] { ALedgerNumber, ACostCentreCode }) == null) { // That one does not exist, so try our new 4 digit one if (ACostCentreTableRef.Rows.Find(new object[] { ALedgerNumber, code }) != null) { // Swap the short code for the longer one AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationWarningInLine, ARowNumber), String.Format(Catalog.GetString( "The cost centre code '{0}' does not exist. The code has been converted to '{1}' (which does exist). Please check that this is what you intended."), ACostCentreCode, code), TResultSeverity.Resv_Noncritical)); ACostCentreCode = code; } } } }
public void Init() { TPetraServerConnector.Connect(); FLedgerNumber = CommonNUnitFunctions.CreateNewLedger(); // add costcentre 7300 for gift batch ACostCentreTable CostCentres = new ACostCentreTable(); ACostCentreRow CCRow = CostCentres.NewRowTyped(); CCRow.LedgerNumber = FLedgerNumber; CCRow.CostCentreCode = "7300"; CCRow.CostCentreName = "7300"; CCRow.CostCentreType = MFinanceConstants.FOREIGN_CC_TYPE; CCRow.CostCentreToReportTo = MFinanceConstants.INTER_LEDGER_HEADING; CCRow.PostingCostCentreFlag = true; CCRow.CostCentreActiveFlag = true; CostCentres.Rows.Add(CCRow); ACostCentreAccess.SubmitChanges(CostCentres, null); System.Diagnostics.Debug.WriteLine("Init: " + this.ToString()); }
/// <summary> /// return a list of costcentres that does not contail any costcentre linked to a person /// </summary> public static string WithoutPersonCostCentres(int ALedgerNumber, String ACostCentreList) { // remove all costcentres that report to a costcentre which name ends with Personalkosten ACostCentreTable costcentres = ACostCentreAccess.LoadViaALedger(ALedgerNumber, null); costcentres.DefaultView.Sort = ACostCentreTable.GetCostCentreCodeDBName(); string[] costcentresList = ACostCentreList.Split(new char[] { ',' }); List <string> newList = new List <string>(); foreach (string cc in costcentresList) { ACostCentreRow costcentre = (ACostCentreRow)costcentres.DefaultView.FindRows(cc)[0].Row; ACostCentreRow parentCC = (ACostCentreRow)costcentres.DefaultView.FindRows(costcentre.CostCentreToReportTo)[0].Row; if (!parentCC.CostCentreName.EndsWith("Personalkosten")) { newList.Add(cc); } } return(String.Join(",", newList.ToArray())); }
public static void GenerateHOSAReports(int ALedgerNumber, int APeriodNumber, int AIchNumber, string ACurrencySelect, out TVerificationResultCollection AVerificationResult ) { AVerificationResult = new TVerificationResultCollection(); //Begin the transaction bool NewTransaction = false; TDBTransaction DBTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted, out NewTransaction); ALedgerTable ALedger = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, DBTransaction); AJournalTable AJournal = new AJournalTable(); ATransactionTable ATransaction = new ATransactionTable(); ACostCentreTable ACostCentre = new ACostCentreTable(); try { #if TODO ALedgerRow LedgerRow = PostingDS.ALedger[0]; //Find the Ledger Name = Partner Short Name PPartnerTable PartnerTable = PPartnerAccess.LoadByPrimaryKey(LedgerRow.PartnerKey, DBTransaction); PPartnerRow PartnerRow = (PPartnerRow)PartnerTable.Rows[0]; string LedgerName = PartnerRow.PartnerShortName; #endif // // Load the Journals, and Transactions for this period: String JournalQuery = "SELECT PUB_a_journal.* FROM PUB_a_batch, PUB_a_journal WHERE " + "PUB_a_batch.a_ledger_number_i = " + ALedgerNumber + " AND PUB_a_batch.a_batch_year_i = " + ALedger[0].CurrentFinancialYear + " AND PUB_a_batch.a_batch_period_i = " + APeriodNumber + " AND PUB_a_batch.a_batch_status_c = 'Posted'" + " AND PUB_a_batch.a_ledger_number_i = PUB_a_journal.a_ledger_number_i" + " AND PUB_a_batch.a_batch_number_i = PUB_a_journal.a_batch_number_i"; DBAccess.GDBAccessObj.SelectDT(AJournal, JournalQuery, DBTransaction); String TransactionQuery = "SELECT PUB_a_transaction.* FROM PUB_a_batch, PUB_a_transaction WHERE " + "PUB_a_batch.a_ledger_number_i = " + ALedgerNumber + " AND PUB_a_batch.a_batch_year_i = " + ALedger[0].CurrentFinancialYear + " AND PUB_a_batch.a_batch_period_i = " + APeriodNumber + " AND PUB_a_batch.a_batch_status_c = 'Posted'" + " AND PUB_a_batch.a_ledger_number_i = PUB_a_transaction.a_ledger_number_i" + " AND PUB_a_batch.a_batch_number_i = PUB_a_transaction.a_batch_number_i"; DBAccess.GDBAccessObj.SelectDT(ATransaction, TransactionQuery, DBTransaction); String CostCentreQuery = "SELECT * FROM a_cost_centre WHERE " + ACostCentreTable.GetLedgerNumberDBName() + " = " + ALedgerNumber + " AND " + ACostCentreTable.GetPostingCostCentreFlagDBName() + " = True" + " AND " + ACostCentreTable.GetCostCentreTypeDBName() + " LIKE '" + MFinanceConstants.FOREIGN_CC_TYPE + "'" + " ORDER BY " + ACostCentreTable.GetCostCentreCodeDBName(); DBAccess.GDBAccessObj.SelectDT(ACostCentre, CostCentreQuery, DBTransaction); //Iterate through the cost centres foreach (ACostCentreRow CostCentreRow in ACostCentre.Rows) { bool TransactionExists = false; //Iterate through the journals foreach (AJournalRow JournalRow in AJournal.Rows) { int BatchNumber = JournalRow.BatchNumber; int JournalNumber = JournalRow.JournalNumber; #if TODO String TransFilter = ATransactionTable.GetBatchNumberDBName() + " = " + BatchNumber.ToString() + " AND " + ATransactionTable.GetJournalNumberDBName() + " = " + JournalNumber.ToString() + " AND " + ATransactionTable.GetCostCentreCodeDBName() + " = '" + CostCentreRow.CostCentreCode + "'" + " AND (" + ATransactionTable.GetIchNumberDBName() + " = 0" + " OR " + ATransactionTable.GetIchNumberDBName() + " = " + AIchNumber.ToString() + ")"; DataRow[] FoundTransRows = BatchDS.ATransaction.Select(TransFilter); foreach (DataRow untypedTransRow in FoundTransRows) { ATransactionRow TransactionRow = (ATransactionRow)untypedTransRow; TransactionExists = true; string DefaultData = ALedgerNumber.ToString() + "," + LedgerName + "," + APeriodNumber.ToString() + "," + APeriodNumber.ToString() + "," + CostCentreRow.CostCentreCode + "," + "" + "," + "" + "," + "" + "," + "A" + "," + LedgerRow.CurrentFinancialYear.ToString() + "," + LedgerRow.CurrentPeriod.ToString() + "," + MFinanceConstants.MAX_PERIODS.ToString() + "," + "h" + "," + ACurrency + "," + AIchNumber.ToString(); string ReportTitle = "Home Office Stmt of Acct: " + CostCentreRow.CostCentreName; //call code for gl2120p.p Produces Account Detail, Analysis Attribute and HOSA Reprint reports. /* RUN sm9000.w ("gl2120p.p", * lv_report_title_c, * lv_default_data_c).*/ //TODO: call code to produce reports break; } #endif if (TransactionExists) { //only need to run above code once for 1 transaction per cost centre code break; //goto next cost centre else try next journal } } } if (NewTransaction) { DBAccess.GDBAccessObj.RollbackTransaction(); } } catch (Exception Exp) { if (NewTransaction) { DBAccess.GDBAccessObj.RollbackTransaction(); } TLogging.Log(Exp.Message); TLogging.Log(Exp.StackTrace); throw; } }
} // Test_2YearEnds void CheckGLMEntry(int ALedgerNumber, int AYear, string AAccount, decimal cc1Base, decimal cc1Closing, decimal cc2Base, decimal cc2Closing, decimal cc3Base, decimal cc3Closing) { TGlmInfo glmInfo = new TGlmInfo(ALedgerNumber, AYear, AAccount); glmInfo.Reset(); int intCnt = 0; bool blnFnd1 = false; bool blnFnd2 = false; bool blnFnd3 = false; TCacheable cache = new Ict.Petra.Server.MFinance.Cacheable.TCacheable(); Type dummy; ACostCentreTable costcentres = (ACostCentreTable)cache.GetCacheableTable(TCacheableFinanceTablesEnum.CostCentreList, string.Empty, false, ALedgerNumber, out dummy); while (glmInfo.MoveNext()) { // TLogging.Log("glmInfo.CostCentreCode: " + glmInfo.CostCentreCode); if (glmInfo.CostCentreCode.Equals("4301")) { Assert.AreEqual(cc1Base, glmInfo.YtdActualBase, "CheckGLMEntry (" + ALedgerNumber + ", " + AYear + ", 4301, " + AAccount + ")"); Assert.AreEqual(cc1Closing, glmInfo.ClosingPeriodActualBase, "CheckGLMEntry (" + ALedgerNumber + ", " + AYear + ", 4301, " + AAccount + ")"); blnFnd1 = true; } if (glmInfo.CostCentreCode.Equals("4302")) { Assert.AreEqual(cc2Base, glmInfo.YtdActualBase, "CheckGLMEntry (" + ALedgerNumber + ", " + AYear + ", 4302, " + AAccount + ")"); Assert.AreEqual(cc2Closing, glmInfo.ClosingPeriodActualBase, "CheckGLMEntry (" + ALedgerNumber + ", " + AYear + ", 4302, " + AAccount + ")"); blnFnd2 = true; } if (glmInfo.CostCentreCode.Equals("4303")) { Assert.AreEqual(cc3Base, glmInfo.YtdActualBase, "CheckGLMEntry (" + ALedgerNumber + ", " + AYear + ", 4303, " + AAccount + ")"); Assert.AreEqual(cc3Closing, glmInfo.ClosingPeriodActualBase, "CheckGLMEntry (" + ALedgerNumber + ", " + AYear + ", 4303, " + AAccount + ")"); blnFnd3 = true; } if (((ACostCentreRow)costcentres.Rows.Find(new object[] { ALedgerNumber, glmInfo.CostCentreCode })).PostingCostCentreFlag) { ++intCnt; } } Assert.IsTrue(blnFnd1, "CheckGLMEntry (" + ALedgerNumber + ", " + AYear + ", 4301, " + AAccount + ")"); Assert.IsTrue(blnFnd2, "CheckGLMEntry (" + ALedgerNumber + ", " + AYear + ", 4302, " + AAccount + ")"); Assert.IsTrue(blnFnd3, "CheckGLMEntry (" + ALedgerNumber + ", " + AYear + ", 4303, " + AAccount + ")"); Assert.AreEqual(3, intCnt, "CheckGLMEntry expects 3 posting cost centres ..."); }
private static bool ValidateKeyBudgetFields(int ALedgerNumber, int ARowNumber, ref ACostCentreTable ACostCentreTbl, ref AAccountTable AAccountTbl, string ACostCentre, string AAccount, string ABudgetType, string ABudgetYearStringUpper, ref TVerificationResultCollection AVerificationResult) { string VerificationMessage = string.Empty; ACostCentreTable CCTable = ACostCentreTbl; AAccountTable AccTable = AAccountTbl; ACostCentreRow CostCentreRow = null; AAccountRow AccountRow = null; if (CCTable == null) { try { TDBTransaction transaction = null; DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref transaction, delegate { CCTable = ACostCentreAccess.LoadViaALedger(ALedgerNumber, transaction); AccTable = AAccountAccess.LoadViaALedger(ALedgerNumber, transaction); #region Validate Data if ((CCTable == null) || (CCTable.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Cost Centre data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } else if ((AccTable == null) || (AccTable.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Account data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } #endregion Validate Data }); ACostCentreTbl = CCTable; AAccountTbl = AccTable; } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } } //Check for missing or inactive cost centre CostCentreRow = (ACostCentreRow)ACostCentreTbl.Rows.Find(new object[] { ALedgerNumber, ACostCentre }); if (CostCentreRow == null) { VerificationMessage += String.Format(Catalog.GetString(" Cost Centre: '{0}' does not exist."), ACostCentre); } else if (!CostCentreRow.CostCentreActiveFlag) { VerificationMessage += String.Format(Catalog.GetString(" Cost Centre: '{0}' is currently inactive."), ACostCentre); } //Check for missing or inactive account code AccountRow = (AAccountRow)AAccountTbl.Rows.Find(new object[] { ALedgerNumber, AAccount }); if (AccountRow == null) { VerificationMessage += String.Format(Catalog.GetString(" Account: '{0}' does not exist."), AAccount); } else if (!AccountRow.AccountActiveFlag) { VerificationMessage += String.Format(Catalog.GetString(" Account: '{0}' is currently inactive."), AAccount); } //Check Budget Type if ((ABudgetType != MFinanceConstants.BUDGET_ADHOC) && (ABudgetType != MFinanceConstants.BUDGET_SAME) && (ABudgetType != MFinanceConstants.BUDGET_INFLATE_N) && (ABudgetType != MFinanceConstants.BUDGET_SPLIT) && (ABudgetType != MFinanceConstants.BUDGET_INFLATE_BASE)) { VerificationMessage += String.Format(Catalog.GetString(" Budget Type: '{0}' does not exist."), ABudgetType); } //Check Budget Year if ((ABudgetYearStringUpper != MFinanceConstants.BUDGET_YEAR_THIS.ToUpper()) && (ABudgetYearStringUpper != MFinanceConstants.BUDGET_YEAR_NEXT.ToUpper())) { VerificationMessage += String.Format(Catalog.GetString(" Budget Year: '{0}' should be '{1}' or '{2}'."), ABudgetYearStringUpper, MFinanceConstants.BUDGET_YEAR_THIS, MFinanceConstants.BUDGET_YEAR_NEXT); } //Check if errors have occurred if (VerificationMessage.Length > 0) { AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Row: " + ARowNumber.ToString("0000")), VerificationMessage, TResultSeverity.Resv_Noncritical)); return false; } else { return true; } }
/// <summary> /// Validates the GL Detail data. /// </summary> /// <param name="AContext">Context that describes where the data validation failed.</param> /// <param name="ABatchRow">Manually added to bring over some GL Batch fields</param> /// <param name="ARow">The <see cref="DataRow" /> which holds the the data against which the validation is run.</param> /// <param name="AControl"></param> /// <param name="AVerificationResultCollection">Will be filled with any <see cref="TVerificationResult" /> items if /// data validation errors occur.</param> /// <param name="AValidationControlsDict">A <see cref="TValidationControlsDict" /> containing the Controls that /// display data that is about to be validated.</param> /// <param name="AValidationCostCentreTable">REQUIRED for importing. A reference to a cost centre table so that inputs can be validated.</param> /// <param name="AvalidationAccountTable">REQUIRED for importing. A reference to an account table so that inputs can be validated.</param> /// <returns>True if the validation found no data validation errors, otherwise false.</returns> public static bool ValidateGLDetailManual(object AContext, ABatchRow ABatchRow, ATransactionRow ARow, Control AControl, ref TVerificationResultCollection AVerificationResultCollection, TValidationControlsDict AValidationControlsDict, ACostCentreTable AValidationCostCentreTable = null, AAccountTable AvalidationAccountTable = null) { DataColumn ValidationColumn; TValidationControlsData ValidationControlsData; TVerificationResult VerificationResult = null; object ValidationContext; int VerifResultCollAddedCount = 0; // Don't validate deleted DataRows or non-unposted batches if ((ABatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED) || (ARow.RowState == DataRowState.Deleted)) { return true; } bool isImporting = AContext.ToString().Contains("Importing"); // When used by the GUI TransactionAmount is not in the dictionary so had to pass the control directly // But when importing we do have a dictionary entry if (isImporting) { // 'GL amount must be non-zero and positive ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnTransactionAmountId]; if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { VerificationResult = TNumericalChecks.IsPositiveDecimal(ARow.TransactionAmount, ValidationControlsData.ValidationControlLabel, AContext, ValidationColumn, AControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } } } else { if ((AControl != null) && AControl.Name.EndsWith("Amount")) { // 'GL amount must be non-zero and positive ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnTransactionAmountId]; ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})", ARow.TransactionNumber, ARow.BatchNumber, ARow.JournalNumber); VerificationResult = TNumericalChecks.IsPositiveOrZeroDecimal(ARow.TransactionAmount, "Amount of " + ValidationContext, AContext, ValidationColumn, AControl); if (VerificationResult != null) { VerificationResult.SuppressValidationToolTip = true; } // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } return VerifResultCollAddedCount == 0; } } // 'Narrative must not be empty ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnNarrativeId]; ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})", ARow.TransactionNumber, ARow.BatchNumber, ARow.JournalNumber); if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { VerificationResult = TStringChecks.StringMustNotBeEmpty(ARow.Narrative, (isImporting) ? ValidationControlsData.ValidationControlLabel : "Narrative of " + ValidationContext, AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } } // 'Entered From Date' must be valid ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnTransactionDateId]; ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})", ARow.TransactionNumber, ARow.BatchNumber, ARow.JournalNumber); if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { DateTime StartDatePeriod; DateTime EndDatePeriod; TSharedFinanceValidationHelper.GetValidPeriodDates(ARow.LedgerNumber, ABatchRow.BatchYear, 0, ABatchRow.BatchPeriod, out StartDatePeriod, out EndDatePeriod); VerificationResult = (TScreenVerificationResult)TDateChecks.IsDateBetweenDates(ARow.TransactionDate, StartDatePeriod, EndDatePeriod, (isImporting) ? ValidationControlsData.ValidationControlLabel : "Transaction Date for " + ValidationContext.ToString(), TDateBetweenDatesCheckType.dbdctUnspecific, TDateBetweenDatesCheckType.dbdctUnspecific, AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } } if ((AControl != null) && AControl.Name.EndsWith("Reference")) { //TODO: Check if "Reference" is mandatory then make sure it is set ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnReferenceId]; ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})", ARow.TransactionNumber, ARow.BatchNumber, ARow.JournalNumber); if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { VerificationResult = TStringChecks.StringMustNotBeEmpty(ARow.Reference, (isImporting) ? ValidationControlsData.ValidationControlLabel : "Reference of " + ValidationContext, AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } } } // 'CostCentre' must be valid ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnCostCentreCodeId]; ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})", ARow.TransactionNumber, ARow.BatchNumber, ARow.JournalNumber); if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { if ((AValidationCostCentreTable != null) && !ARow.IsCostCentreCodeNull()) { // Code must exist in the cost centre table ACostCentreRow foundRow = (ACostCentreRow)AValidationCostCentreTable.Rows.Find( new object[] { ARow.LedgerNumber, ARow.CostCentreCode }); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( ValidationContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Cost centre code '{0}' does not exist."), ARow.CostCentreCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } // cost centre must be a posting cost centre if ((foundRow != null) && !foundRow.PostingCostCentreFlag) { if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(ValidationContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Cost centre code '{0}' is not a posting cost centre."), ARow.CostCentreCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } // cost centre must not be inactive if ((foundRow != null) && !foundRow.CostCentreActiveFlag) { if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(ValidationContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Cost centre code '{0}' is an inactive cost centre."), ARow.CostCentreCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } } } // 'Account code' must be valid ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnAccountCodeId]; ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})", ARow.TransactionNumber, ARow.BatchNumber, ARow.JournalNumber); if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { if ((AvalidationAccountTable != null) && !ARow.IsAccountCodeNull()) { // Code must exist in the account table AAccountRow foundRow = (AAccountRow)AvalidationAccountTable.Rows.Find( new object[] { ARow.LedgerNumber, ARow.AccountCode }); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( ValidationContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Account code '{0}' does not exist."), ARow.AccountCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } // Account code must be a posting Account code if ((foundRow != null) && !foundRow.PostingStatus) { if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(ValidationContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Account code '{0}' is not a posting account."), ARow.AccountCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } // Account code must not be inactive if ((foundRow != null) && !foundRow.AccountActiveFlag) { if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(ValidationContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Account code '{0}' is an inactive account."), ARow.AccountCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } } } return VerifResultCollAddedCount == 0; }
private void ParseTransactionLine(AGiftRow AGift, AGiftBatchRow AGiftBatch, ref AGiftRow APreviousGift, int ANumberOfColumns, ref decimal ATotalBatchAmount, ref string AImportMessage, int ARowNumber, TVerificationResultCollection AMessages, TValidationControlsDict AValidationControlsDictGift, TValidationControlsDict AValidationControlsDictGiftDetail, ACostCentreTable AValidationCostCentreTable, AMotivationGroupTable AValidationMotivationGroupTable, AMotivationDetailTable AValidationMotivationDetailTable, AMethodOfGivingTable AValidationMethodOfGivingTable, AMethodOfPaymentTable AValidationMethodOfPaymentTable, ref GiftBatchTDSAGiftDetailTable ANeedRecipientLedgerNumber, out AGiftDetailRow AGiftDetails) { // Is this the format with extra columns? // Actually if it has the extra columns but does not have the optional final 8 columns we cannot distiguish using this test... // A file without extra columns will have between 13 and 21 columns - depending on whether some of the optional ones at the end are included. // A file with extra columns will be between 19 and 27. // So any count between 19 and 21 is ambiguous. We will assume that if the file has extra columns it also has // at least enough of the optional ones to exceed 21. bool HasExtraColumns = (ANumberOfColumns > 21); AImportMessage = Catalog.GetString("Importing the gift data"); AGift.DonorKey = ImportInt64(Catalog.GetString("Donor key"), FMainDS.AGift.ColumnDonorKey, ARowNumber, AMessages, AValidationControlsDictGift); ImportString(Catalog.GetString("short name of donor (unused)"), null, null); // unused // This group is optional and database NULL's are allowed AGift.MethodOfGivingCode = ImportString(Catalog.GetString("Method of giving Code"), FMainDS.AGift.ColumnMethodOfGivingCode, AValidationControlsDictGift, false); AGift.MethodOfPaymentCode = ImportString(Catalog.GetString("Method Of Payment Code"), FMainDS.AGift.ColumnMethodOfPaymentCode, AValidationControlsDictGift, false); AGift.Reference = ImportString(Catalog.GetString("Reference"), FMainDS.AGift.ColumnReference, AValidationControlsDictGift, false); AGift.ReceiptLetterCode = ImportString(Catalog.GetString("Receipt letter code"), FMainDS.AGift.ColumnReceiptLetterCode, AValidationControlsDictGift, false); if (HasExtraColumns) { ImportInt32(Catalog.GetString("Receipt number"), FMainDS.AGift.ColumnReceiptNumber, ARowNumber, AMessages, AValidationControlsDictGift); ImportBoolean(Catalog.GetString("First time gift"), FMainDS.AGift.ColumnFirstTimeGift, AValidationControlsDictGift); ImportBoolean(Catalog.GetString("Receipt printed"), FMainDS.AGift.ColumnReceiptPrinted, AValidationControlsDictGift); } AImportMessage = Catalog.GetString("Importing the gift details"); AGiftDetails = FMainDS.AGiftDetail.NewRowTyped(true); if ((APreviousGift != null) && (AGift.DonorKey == APreviousGift.DonorKey) && (AGift.MethodOfGivingCode == APreviousGift.MethodOfGivingCode) && (AGift.MethodOfPaymentCode == APreviousGift.MethodOfPaymentCode) && (AGift.Reference == APreviousGift.Reference) && (AGift.ReceiptLetterCode == APreviousGift.ReceiptLetterCode) && (AGift.ReceiptNumber == APreviousGift.ReceiptNumber) && (AGift.FirstTimeGift == APreviousGift.FirstTimeGift) && (AGift.ReceiptPrinted == APreviousGift.ReceiptPrinted)) { // this row is a new detail for the previousGift AGift = APreviousGift; AGift.LastDetailNumber++; AGiftDetails.DetailNumber = AGift.LastDetailNumber; } else { APreviousGift = AGift; AGift.LedgerNumber = AGiftBatch.LedgerNumber; AGift.BatchNumber = AGiftBatch.BatchNumber; AGift.GiftTransactionNumber = AGiftBatch.LastGiftNumber + 1; AGiftBatch.LastGiftNumber++; AGift.LastDetailNumber = 1; FMainDS.AGift.Rows.Add(AGift); AGiftDetails.DetailNumber = 1; } AGiftDetails.LedgerNumber = AGift.LedgerNumber; AGiftDetails.BatchNumber = AGiftBatch.BatchNumber; AGiftDetails.GiftTransactionNumber = AGift.GiftTransactionNumber; FMainDS.AGiftDetail.Rows.Add(AGiftDetails); AGiftDetails.RecipientKey = ImportInt64(Catalog.GetString("Recipient key"), FMainDS.AGiftDetail.ColumnRecipientKey, ARowNumber, AMessages, AValidationControlsDictGiftDetail); ImportString(Catalog.GetString("short name of recipient (unused)"), null, null); // unused if (HasExtraColumns) { ImportInt32(Catalog.GetString("Recipient ledger number"), FMainDS.AGiftDetail.ColumnRecipientLedgerNumber, ARowNumber, AMessages, AValidationControlsDictGiftDetail); } // we always calculate RecipientLedgerNumber AGiftDetails.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber( AGiftDetails.RecipientKey, AGiftBatch.GlEffectiveDate); decimal currentGiftAmount = ImportDecimal(Catalog.GetString("Gift amount"), FMainDS.AGiftDetail.ColumnGiftTransactionAmount, ARowNumber, AMessages, AValidationControlsDictGiftDetail); AGiftDetails.GiftTransactionAmount = currentGiftAmount; // amount in batch currency ATotalBatchAmount += currentGiftAmount; AGiftDetails.GiftAmount = GLRoutines.Divide(currentGiftAmount, AGiftBatch.ExchangeRateToBase); // amount in ledger currency if (HasExtraColumns) { // amount in international currency ImportDecimal(Catalog.GetString("Gift amount intl"), FMainDS.AGiftDetail.ColumnGiftAmountIntl, ARowNumber, AMessages, AValidationControlsDictGiftDetail); } AGiftDetails.ConfidentialGiftFlag = ImportBoolean(Catalog.GetString("Confidential gift"), FMainDS.AGiftDetail.ColumnConfidentialGiftFlag, AValidationControlsDictGiftDetail, "no"); AGiftDetails.MotivationGroupCode = ImportString(Catalog.GetString("Motivation group code"), FMainDS.AGiftDetail.ColumnMotivationGroupCode, AValidationControlsDictGiftDetail); AGiftDetails.MotivationDetailCode = ImportString(Catalog.GetString("Motivation detail"), FMainDS.AGiftDetail.ColumnMotivationDetailCode, AValidationControlsDictGiftDetail); if (HasExtraColumns) { ImportString(Catalog.GetString("Cost centre code"), FMainDS.AGiftDetail.ColumnCostCentreCode, AValidationControlsDictGiftDetail); } // "In Petra Cost Centre is always inferred from recipient field and motivation detail so is not needed in the import." AGiftDetails.CostCentreCode = InferCostCentre(AGiftDetails); // All the remaining columns are optional and can contain database NULL AGiftDetails.GiftCommentOne = ImportString(Catalog.GetString("Gift comment one"), FMainDS.AGiftDetail.ColumnGiftCommentOne, AValidationControlsDictGiftDetail, false); string commentOneType = ImportString(Catalog.GetString("Comment one type"), FMainDS.AGiftDetail.ColumnCommentOneType, AValidationControlsDictGiftDetail, false); AGiftDetails.MailingCode = ImportString(Catalog.GetString("Mailing code"), FMainDS.AGiftDetail.ColumnMailingCode, AValidationControlsDictGiftDetail, false); AGiftDetails.GiftCommentTwo = ImportString(Catalog.GetString("Gift comment two"), FMainDS.AGiftDetail.ColumnGiftCommentTwo, AValidationControlsDictGiftDetail, false); string commentTwoType = ImportString(Catalog.GetString("Comment two type"), FMainDS.AGiftDetail.ColumnCommentTwoType, AValidationControlsDictGiftDetail, false); AGiftDetails.GiftCommentThree = ImportString(Catalog.GetString("Gift comment three"), FMainDS.AGiftDetail.ColumnGiftCommentThree, AValidationControlsDictGiftDetail, false); string commentThreeType = ImportString(Catalog.GetString("Comment three type"), FMainDS.AGiftDetail.ColumnCommentThreeType, AValidationControlsDictGiftDetail, false); SetCommentTypeCase(ref commentOneType); AGiftDetails.CommentOneType = commentOneType; SetCommentTypeCase(ref commentTwoType); AGiftDetails.CommentOneType = commentTwoType; SetCommentTypeCase(ref commentThreeType); AGiftDetails.CommentOneType = commentThreeType; // Find the default Tax deductabilty from the motivation detail. This ensures that the column can be missing. AMotivationDetailRow motivationDetailRow = (AMotivationDetailRow)AValidationMotivationDetailTable.Rows.Find( new object[] { FLedgerNumber, AGiftDetails.MotivationGroupCode, AGiftDetails.MotivationDetailCode }); string defaultTaxDeductible = ((motivationDetailRow != null) && !motivationDetailRow.IsTaxDeductibleAccountNull() && motivationDetailRow.TaxDeductible) ? "yes" : "no"; AGiftDetails.TaxDeductible = ImportBoolean(Catalog.GetString("Tax deductible"), FMainDS.AGiftDetail.ColumnTaxDeductible, AValidationControlsDictGiftDetail, defaultTaxDeductible); // Date entered cannot be imported although it can be modified in the GUI. // This is because it would have to be the last column in the import for compatibility // but it belongs with the gift and not the detail so it would need to go in an earlier column. // For now the import date entered is the effective date. AGift.DateEntered = AGiftBatch.GlEffectiveDate; // Enforce the correct case for our GIFT constant if (String.Compare(AGiftDetails.MotivationGroupCode, MFinanceConstants.MOTIVATION_GROUP_GIFT, true) == 0) { AGiftDetails.MotivationGroupCode = MFinanceConstants.MOTIVATION_GROUP_GIFT; } TPartnerClass RecipientClass; string RecipientDescription; TPartnerServerLookups.GetPartnerShortName(AGiftDetails.RecipientKey, out RecipientDescription, out RecipientClass); // If the gift has a Family recipient with no Gift Destination then the import will fail. Gift is added to a table and returned to client. if ((AGiftDetails.RecipientLedgerNumber == 0) && (AGiftDetails.MotivationGroupCode == MFinanceConstants.MOTIVATION_GROUP_GIFT)) { if (RecipientClass == TPartnerClass.FAMILY) { ((GiftBatchTDSAGiftDetailRow)AGiftDetails).RecipientDescription = RecipientDescription; ANeedRecipientLedgerNumber.Rows.Add((object[])AGiftDetails.ItemArray.Clone()); } } AImportMessage = Catalog.GetString("Validating the gift data"); int messageCountBeforeValidate = AMessages.Count; // Do our standard validation on this gift AGiftValidation.Validate(this, AGift, ref AMessages, AValidationControlsDictGift); TSharedFinanceValidation_Gift.ValidateGiftManual(this, AGift, AGiftBatch.BatchYear, AGiftBatch.BatchPeriod, null, ref AMessages, AValidationControlsDictGift, AValidationMethodOfGivingTable, AValidationMethodOfPaymentTable); AImportMessage = Catalog.GetString("Validating the gift details data"); AGiftDetailValidation.Validate(this, AGiftDetails, ref AMessages, AValidationControlsDictGiftDetail); TSharedFinanceValidation_Gift.ValidateGiftDetailManual(this, (GiftBatchTDSAGiftDetailRow)AGiftDetails, ref AMessages, AValidationControlsDictGiftDetail, RecipientClass, AValidationCostCentreTable, AValidationMotivationGroupTable, AValidationMotivationDetailTable, AGiftDetails.RecipientKey); for (int i = messageCountBeforeValidate; i < AMessages.Count; i++) { ((TVerificationResult)AMessages[i]).OverrideResultContext(String.Format(MCommonConstants.StrValidationErrorInLine, ARowNumber)); if (AMessages[i] is TScreenVerificationResult) { TVerificationResult downgrade = new TVerificationResult((TScreenVerificationResult)AMessages[i]); AMessages.RemoveAt(i); AMessages.Insert(i, downgrade); } } }
/// <summary> /// Validates the Gift Batch data. /// </summary> /// <param name="AContext">Context that describes where the data validation failed.</param> /// <param name="ARow">The <see cref="DataRow" /> which holds the the data against which the validation is run.</param> /// <param name="AVerificationResultCollection">Will be filled with any <see cref="TVerificationResult" /> items if /// data validation errors occur.</param> /// <param name="AValidationControlsDict">A <see cref="TValidationControlsDict" /> containing the Controls that /// display data that is about to be validated.</param> /// <param name="AAccountTableRef">Account Table. A reference to this table is REQUIRED when importing - optional otherwise</param> /// <param name="ACostCentreTableRef">Cost centre table. A reference to this table is REQUIRED when importing - optional otherwise</param> /// <param name="AAccountPropertyTableRef">Account Property Table. A reference to this table is REQUIRED when importing - optional otherwise</param> /// <param name="AAccountingPeriodTableRef">Accounting Period Table. A reference to this table is REQUIRED when importing - optional otherwise</param> /// <param name="ACorporateExchangeTableRef">Corporate exchange rate table. A reference to this table is REQUIRED when importing - optional otherwise</param> /// <param name="ACurrencyTableRef">Currency table. A reference to this table is REQUIRED when importing - optional otherwise</param> /// <param name="ABaseCurrency">Ledger base currency. Required when importing</param> /// <param name="AInternationalCurrency">Ledger international currency. Required when importing</param> /// <returns>True if the validation found no data validation errors, otherwise false.</returns> public static bool ValidateGiftBatchManual(object AContext, AGiftBatchRow ARow, ref TVerificationResultCollection AVerificationResultCollection, TValidationControlsDict AValidationControlsDict, AAccountTable AAccountTableRef = null, ACostCentreTable ACostCentreTableRef = null, AAccountPropertyTable AAccountPropertyTableRef = null, AAccountingPeriodTable AAccountingPeriodTableRef = null, ACorporateExchangeRateTable ACorporateExchangeTableRef = null, ACurrencyTable ACurrencyTableRef = null, string ABaseCurrency = null, string AInternationalCurrency = null) { DataColumn ValidationColumn; TValidationControlsData ValidationControlsData; TScreenVerificationResult VerificationResult; object ValidationContext; int VerifResultCollAddedCount = 0; // Don't validate deleted or posted DataRows if ((ARow.RowState == DataRowState.Deleted) || (ARow.BatchStatus == MFinanceConstants.BATCH_POSTED)) { return true; } bool IsImporting = AContext.ToString().Contains("Importing"); // Bank Account Code must be active ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnBankAccountCodeId]; ValidationContext = ARow.BankAccountCode; if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { if (!ARow.IsBankAccountCodeNull() && (AAccountTableRef != null)) { // We even need to check that the code exists! AAccountRow foundRow = (AAccountRow)AAccountTableRef.Rows.Find(new object[] { ARow.LedgerNumber, ARow.BankAccountCode }); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Unknown bank account code '{0}'."), ARow.BankAccountCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } // If it does exist and the account is a foreign currency account then the batch currency must match if ((foundRow != null) && foundRow.ForeignCurrencyFlag) { if ((foundRow.ForeignCurrencyCode != ARow.CurrencyCode) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString( "The bank account code '{0}' is a foreign currency account so the currency code for the batch must be '{1}'."), ARow.BankAccountCode, foundRow.ForeignCurrencyCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } // If it does exist it must be a posting account if (foundRow != null) { if (!foundRow.PostingStatus && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString( "The bank account code '{0}' is not a posting account."), ARow.BankAccountCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } if ((foundRow != null) && (ARow.GiftType == MFinanceConstants.GIFT_TYPE_GIFT)) { // The account must be a bank account as defined in the AccountProperty table if (AAccountPropertyTableRef != null) { AAccountPropertyRow foundRow2 = (AAccountPropertyRow)AAccountPropertyTableRef.Rows.Find( new object[] { ARow.LedgerNumber, ARow.BankAccountCode, "BANK ACCOUNT", "true" }); if ((foundRow2 == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString( "The bank account code '{0}' must be associated with a real 'Bank Account' when the gift type is a 'Gift'."), ARow.BankAccountCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } } } VerificationResult = (TScreenVerificationResult)TStringChecks.ValidateValueIsActive(ARow.LedgerNumber, AAccountTableRef, ValidationContext.ToString(), AAccountTable.GetAccountActiveFlagDBName(), AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if ((VerificationResult != null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } } // Bank Cost Centre Code validation ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnBankCostCentreId]; ValidationContext = ARow.BankCostCentre; if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { if (!ARow.IsBankCostCentreNull() && (ACostCentreTableRef != null)) { // We even need to check that the code exists! ACostCentreRow foundRow = (ACostCentreRow)ACostCentreTableRef.Rows.Find(new object[] { ARow.LedgerNumber, ARow.BankCostCentre }); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TScreenVerificationResult(ValidationContext, ValidationColumn, String.Format(Catalog.GetString("Unknown Bank Cost Centre: '{0}'."), ARow.BankCostCentre), ValidationControlsData.ValidationControl, TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } // Even if the cost centre exists it must be a 'posting' cost centre if (foundRow != null) { if (!foundRow.PostingCostCentreFlag && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TScreenVerificationResult(ValidationContext, ValidationColumn, String.Format(Catalog.GetString("The cost centre '{0}' is not a Posting Cost Centre."), ARow.BankCostCentre), ValidationControlsData.ValidationControl, TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } } // Bank Cost Centre Code must be active VerificationResult = (TScreenVerificationResult)TStringChecks.ValidateValueIsActive(ARow.LedgerNumber, ACostCentreTableRef, ValidationContext.ToString(), ACostCentreTable.GetCostCentreActiveFlagDBName(), AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if ((VerificationResult != null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } } // Currency Code validation ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnCurrencyCodeId]; ValidationContext = ARow.BatchNumber; if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { if (!ARow.IsCurrencyCodeNull() && (ACurrencyTableRef != null)) { // Currency code must exist in the currency table ACurrencyRow foundRow = (ACurrencyRow)ACurrencyTableRef.Rows.Find(ARow.CurrencyCode); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TScreenVerificationResult(ValidationContext, ValidationColumn, String.Format(Catalog.GetString("Unknown currency code '{0}'."), ARow.CurrencyCode), ValidationControlsData.ValidationControl, TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } } // 'Exchange Rate' must be greater than 0 ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnExchangeRateToBaseId]; ValidationContext = ARow.BatchNumber; if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { if (!ARow.IsExchangeRateToBaseNull()) { VerificationResult = (TScreenVerificationResult)TNumericalChecks.IsPositiveDecimal(ARow.ExchangeRateToBase, ValidationControlsData.ValidationControlLabel + (IsImporting ? String.Empty : " of Batch Number " + ValidationContext.ToString()), AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } // Exchange rate must be 1.00 if the currency is the the base ledger currency if ((ABaseCurrency != null) && (!ARow.IsCurrencyCodeNull()) && (ARow.CurrencyCode == ABaseCurrency) && (ARow.ExchangeRateToBase != 1.00m)) { if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, new TScreenVerificationResult(ValidationContext, ValidationColumn, Catalog.GetString("A batch in the ledger base currency must have exchange rate of 1.00."), ValidationControlsData.ValidationControl, TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } } } // 'Effective From Date' must be valid ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnGlEffectiveDateId]; ValidationContext = ARow.BatchNumber; DateTime StartDateCurrentPeriod; DateTime EndDateLastForwardingPeriod; TSharedFinanceValidationHelper.GetValidPostingDateRange(ARow.LedgerNumber, out StartDateCurrentPeriod, out EndDateLastForwardingPeriod); if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { VerificationResult = (TScreenVerificationResult)TDateChecks.IsDateBetweenDates(ARow.GlEffectiveDate, StartDateCurrentPeriod, EndDateLastForwardingPeriod, ValidationControlsData.ValidationControlLabel + (IsImporting ? String.Empty : " of Batch Number " + ValidationContext.ToString()), TDateBetweenDatesCheckType.dbdctUnspecific, TDateBetweenDatesCheckType.dbdctUnspecific, AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } // If the GL date was good we need to have a corporate exchange rate for base currency to Intl for the first day of the period if ((VerificationResult == null) && (ACorporateExchangeTableRef != null) && !ARow.IsGlEffectiveDateNull() && (ABaseCurrency != null) && (AInternationalCurrency != null) && (ABaseCurrency != AInternationalCurrency)) { DateTime firstOfMonth; if (TSharedFinanceValidationHelper.GetFirstDayOfAccountingPeriod(ARow.LedgerNumber, ARow.GlEffectiveDate, out firstOfMonth)) { ACorporateExchangeRateRow foundRow = (ACorporateExchangeRateRow)ACorporateExchangeTableRef.Rows.Find( new object[] { ABaseCurrency, AInternationalCurrency, firstOfMonth }); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString( "International currency: there is no Corporate Exchange Rate defined for '{0}' to '{1}' for the month starting on '{2}'."), ABaseCurrency, AInternationalCurrency, StringHelper.DateToLocalizedString(firstOfMonth)), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } } } // Gift Type must be one of our predefined constants ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnGiftTypeId]; ValidationContext = ARow.BatchNumber; if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { if (!ARow.IsGiftTypeNull()) { // Ensure the gift type is correct and that it matches one of the allowable options (applies when importing) if ((ARow.GiftType != MFinanceConstants.GIFT_TYPE_GIFT) && (ARow.GiftType != MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND) && (ARow.GiftType != MFinanceConstants.GIFT_TYPE_OTHER)) { if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TScreenVerificationResult(ValidationContext, ValidationColumn, String.Format(Catalog.GetString("Unknown gift type '{0}'. Expected one of '{1}', '{2}' or '{3}'"), ARow.GiftType, MFinanceConstants.GIFT_TYPE_GIFT, MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND, MFinanceConstants.GIFT_TYPE_OTHER), ValidationControlsData.ValidationControl, TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } } } return VerifResultCollAddedCount == 0; }
/// <summary> /// Check if a given cost centre is active /// </summary> /// <param name="ALedgerNumber"></param> /// <param name="ACostCentreCode"></param> /// <param name="ACostCentreList"></param> /// <param name="ACostCentreExists"></param> /// <returns></returns> public static bool CostCentreIsActive(Int32 ALedgerNumber, string ACostCentreCode, ACostCentreTable ACostCentreList, out bool ACostCentreExists) { ACostCentreExists = false; bool RetVal = false; ACostCentreRow CurrentCostCentreRow = null; if (ACostCentreList != null) { CurrentCostCentreRow = (ACostCentreRow)ACostCentreList.Rows.Find(new object[] { ALedgerNumber, ACostCentreCode }); if (CurrentCostCentreRow != null) { ACostCentreExists = true; RetVal = CurrentCostCentreRow.CostCentreActiveFlag; } } return RetVal; }
public void TestPostGiftBatchWithMotivationDetailCostCentre() { // import a gift batch, that we will modify later TGiftImporting importer = new TGiftImporting(); string testFile = TAppSettingsManager.GetValue("GiftBatch.file", "../../csharp/ICT/Testing/lib/MFinance/SampleData/sampleGiftBatch.csv"); StreamReader sr = new StreamReader(testFile); string FileContent = sr.ReadToEnd(); FileContent = FileContent.Replace("{ledgernumber}", FLedgerNumber.ToString()); FileContent = FileContent.Replace("{thisyear}", DateTime.Today.Year.ToString()); sr.Close(); Hashtable parameters = new Hashtable(); parameters.Add("Delimiter", ","); parameters.Add("ALedgerNumber", FLedgerNumber); parameters.Add("DateFormatString", "yyyy-MM-dd"); parameters.Add("NumberFormat", "American"); parameters.Add("NewLine", Environment.NewLine); TVerificationResultCollection VerificationResult = null; GiftBatchTDSAGiftDetailTable NeedRecipientLedgerNumber; if (!importer.ImportGiftBatches(parameters, FileContent, out NeedRecipientLedgerNumber, out VerificationResult)) { Assert.Fail("Gift Batch was not imported: " + VerificationResult.BuildVerificationResultString()); } int BatchNumber = importer.GetLastGiftBatchNumber(); Assert.AreNotEqual(-1, BatchNumber, "Should have imported the gift batch and returned a valid batch number"); bool NewTransaction = false; TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted, out NewTransaction); // create a new costcentre const string newCostCentre = "100001"; if (!ACostCentreAccess.Exists(FLedgerNumber, newCostCentre, Transaction)) { ACostCentreTable cc = new ACostCentreTable(); ACostCentreRow ccrow = cc.NewRowTyped(); ccrow.LedgerNumber = FLedgerNumber; ccrow.CostCentreCode = newCostCentre; ccrow.CostCentreName = newCostCentre; ccrow.PostingCostCentreFlag = true; ccrow.CostCentreToReportTo = (FLedgerNumber*100).ToString("0000"); ccrow.CostCentreType = MFinanceConstants.LOCAL_CC_TYPE; cc.Rows.Add(ccrow); ACostCentreAccess.SubmitChanges(cc, Transaction, UserInfo.GUserInfo.UserID); } // create a new motivation detail if (!AMotivationDetailAccess.Exists(FLedgerNumber, MFinanceConstants.MOTIVATION_GROUP_GIFT, newCostCentre, Transaction)) { AMotivationDetailTable mot = new AMotivationDetailTable(); AMotivationDetailRow motrow = mot.NewRowTyped(); motrow.LedgerNumber = FLedgerNumber; motrow.MotivationGroupCode = MFinanceConstants.MOTIVATION_GROUP_GIFT; motrow.MotivationDetailCode = newCostCentre; motrow.AccountCode = "0100"; motrow.CostCentreCode = newCostCentre; motrow.MotivationDetailDesc = newCostCentre; mot.Rows.Add(motrow); AMotivationDetailAccess.SubmitChanges(mot, Transaction, UserInfo.GUserInfo.UserID); } // modify the gift batch with that motivation detail, but with wrong costcentre AGiftDetailTable giftdetails = AGiftDetailAccess.LoadByPrimaryKey(FLedgerNumber, BatchNumber, 1, 1, null, Transaction); giftdetails[0].MotivationDetailCode = newCostCentre; giftdetails[0].RecipientKey = 0; Assert.AreNotEqual(newCostCentre, giftdetails[0].CostCentreCode, "cost centre code should not match the one defined by the motivation detail"); AGiftDetailAccess.SubmitChanges(giftdetails, Transaction); DBAccess.GDBAccessObj.CommitTransaction(); if (!TGiftTransactionWebConnector.PostGiftBatch(FLedgerNumber, BatchNumber, out VerificationResult)) { Assert.Fail("Gift Batch was not posted: " + VerificationResult.BuildVerificationResultString()); } Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted, out NewTransaction); giftdetails = AGiftDetailAccess.LoadByPrimaryKey(FLedgerNumber, BatchNumber, 1, 1, null, Transaction); Assert.AreEqual(newCostCentre, giftdetails[0].CostCentreCode, "cost centre code should have been adjusted because of the motivation detail"); DBAccess.GDBAccessObj.CommitTransaction(); }
/// <summary> /// Validates the Gift Detail data. /// </summary> /// <param name="AContext">Context that describes where the data validation failed.</param> /// <param name="ARow">The <see cref="DataRow" /> which holds the the data against which the validation is run.</param> /// <param name="AVerificationResultCollection">Will be filled with any <see cref="TVerificationResult" /> items if /// data validation errors occur.</param> /// <param name="AValidationControlsDict">A <see cref="TValidationControlsDict" /> containing the Controls that /// display data that is about to be validated.</param> /// <param name="ARecipientPartnerClass">Recipient's Partner Class (used for Motivation Detail validation).</param> /// <param name="ASetupForILT">Optional - Is the recipient set up for inter-ledger transfers.</param> /// <param name="ACostCentres">Optional - a CostCentres table. Is required for import validation. </param> /// <param name="AAccounts">Optional - a Accounts table. Is required for import validation. </param> /// <param name="AMotivationGroups">Optional - a MotivationGroups table. Is required for import validation. </param> /// <param name="AMotivationDetails">Optional - a MotivationDetails table. Is required for import validation. </param> /// <param name="AMailingTable">Optional - a Mailing table. Is required for import validation. </param> /// <param name="ARecipientField">Optional The recipient field for the gift. Is required for import validation. </param> /// <returns>True if the validation found no data validation errors, otherwise false.</returns> public static bool ValidateGiftDetailManual(object AContext, GiftBatchTDSAGiftDetailRow ARow, ref TVerificationResultCollection AVerificationResultCollection, TValidationControlsDict AValidationControlsDict, TPartnerClass? ARecipientPartnerClass, bool? ASetupForILT = null, ACostCentreTable ACostCentres = null, AAccountTable AAccounts = null, AMotivationGroupTable AMotivationGroups = null, AMotivationDetailTable AMotivationDetails = null, PMailingTable AMailingTable = null, Int64 ARecipientField = -1) { DataColumn ValidationColumn; TValidationControlsData ValidationControlsData; TVerificationResult VerificationResult = null; object ValidationContext; int VerifResultCollAddedCount = 0; bool ValidPartner = true; // Don't validate deleted DataRows if (ARow.RowState == DataRowState.Deleted) { return true; } bool isImporting = AContext.ToString().Contains("Importing"); // Check if valid recipient ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnRecipientKeyId]; ValidationContext = String.Format("Batch no. {0}, gift no. {1}, detail no. {2}", ARow.BatchNumber, ARow.GiftTransactionNumber, ARow.DetailNumber); VerificationResult = TSharedPartnerValidation_Partner.IsValidPartner( ARow.RecipientKey, new TPartnerClass[] { TPartnerClass.FAMILY, TPartnerClass.UNIT }, true, isImporting ? Catalog.GetString("Recipient key") : "Recipient of " + THelper.NiceValueDescription(ValidationContext.ToString()), AContext, ValidationColumn, null); if (VerificationResult != null) { AVerificationResultCollection.Remove(ValidationColumn); AVerificationResultCollection.AddAndIgnoreNullValue(VerificationResult); ValidPartner = false; } // 'Gift amount must be non-zero ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnGiftTransactionAmountId]; ValidationContext = String.Format("Batch Number {0} (transaction:{1} detail:{2})", ARow.BatchNumber, ARow.GiftTransactionNumber, ARow.DetailNumber); if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { VerificationResult = TNumericalChecks.IsNonZeroDecimal(ARow.GiftTransactionAmount, ValidationControlsData.ValidationControlLabel + (isImporting ? String.Empty : " of " + ValidationContext), AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } } // If recipient is non-zero, field must also be non-zero. Only check for valid recipient keys. ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnRecipientLedgerNumberId]; ValidationContext = String.Format("batch:{0} transaction:{1} detail:{2}", ARow.BatchNumber, ARow.GiftTransactionNumber, ARow.DetailNumber); if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { if ((ARow.RecipientKey > 0) && ValidPartner && (ARow.RecipientLedgerNumber == 0)) { VerificationResult = TNumericalChecks.IsGreaterThanZero(ARow.RecipientLedgerNumber, "Recipient field of " + ValidationContext + " is 0", AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } } // Motivation Group code must exist if (!ARow.IsMotivationGroupCodeNull() && (AMotivationGroups != null)) { AMotivationGroupRow foundRow = (AMotivationGroupRow)AMotivationGroups.Rows.Find( new object[] { ARow.LedgerNumber, ARow.MotivationGroupCode }); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Unknown motivation group code '{0}'."), ARow.MotivationGroupCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } } if (!isImporting) { // NOTE AlanP Oct 2014. This gets checked by standard validation so may no longer be necessary? // (There was a bug in standard validation where NULL and empty string checks did not quite work as they should ... // so maybe this was necessary before. Anyway I am leaving it in for now. I know that importing works fine, // but maybe it is necessary in other circumstances?) // Motivation Detail must not be null ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnMotivationDetailCodeId]; ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})", ARow.BatchNumber, ARow.GiftTransactionNumber, ARow.DetailNumber); if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { if (ARow.IsMotivationDetailCodeNull() || (ARow.MotivationDetailCode == String.Empty)) { VerificationResult = TGeneralChecks.ValueMustNotBeNullOrEmptyString(ARow.MotivationDetailCode, (isImporting ? ValidationControlsData.ValidationControlLabel : "Motivation Detail code " + ValidationContext), AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } } } } // Motivation Detail must be valid ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnMotivationDetailCodeId]; ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})", ARow.BatchNumber, ARow.GiftTransactionNumber, ARow.DetailNumber); if (!ARow.IsMotivationDetailCodeNull() && (AMotivationDetails != null)) { AMotivationDetailRow foundRow = (AMotivationDetailRow)AMotivationDetails.Rows.Find( new object[] { ARow.LedgerNumber, ARow.MotivationGroupCode, ARow.MotivationDetailCode }); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Unknown motivation detail code '{0}' for group '{1}'."), ARow.MotivationDetailCode, ARow.MotivationGroupCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } if ((foundRow != null) && (foundRow.MotivationStatus == false) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Motivation detail code '{0}' is no longer in use."), ARow.MotivationDetailCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } if ((foundRow != null) && (foundRow.RecipientKey != 0) && (ARow.RecipientKey != 0) && (foundRow.RecipientKey != ARow.RecipientKey) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString( "The recipient partner key for motivation detail code '{0}' does not match the recipient partner key in the import line."), ARow.MotivationDetailCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } // Motivation Detail must not be 'Field' or 'Keymin' if the recipient is a Family partner ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnMotivationDetailCodeId]; ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})", ARow.BatchNumber, ARow.GiftTransactionNumber, ARow.DetailNumber); if (!ARow.IsMotivationDetailCodeNull() && (ARow.MotivationGroupCode == MFinanceConstants.MOTIVATION_GROUP_GIFT) && (ARecipientPartnerClass != null) && ((ARow.MotivationDetailCode == MFinanceConstants.GROUP_DETAIL_FIELD) || (ARow.MotivationDetailCode == MFinanceConstants.GROUP_DETAIL_KEY_MIN)) && (ARecipientPartnerClass == TPartnerClass.FAMILY)) { if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { VerificationResult = new TVerificationResult(AContext, String.Format(Catalog.GetString("Motivation Detail code '{0}' is not allowed for Family recipients."), ARow.MotivationDetailCode), TResultSeverity.Resv_Critical); if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, new TScreenVerificationResult(VerificationResult, ValidationColumn, ValidationControlsData.ValidationControl), ValidationColumn, true)) { VerifResultCollAddedCount++; } } } // Cost Centre Code must exist and be active. Only required for importing because the GUI does this for us otherwise. if (isImporting && (ACostCentres != null) && !ARow.IsCostCentreCodeNull()) { ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnCostCentreCodeId]; ValidationContext = ARow.CostCentreCode; if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { // We even need to check that the code exists! DataRow foundRow = ACostCentres.Rows.Find(new object[] { ARow.LedgerNumber, ARow.CostCentreCode }); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TScreenVerificationResult(ValidationContext, ValidationColumn, String.Format(Catalog.GetString("Unknown cost centre code '{0}'."), ARow.CostCentreCode), ValidationControlsData.ValidationControl, TResultSeverity.Resv_Critical), /* * new TVerificationResult(ValidationContext, * String.Format(Catalog.GetString("Unknown cost centre code '{0}'."), ARow.CostCentreCode), * TResultSeverity.Resv_Critical), */ ValidationColumn)) { VerifResultCollAddedCount++; } VerificationResult = (TScreenVerificationResult)TStringChecks.ValidateValueIsActive(ARow.LedgerNumber, ACostCentres, ValidationContext.ToString(), ACostCentreTable.GetCostCentreActiveFlagDBName(), AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if ((VerificationResult != null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } } } // Account Code must exist and be active. Only required for importing because the GUI does this for us otherwise. if (isImporting && (AAccounts != null) && !ARow.IsAccountCodeNull()) { DataColumn[] ValidationColumns = new DataColumn[] { ARow.Table.Columns[AGiftDetailTable.ColumnAccountCodeId], ARow.Table.Columns[AGiftDetailTable.ColumnTaxDeductibleAccountCodeId] }; string[] AccountCodes = new string[] { ARow.AccountCode, ARow.TaxDeductibleAccountCode }; for (int i = 0; i < 2; i++) { if (AValidationControlsDict.TryGetValue(ValidationColumns[i], out ValidationControlsData)) { // We even need to check that the code exists! DataRow foundRow = AAccounts.Rows.Find(new object[] { ARow.LedgerNumber, AccountCodes[i] }); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(AccountCodes[i], String.Format(Catalog.GetString("Unknown account code '{0}'."), AccountCodes[i]), TResultSeverity.Resv_Critical), ValidationColumns[i])) { VerifResultCollAddedCount++; } VerificationResult = (TScreenVerificationResult)TStringChecks.ValidateValueIsActive(ARow.LedgerNumber, AAccounts, AccountCodes[i], AAccountTable.GetAccountActiveFlagDBName(), AContext, ValidationColumns[i], ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if ((VerificationResult != null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumns[i], true)) { VerifResultCollAddedCount++; } } } } // Mailing code must exist ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnMailingCodeId]; ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})", ARow.BatchNumber, ARow.GiftTransactionNumber, ARow.DetailNumber); if (!ARow.IsMailingCodeNull() && (AMailingTable != null)) { PMailingRow foundRow = (PMailingRow)AMailingTable.Rows.Find(ARow.MailingCode); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Unknown mailing code '{0}'."), ARow.MailingCode), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } // Detail comments type 1 must not be null if associated comment is not null ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnCommentOneTypeId]; ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})", ARow.BatchNumber, ARow.GiftTransactionNumber, ARow.DetailNumber); if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { if (!ARow.IsGiftCommentOneNull() && (ARow.GiftCommentOne != String.Empty)) { VerificationResult = TGeneralChecks.ValueMustNotBeNullOrEmptyString(ARow.CommentOneType, (isImporting ? ValidationControlsData.ValidationControlLabel : "Comment 1 type " + ValidationContext), AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } if (VerificationResult == null) { // There is a comment type for the comment - but it needs to be one of the valid types if ((ARow.CommentOneType != MFinanceConstants.GIFT_COMMENT_TYPE_DONOR) && (ARow.CommentOneType != MFinanceConstants.GIFT_COMMENT_TYPE_RECIPIENT) && (ARow.CommentOneType != MFinanceConstants.GIFT_COMMENT_TYPE_BOTH) && (ARow.CommentOneType != MFinanceConstants.GIFT_COMMENT_TYPE_OFFICE) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Comment type must be one of '{0}', '{1}', '{2}' or '{3}'."), MFinanceConstants.GIFT_COMMENT_TYPE_DONOR, MFinanceConstants.GIFT_COMMENT_TYPE_RECIPIENT, MFinanceConstants.GIFT_COMMENT_TYPE_BOTH, MFinanceConstants.GIFT_COMMENT_TYPE_OFFICE), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } } } // Detail comments type 2 must not be null if associated comment is not null ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnCommentTwoTypeId]; ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})", ARow.BatchNumber, ARow.GiftTransactionNumber, ARow.DetailNumber); if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { if (!ARow.IsGiftCommentTwoNull() && (ARow.GiftCommentTwo != String.Empty)) { VerificationResult = TGeneralChecks.ValueMustNotBeNullOrEmptyString(ARow.CommentTwoType, (isImporting ? ValidationControlsData.ValidationControlLabel : "Comment 2 type " + ValidationContext), AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } if (VerificationResult == null) { // There is a comment type for the comment - but it needs to be one of the valid types if ((ARow.CommentTwoType != MFinanceConstants.GIFT_COMMENT_TYPE_DONOR) && (ARow.CommentTwoType != MFinanceConstants.GIFT_COMMENT_TYPE_RECIPIENT) && (ARow.CommentTwoType != MFinanceConstants.GIFT_COMMENT_TYPE_BOTH) && (ARow.CommentTwoType != MFinanceConstants.GIFT_COMMENT_TYPE_OFFICE) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Comment type must be one of '{0}', '{1}', '{2}' or '{3}'."), MFinanceConstants.GIFT_COMMENT_TYPE_DONOR, MFinanceConstants.GIFT_COMMENT_TYPE_RECIPIENT, MFinanceConstants.GIFT_COMMENT_TYPE_BOTH, MFinanceConstants.GIFT_COMMENT_TYPE_OFFICE), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } } } // Detail comments type 3 must not be null if associated comment is not null ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnCommentThreeTypeId]; ValidationContext = String.Format("(batch:{0} transaction:{1} detail:{2})", ARow.BatchNumber, ARow.GiftTransactionNumber, ARow.DetailNumber); if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData)) { if (!ARow.IsGiftCommentThreeNull() && (ARow.GiftCommentThree != String.Empty)) { VerificationResult = TGeneralChecks.ValueMustNotBeNullOrEmptyString(ARow.CommentThreeType, (isImporting ? ValidationControlsData.ValidationControlLabel : "Comment 3 type " + ValidationContext), AContext, ValidationColumn, ValidationControlsData.ValidationControl); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true)) { VerifResultCollAddedCount++; } if (VerificationResult == null) { // There is a comment type for the comment - but it needs to be one of the valid types if ((ARow.CommentThreeType != MFinanceConstants.GIFT_COMMENT_TYPE_DONOR) && (ARow.CommentThreeType != MFinanceConstants.GIFT_COMMENT_TYPE_RECIPIENT) && (ARow.CommentThreeType != MFinanceConstants.GIFT_COMMENT_TYPE_BOTH) && (ARow.CommentThreeType != MFinanceConstants.GIFT_COMMENT_TYPE_OFFICE) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( AContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Comment type must be one of '{0}', '{1}', '{2}' or '{3}'."), MFinanceConstants.GIFT_COMMENT_TYPE_DONOR, MFinanceConstants.GIFT_COMMENT_TYPE_RECIPIENT, MFinanceConstants.GIFT_COMMENT_TYPE_BOTH, MFinanceConstants.GIFT_COMMENT_TYPE_OFFICE), TResultSeverity.Resv_Critical), ValidationColumn)) { VerifResultCollAddedCount++; } } } } return VerifResultCollAddedCount == 0; }
/// <summary> /// Call this to initialise the 'Lists' (tables) for the ComboBoxes /// </summary> /// <param name="ALoadAndFilterLogicObject">Supply a reference to the Filter Logic object because it needs a reference to the same Lists</param> public void RefreshBankAccountAndCostCentreData(TUC_GiftBatches_LoadAndFilter ALoadAndFilterLogicObject) { //Populate CostCentreList variable DataTable costCentreList = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.CostCentreList, FLedgerNumber); ACostCentreTable tmpCostCentreTable = new ACostCentreTable(); FMainDS.Tables.Add(tmpCostCentreTable); DataUtilities.ChangeDataTableToTypedDataTable(ref costCentreList, FMainDS.Tables[tmpCostCentreTable.TableName].GetType(), ""); FMainDS.RemoveTable(tmpCostCentreTable.TableName); FCostCentreTable = (ACostCentreTable)costCentreList; ALoadAndFilterLogicObject.CostCentreTable = FCostCentreTable; //Populate AccountList variable DataTable accountList = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.AccountList, FLedgerNumber); AAccountTable tmpAccountTable = new AAccountTable(); FMainDS.Tables.Add(tmpAccountTable); DataUtilities.ChangeDataTableToTypedDataTable(ref accountList, FMainDS.Tables[tmpAccountTable.TableName].GetType(), ""); FMainDS.RemoveTable(tmpAccountTable.TableName); FAccountTable = (AAccountTable)accountList; ALoadAndFilterLogicObject.AccountTable = FAccountTable; }
/// <summary> /// Validates the GL Detail data. /// </summary> /// <param name="AContext">Context that describes where the data validation failed.</param> /// <param name="ABatchRow">Manually added to bring over some GL Batch fields</param> /// <param name="ARow">The <see cref="DataRow" /> which holds the the data against which the validation is run.</param> /// <param name="AVerificationResultCollection">Will be filled with any <see cref="TVerificationResult" /> items if /// data validation errors occur.</param> /// <param name="AValidationCostCentreTable">REQUIRED for importing. A reference to a cost centre table so that inputs can be validated.</param> /// <param name="AvalidationAccountTable">REQUIRED for importing. A reference to an account table so that inputs can be validated.</param> /// <returns>True if the validation found no data validation errors, otherwise false.</returns> public static bool ValidateGLDetailManual(object AContext, ABatchRow ABatchRow, ATransactionRow ARow, ref TVerificationResultCollection AVerificationResultCollection, ACostCentreTable AValidationCostCentreTable = null, AAccountTable AvalidationAccountTable = null) { DataColumn ValidationColumn; TVerificationResult VerificationResult = null; object ValidationContext; int VerifResultCollAddedCount = 0; // Don't validate deleted DataRows or non-unposted batches if ((ABatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED) || (ARow.RowState == DataRowState.Deleted)) { return(true); } bool isImporting = AContext.ToString().Contains("Importing"); // When used by the GUI TransactionAmount is not in the dictionary so had to pass the control directly // But when importing we do have a dictionary entry if (isImporting) { // 'GL amount must be non-zero and positive ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnTransactionAmountId]; if (true) { VerificationResult = TNumericalChecks.IsPositiveDecimal(ARow.TransactionAmount, String.Empty, AContext, ValidationColumn); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult)) { VerifResultCollAddedCount++; } } } else { if (true) { // 'GL amount must be non-zero and positive ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnTransactionAmountId]; ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})", ARow.TransactionNumber, ARow.BatchNumber, ARow.JournalNumber); VerificationResult = TNumericalChecks.IsPositiveOrZeroDecimal(ARow.TransactionAmount, "Amount of " + ValidationContext, AContext, ValidationColumn); if (VerificationResult != null) { VerificationResult.SuppressValidationToolTip = true; } // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult)) { VerifResultCollAddedCount++; } return(VerifResultCollAddedCount == 0); } } // 'Narrative must not be empty ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnNarrativeId]; ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})", ARow.TransactionNumber, ARow.BatchNumber, ARow.JournalNumber); if (true) { VerificationResult = TStringChecks.StringMustNotBeEmpty(ARow.Narrative, (isImporting) ? String.Empty : "Narrative of " + ValidationContext, AContext, ValidationColumn); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult)) { VerifResultCollAddedCount++; } } // 'Entered From Date' must be valid ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnTransactionDateId]; ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})", ARow.TransactionNumber, ARow.BatchNumber, ARow.JournalNumber); if (true) { DateTime StartDatePeriod; DateTime EndDatePeriod; TSharedFinanceValidationHelper.GetValidPeriodDates(ARow.LedgerNumber, ABatchRow.BatchYear, 0, ABatchRow.BatchPeriod, out StartDatePeriod, out EndDatePeriod); VerificationResult = (TScreenVerificationResult)TDateChecks.IsDateBetweenDates(ARow.TransactionDate, StartDatePeriod, EndDatePeriod, (isImporting) ? String.Empty : "Transaction Date for " + ValidationContext.ToString(), TDateBetweenDatesCheckType.dbdctUnspecific, TDateBetweenDatesCheckType.dbdctUnspecific, AContext, ValidationColumn); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult)) { VerifResultCollAddedCount++; } } if (true) { // "Reference" is mandatory ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnReferenceId]; ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})", ARow.TransactionNumber, ARow.BatchNumber, ARow.JournalNumber); if (true) { VerificationResult = TStringChecks.StringMustNotBeEmpty(ARow.Reference, (isImporting) ? String.Empty : "Reference of " + ValidationContext, AContext, ValidationColumn); // Handle addition/removal to/from TVerificationResultCollection if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult)) { VerifResultCollAddedCount++; } } } // 'CostCentre' must be valid ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnCostCentreCodeId]; ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})", ARow.TransactionNumber, ARow.BatchNumber, ARow.JournalNumber); if (true) { if ((AValidationCostCentreTable != null) && !ARow.IsCostCentreCodeNull()) { // Code must exist in the cost centre table ACostCentreRow foundRow = (ACostCentreRow)AValidationCostCentreTable.Rows.Find( new object[] { ARow.LedgerNumber, ARow.CostCentreCode }); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( ValidationContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Cost centre code '{0}' does not exist."), ARow.CostCentreCode), TResultSeverity.Resv_Critical))) { VerifResultCollAddedCount++; } // cost centre must be a posting cost centre if ((foundRow != null) && !foundRow.PostingCostCentreFlag) { if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(ValidationContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Cost centre code '{0}' is not a posting cost centre."), ARow.CostCentreCode), TResultSeverity.Resv_Critical))) { VerifResultCollAddedCount++; } } //TODO: Maybe add a user preference to determine what to do with inactive values on importing // cost centre must not be inactive //if ((foundRow != null) && !foundRow.CostCentreActiveFlag) //{ // if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(ValidationContext, // new TVerificationResult(ValidationContext, // String.Format(Catalog.GetString("Cost centre code '{0}' is an inactive cost centre."), ARow.CostCentreCode), // TResultSeverity.Resv_Critical), // ValidationColumn)) // { // VerifResultCollAddedCount++; // } //} } } // 'Account code' must be valid ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnAccountCodeId]; ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})", ARow.TransactionNumber, ARow.BatchNumber, ARow.JournalNumber); if (true) { if ((AvalidationAccountTable != null) && !ARow.IsAccountCodeNull()) { // Code must exist in the account table AAccountRow foundRow = (AAccountRow)AvalidationAccountTable.Rows.Find( new object[] { ARow.LedgerNumber, ARow.AccountCode }); if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove( ValidationContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Account code '{0}' does not exist."), ARow.AccountCode), TResultSeverity.Resv_Critical))) { VerifResultCollAddedCount++; } // Account code must be a posting Account code if ((foundRow != null) && !foundRow.PostingStatus) { if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(ValidationContext, new TVerificationResult(ValidationContext, String.Format(Catalog.GetString("Account code '{0}' is not a posting account."), ARow.AccountCode), TResultSeverity.Resv_Critical))) { VerifResultCollAddedCount++; } } //TODO: Maybe add a user preference to determine what to do with inactive values on importing // Account code must not be inactive //if ((foundRow != null) && !foundRow.AccountActiveFlag) //{ // if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(ValidationContext, // new TVerificationResult(ValidationContext, // String.Format(Catalog.GetString("Account code '{0}' is an inactive account."), ARow.AccountCode), // TResultSeverity.Resv_Critical), // ValidationColumn)) // { // VerifResultCollAddedCount++; // } //} } } return(VerifResultCollAddedCount == 0); }
private static void GetReportingCostCentres(ACostCentreTable ACostCentres, List <string>AResult, string ASummaryCostCentreCode) { if (ASummaryCostCentreCode.Length == 0) { return; } string[] CostCentres = ASummaryCostCentreCode.Split(new char[] { ',' }); foreach (string costcentre in CostCentres) { DataRowView[] ReportingCostCentres = ACostCentres.DefaultView.FindRows(costcentre); if (ReportingCostCentres.Length > 0) { foreach (DataRowView rv in ReportingCostCentres) { ACostCentreRow row = (ACostCentreRow)rv.Row; if (row.PostingCostCentreFlag) { AResult.Add(row.CostCentreCode); } else { GetReportingCostCentres(ACostCentres, AResult, row.CostCentreCode); } } } else { DataView dv = new DataView(ACostCentres); dv.Sort = ACostCentreTable.GetCostCentreCodeDBName(); ACostCentreRow cc = (ACostCentreRow)dv.FindRows(costcentre)[0].Row; if (cc.PostingCostCentreFlag) { AResult.Add(costcentre); } } } }
private void RevaluateAccount(DataView GLMView, decimal AExchangeRate) { foreach (DataRowView RowView in GLMView) { AGeneralLedgerMasterRow glmRow = (AGeneralLedgerMasterRow)RowView.Row; ACostCentreTable tempTbl = null; AGeneralLedgerMasterPeriodTable glmpTbl = null; TDBTransaction transaction = null; DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref transaction, delegate { tempTbl = ACostCentreAccess.LoadByPrimaryKey(F_LedgerNum, glmRow.CostCentreCode, transaction); glmpTbl = AGeneralLedgerMasterPeriodAccess.LoadByPrimaryKey(glmRow.GlmSequence, F_AccountingPeriod, transaction); }); if (tempTbl.Rows.Count == 0) { continue; // I really don't expect this, but if it does happen, this will prevent a crash! } ACostCentreRow tempRow = tempTbl[0]; if (!tempRow.PostingCostCentreFlag) { continue; // I do expect this - many rows are not "posting" cost centres. } try { if (glmpTbl.Rows.Count == 0) { continue; // I really don't expect this, but if it does happen, this will prevent a crash! } AGeneralLedgerMasterPeriodRow glmpRow = glmpTbl[0]; // // If ActualForeign has not been set, I can't allow the ORM to even attempt to access them: // (If ActualForeign is NULL, that's probably a fault, but this has occured in historical data.) if (glmpRow.IsActualBaseNull() || glmpRow.IsActualForeignNull()) { continue; } decimal delta = AccountDelta(glmpRow.ActualBase, glmpRow.ActualForeign, AExchangeRate, F_BaseCurrencyDigits); if (delta != 0) { // Now we have the relevant Cost Centre ... RevaluateCostCentre(glmRow.AccountCode, glmRow.CostCentreCode, delta); } else { string strMessage = String.Format( Catalog.GetString("The account {1}:{0} does not require revaluation."), glmRow.AccountCode, glmRow.CostCentreCode, AExchangeRate); FVerificationCollection.Add(new TVerificationResult( strStatusContent, strMessage, TResultSeverity.Resv_Noncritical)); } } catch (EVerificationException terminate) { FVerificationCollection = terminate.ResultCollection(); } catch (DivideByZeroException) { FVerificationCollection.Add(new TVerificationResult( strStatusContent, Catalog.GetString("DivideByZeroException"), TResultSeverity.Resv_Noncritical)); } catch (OverflowException) { FVerificationCollection.Add(new TVerificationResult( strStatusContent, Catalog.GetString("OverflowException"), TResultSeverity.Resv_Noncritical)); } } }
private void SetupExtraGridFunctionality() { DataTable CostCentreListTable = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.CostCentreList, FLedgerNumber); ACostCentreTable tmpCostCentreTable = new ACostCentreTable(); FMainDS.Tables.Add(tmpCostCentreTable); DataUtilities.ChangeDataTableToTypedDataTable(ref CostCentreListTable, FMainDS.Tables[tmpCostCentreTable.TableName].GetType(), ""); FMainDS.RemoveTable(tmpCostCentreTable.TableName); if ((CostCentreListTable == null) || (CostCentreListTable.Rows.Count == 0)) { FCostCentreList = null; } else { FCostCentreList = (ACostCentreTable)CostCentreListTable; } DataTable AccountListTable = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.AccountList, FLedgerNumber); AAccountTable tmpAccountTable = new AAccountTable(); FMainDS.Tables.Add(tmpAccountTable); DataUtilities.ChangeDataTableToTypedDataTable(ref AccountListTable, FMainDS.Tables[tmpAccountTable.TableName].GetType(), ""); FMainDS.RemoveTable(tmpAccountTable.TableName); if ((AccountListTable == null) || (AccountListTable.Rows.Count == 0)) { FAccountList = null; } else { FAccountList = (AAccountTable)AccountListTable; } //Prepare grid to highlight inactive accounts/cost centres // Create a cell view for special conditions SourceGrid.Cells.Views.Cell strikeoutCell = new SourceGrid.Cells.Views.Cell(); strikeoutCell.Font = new System.Drawing.Font(grdDetails.Font, FontStyle.Strikeout); //strikeoutCell.ForeColor = Color.Crimson; // Create a condition, apply the view when true, and assign a delegate to handle it SourceGrid.Conditions.ConditionView conditionAccountCodeActive = new SourceGrid.Conditions.ConditionView(strikeoutCell); conditionAccountCodeActive.EvaluateFunction = delegate(SourceGrid.DataGridColumn column, int gridRow, object itemRow) { DataRowView row = (DataRowView)itemRow; string accountCode = row[ATransactionTable.ColumnAccountCodeId].ToString(); return !AccountIsActive(accountCode); }; SourceGrid.Conditions.ConditionView conditionCostCentreCodeActive = new SourceGrid.Conditions.ConditionView(strikeoutCell); conditionCostCentreCodeActive.EvaluateFunction = delegate(SourceGrid.DataGridColumn column, int gridRow, object itemRow) { DataRowView row = (DataRowView)itemRow; string costCentreCode = row[ATransactionTable.ColumnCostCentreCodeId].ToString(); return !CostCentreIsActive(costCentreCode); }; //Add conditions to columns int indexOfCostCentreCodeDataColumn = 2; int indexOfAccountCodeDataColumn = 3; grdDetails.Columns[indexOfCostCentreCodeDataColumn].Conditions.Add(conditionCostCentreCodeActive); grdDetails.Columns[indexOfAccountCodeDataColumn].Conditions.Add(conditionAccountCodeActive); //Prepare Analysis attributes grid to highlight inactive analysis codes // Create a cell view for special conditions SourceGrid.Cells.Views.Cell strikeoutCell2 = new SourceGrid.Cells.Views.Cell(); strikeoutCell2.Font = new System.Drawing.Font(grdAnalAttributes.Font, FontStyle.Strikeout); //strikeoutCell.ForeColor = Color.Crimson; // Create a condition, apply the view when true, and assign a delegate to handle it SourceGrid.Conditions.ConditionView conditionAnalysisCodeActive = new SourceGrid.Conditions.ConditionView(strikeoutCell2); conditionAnalysisCodeActive.EvaluateFunction = delegate(SourceGrid.DataGridColumn column2, int gridRow2, object itemRow2) { DataRowView row2 = (DataRowView)itemRow2; string analysisCode = row2[ATransAnalAttribTable.ColumnAnalysisTypeCodeId].ToString(); return !FAnalysisAttributesLogic.AnalysisCodeIsActive( cmbDetailAccountCode.GetSelectedString(), FCacheDS.AAnalysisAttribute, analysisCode); }; // Create a condition, apply the view when true, and assign a delegate to handle it SourceGrid.Conditions.ConditionView conditionAnalysisAttributeValueActive = new SourceGrid.Conditions.ConditionView(strikeoutCell2); conditionAnalysisAttributeValueActive.EvaluateFunction = delegate(SourceGrid.DataGridColumn column2, int gridRow2, object itemRow2) { if (itemRow2 != null) { DataRowView row2 = (DataRowView)itemRow2; string analysisCode = row2[ATransAnalAttribTable.ColumnAnalysisTypeCodeId].ToString(); string analysisAttributeValue = row2[ATransAnalAttribTable.ColumnAnalysisAttributeValueId].ToString(); return !TAnalysisAttributes.AnalysisAttributeValueIsActive(ref FcmbAnalAttribValues, FCacheDS.AFreeformAnalysis, analysisCode, analysisAttributeValue); } else { return false; } }; //Add conditions to columns int indexOfAnalysisCodeColumn = 0; int indexOfAnalysisAttributeValueColumn = 1; grdAnalAttributes.Columns[indexOfAnalysisCodeColumn].Conditions.Add(conditionAnalysisCodeActive); grdAnalAttributes.Columns[indexOfAnalysisAttributeValueColumn].Conditions.Add(conditionAnalysisAttributeValueActive); }
private void SetupExtraGridFunctionality() { //Populate CostCentreList variable DataTable costCentreList = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.CostCentreList, FLedgerNumber); ACostCentreTable tmpCostCentreTable = new ACostCentreTable(); FMainDS.Tables.Add(tmpCostCentreTable); DataUtilities.ChangeDataTableToTypedDataTable(ref costCentreList, FMainDS.Tables[tmpCostCentreTable.TableName].GetType(), ""); FMainDS.RemoveTable(tmpCostCentreTable.TableName); FCostCentreTable = (ACostCentreTable)costCentreList; //Populate AccountList variable DataTable accountList = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.AccountList, FLedgerNumber); AAccountTable tmpAccountTable = new AAccountTable(); FMainDS.Tables.Add(tmpAccountTable); DataUtilities.ChangeDataTableToTypedDataTable(ref accountList, FMainDS.Tables[tmpAccountTable.TableName].GetType(), ""); FMainDS.RemoveTable(tmpAccountTable.TableName); FAccountTable = (AAccountTable)accountList; //Prepare grid to highlight inactive accounts/cost centres // Create a cell view for special conditions SourceGrid.Cells.Views.Cell strikeoutCell = new SourceGrid.Cells.Views.Cell(); strikeoutCell.Font = new System.Drawing.Font(grdDetails.Font, FontStyle.Strikeout); //strikeoutCell.ForeColor = Color.Crimson; // Create a condition, apply the view when true, and assign a delegate to handle it SourceGrid.Conditions.ConditionView conditionAccountCodeActive = new SourceGrid.Conditions.ConditionView(strikeoutCell); conditionAccountCodeActive.EvaluateFunction = delegate(SourceGrid.DataGridColumn column, int gridRow, object itemRow) { DataRowView row = (DataRowView)itemRow; string accountCode = row[ABudgetTable.ColumnAccountCodeId].ToString(); return !AccountIsActive(accountCode); }; SourceGrid.Conditions.ConditionView conditionCostCentreCodeActive = new SourceGrid.Conditions.ConditionView(strikeoutCell); conditionCostCentreCodeActive.EvaluateFunction = delegate(SourceGrid.DataGridColumn column, int gridRow, object itemRow) { DataRowView row = (DataRowView)itemRow; string costCentreCode = row[ABudgetTable.ColumnCostCentreCodeId].ToString(); return !CostCentreIsActive(costCentreCode); }; //Add conditions to columns int indexOfCostCentreCodeDataColumn = 0; int indexOfAccountCodeDataColumn = 1; grdDetails.Columns[indexOfCostCentreCodeDataColumn].Conditions.Add(conditionCostCentreCodeActive); grdDetails.Columns[indexOfAccountCodeDataColumn].Conditions.Add(conditionAccountCodeActive); }
/// <summary> /// This array of CostCentres may contain some funds that should not be processed /// through ICH. /// I need to process those here, and remove them from the list. /// /// </summary> private static StringDictionary GetDestinationAccountCodes(int ALedgerNumber, ACostCentreTable CostCentreTbl, TDBTransaction ATransaction) { AAccountPropertyTable AccountPropertyTbl = new AAccountPropertyTable(); AAccountPropertyRow TemplateRow = AccountPropertyTbl.NewRowTyped(false); TemplateRow.LedgerNumber = ALedgerNumber; TemplateRow.PropertyCode = "CLEARING-ACCOUNT-FOR-CC"; AccountPropertyTbl = AAccountPropertyAccess.LoadUsingTemplate(TemplateRow, ATransaction); StringDictionary ReportingAccountForCC = new StringDictionary(); foreach (AAccountPropertyRow Row in AccountPropertyTbl.Rows) { String[] CcList = Row.PropertyValue.Split(','); foreach (String CC in CcList) { ReportingAccountForCC.Add(CC, Row.AccountCode); } } foreach (DataRow UntypedCCRow in CostCentreTbl.Rows) { ACostCentreRow CostCentreRow = (ACostCentreRow)UntypedCCRow; if (!ReportingAccountForCC.ContainsKey(CostCentreRow.CostCentreCode)) { ReportingAccountForCC.Add(CostCentreRow.CostCentreCode, MFinanceConstants.ICH_ACCT_ICH); } } return ReportingAccountForCC; }
private void ParseBatchLine(ref AGiftBatchRow AGiftBatch, ref TDBTransaction ATransaction, ref ALedgerTable ALedgerTable, ref string AImportMessage, int ARowNumber, TVerificationResultCollection AMessages, TValidationControlsDict AValidationControlsDictBatch, AAccountTable AValidationAccountTable, AAccountPropertyTable AValidationAccountPropertyTable, AAccountingPeriodTable AValidationAccountingPeriodTable, ACostCentreTable AValidationCostCentreTable, ACorporateExchangeRateTable AValidationCorporateExchTable, ACurrencyTable AValidationCurrencyTable) { // There are 8 elements to import (the last of which can be blank) string BatchDescription = ImportString(Catalog.GetString("Batch description"), FMainDS.AGiftBatch.ColumnBatchDescription, AValidationControlsDictBatch); string BankAccountCode = ImportString(Catalog.GetString("Bank account code"), FMainDS.AGiftBatch.ColumnBankAccountCode, AValidationControlsDictBatch).ToUpper(); decimal HashTotal = ImportDecimal(Catalog.GetString("Hash total"), FMainDS.AGiftBatch.ColumnHashTotal, ARowNumber, AMessages, AValidationControlsDictBatch); DateTime GlEffectiveDate = ImportDate(Catalog.GetString("Effective Date"), FMainDS.AGiftBatch.ColumnGlEffectiveDate, ARowNumber, AMessages, AValidationControlsDictBatch); AImportMessage = "Creating new batch"; // This call sets: BatchNumber, BatchYear, BatchPeriod, GlEffectiveDate, ExchangeRateToBase, BatchDescription, BankAccountCode // BankCostCentre and CurrencyCode. The effective date will NOT be modified. // The first three are not validated because they should be ok by default AGiftBatch = TGiftBatchFunctions.CreateANewGiftBatchRow(ref FMainDS, ref ATransaction, ref ALedgerTable, FLedgerNumber, GlEffectiveDate, false); // Now we modify some of these in the light of the imported data AGiftBatch.BatchDescription = BatchDescription; AGiftBatch.BankAccountCode = BankAccountCode; AGiftBatch.HashTotal = HashTotal; AGiftBatch.CurrencyCode = ImportString(Catalog.GetString("Currency code"), FMainDS.AGiftBatch.ColumnCurrencyCode, AValidationControlsDictBatch); AGiftBatch.ExchangeRateToBase = ImportDecimal(Catalog.GetString("Exchange rate to base"), FMainDS.AGiftBatch.ColumnExchangeRateToBase, ARowNumber, AMessages, AValidationControlsDictBatch); AGiftBatch.BankCostCentre = ImportString(Catalog.GetString("Bank cost centre"), FMainDS.AGiftBatch.ColumnBankCostCentre, AValidationControlsDictBatch).ToUpper(); AGiftBatch.GiftType = ImportString(Catalog.GetString("Gift type"), FMainDS.AGiftBatch.ColumnGiftType, AValidationControlsDictBatch); // If GiftType was empty, will default to GIFT // In all cases we ensure that the case entered by the user is converted to the case of our constants if ((AGiftBatch.GiftType == String.Empty) || (String.Compare(AGiftBatch.GiftType, MFinanceConstants.GIFT_TYPE_GIFT, true) == 0)) { AGiftBatch.GiftType = MFinanceConstants.GIFT_TYPE_GIFT; } else if (String.Compare(AGiftBatch.GiftType, MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND, true) == 0) { AGiftBatch.GiftType = MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND; } else if (String.Compare(AGiftBatch.GiftType, MFinanceConstants.GIFT_TYPE_OTHER, true) == 0) { AGiftBatch.GiftType = MFinanceConstants.GIFT_TYPE_OTHER; } int messageCountBeforeValidate = AMessages.Count; // Do our standard gift batch validation checks on this row AImportMessage = Catalog.GetString("Validating the gift batch data"); AGiftBatchValidation.Validate(this, AGiftBatch, ref AMessages, AValidationControlsDictBatch); // And do the additional manual ones AImportMessage = Catalog.GetString("Additional validation of the gift batch data"); TSharedFinanceValidation_Gift.ValidateGiftBatchManual(this, AGiftBatch, ref AMessages, AValidationControlsDictBatch, AValidationAccountTable, AValidationCostCentreTable, AValidationAccountPropertyTable, AValidationAccountingPeriodTable, AValidationCorporateExchTable, AValidationCurrencyTable, FLedgerBaseCurrency, FLedgerIntlCurrency); 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); } } if (AGiftBatch.ExchangeRateToBase > 10000000) // Huge numbers here indicate that the decimal comma/point is incorrect. { AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationErrorInLine, ARowNumber), String.Format(Catalog.GetString("A huge exchange rate of {0} suggests a decimal point format problem."), AGiftBatch.ExchangeRateToBase), TResultSeverity.Resv_Noncritical)); } }
private static Boolean ExportDonations(Int32 ADaySpan) { GetGiftBatches(ADaySpan); StreamWriter sw1 = File.CreateText(FExportFilePath + "donor.csv"); sw1.WriteLine("first_name,last_name,partner_key,email,address,telephone,anonymous,class"); StreamWriter sw2 = File.CreateText(FExportFilePath + "donation.csv"); sw2.WriteLine("donor,recipient,trans_amount,trans_currency,base_amount,admin_gif,admin_ict,admin_other," + "base_currency,intl_amount,intl_currency,date,id,source_ledger,recipient_field,anonymous,comment1,for1,comment2,for2,comment3,for3"); foreach (BatchKey Batch in GiftBatches) { String GiftBatchQuery = "SELECT " + "PUB_a_gift.p_donor_key_n AS DonorKey, " + "PUB_a_gift_detail.p_recipient_key_n AS RecipientKey, " + "PUB_a_gift_detail.a_gift_transaction_amount_n AS TransactionAmount, " + "PUB_a_gift_batch.a_currency_code_c AS CurrencyCode, " + "PUB_a_gift_detail.a_gift_amount_n AS GiftAmount, " + "PUB_a_ledger.a_base_currency_c AS BaseCurrency, " + "PUB_a_gift_detail.a_gift_amount_intl_n AS IntlAmount, " + "PUB_a_gift_detail.a_cost_centre_code_c AS CostCentre, " + "PUB_a_ledger.a_intl_currency_c AS IntlCurrency, " + "PUB_a_gift_batch.a_gl_effective_date_d AS EffectiveDate, " + "PUB_a_gift_batch.a_batch_number_i AS BatchNumber, " + "PUB_a_gift.a_gift_transaction_number_i AS TransactionNumber, " + "PUB_a_gift_detail.a_detail_number_i AS DetailNumber, " + "PUB_a_gift_detail.a_confidential_gift_flag_l AS Confidential, " + "PUB_a_gift_detail.a_gift_comment_one_c AS CommentOne, " + "PUB_a_gift_detail.a_comment_one_type_c AS CommentOneType, " + "PUB_a_gift_detail.a_gift_comment_two_c AS CommentTwo, " + "PUB_a_gift_detail.a_comment_two_type_c AS CommentTwoType, " + "PUB_a_gift_detail.a_gift_comment_three_c AS CommentThree, " + "PUB_a_gift_detail.a_comment_three_type_c AS CommentThreeType " + "FROM PUB_a_gift_batch " + "LEFT JOIN PUB_a_gift ON PUB_a_gift_batch.a_batch_number_i = PUB_a_gift.a_batch_number_i AND PUB_a_gift_batch.a_ledger_number_i = PUB_a_gift.a_ledger_number_i " + "LEFT JOIN PUB_a_gift_detail on PUB_a_gift_detail.a_ledger_number_i = PUB_a_gift.a_ledger_number_i AND PUB_a_gift_detail.a_batch_number_i = PUB_a_gift.a_batch_number_i AND PUB_a_gift_detail.a_gift_transaction_number_i = PUB_a_gift.a_gift_transaction_number_i " + "LEFT JOIN PUB_a_motivation_detail ON PUB_a_motivation_detail.a_ledger_number_i = PUB_a_gift_detail.a_ledger_number_i AND PUB_a_motivation_detail.a_motivation_group_code_c = PUB_a_gift_detail.a_motivation_group_code_c AND PUB_a_motivation_detail.a_motivation_detail_code_c = PUB_a_gift_detail.a_motivation_detail_code_c " + "LEFT JOIN PUB_p_partner on PUB_a_gift.p_donor_key_n = PUB_p_partner.p_partner_key_n " + "LEFT JOIN PUB_a_ledger on PUB_a_gift_batch.a_ledger_number_i = PUB_a_ledger.a_ledger_number_i " + "WHERE PUB_a_gift_batch.a_ledger_number_i = " + Batch.LedgerNumber + " " + "AND PUB_a_gift_batch.a_batch_number_i = " + Batch.BatchNumber + " " + "AND PUB_a_motivation_detail.a_export_to_intranet_l = true " + "ORDER BY PUB_a_gift.p_donor_key_n"; DataSet GiftBatchDS = DBAccess.GDBAccessObj.Select(GiftBatchQuery, "GiftBatchTbl", FTransaction); foreach (DataRow Row in GiftBatchDS.Tables["GiftBatchTbl"].Rows) { Int32 RecipientKey = Convert.ToInt32(Row["RecipientKey"]); Int32 RecipientFund = Batch.LedgerNumber; // If no RecipientKey was specified, I need to get one: if (RecipientKey == 0) { // If the Gift is on a foreign ledger, // then RecipientKey is the PartnerKey of that ledger ACostCentreTable CostCentreTbl = ACostCentreAccess.LoadByPrimaryKey(Batch.LedgerNumber, Row["CostCentre"].ToString(), FTransaction); if ((CostCentreTbl.Rows.Count == 1) && (CostCentreTbl[0].CostCentreType == "Foreign")) { AValidLedgerNumberTable ValidLedgerNumberTbl = AValidLedgerNumberAccess.LoadViaACostCentre(Batch.LedgerNumber, Row["CostCentre"].ToString(), FTransaction); if (ValidLedgerNumberTbl.Rows.Count == 1) { RecipientKey = Convert.ToInt32(ValidLedgerNumberTbl[0].PartnerKey); RecipientFund = RecipientKey; } } } // Otherwise, I can derive a RecipientKey from the Ledger Number. if (RecipientKey == 0) { RecipientKey = Batch.LedgerNumber * 1000000; RecipientFund = RecipientKey; } GetDonor(Convert.ToInt32(Row["DonorKey"])); // This adds the Donor to my list if it's not already present. GetRecipient(RecipientKey); // This adds the recipient to my list if it's not already present. decimal GIFFee; decimal ICTFee; decimal OtherFee; GetAdminFees(Batch.LedgerNumber, Convert.ToInt32(Row["BatchNumber"]), Convert.ToInt32(Row["TransactionNumber"]), Convert.ToInt32(Row["DetailNumber"]), out GIFFee, out ICTFee, out OtherFee); sw2.WriteLine(String.Format( "{0:D10},{1:D10},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},\"{12},{13},{14},{15}\",{16:D10},{17:D10},{18},\"{19}\",\"{20}\",\"{21}\",\"{22}\",\"{23}\",\"{24}\"", Row["DonorKey"], // 0 RecipientKey, // 1 Row["TransactionAmount"], // 2 Row["CurrencyCode"], // 3 Row["GiftAmount"], // 4 GIFFee, // 5 ICTFee, // 6 OtherFee, // 7 Row["BaseCurrency"], // 8 Row["IntlAmount"], // 9 Row["IntlCurrency"], // 10 PutDate(Row["EffectiveDate"]), // 11 Batch.LedgerNumber, // 12 Row["BatchNumber"], // 13 Row["TransactionNumber"], // 14 Row["DetailNumber"], // 15 Batch.LedgerNumber * 1000000, // 16 RecipientFund, // 17 Row["Confidential"], // 18 Row["CommentOne"], // 19 Row["CommentOneType"], // 20 Row["CommentTwo"], // 21 Row["CommentTwoType"], // 22 Row["CommentThree"], // 23 Row["CommentThreeType"] // 24 )); } } foreach (Int64 PartnerKey in DonorList.Keys) { PartnerDetails Row = DonorList[PartnerKey]; sw1.WriteLine(String.Format("\"{0}\",\"{1}\",{2:D10},\"{3}\",\"{4}\",{5},{6},{7}", Row.FirstName, Row.LastName, PartnerKey, Row.Email, Row.Address, Row.Telephone, Row.Anonymous ? "true" : "false", Row.Class)); } sw1.Close(); sw2.Close(); StreamWriter sw3 = File.CreateText(FExportFilePath + "recipient.csv"); sw3.WriteLine("recipient,first_name,last_name,email,class"); foreach (Int64 PartnerKey in RecipientList.Keys) { PartnerDetails Row = RecipientList[PartnerKey]; sw3.WriteLine(String.Format("{0},\"{1}\",\"{2}\",\"{3}\",{4}", PartnerKey, Row.FirstName, Row.LastName, Row.Email, Row.Class)); } sw3.Close(); return(true); }
private void CalculateAccountInfo() { FaccountInfo = new TAccountInfo(FledgerInfo); bool blnIncomeFound = false; bool blnExpenseFound = false; String strIncomeAccount = TAccountTypeEnum.Income.ToString(); String strExpenseAccount = TAccountTypeEnum.Expense.ToString(); FaccountInfo.Reset(); FAccountList = new List <String>(); while (FaccountInfo.MoveNext()) { if (FaccountInfo.PostingStatus) { if (FaccountInfo.AccountType == strIncomeAccount) { FAccountList.Add(FaccountInfo.AccountCode); blnIncomeFound = true; } if (FaccountInfo.AccountType == strExpenseAccount) { FAccountList.Add(FaccountInfo.AccountCode); blnExpenseFound = true; } } } if (!blnIncomeFound) { TVerificationResult tvt = new TVerificationResult(Catalog.GetString("No Income Account found"), Catalog.GetString("At least one income account is required."), "", TPeriodEndErrorAndStatusCodes.PEEC_09.ToString(), TResultSeverity.Resv_Critical); FverificationResults.Add(tvt); FHasCriticalErrors = true; } if (!blnExpenseFound) { TVerificationResult tvt = new TVerificationResult(Catalog.GetString("No Expense Account found"), Catalog.GetString("At least one expense account is required."), "", TPeriodEndErrorAndStatusCodes.PEEC_10.ToString(), TResultSeverity.Resv_Critical); FverificationResults.Add(tvt); FHasCriticalErrors = true; } FaccountInfo.SetSpecialAccountCode(TAccountPropertyEnum.ICH_ACCT); if (FaccountInfo.IsValid) { FAccountList.Add(FaccountInfo.AccountCode); } else { TVerificationResult tvt = new TVerificationResult(Catalog.GetString("No ICH_ACCT Account defined"), Catalog.GetString("An ICH Account must be defined."), "", TPeriodEndErrorAndStatusCodes.PEEC_11.ToString(), TResultSeverity.Resv_Critical); FverificationResults.Add(tvt); FHasCriticalErrors = true; } TDBTransaction Transaction = null; DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { FCostCentreTbl = ACostCentreAccess.LoadViaALedger(FledgerInfo.LedgerNumber, Transaction); }); FCostCentreTbl.DefaultView.Sort = ACostCentreTable.GetCostCentreCodeDBName(); }