/// Returns true if it seems to be OK. private Boolean CloseRevaluationAccountingBatch(out Int32 glBatchNumber) { Boolean blnReturnValue = false; glBatchNumber = -1; if (F_GLDataset != null) { F_batch.BatchCreditTotal = F_journal.JournalCreditTotal; F_batch.BatchDebitTotal = F_journal.JournalDebitTotal; TVerificationResultCollection AVerifications; blnReturnValue = (TGLTransactionWebConnector.SaveGLBatchTDS( ref F_GLDataset, out AVerifications) == TSubmitChangesResult.scrOK); if (!blnReturnValue) { return(false); } F_GLDataset.AcceptChanges(); blnReturnValue = (TGLTransactionWebConnector.PostGLBatch( F_batch.LedgerNumber, F_batch.BatchNumber, out AVerifications)); if (blnReturnValue) { glBatchNumber = F_batch.BatchNumber; } } return(blnReturnValue); } // Close Revaluation Accounting Batch
private void CloseRevaluationAccountingBatch() { if (F_GLDataset != null) { F_batch.BatchCreditTotal = F_journal.JournalCreditTotal; F_batch.BatchDebitTotal = F_journal.JournalDebitTotal; TVerificationResultCollection AVerifications; bool blnReturnValue = (TGLTransactionWebConnector.SaveGLBatchTDS( ref F_GLDataset, out AVerifications) == TSubmitChangesResult.scrOK); F_GLDataset.AcceptChanges(); if (blnReturnValue) { //blnVerificationCollectionContainsData = true; } blnReturnValue = (TGLTransactionWebConnector.PostGLBatch( F_batch.LedgerNumber, F_batch.BatchNumber, out AVerifications)); } }
/// <summary> /// Posts a batch /// </summary> /// <param name="ACurrentBatchRow">The data row corresponding to the batch to post</param> /// <param name="AEffectiveDate">The effective date for the batch</param> /// <param name="AStartDateCurrentPeriod">The earliest postable date</param> /// <param name="AEndDateLastForwardingPeriod">The latest postable date</param> /// <returns> /// True if the batch was successfully posted /// </returns> public bool PostBatch(ABatchRow ACurrentBatchRow, DateTime AEffectiveDate, DateTime AStartDateCurrentPeriod, DateTime AEndDateLastForwardingPeriod) { if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)) { return(false); } int CurrentBatchNumber = ACurrentBatchRow.BatchNumber; //Make sure that all control data is in dataset FMyForm.GetLatestControlData(); if (FPetraUtilsObject.HasChanges) { //Keep this conditional check separate so that it only gets called when necessary // and doesn't result in the executon of the next else if which calls same method if (!FMyForm.SaveChangesManual(FMyForm.FCurrentGLBatchAction)) { return(false); } } //This has to be called here as if there are no changes then the DataSavingValidating method // which calls the method below, will not run. else if (!FMyForm.GetTransactionsControl().AllowInactiveFieldValues(FLedgerNumber, CurrentBatchNumber, FMyForm.FCurrentGLBatchAction)) { return(false); } //Load all Batch data FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAndRelatedTables(FLedgerNumber, CurrentBatchNumber)); if (FCacheDS == null) { FCacheDS = TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, false); } if (FAccountTable == null) { SetAccountCostCentreTableVariables(); } if ((AEffectiveDate.Date < AStartDateCurrentPeriod) || (AEffectiveDate.Date > AEndDateLastForwardingPeriod)) { MessageBox.Show(String.Format(Catalog.GetString( "The Date Effective is outside the periods available for posting. Enter a date between {0:d} and {1:d}."), AStartDateCurrentPeriod, AEndDateLastForwardingPeriod)); return(false); } // check that a corportate exchange rate exists FMyForm.WarnAboutMissingIntlExchangeRate = true; if (FMyForm.GetInternationalCurrencyExchangeRate() == 0) { return(false); } if ((MessageBox.Show(String.Format(Catalog.GetString("Are you sure you want to post GL batch {0}?"), CurrentBatchNumber), Catalog.GetString("Question"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) != System.Windows.Forms.DialogResult.Yes)) { return(false); } TVerificationResultCollection Verifications = new TVerificationResultCollection(); try { Cursor.Current = Cursors.WaitCursor; Thread postingThread = new Thread(() => PostGLBatch(CurrentBatchNumber, out Verifications)); postingThread.SetApartmentState(ApartmentState.STA); using (TProgressDialog dialog = new TProgressDialog(postingThread)) { dialog.ShowDialog(); } if (TVerificationHelper.ResultsContainErrorCode(Verifications, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION)) { TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog(); } else if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications)) { TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); StringBuilder errorMessages = new StringBuilder(); int counter = 0; errorMessages.AppendLine(Catalog.GetString("________________________GL Posting Errors________________________")); errorMessages.AppendLine(); foreach (TVerificationResult verif in Verifications) { counter++; errorMessages.AppendLine(counter.ToString("000") + " - " + verif.ResultText); errorMessages.AppendLine(); } extendedMessageBox.ShowDialog(errorMessages.ToString(), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); } else { MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"), Catalog.GetString("Success"), MessageBoxButtons.OK, MessageBoxIcon.Information); } // refresh the grid, to reflect that the batch has been posted (or even maybe had been posted by another user) FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAndRelatedTables(FLedgerNumber, CurrentBatchNumber)); // make sure that the current dataset is clean, // otherwise the next save would try to modify the posted batch, even though no values have been changed FMainDS.AcceptChanges(); // Ensure these tabs will ask the server for updates FMyForm.GetTransactionsControl().ClearCurrentSelection(); FMyForm.GetJournalsControl().ClearCurrentSelection(); FMyUserControl.UpdateDisplay(); } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { Cursor.Current = Cursors.Default; } return(true); }
/// <summary> /// Posts a batch /// </summary> /// <param name="ACurrentBatchRow">The data row corresponding to the batch to post</param> /// <param name="AEffectiveDate">The effective date for the batch</param> /// <param name="AStartDateCurrentPeriod">The earliest postable date</param> /// <param name="AEndDateLastForwardingPeriod">The latest postable date</param> /// <returns>True if the batch was successfully posted</returns> public bool PostBatch(ABatchRow ACurrentBatchRow, DateTime AEffectiveDate, DateTime AStartDateCurrentPeriod, DateTime AEndDateLastForwardingPeriod) { bool RetVal = false; if (!SaveBatchForPosting()) { return(RetVal); } // TODO: display progress of posting TVerificationResultCollection Verifications; int CurrentBatchNumber = ACurrentBatchRow.BatchNumber; if ((AEffectiveDate.Date < AStartDateCurrentPeriod) || (AEffectiveDate.Date > AEndDateLastForwardingPeriod)) { MessageBox.Show(String.Format(Catalog.GetString( "The Date Effective is outside the periods available for posting. Enter a date between {0:d} and {1:d}."), AStartDateCurrentPeriod, AEndDateLastForwardingPeriod)); return(RetVal); } if (MessageBox.Show(String.Format(Catalog.GetString("Are you sure you want to post batch {0}?"), CurrentBatchNumber), Catalog.GetString("Question"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes) { try { Cursor.Current = Cursors.WaitCursor; if (!TRemote.MFinance.GL.WebConnectors.PostGLBatch(FLedgerNumber, CurrentBatchNumber, out Verifications)) { string ErrorMessages = String.Empty; foreach (TVerificationResult verif in Verifications) { ErrorMessages += "[" + verif.ResultContext + "] " + verif.ResultTextCaption + ": " + verif.ResultText + Environment.NewLine; } System.Windows.Forms.MessageBox.Show(ErrorMessages, Catalog.GetString("Posting failed"), MessageBoxButtons.OK, MessageBoxIcon.Error); } else { // I don't need to call this directly, because the server calls it: // TFrmGLBatch.PrintPostingRegister(FLedgerNumber, CurrentBatchNumber); // TODO: print reports on successfully posted batch MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"), Catalog.GetString("Success"), MessageBoxButtons.OK, MessageBoxIcon.Information); // refresh the grid, to reflect that the batch has been posted FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAndContent(FLedgerNumber, CurrentBatchNumber)); // make sure that the current dataset is clean, // otherwise the next save would try to modify the posted batch, even though no values have been changed FMainDS.AcceptChanges(); // Ensure these tabs will ask the server for updates FMyForm.GetJournalsControl().ClearCurrentSelection(); FMyForm.GetTransactionsControl().ClearCurrentSelection(); FMyUserControl.UpdateDisplay(); RetVal = true; } } finally { Cursor.Current = Cursors.Default; } } return(RetVal); }
public static GLBatchTDS LoadATransactionATransAnalAttrib(Int32 ALedgerNumber, Int32 ABatchNumber, Int32 AJournalNumber) { string strAnalAttr = string.Empty; bool newTransaction = false; TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, out newTransaction); GLBatchTDS MainDS = new GLBatchTDS(); ATransactionAccess.LoadViaAJournal(MainDS, ALedgerNumber, ABatchNumber, AJournalNumber, Transaction); ATransAnalAttribAccess.LoadViaAJournal(MainDS, ALedgerNumber, ABatchNumber, AJournalNumber, Transaction); foreach (GLBatchTDSATransactionRow transRow in MainDS.ATransaction.Rows) { MainDS.ATransAnalAttrib.DefaultView.RowFilter = String.Format("{0} = {1}", ATransAnalAttribTable.GetTransactionNumberDBName(), transRow.TransactionNumber); foreach (DataRowView rv in MainDS.ATransAnalAttrib.DefaultView) { ATransAnalAttribRow Row = (ATransAnalAttribRow)rv.Row; if (strAnalAttr.Length > 0) { strAnalAttr += ", "; } strAnalAttr += (Row.AnalysisTypeCode + "=" + Row.AnalysisAttributeValue); } if (transRow.AnalysisAttributes != strAnalAttr) { transRow.AnalysisAttributes = strAnalAttr; } //reset the attributes string strAnalAttr = string.Empty; } MainDS.ATransAnalAttrib.DefaultView.RowFilter = string.Empty; if (newTransaction) { DBAccess.GDBAccessObj.RollbackTransaction(); } MainDS.AcceptChanges(); return MainDS; }
public static void SubmitRecurringGLBatch(Hashtable requestParams) { Boolean NewTransaction = false; GLBatchTDS GLMainDS = new GLBatchTDS(); ABatchRow BatchRow; Int32 ALedgerNumber = (Int32)requestParams["ALedgerNumber"]; Int32 ABatchNumber = (Int32)requestParams["ABatchNumber"]; DateTime AEffectiveDate = (DateTime)requestParams["AEffectiveDate"]; Decimal AExchangeRateToBase = (Decimal)requestParams["AExchangeRateToBase"];; Decimal AExchangeRateIntlToBase = (Decimal)requestParams["AExchangeRateIntlToBase"]; int PeriodNumber, YearNr; bool TransactionInIntlCurrency = false; TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.Serializable, TEnforceIsolationLevel.eilMinimum, out NewTransaction); try { ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction); // make sure that recurring GL batch is fully loaded, including journals, transactions and attributes GLBatchTDS RGLMainDS = LoadARecurringBatchAndContent(ALedgerNumber, ABatchNumber); // Assuming all relevant data is loaded in FMainDS foreach (ARecurringBatchRow recBatch in RGLMainDS.ARecurringBatch.Rows) { if ((recBatch.BatchNumber == ABatchNumber) && (recBatch.LedgerNumber == ALedgerNumber)) { GLMainDS = CreateABatch(ALedgerNumber); BatchRow = (ABatchRow)GLMainDS.ABatch.Rows[0]; BatchRow.DateEffective = AEffectiveDate; BatchRow.BatchDescription = recBatch.BatchDescription; BatchRow.BatchControlTotal = recBatch.BatchControlTotal; BatchRow.BatchRunningTotal = recBatch.BatchRunningTotal; BatchRow.BatchCreditTotal = recBatch.BatchCreditTotal; BatchRow.BatchDebitTotal = recBatch.BatchDebitTotal; if (TFinancialYear.IsValidPostingPeriod(ALedgerNumber, AEffectiveDate, out PeriodNumber, out YearNr, Transaction)) { BatchRow.BatchYear = YearNr; BatchRow.BatchPeriod = PeriodNumber; } foreach (ARecurringJournalRow recJournal in RGLMainDS.ARecurringJournal.Rows) { if ((recJournal.BatchNumber == ABatchNumber) && (recJournal.LedgerNumber == ALedgerNumber)) { // create the journal from recJournal AJournalRow JournalRow = GLMainDS.AJournal.NewRowTyped(); JournalRow.LedgerNumber = BatchRow.LedgerNumber; JournalRow.BatchNumber = BatchRow.BatchNumber; JournalRow.JournalNumber = recJournal.JournalNumber; JournalRow.JournalDescription = recJournal.JournalDescription; JournalRow.SubSystemCode = recJournal.SubSystemCode; JournalRow.TransactionTypeCode = recJournal.TransactionTypeCode; JournalRow.TransactionCurrency = recJournal.TransactionCurrency; JournalRow.JournalCreditTotal = recJournal.JournalCreditTotal; JournalRow.JournalDebitTotal = recJournal.JournalDebitTotal; JournalRow.ExchangeRateToBase = AExchangeRateToBase; JournalRow.DateEffective = AEffectiveDate; JournalRow.JournalPeriod = recJournal.JournalPeriod; GLMainDS.AJournal.Rows.Add(JournalRow); if (JournalRow.JournalNumber > BatchRow.LastJournal) { BatchRow.LastJournal = JournalRow.JournalNumber; } TransactionInIntlCurrency = (JournalRow.TransactionCurrency == LedgerTable[0].IntlCurrency); //TODO (not here, but in the client or while posting) Check for expired key ministry (while // Posting) foreach (ARecurringTransactionRow recTransaction in RGLMainDS.ARecurringTransaction.Rows) { if ((recTransaction.JournalNumber == recJournal.JournalNumber) && (recTransaction.BatchNumber == ABatchNumber) && (recTransaction.LedgerNumber == ALedgerNumber)) { ATransactionRow TransactionRow = GLMainDS.ATransaction.NewRowTyped(); TransactionRow.LedgerNumber = JournalRow.LedgerNumber; TransactionRow.BatchNumber = JournalRow.BatchNumber; TransactionRow.JournalNumber = JournalRow.JournalNumber; TransactionRow.TransactionNumber = recTransaction.TransactionNumber; if (TransactionRow.TransactionNumber > JournalRow.LastTransactionNumber) { JournalRow.LastTransactionNumber = TransactionRow.TransactionNumber; } TransactionRow.Narrative = recTransaction.Narrative; TransactionRow.AccountCode = recTransaction.AccountCode; TransactionRow.CostCentreCode = recTransaction.CostCentreCode; TransactionRow.TransactionAmount = recTransaction.TransactionAmount; TransactionRow.AmountInBaseCurrency = GLRoutines.Divide(recTransaction.TransactionAmount, AExchangeRateToBase); if (!TransactionInIntlCurrency) { TransactionRow.AmountInIntlCurrency = GLRoutines.Divide((decimal)TransactionRow.AmountInBaseCurrency, AExchangeRateIntlToBase); } else { TransactionRow.AmountInIntlCurrency = TransactionRow.TransactionAmount; } TransactionRow.TransactionDate = AEffectiveDate; TransactionRow.DebitCreditIndicator = recTransaction.DebitCreditIndicator; TransactionRow.HeaderNumber = recTransaction.HeaderNumber; TransactionRow.DetailNumber = recTransaction.DetailNumber; TransactionRow.SubType = recTransaction.SubType; TransactionRow.Reference = recTransaction.Reference; GLMainDS.ATransaction.Rows.Add(TransactionRow); foreach (ARecurringTransAnalAttribRow recAnalAttrib in RGLMainDS.ARecurringTransAnalAttrib.Rows) { if ((recAnalAttrib.TransactionNumber == recTransaction.TransactionNumber) && (recTransaction.JournalNumber == recJournal.JournalNumber) && (recTransaction.BatchNumber == ABatchNumber) && (recTransaction.LedgerNumber == ALedgerNumber)) { ATransAnalAttribRow TransAnalAttribRow = GLMainDS.ATransAnalAttrib.NewRowTyped(); TransAnalAttribRow.LedgerNumber = JournalRow.LedgerNumber; TransAnalAttribRow.BatchNumber = JournalRow.BatchNumber; TransAnalAttribRow.JournalNumber = JournalRow.JournalNumber; TransAnalAttribRow.TransactionNumber = recTransaction.TransactionNumber; TransAnalAttribRow.AnalysisTypeCode = recAnalAttrib.AnalysisTypeCode; TransAnalAttribRow.AccountCode = recAnalAttrib.AccountCode; TransAnalAttribRow.CostCentreCode = recAnalAttrib.CostCentreCode; TransAnalAttribRow.AnalysisAttributeValue = recAnalAttrib.AnalysisAttributeValue; GLMainDS.ATransAnalAttrib.Rows.Add(TransAnalAttribRow); } } } } } } } } ABatchAccess.SubmitChanges(GLMainDS.ABatch, Transaction); ALedgerAccess.SubmitChanges(LedgerTable, Transaction); AJournalAccess.SubmitChanges(GLMainDS.AJournal, Transaction); ATransactionAccess.SubmitChanges(GLMainDS.ATransaction, Transaction); ATransAnalAttribAccess.SubmitChanges(GLMainDS.ATransAnalAttrib, Transaction); if (NewTransaction) { DBAccess.GDBAccessObj.CommitTransaction(); } GLMainDS.AcceptChanges(); } catch (Exception Exc) { TLogging.Log("An Exception occured during the submission of a Recurring GL Batch:" + Environment.NewLine + Exc.ToString()); if (NewTransaction) { DBAccess.GDBAccessObj.RollbackTransaction(); } throw new EOPAppException("Error in SubmitRecurringGLBatch", Exc); } }
/// <summary> /// this supports the transaction export files from Petra 2.x. /// Lines do NOT start with T for transaction /// </summary> public void ImportTransactions(ABatchRow ACurrentBatchRow, AJournalRow ACurrentJournalRow, TImportDataSourceEnum AImportDataSource) { bool ok = false; bool RefreshGUIAfterImport = false; OpenFileDialog dialog = null; if (FPetraUtilsObject.HasChanges && !FMyForm.SaveChanges()) { // saving failed, therefore do not try to import MessageBox.Show(Catalog.GetString("Please save your changes before Importing new transactions"), Catalog.GetString( "Import GL Transactions"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((ACurrentBatchRow == null) || (ACurrentJournalRow == null) || (ACurrentJournalRow.JournalStatus != MFinanceConstants.BATCH_UNPOSTED)) { MessageBox.Show(Catalog.GetString("Please select an unposted journal to import transactions."), Catalog.GetString("Import GL Transactions")); return; } if (ACurrentJournalRow.LastTransactionNumber > 0) { if (MessageBox.Show(Catalog.GetString( "The current journal already contains some transactions. Do you really want to add more transactions to this journal?"), Catalog.GetString("Import GL Transactions"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No) { return; } } bool datesMayBeIntegers = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false); FdlgSeparator = new TDlgSelectCSVSeparator(false); FdlgSeparator.DateMayBeInteger = datesMayBeIntegers; if (AImportDataSource == TImportDataSourceEnum.FromClipboard) { string importString = Clipboard.GetText(TextDataFormat.UnicodeText); if ((importString == null) || (importString.Length == 0)) { MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"), Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } FdlgSeparator.CSVData = importString; } else if (AImportDataSource == TImportDataSourceEnum.FromFile) { dialog = new OpenFileDialog(); string exportPath = TClientSettings.GetExportPath(); string fullPath = TUserDefaults.GetStringDefault("Imp Filename", exportPath + Path.DirectorySeparatorChar + "import.csv"); TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath); dialog.Title = Catalog.GetString("Import Transactions from CSV File"); dialog.Filter = Catalog.GetString("GL Transactions files (*.csv)|*.csv|Text Files (*.txt)|*.txt"); // This call fixes Windows7 Open File Dialogs. It must be the line before ShowDialog() TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath)); if (dialog.ShowDialog() == DialogResult.OK) { Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Transaction Import"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } } else { return; } } else { // unknown source!! return; } String impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator.DateFormat = dateFormatString; FdlgSeparator.NumberFormat = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN; FdlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(FdlgSeparator.FileContent) ?? ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";"); if (FdlgSeparator.ShowDialog() == DialogResult.OK) { Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", FLedgerNumber); requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator); requestParams.Add("DateFormatString", FdlgSeparator.DateFormat); requestParams.Add("DatesMayBeIntegers", datesMayBeIntegers); requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat); requestParams.Add("NewLine", Environment.NewLine); requestParams.Add("LastTransactionNumber", ACurrentJournalRow.LastTransactionNumber); TVerificationResultCollection AMessages = new TVerificationResultCollection(); Thread ImportThread = new Thread(() => ImportGLTransactions(requestParams, FdlgSeparator.FileContent, ACurrentBatchRow.BatchNumber, ACurrentJournalRow.JournalNumber, out AMessages, out ok, out RefreshGUIAfterImport)); using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread)) { ImportDialog.ShowDialog(); } ShowMessages(AMessages); } // It is important to save user defaults here, even if there were errors // because in that case the user will want to import the same file again after fixing it. SaveUserDefaults(dialog); if (ok || RefreshGUIAfterImport) { if (ok) { MessageBox.Show(Catalog.GetString("Your data was imported successfully!"), Catalog.GetString("Transactions Import"), MessageBoxButtons.OK, MessageBoxIcon.Information); } // Update the client side with new information from the server FMyForm.Cursor = Cursors.WaitCursor; FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAJournal(FLedgerNumber, ACurrentBatchRow.BatchNumber)); FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransactionAndRelatedTablesForJournal(FLedgerNumber, ACurrentBatchRow.BatchNumber, ACurrentJournalRow.JournalNumber)); FMainDS.AcceptChanges(); FMyForm.Cursor = Cursors.Default; FMyForm.GetTransactionsControl().SelectRow(1); } }
/// <summary> /// Posts a batch /// </summary> /// <param name="ACurrentBatchRow">The data row corresponding to the batch to post</param> /// <param name="AEffectiveDate">The effective date for the batch</param> /// <param name="AStartDateCurrentPeriod">The earliest postable date</param> /// <param name="AEndDateLastForwardingPeriod">The latest postable date</param> /// <param name="AInactiveValuesWarningOnGLPosting">Warn of inactive values</param> /// <returns> /// True if the batch was successfully posted /// </returns> public bool PostBatch(ABatchRow ACurrentBatchRow, DateTime AEffectiveDate, DateTime AStartDateCurrentPeriod, DateTime AEndDateLastForwardingPeriod, bool AInactiveValuesWarningOnGLPosting = true) { bool RetVal = false; if (!SaveBatchForPosting()) { return(RetVal); } //Load all Batch data FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAndContent(FLedgerNumber, ACurrentBatchRow.BatchNumber)); if (FCacheDS == null) { FCacheDS = TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, false); } if (FAccountTable == null) { SetAccountCostCentreTableVariables(); } //Check for inactive values int NumInactiveValues = 0; if (AInactiveValuesWarningOnGLPosting && !AllowInactiveFieldValues(ACurrentBatchRow.BatchNumber, out NumInactiveValues)) { return(RetVal); } bool PostWithInactiveValues = (NumInactiveValues > 0); // TODO: display progress of posting TVerificationResultCollection Verifications; int CurrentBatchNumber = ACurrentBatchRow.BatchNumber; if ((AEffectiveDate.Date < AStartDateCurrentPeriod) || (AEffectiveDate.Date > AEndDateLastForwardingPeriod)) { MessageBox.Show(String.Format(Catalog.GetString( "The Date Effective is outside the periods available for posting. Enter a date between {0:d} and {1:d}."), AStartDateCurrentPeriod, AEndDateLastForwardingPeriod)); return(RetVal); } // check that a corportate exchange rate exists FMyForm.WarnAboutMissingIntlExchangeRate = true; if (FMyForm.GetInternationalCurrencyExchangeRate() == 0) { return(false); } if (PostWithInactiveValues || (MessageBox.Show(String.Format(Catalog.GetString("Are you sure you want to post GL batch {0}?"), CurrentBatchNumber), Catalog.GetString("Question"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes)) { try { Cursor.Current = Cursors.WaitCursor; if (!TRemote.MFinance.GL.WebConnectors.PostGLBatch(FLedgerNumber, CurrentBatchNumber, out Verifications)) { string ErrorMessages = String.Empty; foreach (TVerificationResult verif in Verifications) { ErrorMessages += "[" + verif.ResultContext + "] " + verif.ResultTextCaption + ": " + verif.ResultText + Environment.NewLine; } System.Windows.Forms.MessageBox.Show(ErrorMessages, Catalog.GetString("Posting failed"), MessageBoxButtons.OK, MessageBoxIcon.Error); } else { //I don't need to call this directly, because the server calls it: //TFrmGLBatch.PrintPostingRegister(FLedgerNumber, CurrentBatchNumber); // TODO: print reports on successfully posted batch MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"), Catalog.GetString("Success"), MessageBoxButtons.OK, MessageBoxIcon.Information); // refresh the grid, to reflect that the batch has been posted FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAndContent(FLedgerNumber, CurrentBatchNumber)); // make sure that the current dataset is clean, // otherwise the next save would try to modify the posted batch, even though no values have been changed FMainDS.AcceptChanges(); // Ensure these tabs will ask the server for updates FMyForm.GetJournalsControl().ClearCurrentSelection(); FMyForm.GetTransactionsControl().ClearCurrentSelection(); FMyUserControl.UpdateDisplay(); RetVal = true; } } catch (Exception ex) { string msg = (String.Format(Catalog.GetString("Unexpected error occurred during the posting of GL Batch {0}!{1}{1}{2}{1}{1}{3}"), CurrentBatchNumber, Environment.NewLine, ex.Message, ex.InnerException != null?ex.InnerException.Message:String.Empty)); TLogging.LogException(ex, Utilities.GetMethodSignature()); MessageBox.Show(msg, "Post GL Batch Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { Cursor.Current = Cursors.Default; } } return(RetVal); }
public static GLBatchTDS LoadALedgerTable(Int32 ALedgerNumber) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } #endregion Validate Arguments GLBatchTDS MainDS = new GLBatchTDS(); TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); #region Validate Data if ((MainDS.ALedger == null) || (MainDS.ALedger.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } #endregion Validate Data }); // Remove all Tables that were not filled with data before remoting them. MainDS.RemoveEmptyTables(); MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
public static GLBatchTDS LoadABatch(Int32 ALedgerNumber, int AYear, int APeriod) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } #endregion Validate Arguments GLBatchTDS MainDS = new GLBatchTDS(); TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); #region Validate Data if ((MainDS.ALedger == null) || (MainDS.ALedger.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format( Catalog.GetString("Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } #endregion Validate Data string FilterByPeriod = string.Empty; if (AYear > -1) { FilterByPeriod = String.Format(" AND PUB_{0}.{1} = {2}", ABatchTable.GetTableDBName(), ABatchTable.GetBatchYearDBName(), AYear); if ((APeriod == 0) && (AYear == MainDS.ALedger[0].CurrentFinancialYear)) { //Return current and forwarding periods FilterByPeriod += String.Format(" AND PUB_{0}.{1} >= {2}", ABatchTable.GetTableDBName(), ABatchTable.GetBatchPeriodDBName(), MainDS.ALedger[0].CurrentPeriod); } else if (APeriod > 0) { //Return only specified period FilterByPeriod += String.Format(" AND PUB_{0}.{1} = {2}", ABatchTable.GetTableDBName(), ABatchTable.GetBatchPeriodDBName(), APeriod); } //else //{ // //Nothing to add, returns all periods //} } string SelectClause = String.Format("SELECT * FROM PUB_{0} WHERE {1} = {2}", ABatchTable.GetTableDBName(), ABatchTable.GetLedgerNumberDBName(), ALedgerNumber); DBAccess.GDBAccessObj.Select(MainDS, SelectClause + FilterByPeriod, MainDS.ABatch.TableName, Transaction); }); MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
/// <summary> /// create a new recurring batch. /// it is already stored to the database, to avoid problems with LastBatchNumber /// </summary> public static GLBatchTDS CreateARecurringBatch(Int32 ALedgerNumber) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } #endregion Validate Arguments GLBatchTDS MainDS = new GLBatchTDS(); GLBatchTDS TempDS = new GLBatchTDS(); TDBTransaction Transaction = null; bool SubmissionOK = false; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, TEnforceIsolationLevel.eilMinimum, ref Transaction, ref SubmissionOK, delegate { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); #region Validate Data if ((MainDS.ALedger == null) || (MainDS.ALedger.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } #endregion Validate Data ARecurringBatchAccess.LoadViaALedger(TempDS, ALedgerNumber, Transaction); DataView RecurringBatchDV = new DataView(TempDS.ARecurringBatch); RecurringBatchDV.RowFilter = string.Empty; RecurringBatchDV.Sort = string.Format("{0} DESC", ARecurringBatchTable.GetBatchNumberDBName()); //Recurring batch numbers can be reused so check each time for current highest number if (RecurringBatchDV.Count > 0) { MainDS.ALedger[0].LastRecurringBatchNumber = (int)(RecurringBatchDV[0][ARecurringBatchTable.GetBatchNumberDBName()]); } else { MainDS.ALedger[0].LastRecurringBatchNumber = 0; } ARecurringBatchRow NewRow = MainDS.ARecurringBatch.NewRowTyped(true); NewRow.LedgerNumber = ALedgerNumber; NewRow.BatchNumber = ++MainDS.ALedger[0].LastRecurringBatchNumber; MainDS.ARecurringBatch.Rows.Add(NewRow); //Empty the TempDS TempDS.RejectChanges(); //Submit changes to MainDS GLBatchTDSAccess.SubmitChanges(MainDS); SubmissionOK = true; }); MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
/// <summary> /// create a new batch. /// it is already stored to the database, to avoid problems with LastBatchNumber /// </summary> /// <param name="ALedgerNumber"></param> /// <param name="ABatchDescription"></param> /// <param name="ABatchControlTotal"></param> /// <param name="ADateEffective"></param> /// <returns></returns> public static GLBatchTDS CreateABatch( Int32 ALedgerNumber, string ABatchDescription, decimal ABatchControlTotal, DateTime ADateEffective) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } #endregion Validate Arguments GLBatchTDS MainDS = new GLBatchTDS(); TDBTransaction Transaction = null; bool SubmissionOK = false; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, TEnforceIsolationLevel.eilMinimum, ref Transaction, ref SubmissionOK, delegate { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); #region Validate Data if ((MainDS.ALedger == null) || (MainDS.ALedger.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } #endregion Validate Data ABatchRow NewRow = MainDS.ABatch.NewRowTyped(true); NewRow.LedgerNumber = ALedgerNumber; MainDS.ALedger[0].LastBatchNumber++; NewRow.BatchNumber = MainDS.ALedger[0].LastBatchNumber; NewRow.BatchPeriod = MainDS.ALedger[0].CurrentPeriod; NewRow.BatchYear = MainDS.ALedger[0].CurrentFinancialYear; int FinancialYear, FinancialPeriod; if (ADateEffective != default(DateTime)) { TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber, ref ADateEffective, out FinancialYear, out FinancialPeriod, Transaction, false); NewRow.DateEffective = ADateEffective; NewRow.BatchPeriod = FinancialPeriod; NewRow.BatchYear = FinancialYear; } NewRow.BatchDescription = ABatchDescription; NewRow.BatchControlTotal = ABatchControlTotal; MainDS.ABatch.Rows.Add(NewRow); GLBatchTDSAccess.SubmitChanges(MainDS); SubmissionOK = true; }); MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
} // Import GL Batches /// <summary> /// Wrapper for importing GL Transactions. Called from client side /// </summary> /// <param name="ARequestParams"></param> /// <param name="AImportString"></param> /// <param name="ALedgerNumber"></param> /// <param name="ABatchNumber"></param> /// <param name="AJournalNumber"></param> /// <param name="AMessages"></param> /// <returns></returns> public bool ImportGLTransactions( Hashtable ARequestParams, String AImportString, Int32 ALedgerNumber, Int32 ABatchNumber, Int32 AJournalNumber, out TVerificationResultCollection AMessages) { string ImportMessage = Catalog.GetString("Initialising"); TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(), Catalog.GetString("Importing GL Batches"), 100); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Initialising"), 5); TVerificationResultCollection Messages = new TVerificationResultCollection(); // fix for Mono issue with out parameter: https://bugzilla.xamarin.com/show_bug.cgi?id=28196 AMessages = Messages; GLSetupTDS SetupDS = new GLSetupTDS(); SetupDS.CaseSensitive = true; StringReader sr = new StringReader(AImportString); FDelimiter = (String)ARequestParams["Delimiter"]; Int32 LedgerNumber = (Int32)ARequestParams["ALedgerNumber"]; FDateFormatString = (String)ARequestParams["DateFormatString"]; String NumberFormat = (String)ARequestParams["NumberFormat"]; FNewLine = (String)ARequestParams["NewLine"]; FCultureInfoNumberFormat = new CultureInfo(NumberFormat.Equals("American") ? "en-US" : "de-DE"); FCultureInfoDate = new CultureInfo("en-GB"); FCultureInfoDate.DateTimeFormat.ShortDatePattern = FDateFormatString; TDBTransaction Transaction = null; Int32 RowNumber = 0; Int32 InitialTextLength = AImportString.Length; Int32 TextProcessedLength = 0; Int32 PercentDone = 10; Int32 PreviousPercentDone = 0; bool submissionOK = false; Boolean CancelledByUser = false; // Create some validation dictionaries TValidationControlsDict ValidationControlsDictTransaction = new TValidationControlsDict(); try { // This needs to be initialised because we will be calling the method TSharedFinanceValidationHelper.GetValidPostingDateRangeDelegate = @TFinanceServerLookups.GetCurrentPostingRangeDates; TSharedFinanceValidationHelper.GetValidPeriodDatesDelegate = @TAccountingPeriodsWebConnector.GetPeriodDates; DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref submissionOK, delegate { // Construct our DataSet - we use all the journals for the batch so we can update the batch totals. GLBatchTDS MainDS = new GLBatchTDS(); ABatchTable BatchTable = ABatchAccess.LoadByPrimaryKey(ALedgerNumber, ABatchNumber, Transaction); MainDS.ABatch.Merge(BatchTable); AJournalTable JournalTable = AJournalAccess.LoadViaABatch(ALedgerNumber, ABatchNumber, Transaction); MainDS.AJournal.Merge(JournalTable); ATransactionTable TransactionTable = ATransactionAccess.LoadViaABatch(ALedgerNumber, ABatchNumber, Transaction); MainDS.ATransaction.Merge(TransactionTable); ATransAnalAttribTable TransAnalAttributeTable = ATransAnalAttribAccess.LoadViaAJournal(ALedgerNumber, ABatchNumber, AJournalNumber, Transaction); MainDS.ATransAnalAttrib.Merge(TransAnalAttributeTable); MainDS.AcceptChanges(); ABatchRow NewBatchRow = (ABatchRow)MainDS.ABatch.Rows.Find(new object[] { ALedgerNumber, ABatchNumber }); AJournalRow NewJournalRow = (AJournalRow)MainDS.AJournal.Rows.Find(new object[] { ALedgerNumber, ABatchNumber, AJournalNumber }); // Load supplementary tables that we are going to need for validation ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction); AAnalysisTypeAccess.LoadViaALedger(SetupDS, LedgerNumber, Transaction); AFreeformAnalysisAccess.LoadViaALedger(SetupDS, LedgerNumber, Transaction); AAnalysisAttributeAccess.LoadViaALedger(SetupDS, LedgerNumber, Transaction); ACostCentreAccess.LoadViaALedger(SetupDS, LedgerNumber, Transaction); AAccountAccess.LoadViaALedger(SetupDS, LedgerNumber, Transaction); ALedgerInitFlagAccess.LoadViaALedger(SetupDS, LedgerNumber, Transaction); DateTime firstDayOfMonth; decimal intlRateFromBase = -1.0m; if (LedgerTable.Rows.Count > 0) { string intlCurrency = LedgerTable[0].IntlCurrency; string baseCurrency = LedgerTable[0].BaseCurrency; if (TSharedFinanceValidationHelper.GetFirstDayOfAccountingPeriod(LedgerNumber, NewJournalRow.DateEffective, out firstDayOfMonth)) { intlRateFromBase = TExchangeRateTools.GetCorporateExchangeRate(baseCurrency, intlCurrency, firstDayOfMonth, NewJournalRow.DateEffective); } if (intlRateFromBase <= 0.0m) { Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, 1), String.Format( "There is no Corporate Exchange Rate for {0} to {1} applicable to the period {2} to {3}. Please set up an appropriate rate and then import the data again.", baseCurrency, intlCurrency, StringHelper.DateToLocalizedString(firstDayOfMonth), StringHelper.DateToLocalizedString(NewJournalRow.DateEffective)), TResultSeverity.Resv_Critical)); } } ImportMessage = Catalog.GetString("Parsing first line"); // Go round a loop reading the file line by line FImportLine = sr.ReadLine(); while (FImportLine != null) { RowNumber++; TextProcessedLength += (FImportLine.Length + FNewLine.Length); PercentDone = 10 + ((TextProcessedLength * 90) / InitialTextLength); // skip empty lines and commented lines if ((FImportLine.Trim().Length > 0) && !FImportLine.StartsWith("/*") && !FImportLine.StartsWith("#")) { int numberOfElements = StringHelper.GetCSVList(FImportLine, FDelimiter).Count + 1; if (numberOfElements < 8) { Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, RowNumber), Catalog.GetString("Wrong number of transaction columns. Expected at least 8 columns."), TResultSeverity.Resv_Critical)); FImportLine = sr.ReadLine(); if (FImportLine != null) { TextProcessedLength += (FImportLine.Length + FNewLine.Length); } continue; } ImportGLTransactionsInner(LedgerNumber, RowNumber, ref MainDS, ref SetupDS, ref NewBatchRow, ref NewJournalRow, intlRateFromBase, ref Transaction, ref ImportMessage, ref Messages, ref ValidationControlsDictTransaction); } // if the CSV line qualifies if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true) { CancelledByUser = true; break; } if (Messages.Count > 100) { // This probably means that it is a big file and the user has made the same mistake many times over break; } // Update progress tracker every few percent if ((PercentDone - PreviousPercentDone) > 3) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), String.Format(Catalog.GetString("Importing row {0}"), RowNumber), (PercentDone > 98) ? 98 : PercentDone); PreviousPercentDone = PercentDone; } // Read the next line FImportLine = sr.ReadLine(); if (FImportLine != null) { TextProcessedLength += (FImportLine.Length + FNewLine.Length); } } // while CSV lines if (CancelledByUser) { Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, String.Format(Catalog.GetString("{0} messages reported."), Messages.Count), TResultSeverity.Resv_Info)); Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, "The import was cancelled by the user.", TResultSeverity.Resv_Info)); return; } // Finished reading the file - did we have critical errors? if (!TVerificationHelper.IsNullOrOnlyNonCritical(Messages)) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Batch has critical errors"), 0); if (FImportLine == null) { // We did reach the end of the file Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, Catalog.GetString( "Reached the end of file but errors occurred. When these errors are fixed the batch will import successfully."), TResultSeverity.Resv_Info)); } else { // We gave up before the end Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation, Catalog.GetString( "Stopped reading the file after generating more than 100 messages. The file may contian more errors beyond the ones listed here."), TResultSeverity.Resv_Info)); } // Do finally actions and then return false return; } // Everything is ok, so we can do our finish actions //Finally submit all our changes ImportMessage = Catalog.GetString("Saving transactions"); ATransactionAccess.SubmitChanges(MainDS.ATransaction, Transaction); MainDS.ATransaction.AcceptChanges(); ImportMessage = Catalog.GetString("Saving analysis attributes"); ATransAnalAttribAccess.SubmitChanges(MainDS.ATransAnalAttrib, Transaction); MainDS.ATransAnalAttrib.AcceptChanges(); // update the totals of the batch that has just been imported ImportMessage = Catalog.GetString("Saving changes to totals"); GLRoutines.UpdateBatchTotals(ref MainDS, ref NewBatchRow); ImportMessage = Catalog.GetString("Saving journal totals"); AJournalAccess.SubmitChanges(MainDS.AJournal, Transaction); MainDS.AJournal.AcceptChanges(); ImportMessage = Catalog.GetString("Saving batch totals"); ABatchAccess.SubmitChanges(MainDS.ABatch, Transaction); MainDS.ABatch.AcceptChanges(); // Now we are done!!! submissionOK = true; }); // Begin Auto Transaction } // try catch (Exception ex) { // Parse the exception text for possible references to database foreign keys // Make the message more friendly in that case String friendlyExceptionText = MakeFriendlyFKExceptions(ex, "T"); if (RowNumber > 0) { // At least we made a start string msg = ImportMessage; if (friendlyExceptionText.Length > 0) { msg += FNewLine + friendlyExceptionText; } if (ImportMessage.StartsWith(Catalog.GetString("Saving "))) { // Do not display any specific line number because these errors occur outside the parsing loop Messages.Add(new TVerificationResult(MCommonConstants.StrExceptionWhileSavingTransactions, msg, TResultSeverity.Resv_Critical)); } else { Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrExceptionWhileParsingLine, RowNumber), msg, TResultSeverity.Resv_Critical)); } } else { // We got an exception before we even started parsing the rows (getting a transaction?) Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrExceptionWhileParsingLine, RowNumber), friendlyExceptionText, TResultSeverity.Resv_Critical)); } TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Exception Occurred"), 0); } finally { sr.Close(); if (submissionOK) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Gift batch import successful"), 100); } else { Messages.Add(new TVerificationResult("Import information", Catalog.GetString("None of the data from the import was saved."), TResultSeverity.Resv_Critical)); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Data could not be saved."), 0); } TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); } // end of 'finally' // Set our 'out' parameters AMessages = Messages; return submissionOK; } // Import GL Transactions
private static GLBatchTDS ReduceGLDataSet(ref GLBatchTDS AMainDS, Int32 ALedgerNumber, Int32 ABatchNumber, bool AKeepThisBatchOnly = true) { #region Validate Arguments if (AMainDS == null) { throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString("Function:{0} - The GL Batch dataset is null!"), Utilities.GetMethodName(true))); } else if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } #endregion Validate Arguments GLBatchTDS ReducedDS = new GLBatchTDS(); ReducedDS.Merge(AMainDS); DataView BatchDV = new DataView(ReducedDS.ABatch); DataView JournalDV = new DataView(ReducedDS.AJournal); DataView TransactionDV = new DataView(ReducedDS.ATransaction); DataView AnalysisAttribDV = new DataView(ReducedDS.ATransAnalAttrib); //Recurring DataView RecurringBatchDV = new DataView(ReducedDS.ARecurringBatch); DataView RecurringJournalDV = new DataView(ReducedDS.ARecurringJournal); DataView RecurringTransactionDV = new DataView(ReducedDS.ARecurringTransaction); DataView RecurringAnalysisAttribDV = new DataView(ReducedDS.ARecurringTransAnalAttrib); string CommonRowFilter = StandardRowFilterByLedgerAndBatch(ALedgerNumber, ABatchNumber, !AKeepThisBatchOnly); AnalysisAttribDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in AnalysisAttribDV) { drv.Delete(); } TransactionDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in TransactionDV) { drv.Delete(); } JournalDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in JournalDV) { drv.Delete(); } BatchDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in BatchDV) { drv.Delete(); } //Recurring RecurringAnalysisAttribDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in RecurringAnalysisAttribDV) { drv.Delete(); } RecurringTransactionDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in RecurringTransactionDV) { drv.Delete(); } RecurringJournalDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in RecurringJournalDV) { drv.Delete(); } RecurringBatchDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in RecurringBatchDV) { drv.Delete(); } ReducedDS.AcceptChanges(); return ReducedDS; }
/// <summary> /// create a new batch. /// it is already stored to the database, to avoid problems with LastBatchNumber /// </summary> /// <param name="ALedgerNumber"></param> /// <param name="ABatchDescription"></param> /// <param name="ABatchControlTotal"></param> /// <param name="ADateEffective"></param> /// <returns></returns> public static GLBatchTDS CreateABatch( Int32 ALedgerNumber, string ABatchDescription, decimal ABatchControlTotal, DateTime ADateEffective) { TDBTransaction Transaction = null; bool SubmissionOK = false; GLBatchTDS MainDS = null; //Error handling string ErrorContext = "Create a Batch"; string ErrorMessage = String.Empty; //Set default type as non-critical TResultSeverity ErrorType = TResultSeverity.Resv_Noncritical; TVerificationResultCollection VerificationResult = null; MainDS = new GLBatchTDS(); DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, TEnforceIsolationLevel.eilMinimum, ref Transaction, ref SubmissionOK, delegate { try { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); ABatchRow NewRow = MainDS.ABatch.NewRowTyped(true); NewRow.LedgerNumber = ALedgerNumber; MainDS.ALedger[0].LastBatchNumber++; NewRow.BatchNumber = MainDS.ALedger[0].LastBatchNumber; NewRow.BatchPeriod = MainDS.ALedger[0].CurrentPeriod; NewRow.BatchYear = MainDS.ALedger[0].CurrentFinancialYear; int FinancialYear, FinancialPeriod; if (ADateEffective != default(DateTime)) { TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber, ref ADateEffective, out FinancialYear, out FinancialPeriod, Transaction, false); NewRow.DateEffective = ADateEffective; NewRow.BatchPeriod = FinancialPeriod; NewRow.BatchYear = FinancialYear; } NewRow.BatchDescription = ABatchDescription; NewRow.BatchControlTotal = ABatchControlTotal; MainDS.ABatch.Rows.Add(NewRow); GLBatchTDSAccess.SubmitChanges(MainDS); MainDS.AcceptChanges(); SubmissionOK = true; } catch (Exception ex) { ErrorMessage = String.Format(Catalog.GetString("Unknown error while creating a batch for Ledger: {0}." + Environment.NewLine + Environment.NewLine + ex.ToString()), ALedgerNumber); ErrorType = TResultSeverity.Resv_Critical; VerificationResult = new TVerificationResultCollection(); VerificationResult.Add(new TVerificationResult(ErrorContext, ErrorMessage, ErrorType)); throw new EVerificationResultsException(ErrorMessage, VerificationResult, ex.InnerException); } }); return MainDS; }
public static GLBatchTDS LoadARecurringBatch(Int32 ALedgerNumber, TFinanceBatchFilterEnum AFilterBatchStatus) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } #endregion Validate Arguments GLBatchTDS MainDS = new GLBatchTDS(); TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); #region Validate Data if ((MainDS.ALedger == null) || (MainDS.ALedger.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } #endregion Validate Data string SelectClause = String.Format("SELECT * FROM PUB_{0} WHERE {1}={2}", ARecurringBatchTable.GetTableDBName(), ARecurringBatchTable.GetLedgerNumberDBName(), ALedgerNumber); string FilterByBatchStatus = string.Empty; if ((AFilterBatchStatus & TFinanceBatchFilterEnum.fbfEditing) != 0) { FilterByBatchStatus = string.Format(" AND {0} = '{1}'", ARecurringBatchTable.GetBatchStatusDBName(), MFinanceConstants.BATCH_UNPOSTED); } //else if (AFilterBatchStatus == TFinanceBatchFilterEnum.fbfAll) //{ // // FilterByBatchStatus is empty //} DBAccess.GDBAccessObj.Select(MainDS, SelectClause + FilterByBatchStatus, MainDS.ARecurringBatch.TableName, Transaction); }); MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
/// <summary> /// create a new recurring batch. /// it is already stored to the database, to avoid problems with LastBatchNumber /// </summary> public static GLBatchTDS CreateARecurringBatch(Int32 ALedgerNumber) { bool NewTransactionStarted = false; GLBatchTDS MainDS = null; GLBatchTDS Temp = null; //Error handling string ErrorContext = "Create a recurring Batch"; string ErrorMessage = String.Empty; //Set default type as non-critical TResultSeverity ErrorType = TResultSeverity.Resv_Noncritical; TVerificationResultCollection VerificationResult = null; try { MainDS = new GLBatchTDS(); Temp = new GLBatchTDS(); TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction (IsolationLevel.Serializable, TEnforceIsolationLevel.eilMinimum, out NewTransactionStarted); ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); ARecurringBatchAccess.LoadViaALedger(Temp, ALedgerNumber, Transaction); DataView RecurringBatchDV = new DataView(Temp.ARecurringBatch); RecurringBatchDV.RowFilter = string.Empty; RecurringBatchDV.Sort = string.Format("{0} DESC", ARecurringBatchTable.GetBatchNumberDBName()); //Recurring batch numbers can be reused so check each time for current highest number if (RecurringBatchDV.Count > 0) { MainDS.ALedger[0].LastRecurringBatchNumber = (int)(RecurringBatchDV[0][ARecurringBatchTable.GetBatchNumberDBName()]); } else { MainDS.ALedger[0].LastRecurringBatchNumber = 0; } ARecurringBatchRow NewRow = MainDS.ARecurringBatch.NewRowTyped(true); NewRow.LedgerNumber = ALedgerNumber; NewRow.BatchNumber = ++MainDS.ALedger[0].LastRecurringBatchNumber; MainDS.ARecurringBatch.Rows.Add(NewRow); GLBatchTDSAccess.SubmitChanges(MainDS); MainDS.AcceptChanges(); Temp.RejectChanges(); } catch (Exception ex) { ErrorMessage = String.Format(Catalog.GetString("Unknown error while creating a recurring batch for Ledger: {0}." + Environment.NewLine + Environment.NewLine + ex.ToString()), ALedgerNumber); ErrorType = TResultSeverity.Resv_Critical; VerificationResult = new TVerificationResultCollection(); VerificationResult.Add(new TVerificationResult(ErrorContext, ErrorMessage, ErrorType)); throw new EVerificationResultsException(ErrorMessage, VerificationResult, ex.InnerException); } finally { if (NewTransactionStarted) { DBAccess.GDBAccessObj.CommitTransaction(); } } return MainDS; }
public static GLBatchTDS LoadARecurringTransactionARecurringTransAnalAttrib(Int32 ALedgerNumber, Int32 ABatchNumber, Int32 AJournalNumber) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } else if (AJournalNumber <= 0) { throw new ArgumentException(String.Format(Catalog.GetString("Function:{0} - The Journal number must be greater than 0!"), Utilities.GetMethodName(true), AJournalNumber)); } #endregion Validate Arguments string AnalysisAttrList = string.Empty; GLBatchTDS MainDS = new GLBatchTDS(); TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { ARecurringTransactionAccess.LoadViaARecurringJournal(MainDS, ALedgerNumber, ABatchNumber, AJournalNumber, Transaction); ARecurringTransAnalAttribAccess.LoadViaARecurringJournal(MainDS, ALedgerNumber, ABatchNumber, AJournalNumber, Transaction); }); #region Validate Data if ((MainDS.ARecurringTransaction.Count == 0) && (MainDS.ARecurringTransAnalAttrib.Count > 0)) { throw new ApplicationException(String.Format(Catalog.GetString( "Function:{0} - Orphaned GL Transaction Analysis Attributes exist in Recurring GL Batch {1} in Ledger {2}!"), Utilities.GetMethodName(true), ABatchNumber, ALedgerNumber)); } #endregion Validate Data foreach (GLBatchTDSARecurringTransactionRow transRow in MainDS.ARecurringTransaction.Rows) { MainDS.ARecurringTransAnalAttrib.DefaultView.RowFilter = String.Format("{0} = {1}", ARecurringTransAnalAttribTable.GetTransactionNumberDBName(), transRow.TransactionNumber); foreach (DataRowView drv in MainDS.ARecurringTransAnalAttrib.DefaultView) { ARecurringTransAnalAttribRow recurrTransAnalAttrRow = (ARecurringTransAnalAttribRow)drv.Row; if (AnalysisAttrList.Length > 0) { AnalysisAttrList += ", "; } AnalysisAttrList += (recurrTransAnalAttrRow.AnalysisTypeCode + "=" + recurrTransAnalAttrRow.AnalysisAttributeValue); } if (transRow.AnalysisAttributes != AnalysisAttrList) { transRow.AnalysisAttributes = AnalysisAttrList; } //clear the attributes string and table AnalysisAttrList = string.Empty; } MainDS.ARecurringTransAnalAttrib.DefaultView.RowFilter = string.Empty; MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
/// <summary> /// Reverses the specified batch /// </summary> /// <param name="ACurrentBatchRow">The DataRow for the batch to be reversed</param> /// <param name="ADateForReverseBatch">The reversal date - this will get checked to ensure the date is valid</param> /// <param name="AStartDateCurrentPeriod">The earliest date that can be used as reversal date</param> /// <param name="AEndDateLastForwardingPeriod">The latest date that can be used as a reversal date</param> /// <returns></returns> public bool ReverseBatch(ABatchRow ACurrentBatchRow, DateTime ADateForReverseBatch, DateTime AStartDateCurrentPeriod, DateTime AEndDateLastForwardingPeriod) { //TODO: Allow the user in a dialog to specify the reverse date TVerificationResultCollection Verifications; if (FPetraUtilsObject.HasChanges) { // save first, then post if (!FMyForm.SaveChanges()) { // saving failed, therefore do not try to reverse MessageBox.Show(Catalog.GetString("The batch was not reversed due to problems during saving; ") + Environment.NewLine + Catalog.GetString("Please first save the batch, and then you can reverse it!"), Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } } try { FMyForm.Cursor = Cursors.WaitCursor; int SelectedBatchNumber = ACurrentBatchRow.BatchNumber; string Msg = string.Empty; // load journals belonging to batch GLBatchTDS TempDS = TRemote.MFinance.GL.WebConnectors.LoadAJournalAndContent(FLedgerNumber, ACurrentBatchRow.BatchNumber); FMainDS.Merge(TempDS); foreach (AJournalRow Journal in TempDS.AJournal.Rows) { // if at least one journal in the batch has already been reversed then confirm with user if (Journal.Reversed) { Msg = String.Format(Catalog.GetString("One or more of the Journals in Batch {0} have already been reversed. " + "Are you sure you want to continue?"), SelectedBatchNumber); break; } } if (Msg == string.Empty) { Msg = String.Format(Catalog.GetString("Are you sure you want to reverse Batch {0}?"), SelectedBatchNumber); } if (MessageBox.Show(Msg, Catalog.GetString("GL Batch Reversal"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { TFrmBatchDateDialog Form = new TFrmBatchDateDialog(FMyForm); Form.SetParameters(AStartDateCurrentPeriod, AEndDateLastForwardingPeriod, SelectedBatchNumber); if (Form.ShowDialog() == DialogResult.Cancel) { return(false); } ADateForReverseBatch = Form.BatchDate; int ReversalGLBatch; if (!TRemote.MFinance.GL.WebConnectors.ReverseBatch(FLedgerNumber, SelectedBatchNumber, ADateForReverseBatch, out ReversalGLBatch, out Verifications, false)) { string ErrorMessages = String.Empty; foreach (TVerificationResult verif in Verifications) { ErrorMessages += "[" + verif.ResultContext + "] " + verif.ResultTextCaption + ": " + verif.ResultText + Environment.NewLine; } System.Windows.Forms.MessageBox.Show(ErrorMessages, Catalog.GetString("Reversal failed"), MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show( String.Format(Catalog.GetString("A reversal batch has been created, with batch number {0}!"), ReversalGLBatch), Catalog.GetString("Success"), MessageBoxButtons.OK, MessageBoxIcon.Information); // refresh the grid, to reflect that the batch has been reversed FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAndContent(FLedgerNumber, ReversalGLBatch)); // make sure that the current dataset is clean, // otherwise the next save would try to modify the posted batch, even though no values have been changed FMainDS.AcceptChanges(); // Ensure these tabs will ask the server for updates FMyForm.GetJournalsControl().ClearCurrentSelection(); FMyForm.GetTransactionsControl().ClearCurrentSelection(); FMyUserControl.UpdateDisplay(); return(true); } } } catch (Exception) { throw; } finally { FMyForm.Cursor = Cursors.Default; } return(false); }
public static Int32 SubmitRecurringGLBatch(ref GLBatchTDS AGLMainDS, Hashtable ARequestParams, ref Dictionary <string, decimal>AExchangeRatesDictionary, ref TVerificationResultCollection AVerifications) { Int32 NewGLBatchNumber = 0; //Copy parameters for use in Delegate GLBatchTDS RGLMainDS = AGLMainDS; Dictionary <string, decimal>ExchangeRatesDictionary = AExchangeRatesDictionary; TVerificationResultCollection Verifications = AVerifications; Int32 ALedgerNumber = (Int32)ARequestParams["ALedgerNumber"]; Int32 ABatchNumber = (Int32)ARequestParams["ABatchNumber"]; DateTime AEffectiveDate = (DateTime)ARequestParams["AEffectiveDate"]; Decimal AExchangeRateIntlToBase = (Decimal)ARequestParams["AExchangeRateIntlToBase"]; ALedgerRow LedgerRow = (ALedgerRow)AGLMainDS.ALedger[0]; ARecurringBatchRow RBatchRow = (ARecurringBatchRow)AGLMainDS.ARecurringBatch[0]; #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } else if (RBatchRow == null) { throw new ArgumentException(String.Format(Catalog.GetString( "Function:{0} - The data for Ledger:{1} and Batch:{2} does not exist!"), Utilities.GetMethodName(true), ALedgerNumber, ABatchNumber)); } else if (AExchangeRateIntlToBase < 0) { throw new ArgumentException(String.Format(Catalog.GetString( "Function:{0} - The Exchange Rate from International currency to Base currency cannot be a negative number!"), Utilities.GetMethodName(true))); } else if (AExchangeRatesDictionary.Count == 0) { throw new ArgumentException(String.Format(Catalog.GetString( "Function:{0} - There are no exchange rates present for the Journals!"), Utilities.GetMethodName(true))); } //Check the validity of the Journal and transaction numbering // This will also correct invalid LastJournal and LastTransaction numbers else if (!ValidateRecurringGLBatchJournalNumbering(ref AGLMainDS, ref RBatchRow, ref Verifications) || !ValidateRecurringGLJournalTransactionNumbering(ref AGLMainDS, ref RBatchRow, ref Verifications)) { return 0; } else if (AGLMainDS.ARecurringJournal.Count > 0) { string journalCurrencyCode = string.Empty; decimal journalCurrencyExchangeRateToBase; DataView rJournalDV = new DataView(AGLMainDS.ARecurringJournal); rJournalDV.RowFilter = string.Format("{0}={1} And {2}={3}", ARecurringJournalTable.GetLedgerNumberDBName(), ALedgerNumber, ARecurringJournalTable.GetBatchNumberDBName(), ABatchNumber); foreach (DataRowView drv in rJournalDV) { ARecurringJournalRow rjr = (ARecurringJournalRow)drv.Row; journalCurrencyCode = rjr.TransactionCurrency; journalCurrencyExchangeRateToBase = 0; if (!AExchangeRatesDictionary.TryGetValue(journalCurrencyCode, out journalCurrencyExchangeRateToBase) || (rjr.ExchangeRateToBase <= 0)) { Verifications.Add(new TVerificationResult( String.Format(Catalog.GetString("Cannot submit Recurring GL Batch: {0} in Ledger {1}"), ABatchNumber, ALedgerNumber), String.Format(Catalog.GetString( "The Exchange Rate in Journal:{0} (with currency: {1}) to Base currency ({2}) does not exist or is 0!"), journalCurrencyCode, journalCurrencyCode, LedgerRow.BaseCurrency), TResultSeverity.Resv_Critical)); break; } } if (Verifications.Count > 0) { return 0; } } #endregion Validate Arguments GLBatchTDS GLMainDS = new GLBatchTDS(); ABatchRow BatchRow; int PeriodNumber, YearNr; bool TransactionInIntlCurrency = false; TDBTransaction Transaction = null; bool SubmissionOK = false; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, TEnforceIsolationLevel.eilMinimum, ref Transaction, ref SubmissionOK, delegate { ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction); #region Validate Data 1 if ((LedgerTable == null) || (LedgerTable.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } #endregion Validate Data 1 // Assuming all relevant data is loaded in RGLMainDS foreach (ARecurringBatchRow recBatch in RGLMainDS.ARecurringBatch.Rows) { if ((recBatch.BatchNumber == ABatchNumber) && (recBatch.LedgerNumber == ALedgerNumber)) { GLMainDS = CreateABatch(ALedgerNumber); BatchRow = (ABatchRow)GLMainDS.ABatch.Rows[0]; //The new Batch number to be returned NewGLBatchNumber = BatchRow.BatchNumber; BatchRow.DateEffective = AEffectiveDate; BatchRow.BatchDescription = recBatch.BatchDescription; BatchRow.BatchControlTotal = recBatch.BatchControlTotal; BatchRow.BatchRunningTotal = recBatch.BatchRunningTotal; BatchRow.BatchCreditTotal = recBatch.BatchCreditTotal; BatchRow.BatchDebitTotal = recBatch.BatchDebitTotal; if (TFinancialYear.IsValidPostingPeriod(ALedgerNumber, AEffectiveDate, out PeriodNumber, out YearNr, Transaction)) { BatchRow.BatchYear = YearNr; BatchRow.BatchPeriod = PeriodNumber; } foreach (ARecurringJournalRow recJournal in RGLMainDS.ARecurringJournal.Rows) { if ((recJournal.BatchNumber == ABatchNumber) && (recJournal.LedgerNumber == ALedgerNumber)) { string journalCurrencyCode = recJournal.TransactionCurrency; decimal journalCurrencyExchangeRateToBase = 0; ExchangeRatesDictionary.TryGetValue(journalCurrencyCode, out journalCurrencyExchangeRateToBase); // create the journal from recJournal AJournalRow JournalRow = GLMainDS.AJournal.NewRowTyped(); JournalRow.LedgerNumber = BatchRow.LedgerNumber; JournalRow.BatchNumber = BatchRow.BatchNumber; JournalRow.JournalNumber = recJournal.JournalNumber; JournalRow.JournalDescription = recJournal.JournalDescription; JournalRow.SubSystemCode = recJournal.SubSystemCode; JournalRow.TransactionTypeCode = recJournal.TransactionTypeCode; JournalRow.TransactionCurrency = journalCurrencyCode; JournalRow.JournalCreditTotal = recJournal.JournalCreditTotal; JournalRow.JournalDebitTotal = recJournal.JournalDebitTotal; JournalRow.ExchangeRateToBase = journalCurrencyExchangeRateToBase; JournalRow.DateEffective = AEffectiveDate; JournalRow.JournalPeriod = recJournal.JournalPeriod; GLMainDS.AJournal.Rows.Add(JournalRow); if (JournalRow.JournalNumber > BatchRow.LastJournal) { BatchRow.LastJournal = JournalRow.JournalNumber; } TransactionInIntlCurrency = (JournalRow.TransactionCurrency == LedgerTable[0].IntlCurrency); //TODO (not here, but in the client or while posting) Check for expired key ministry (while Posting) foreach (ARecurringTransactionRow recTransaction in RGLMainDS.ARecurringTransaction.Rows) { if ((recTransaction.JournalNumber == recJournal.JournalNumber) && (recTransaction.BatchNumber == ABatchNumber) && (recTransaction.LedgerNumber == ALedgerNumber)) { ATransactionRow TransactionRow = GLMainDS.ATransaction.NewRowTyped(); TransactionRow.LedgerNumber = JournalRow.LedgerNumber; TransactionRow.BatchNumber = JournalRow.BatchNumber; TransactionRow.JournalNumber = JournalRow.JournalNumber; TransactionRow.TransactionNumber = recTransaction.TransactionNumber; if (TransactionRow.TransactionNumber > JournalRow.LastTransactionNumber) { JournalRow.LastTransactionNumber = TransactionRow.TransactionNumber; } TransactionRow.Narrative = recTransaction.Narrative; TransactionRow.AccountCode = recTransaction.AccountCode; TransactionRow.CostCentreCode = recTransaction.CostCentreCode; TransactionRow.TransactionAmount = recTransaction.TransactionAmount; TransactionRow.AmountInBaseCurrency = GLRoutines.Divide(recTransaction.TransactionAmount, journalCurrencyExchangeRateToBase); if (!TransactionInIntlCurrency) { TransactionRow.AmountInIntlCurrency = ((AExchangeRateIntlToBase == 0) ? 0 : GLRoutines.Divide((decimal)TransactionRow. AmountInBaseCurrency, AExchangeRateIntlToBase)); } else { TransactionRow.AmountInIntlCurrency = TransactionRow.TransactionAmount; } TransactionRow.TransactionDate = AEffectiveDate; TransactionRow.DebitCreditIndicator = recTransaction.DebitCreditIndicator; TransactionRow.HeaderNumber = recTransaction.HeaderNumber; TransactionRow.DetailNumber = recTransaction.DetailNumber; TransactionRow.SubType = recTransaction.SubType; TransactionRow.Reference = recTransaction.Reference; GLMainDS.ATransaction.Rows.Add(TransactionRow); foreach (ARecurringTransAnalAttribRow recAnalAttrib in RGLMainDS.ARecurringTransAnalAttrib.Rows) { if ((recAnalAttrib.TransactionNumber == recTransaction.TransactionNumber) && (recTransaction.JournalNumber == recJournal.JournalNumber) && (recTransaction.BatchNumber == ABatchNumber) && (recTransaction.LedgerNumber == ALedgerNumber)) { ATransAnalAttribRow TransAnalAttribRow = GLMainDS.ATransAnalAttrib.NewRowTyped(); TransAnalAttribRow.LedgerNumber = JournalRow.LedgerNumber; TransAnalAttribRow.BatchNumber = JournalRow.BatchNumber; TransAnalAttribRow.JournalNumber = JournalRow.JournalNumber; TransAnalAttribRow.TransactionNumber = recTransaction.TransactionNumber; TransAnalAttribRow.AnalysisTypeCode = recAnalAttrib.AnalysisTypeCode; TransAnalAttribRow.AccountCode = recAnalAttrib.AccountCode; TransAnalAttribRow.CostCentreCode = recAnalAttrib.CostCentreCode; TransAnalAttribRow.AnalysisAttributeValue = recAnalAttrib.AnalysisAttributeValue; GLMainDS.ATransAnalAttrib.Rows.Add(TransAnalAttribRow); } } } } } } } } ALedgerAccess.SubmitChanges(LedgerTable, Transaction); ABatchAccess.SubmitChanges(GLMainDS.ABatch, Transaction); AJournalAccess.SubmitChanges(GLMainDS.AJournal, Transaction); ATransactionAccess.SubmitChanges(GLMainDS.ATransaction, Transaction); ATransAnalAttribAccess.SubmitChanges(GLMainDS.ATransAnalAttrib, Transaction); SubmissionOK = true; }); GLMainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } AVerifications = Verifications; return NewGLBatchNumber; }
/// <summary> /// Method to cancel a specified batch /// </summary> /// <param name="ABatchRowToCancel">The row to cancel</param> /// <returns></returns> public bool CancelBatch(ABatchRow ABatchRowToCancel) { //Assign default value(s) bool CancellationSuccessful = false; if ((ABatchRowToCancel == null)) { return(CancellationSuccessful); } int CurrentBatchNumber = ABatchRowToCancel.BatchNumber; if ((MessageBox.Show(String.Format(Catalog.GetString("You have chosen to cancel this batch ({0}).\n\nDo you really want to cancel it?"), CurrentBatchNumber), Catalog.GetString("Confirm Cancel"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != System.Windows.Forms.DialogResult.Yes)) { return(CancellationSuccessful); } //Backup the Dataset for reversion purposes GLBatchTDS BackupMainDS = (GLBatchTDS)FMainDS.Copy(); BackupMainDS.Merge(FMainDS); bool RowToDeleteIsNew = (ABatchRowToCancel.RowState == DataRowState.Added); if (!RowToDeleteIsNew) { //Remove any changes, which may cause validation issues, before cancelling FMyForm.GetBatchControl().UndoModifiedBatchRow(ABatchRowToCancel, true); if (!(FMyForm.SaveChanges())) { MessageBox.Show(Catalog.GetString("Error in trying to save prior to cancelling current Batch!"), Catalog.GetString("Cancellation Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(CancellationSuccessful); } } try { FMyForm.Cursor = Cursors.WaitCursor; //clear any transactions currently being editied in the Transaction Tab FMyForm.GetTransactionsControl().ClearCurrentSelection(); //clear any journals currently being editied in the Journals Tab FMyForm.GetJournalsControl().ClearCurrentSelection(); //Clear Journals etc for current Batch FMainDS.ATransAnalAttrib.Clear(); FMainDS.ATransaction.Clear(); FMainDS.AJournal.Clear(); //Load tables afresh FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadAJournal(FLedgerNumber, CurrentBatchNumber)); FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransaction(FLedgerNumber, CurrentBatchNumber)); FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransAnalAttribForBatch(FLedgerNumber, CurrentBatchNumber)); FMainDS.AcceptChanges(); //Delete transactions and analysis attributes for (int i = FMainDS.ATransAnalAttrib.Count - 1; i >= 0; i--) { FMainDS.ATransAnalAttrib[i].Delete(); } for (int i = FMainDS.ATransaction.Count - 1; i >= 0; i--) { FMainDS.ATransaction[i].Delete(); } //Update Journal totals and status foreach (AJournalRow journal in FMainDS.AJournal.Rows) { if (journal.BatchNumber == CurrentBatchNumber) { journal.BeginEdit(); journal.JournalStatus = MFinanceConstants.BATCH_CANCELLED; journal.JournalCreditTotal = 0; journal.JournalDebitTotal = 0; journal.LastTransactionNumber = 0; journal.EndEdit(); } } // Edit the batch row ABatchRowToCancel.BeginEdit(); ABatchRowToCancel.BatchCreditTotal = 0; ABatchRowToCancel.BatchDebitTotal = 0; ABatchRowToCancel.BatchControlTotal = 0; ABatchRowToCancel.BatchStatus = MFinanceConstants.BATCH_CANCELLED; ABatchRowToCancel.EndEdit(); FPetraUtilsObject.SetChangedFlag(); //Need to call save if (FMyForm.SaveChanges()) { MessageBox.Show(Catalog.GetString("The batch has been cancelled successfully!"), Catalog.GetString("Success"), MessageBoxButtons.OK, MessageBoxIcon.Information); FMyForm.DisableTransactions(); FMyForm.DisableJournals(); } else { throw new Exception(Catalog.GetString("The batch failed to save after being cancelled! Reopen the form and retry.")); } CancellationSuccessful = true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Cancellation Error", MessageBoxButtons.OK, MessageBoxIcon.Error); //Revert to previous state FMainDS.Merge(BackupMainDS); } finally { FMyForm.Cursor = Cursors.Default; } return(CancellationSuccessful); }
public static GLBatchTDS LoadAJournal(Int32 ALedgerNumber, Int32 ABatchNumber) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } #endregion Validate Arguments GLBatchTDS MainDS = new GLBatchTDS(); TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { AJournalAccess.LoadViaABatch(MainDS, ALedgerNumber, ABatchNumber, Transaction); }); MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
/// <summary> /// Deletes the current row and optionally populates a completion message /// </summary> /// <param name="ARowToDelete">the currently selected row to delete</param> /// <param name="ACompletionMessage">if specified, is the deletion completion message</param> /// <returns>true if row deletion is successful</returns> private bool DeleteRowManual(GLBatchTDSARecurringJournalRow ARowToDelete, ref string ACompletionMessage) { //Assign default value(s) bool DeletionSuccessful = false; ACompletionMessage = string.Empty; if (ARowToDelete == null) { return(DeletionSuccessful); } bool RowToDeleteIsNew = (ARowToDelete.RowState == DataRowState.Added); if (!RowToDeleteIsNew) { //Reject any changes which may fail validation ARowToDelete.RejectChanges(); ShowDetails(ARowToDelete); if (!((TFrmRecurringGLBatch)this.ParentForm).SaveChanges()) { MessageBox.Show(Catalog.GetString("Error in trying to save prior to deleting current recurring journal!"), Catalog.GetString("Deletion Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(DeletionSuccessful); } } //Backup the Dataset for reversion purposes GLBatchTDS BackupMainDS = (GLBatchTDS)FMainDS.Copy(); BackupMainDS.Merge(FMainDS); //Pass copy to delete method. GLBatchTDS TempDS = (GLBatchTDS)FMainDS.Copy(); TempDS.Merge(FMainDS); FJournalNumberToDelete = ARowToDelete.JournalNumber; int TopMostJrnlNo = FBatchRow.LastJournal; try { this.Cursor = Cursors.WaitCursor; //clear any transactions currently being editied in the Transaction Tab ((TFrmRecurringGLBatch)ParentForm).GetTransactionsControl().ClearCurrentSelection(); if (RowToDeleteIsNew) { ProcessNewlyAddedJournalRowForDeletion(FJournalNumberToDelete); } else { //Load all journals for this batch TempDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadARecurringJournalAndContent(FLedgerNumber, FBatchNumber)); TempDS.AcceptChanges(); //Clear the transactions and load newly saved dataset FMainDS.ARecurringTransAnalAttrib.Clear(); FMainDS.ARecurringTransaction.Clear(); FMainDS.ARecurringJournal.Clear(); FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.ProcessRecurrJrnlTransAttribForDeletion(TempDS, FLedgerNumber, FBatchNumber, TopMostJrnlNo, FJournalNumberToDelete)); } FPreviouslySelectedDetailRow = null; FPetraUtilsObject.SetChangedFlag(); ACompletionMessage = String.Format(Catalog.GetString("Recurring Journal no.: {0} deleted successfully."), FJournalNumberToDelete); DeletionSuccessful = true; } catch (Exception ex) { ACompletionMessage = ex.Message; MessageBox.Show(ex.Message, "Deletion Error", MessageBoxButtons.OK, MessageBoxIcon.Error); //Revert to previous state FMainDS.Merge(BackupMainDS); } finally { SetJournalDefaultView(); FFilterAndFindObject.ApplyFilter(); this.Cursor = Cursors.Default; } return(DeletionSuccessful); }
public static GLBatchTDS LoadAJournal(Int32 ALedgerNumber, Int32 ABatchNumber, Int32 AJournalNumber) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } else if (AJournalNumber <= 0) { throw new ArgumentException(String.Format(Catalog.GetString("Function:{0} - The Journal number must be greater than 0!"), Utilities.GetMethodName(true), AJournalNumber)); } #endregion Validate Arguments GLBatchTDS MainDS = new GLBatchTDS(); TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { AJournalAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, AJournalNumber, Transaction); #region Validate Data if ((MainDS.AJournal == null) || (MainDS.AJournal.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - GL Journal data for Journal {1} Batch {2} in Ledger {3} does not exist or could not be accessed!"), Utilities.GetMethodName(true), AJournalNumber, ABatchNumber, ALedgerNumber)); } #endregion Validate Data }); MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
public static void UpdateTotalsOfBatch(Int32 ALedgerNumber, Int32 ABatchNumber) { //TVerificationResultCollection AVerificationResult = new TVerificationResultCollection(); GLBatchTDS glDS = new GLBatchTDS(); decimal sumDebits = 0.0M; decimal sumCredits = 0.0M; //Load all Batch, Journal and Transaction records glDS.Merge(LoadABatchAJournalATransaction(ALedgerNumber, ABatchNumber)); if ((glDS.ABatch == null) || (glDS.ABatch.Count == 0)) { return; } try { ABatchRow currentBatch = (ABatchRow)glDS.ABatch.Rows[0]; glDS.AJournal.DefaultView.RowFilter = string.Empty; foreach (DataRowView journalview in glDS.AJournal.DefaultView) { GLBatchTDSAJournalRow journalrow = (GLBatchTDSAJournalRow)journalview.Row; UpdateTotalsOfJournal(ref glDS, journalrow); sumDebits += journalrow.JournalDebitTotal; sumCredits += journalrow.JournalCreditTotal; } currentBatch.BatchDebitTotal = sumDebits; currentBatch.BatchCreditTotal = sumCredits; currentBatch.BatchRunningTotal = Math.Round(sumDebits - sumCredits, 2); glDS.AcceptChanges(); } catch (Exception) { glDS.RejectChanges(); throw; } }
public static GLBatchTDS LoadARecurringJournalAndContent(Int32 ALedgerNumber, Int32 ABatchNumber) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } #endregion Validate Arguments GLBatchTDS MainDS = new GLBatchTDS(); TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { ARecurringJournalAccess.LoadViaARecurringBatch(MainDS, ALedgerNumber, ABatchNumber, Transaction); ARecurringTransactionTable TransactionTable = new ARecurringTransactionTable(); ARecurringTransactionRow TemplateTransactionRow = TransactionTable.NewRowTyped(false); TemplateTransactionRow.LedgerNumber = ALedgerNumber; TemplateTransactionRow.BatchNumber = ABatchNumber; ARecurringTransactionAccess.LoadUsingTemplate(MainDS, TemplateTransactionRow, Transaction); ARecurringTransAnalAttribTable TransAnalAttribTable = new ARecurringTransAnalAttribTable(); ARecurringTransAnalAttribRow TemplateTransAnalAttribRow = TransAnalAttribTable.NewRowTyped(false); TemplateTransAnalAttribRow.LedgerNumber = ALedgerNumber; TemplateTransAnalAttribRow.BatchNumber = ABatchNumber; ARecurringTransAnalAttribAccess.LoadUsingTemplate(MainDS, TemplateTransAnalAttribRow, Transaction); #region Validate Data if ((MainDS.ARecurringJournal.Count == 0) && (MainDS.ARecurringTransaction.Count > 0)) { throw new ApplicationException(String.Format(Catalog.GetString( "Function:{0} - Orphaned GL Transactions exist in Recurring GL Batch {1} in Ledger {2}!"), Utilities.GetMethodName(true), ABatchNumber, ALedgerNumber)); } else if (((MainDS.ARecurringJournal.Count == 0) || (MainDS.ARecurringTransaction.Count == 0)) && (MainDS.ARecurringTransAnalAttrib.Count > 0)) { throw new ApplicationException(String.Format(Catalog.GetString( "Function:{0} - Orphaned GL Transaction Analysis Attributes exist in Recurring GL Batch {1} in Ledger {2}!"), Utilities.GetMethodName(true), ABatchNumber, ALedgerNumber)); } #endregion Validate Data }); MainDS.AcceptChanges(); } catch (Exception ex) { TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}", Utilities.GetMethodSignature(), Environment.NewLine, ex.Message)); throw ex; } return MainDS; }
public static GLBatchTDS LoadALedgerTable(Int32 ALedgerNumber) { GLBatchTDS MainDS = new GLBatchTDS(); TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted); ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction); // Accept row changes here so that the Client gets 'unmodified' rows MainDS.AcceptChanges(); // Remove all Tables that were not filled with data before remoting them. MainDS.RemoveEmptyTables(); DBAccess.GDBAccessObj.RollbackTransaction(); return MainDS; }
private static GLBatchTDS ReduceGLDataSet(ref GLBatchTDS AMainDS, Int32 ALedgerNumber, Int32 ABatchNumber, bool AKeepThisBatchOnly = true) { #region Validate Arguments if (AMainDS == null) { throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString("Function:{0} - The GL Batch dataset is null!"), Utilities.GetMethodName(true))); } else if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ABatchNumber <= 0) { throw new EFinanceSystemInvalidBatchNumberException(String.Format(Catalog.GetString( "Function:{0} - The Batch number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber, ABatchNumber); } #endregion Validate Arguments GLBatchTDS ReducedDS = new GLBatchTDS(); ReducedDS.Merge(AMainDS); DataView BatchDV = new DataView(ReducedDS.ABatch); DataView JournalDV = new DataView(ReducedDS.AJournal); DataView TransactionDV = new DataView(ReducedDS.ATransaction); DataView AnalysisAttribDV = new DataView(ReducedDS.ATransAnalAttrib); //Recurring DataView RecurringBatchDV = new DataView(ReducedDS.ARecurringBatch); DataView RecurringJournalDV = new DataView(ReducedDS.ARecurringJournal); DataView RecurringTransactionDV = new DataView(ReducedDS.ARecurringTransaction); DataView RecurringAnalysisAttribDV = new DataView(ReducedDS.ARecurringTransAnalAttrib); string CommonRowFilter = StandardRowFilterByLedgerAndBatch(ALedgerNumber, ABatchNumber, !AKeepThisBatchOnly); AnalysisAttribDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in AnalysisAttribDV) { drv.Delete(); } TransactionDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in TransactionDV) { drv.Delete(); } JournalDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in JournalDV) { drv.Delete(); } BatchDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in BatchDV) { drv.Delete(); } //Recurring RecurringAnalysisAttribDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in RecurringAnalysisAttribDV) { drv.Delete(); } RecurringTransactionDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in RecurringTransactionDV) { drv.Delete(); } RecurringJournalDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in RecurringJournalDV) { drv.Delete(); } RecurringBatchDV.RowFilter = CommonRowFilter; foreach (DataRowView drv in RecurringBatchDV) { drv.Delete(); } ReducedDS.AcceptChanges(); return(ReducedDS); }
/// <summary> /// Deletes the current row and optionally populates a completion message /// </summary> /// <param name="ARowToDelete">the currently selected row to delete</param> /// <param name="ACompletionMessage">if specified, is the deletion completion message</param> /// <returns>true if row deletion is successful</returns> private bool DeleteRowManual(GLBatchTDSARecurringJournalRow ARowToDelete, ref string ACompletionMessage) { //Assign default value(s) bool DeletionSuccessful = false; ACompletionMessage = string.Empty; if (ARowToDelete == null) { return(DeletionSuccessful); } //Delete current row ARowToDelete.RejectChanges(); ShowDetails(ARowToDelete); //Take a backup of FMainDS GLBatchTDS BackupMainDS = null; //Pass a copy of FMainDS to the server-side delete method. GLBatchTDS TempDS = (GLBatchTDS)FMainDS.Copy(); TempDS.Merge(FMainDS); int CurrentBatchNumber = ARowToDelete.BatchNumber; bool CurrentBatchJournalTransactionsLoadedAndCurrent = false; FJournalNumberToDelete = ARowToDelete.JournalNumber; int TopMostJrnlNo = FBatchRow.LastJournal; TFrmRecurringGLBatch FMyForm = (TFrmRecurringGLBatch)this.ParentForm; try { this.Cursor = Cursors.WaitCursor; FMyForm.FCurrentGLBatchAction = TGLBatchEnums.GLBatchAction.DELETINGJOURNAL; //Backup the Dataset for reversion purposes BackupMainDS = (GLBatchTDS)FMainDS.GetChangesTyped(false); //Check if current batch transactions are loaded and being viewed in their tab CurrentBatchJournalTransactionsLoadedAndCurrent = (FMyForm.GetTransactionsControl().FBatchNumber == CurrentBatchNumber && FMyForm.GetTransactionsControl().FJournalNumber == FJournalNumberToDelete); //Save and check for inactive values FPetraUtilsObject.SetChangedFlag(); if (!FMyForm.SaveChangesManual(FMyForm.FCurrentGLBatchAction, false, !CurrentBatchJournalTransactionsLoadedAndCurrent)) { string msg = String.Format(Catalog.GetString("Recurring Journal {0} has not been deleted."), FJournalNumberToDelete); MessageBox.Show(msg, Catalog.GetString("Recurring GL Batch Deletion"), MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } //Remove any changes to current batch that may cause validation issues PrepareJournalDataForDeleting(CurrentBatchNumber, FJournalNumberToDelete, true); if (CurrentBatchJournalTransactionsLoadedAndCurrent) { //Clear any transactions currently being edited in the Transaction Tab FMyForm.GetTransactionsControl().ClearCurrentSelection(CurrentBatchNumber, FJournalNumberToDelete); } //Load all journals for this batch TempDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadARecurringJournalAndRelatedTablesForBatch(FLedgerNumber, FBatchNumber)); TempDS.AcceptChanges(); //Clear the transactions and load newly saved dataset FMainDS.ARecurringTransAnalAttrib.Clear(); FMainDS.ARecurringTransaction.Clear(); FMainDS.ARecurringJournal.Clear(); FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.ProcessRecurrJrnlTransAttribForDeletion(TempDS, FLedgerNumber, FBatchNumber, TopMostJrnlNo, FJournalNumberToDelete)); FPreviouslySelectedDetailRow = null; FPetraUtilsObject.SetChangedFlag(); ACompletionMessage = String.Format(Catalog.GetString("Recurring Journal no.: {0} deleted successfully."), FJournalNumberToDelete); DeletionSuccessful = true; } catch (Exception ex) { //Normally set in PostDeleteManual FMyForm.FCurrentGLBatchAction = TGLBatchEnums.GLBatchAction.NONE; //Revert to previous state RevertDataSet(FMainDS, BackupMainDS); TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { SetJournalDefaultView(); FFilterAndFindObject.ApplyFilter(); this.Cursor = Cursors.Default; } return(DeletionSuccessful); }
/// <summary> /// this supports the transaction export files from Petra 2.x. /// Lines do NOT start with T for transaction /// </summary> public void ImportTransactions(ABatchRow ACurrentBatchRow, AJournalRow ACurrentJournalRow, TImportDataSourceEnum AImportDataSource) { bool ok = false; String importString; String impOptions; OpenFileDialog dialog = null; if (FPetraUtilsObject.HasChanges && !FMyForm.SaveChanges()) { // saving failed, therefore do not try to import MessageBox.Show(Catalog.GetString("Please save your changes before Importing new transactions"), Catalog.GetString( "Import GL Transactions"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((ACurrentBatchRow == null) || (ACurrentJournalRow == null) || (ACurrentJournalRow.JournalStatus != MFinanceConstants.BATCH_UNPOSTED)) { MessageBox.Show(Catalog.GetString("Please select an unposted journal to import transactions."), Catalog.GetString("Import GL Transactions")); return; } if (ACurrentJournalRow.LastTransactionNumber > 0) { if (MessageBox.Show(Catalog.GetString( "The current journal already contains some transactions. Do you really want to add more transactions to this journal?"), Catalog.GetString("Import GL Transactions"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No) { return; } } FdlgSeparator = new TDlgSelectCSVSeparator(false); if (AImportDataSource == TImportDataSourceEnum.FromClipboard) { importString = Clipboard.GetText(TextDataFormat.UnicodeText); if ((importString == null) || (importString.Length == 0)) { MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"), Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American"); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator = new TDlgSelectCSVSeparator(false); FdlgSeparator.SelectedSeparator = "\t"; FdlgSeparator.CSVData = importString; FdlgSeparator.DateFormat = dateFormatString; if (impOptions.Length > 1) { FdlgSeparator.NumberFormat = impOptions.Substring(1); } } else if (AImportDataSource == TImportDataSourceEnum.FromFile) { dialog = new OpenFileDialog(); dialog.FileName = TUserDefaults.GetStringDefault("Imp Filename", TClientSettings.GetExportPath() + Path.DirectorySeparatorChar + "import.csv"); dialog.Title = Catalog.GetString("Import Transactions from CSV File"); dialog.Filter = Catalog.GetString("GL Transactions files (*.csv)|*.csv"); impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American"); if (dialog.ShowDialog() == DialogResult.OK) { Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Transaction Import"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } importString = File.ReadAllText(dialog.FileName); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator.DateFormat = dateFormatString; if (impOptions.Length > 1) { FdlgSeparator.NumberFormat = impOptions.Substring(1); } FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1); } else { return; } } else { // unknown source!! The following need a value... impOptions = String.Empty; importString = String.Empty; } if (FdlgSeparator.ShowDialog() == DialogResult.OK) { Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", FLedgerNumber); requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator); requestParams.Add("DateFormatString", FdlgSeparator.DateFormat); requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat); requestParams.Add("NewLine", Environment.NewLine); TVerificationResultCollection AMessages = new TVerificationResultCollection(); Thread ImportThread = new Thread(() => ImportGLTransactions(requestParams, importString, ACurrentBatchRow.BatchNumber, ACurrentJournalRow.JournalNumber, out AMessages, out ok)); using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread)) { ImportDialog.ShowDialog(); } ShowMessages(AMessages); } if (ok) { MessageBox.Show(Catalog.GetString("Your data was imported successfully!"), Catalog.GetString("Transactions Import"), MessageBoxButtons.OK, MessageBoxIcon.Information); SaveUserDefaults(dialog, impOptions); // Update the client side with new information from the server FMyForm.Cursor = Cursors.WaitCursor; FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAJournal(FLedgerNumber, ACurrentBatchRow.BatchNumber)); FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransactionATransAnalAttrib(FLedgerNumber, ACurrentBatchRow.BatchNumber, ACurrentJournalRow.JournalNumber)); FMainDS.AcceptChanges(); FMyForm.Cursor = Cursors.Default; FMyForm.GetTransactionsControl().SelectRow(1); } }