private void RevertDataSet(GLBatchTDS AMainDS, GLBatchTDS ABackupDS, int ASelectRowInGrid = 0)
        {
            if ((ABackupDS != null) && (AMainDS != null))
            {
                AMainDS.RejectChanges();
                AMainDS.Merge(ABackupDS);

                if (ASelectRowInGrid > 0)
                {
                    SelectRowInGrid(ASelectRowInGrid);
                }
            }
        }
        /// <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);
        }
        /// <summary>
        /// The main method that handles all filtering.  Every change on the filter panel causes this event to fire.
        /// It is important to manage the fact that this method may be called recursively and so nesting can be tricky!
        /// </summary>
        /// <param name="AFilterString">On entry this parameter contains the filter control's best guess for the current filter.
        /// The code can modify this string in the light of current control values.</param>
        public void ApplyFilterManual(ref string AFilterString)
        {
            if ((FCurrentLedgerYear < 0) || (FCurrentLedgerPeriod < 0))
            {
                return;
            }

            string workingFilter     = String.Empty;
            string additionalFilter  = String.Empty;
            bool   showingAllPeriods = false;

            // Remove the old base filter
            if (FPrevBaseFilter.Length > 0)
            {
                additionalFilter = AFilterString.Substring(FPrevBaseFilter.Length);

                if (additionalFilter.StartsWith(CommonJoinString.JOIN_STRING_SQL_AND))
                {
                    additionalFilter = additionalFilter.Substring(CommonJoinString.JOIN_STRING_SQL_AND.Length);
                }
            }

            int newYear = FcmbYearEnding.GetSelectedInt32();

            if (newYear != FPrevYearEnding)
            {
                FPrevYearEnding = newYear;
                //TLogging.Log(String.Format("RefreshPeriods for Year {0}", newYear));
                RefreshPeriods(newYear);

                // Apply the last good filter as we unwind the nesting
                AFilterString = FPrevFilter;
                return;
            }

            int newPeriod = FcmbPeriod.GetSelectedInt32();

            if (newYear == -1)
            {
                newYear = FCurrentLedgerYear;

                workingFilter     = String.Format("{0} = {1}", ABatchTable.GetBatchYearDBName(), newYear);
                showingAllPeriods = true;
            }
            else
            {
                workingFilter = String.Format(
                    "{0} = {1}",
                    ABatchTable.GetBatchYearDBName(), newYear);

                if (newPeriod == 0)  //All periods for year
                {
                    //Nothing to add to filter
                    showingAllPeriods = true;
                }
                else if (newPeriod == -1)
                {
                    workingFilter += String.Format(" AND {0} >= {1}", ABatchTable.GetBatchPeriodDBName(), FCurrentLedgerPeriod);
                }
                else if (newPeriod > 0)
                {
                    workingFilter += String.Format(" AND {0} = {1}", ABatchTable.GetBatchPeriodDBName(), newPeriod);
                }
            }

            if (!BatchYearIsLoaded(newYear))
            {
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatch(FLedgerNumber, newYear, newPeriod));
            }

            if (FrbtEditing.Checked)
            {
                StringHelper.JoinAndAppend(ref workingFilter, String.Format("{0} = '{1}'",
                                                                            ABatchTable.GetBatchStatusDBName(),
                                                                            MFinanceConstants.BATCH_UNPOSTED),
                                           CommonJoinString.JOIN_STRING_SQL_AND);
            }
            else if (FrbtPosting.Checked)
            {
                StringHelper.JoinAndAppend(ref workingFilter,
                                           String.Format("({0} = '{1}') AND ({2} = {3}) AND ({2} <> 0) AND (({4} = 0) OR ({4} = {2}))",
                                                         ABatchTable.GetBatchStatusDBName(),
                                                         MFinanceConstants.BATCH_UNPOSTED,
                                                         ABatchTable.GetBatchCreditTotalDBName(),
                                                         ABatchTable.GetBatchDebitTotalDBName(),
                                                         ABatchTable.GetBatchControlTotalDBName()),
                                           CommonJoinString.JOIN_STRING_SQL_AND);
            }
            else //(FrbtAll.Checked)
            {
            }

            FFilterFindPanelObject.FilterPanelControls.SetBaseFilter(workingFilter, FrbtAll.Checked && showingAllPeriods);
            FPrevBaseFilter = workingFilter;

            AFilterString = workingFilter;
            StringHelper.JoinAndAppend(ref AFilterString, additionalFilter, CommonJoinString.JOIN_STRING_SQL_AND);

            FPrevFilter = AFilterString;
        }
Ejemplo n.º 4
0
        private void SubmitBatch(System.Object sender, EventArgs e)
        {
            if (FPreviouslySelectedDetailRow == null)
            {
                MessageBox.Show(Catalog.GetString("Please select a Batch before submitting."));
                return;
            }

            if (FPetraUtilsObject.HasChanges)
            {
                // save first, then submit
                if (!((TFrmRecurringGLBatch)ParentForm).SaveChanges())
                {
                    // saving failed, therefore do not try to post
                    MessageBox.Show(Catalog.GetString(
                                        "The recurring batch was not submitted due to problems during saving; ") + Environment.NewLine +
                                    Catalog.GetString("Please fix the batch first and then submit it."),
                                    Catalog.GetString("Submit Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            if ((FPreviouslySelectedDetailRow.BatchControlTotal != 0) &&
                (FPreviouslySelectedDetailRow.BatchDebitTotal != FPreviouslySelectedDetailRow.BatchControlTotal))
            {
                MessageBox.Show(String.Format(Catalog.GetString(
                                                  "The recurring gl batch total ({0}) for batch {1} does not equal the hash total ({2})."),
                                              FPreviouslySelectedDetailRow.BatchDebitTotal,
                                              FPreviouslySelectedDetailRow.BatchNumber,
                                              FPreviouslySelectedDetailRow.BatchControlTotal));

                txtDetailBatchControlTotal.Focus();
                txtDetailBatchControlTotal.SelectAll();
                return;
            }

            if (!LoadAllBatchData() || !AllowInactiveFieldValues(FPreviouslySelectedDetailRow.BatchNumber))
            {
                return;
            }

            TFrmRecurringGLBatchSubmit SubmitForm = new TFrmRecurringGLBatchSubmit(FPetraUtilsObject.GetForm());

            try
            {
                ParentForm.ShowInTaskbar = false;

                GLBatchTDS submitRecurringDS = (GLBatchTDS)FMainDS.Clone();
                int        currentBatch      = FPreviouslySelectedDetailRow.BatchNumber;

                submitRecurringDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadARecurringBatchAndContent(FLedgerNumber, currentBatch));

                SubmitForm.SubmitMainDS = submitRecurringDS;
                SubmitForm.ShowDialog();
            }
            finally
            {
                SubmitForm.Dispose();
                ParentForm.ShowInTaskbar = 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);
        }
Ejemplo n.º 6
0
        /// <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);
        }
Ejemplo n.º 7
0
        private static void UpdateTotalsOfBatchesAndJournals(ref GLBatchTDS AInspectDS,
            Int32 ALedgerNumber,
            int[] ABatchNumbers,
            bool ABatchTableInDataSet,
            bool AJournalTableInDataSet)
        {
            Int32 currJournalNumber = -1;

            ABatchRow currentBatchRow = null;

            foreach (int currBatchNumber in ABatchNumbers)
            {
                if (!ABatchTableInDataSet && !AJournalTableInDataSet)
                {
                    if (AInspectDS.ATransaction.Count > 0)
                    {
                        AInspectDS.ATransaction.DefaultView.RowFilter = String.Format("{0} = {1}",
                            ATransactionTable.GetBatchNumberDBName(),
                            currBatchNumber);

                        List <int>journalNums = new List <int>();

                        foreach (DataRowView dr in AInspectDS.ATransaction.DefaultView)
                        {
                            ATransactionRow tr = (ATransactionRow)dr.Row;

                            currJournalNumber = tr.JournalNumber;

                            if (!journalNums.Contains(currJournalNumber))
                            {
                                journalNums.Add(currJournalNumber);
                            }
                        }

                        if (journalNums.Count == 1)
                        {
                            AInspectDS.Merge(LoadABatch(ALedgerNumber, currBatchNumber), true);
                            AInspectDS.Merge(LoadAJournalATransaction(ALedgerNumber, currBatchNumber, currJournalNumber), true);
                        }
                        else
                        {
                            //Multiple journals
                            AInspectDS.Merge(LoadABatchAJournalATransaction(ALedgerNumber, currBatchNumber), true);
                        }
                    }
                    else
                    {
                        AInspectDS.Merge(LoadABatchAJournalATransaction(ALedgerNumber, currBatchNumber), true);
                    }
                }
                else if (!ABatchTableInDataSet)
                {
                    AInspectDS.AJournal.DefaultView.RowFilter = String.Format("{0} = {1}",
                        AJournalTable.GetBatchNumberDBName(),
                        currBatchNumber);

                    if (AInspectDS.AJournal.DefaultView.Count == 1)
                    {
                        currJournalNumber = ((AJournalRow)AInspectDS.AJournal.DefaultView[0].Row).JournalNumber;
                        AInspectDS.Merge(LoadABatch(ALedgerNumber, currBatchNumber), true);
                        AInspectDS.Merge(LoadAJournalATransaction(ALedgerNumber, currBatchNumber, currJournalNumber), true);
                    }
                    else
                    {
                        AInspectDS.Merge(LoadABatchAJournalATransaction(ALedgerNumber, currBatchNumber), true);
                    }
                }
                else if (!AJournalTableInDataSet)
                {
                    if (AInspectDS.ATransaction.Count > 0)
                    {
                        AInspectDS.ATransaction.DefaultView.RowFilter = String.Format("{0} = {1}",
                            ATransactionTable.GetBatchNumberDBName(),
                            currBatchNumber);

                        List <int>journalNums = new List <int>();

                        foreach (DataRowView dr in AInspectDS.ATransaction.DefaultView)
                        {
                            ATransactionRow tr = (ATransactionRow)dr.Row;

                            currJournalNumber = tr.JournalNumber;

                            if (!journalNums.Contains(currJournalNumber))
                            {
                                journalNums.Add(currJournalNumber);
                            }
                        }

                        if (journalNums.Count == 1)
                        {
                            AInspectDS.Merge(LoadAJournalATransaction(ALedgerNumber, currBatchNumber, currJournalNumber), true);
                        }
                        else
                        {
                            //Multiple journals
                            AInspectDS.Merge(LoadAJournalATransaction(ALedgerNumber, currBatchNumber), true);
                        }
                    }
                    else
                    {
                        AInspectDS.Merge(LoadAJournalATransaction(ALedgerNumber, currBatchNumber), true);
                    }
                }
                else
                {
                    AInspectDS.AJournal.DefaultView.RowFilter = String.Format("{0} = {1}",
                        AJournalTable.GetBatchNumberDBName(),
                        currBatchNumber);

                    if (AInspectDS.AJournal.DefaultView.Count == 1)
                    {
                        currJournalNumber = ((AJournalRow)AInspectDS.AJournal.DefaultView[0].Row).JournalNumber;
                        AInspectDS.Merge(LoadATransaction(ALedgerNumber, currBatchNumber, currJournalNumber), true);
                    }
                    else
                    {
                        //Multiple journals
                        AInspectDS.Merge(LoadATransactionForBatch(ALedgerNumber, currBatchNumber), true);
                    }
                }

                //Read current batch and update totals
                currentBatchRow = (ABatchRow)AInspectDS.ABatch.Rows.Find(new object[] { ALedgerNumber, currBatchNumber });

                UpdateTotalsOfBatch(ref AInspectDS, currentBatchRow);
            }
        }
Ejemplo n.º 8
0
        public static bool UpdateRecurringBatchTotalsWithLoad(ref GLBatchTDS AMainDS,
            Int32 ALedgerNumber, Int32 ABatchNumber)
        {
            #region Validate Arguments

            if (AMainDS == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Recurring 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

            bool AmountsUpdated = false;

            //Take a copy of the dataset but with specified batch only
            GLBatchTDS SingleBatchDS = GLRoutines.SingleBatchOnlyDataSet(ref AMainDS, ALedgerNumber, ABatchNumber);

            #region Validate Data

            if (SingleBatchDS.ARecurringBatch.Count == 0)
            {
                throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString(
                            "Function:{0} - GL Batch data for Batch {1} in Ledger {2} does not exist or could not be accessed!"),
                        Utilities.GetMethodName(true),
                        ABatchNumber,
                        ALedgerNumber));
            }

            #endregion Validate Data

            //Assign
            ARecurringBatchRow CurrentRecurringBatchRow = SingleBatchDS.ARecurringBatch[0];

            if (SingleBatchDS.ARecurringJournal.Count == 0)
            {
                //Try to load all data
                SingleBatchDS.Merge(LoadARecurringBatchARecurJournalARecurTransaction(ALedgerNumber, ABatchNumber));
            }
            else if (SingleBatchDS.ARecurringTransaction.Count == 0)
            {
                //Try to load all data
                SingleBatchDS.Merge(LoadARecurringTransaction(ALedgerNumber, ABatchNumber));
            }

            SingleBatchDS.AcceptChanges();

            AmountsUpdated = GLRoutines.UpdateRecurringBatchTotals(ref SingleBatchDS, ref CurrentRecurringBatchRow);

            if (AmountsUpdated)
            {
                SingleBatchDS.AcceptChanges();
                AMainDS.Merge(SingleBatchDS);
            }

            return AmountsUpdated;
        }
Ejemplo n.º 9
0
        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>
        /// Method to cancel a specified journal
        /// </summary>
        /// <param name="ACurrentJournalRow">The row to cancel</param>
        /// <param name="AJournalDescriptionTextBox">Pass a reference to a TextBox that is used to display the journal description text.  This is required
        /// to ensure that validation passes when the cancelled journal is saved.</param>
        /// <param name="AExchangeRateToBaseTextBox">Pass a reference to a TextBox that is used to display the exchange rate to base.  This is required
        /// to ensure that validation passes when the cancelled journal is saved.</param>
        /// <returns>True if the journal is cancelled.</returns>
        public bool CancelRow(GLBatchTDSAJournalRow ACurrentJournalRow,
                              TextBox AJournalDescriptionTextBox,
                              TTxtNumericTextBox AExchangeRateToBaseTextBox)
        {
            if ((ACurrentJournalRow == null) || !FMyForm.SaveChanges())
            {
                return(false);
            }

            int CurrentBatchNumber   = ACurrentJournalRow.BatchNumber;
            int CurrentJournalNumber = ACurrentJournalRow.JournalNumber;

            if ((MessageBox.Show(String.Format(Catalog.GetString(
                                                   "You have chosen to cancel this journal ({0}).\n\nDo you really want to cancel it?"),
                                               CurrentJournalNumber),
                                 Catalog.GetString("Confirm Cancel"),
                                 MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes))
            {
                try
                {
                    //clear any transactions currently being editied in the Transaction Tab
                    FMyForm.GetTransactionsControl().ClearCurrentSelection();

                    //Load any new data
                    FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransactionATransAnalAttrib(FLedgerNumber, CurrentBatchNumber,
                                                                                                     CurrentJournalNumber));

                    DataView dvAA = new DataView(FMainDS.ATransAnalAttrib);

                    dvAA.RowFilter = String.Format("{0}={1} AND {2}={3}",
                                                   ATransAnalAttribTable.GetBatchNumberDBName(),
                                                   CurrentBatchNumber,
                                                   ATransAnalAttribTable.GetJournalNumberDBName(),
                                                   CurrentJournalNumber);

                    //Delete Analysis Attribs
                    foreach (DataRowView dvr in dvAA)
                    {
                        dvr.Delete();
                    }

                    DataView dvTr = new DataView(FMainDS.ATransaction);

                    dvTr.RowFilter = String.Format("{0}={1} AND {2}={3}",
                                                   ATransactionTable.GetBatchNumberDBName(),
                                                   CurrentBatchNumber,
                                                   ATransactionTable.GetJournalNumberDBName(),
                                                   CurrentJournalNumber);

                    //Delete Transactions
                    foreach (DataRowView dvr in dvTr)
                    {
                        dvr.Delete();
                    }

                    ACurrentJournalRow.BeginEdit();
                    ACurrentJournalRow.JournalStatus = MFinanceConstants.BATCH_CANCELLED;

                    //Ensure validation passes
                    if (ACurrentJournalRow.JournalDescription.Length == 0)
                    {
                        AJournalDescriptionTextBox.Text = " ";
                    }

                    if (ACurrentJournalRow.ExchangeRateToBase == 0)
                    {
                        AExchangeRateToBaseTextBox.NumberValueDecimal = 1;
                    }

                    ABatchRow CurrentBatchRow = FMyForm.GetBatchControl().GetSelectedDetailRow();

                    CurrentBatchRow.BatchCreditTotal -= ACurrentJournalRow.JournalCreditTotal;
                    CurrentBatchRow.BatchDebitTotal  -= ACurrentJournalRow.JournalDebitTotal;

                    if (CurrentBatchRow.BatchControlTotal != 0)
                    {
                        CurrentBatchRow.BatchControlTotal -= ACurrentJournalRow.JournalCreditTotal;
                    }

                    ACurrentJournalRow.JournalCreditTotal = 0;
                    ACurrentJournalRow.JournalDebitTotal  = 0;
                    ACurrentJournalRow.EndEdit();

                    FPetraUtilsObject.SetChangedFlag();

                    //Need to call save
                    if (FMyForm.SaveChanges())
                    {
                        MessageBox.Show(Catalog.GetString("The journal has been cancelled successfully!"),
                                        Catalog.GetString("Success"),
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);

                        FMyForm.DisableTransactions();
                    }
                    else
                    {
                        // saving failed, therefore do not try to post
                        MessageBox.Show(Catalog.GetString(
                                            "The journal has been cancelled but there were problems during saving; ") + Environment.NewLine +
                                        Catalog.GetString("Please try and save the cancellation immediately."),
                                        Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    return(true);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            return(false);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// The main method that handles all filtering.  Every change on the filter panel causes this event to fire.
        /// It is important to manage the fact that this method may be called recursively and so nesting can be tricky!
        /// </summary>
        /// <param name="AFilterString">On entry this parameter contains the filter control's best guess for the current filter.
        /// The code can modify this string in the light of current control values.</param>
        public void ApplyFilterManual(ref string AFilterString)
        {
            if ((FCurrentLedgerYear < 0) || (FCurrentLedgerPeriod < 0))
            {
                return;
            }

            string WorkingFilter     = String.Empty;
            string AdditionalFilter  = String.Empty;
            bool   ShowingAllPeriods = false;

            // Remove the old base filter
            if (FPrevBaseFilter.Length > 0)
            {
                AdditionalFilter = AFilterString.Substring(FPrevBaseFilter.Length);

                if (AdditionalFilter.StartsWith(CommonJoinString.JOIN_STRING_SQL_AND))
                {
                    AdditionalFilter = AdditionalFilter.Substring(CommonJoinString.JOIN_STRING_SQL_AND.Length);
                }
            }

            int NewYear = FcmbYearEnding.GetSelectedInt32();

            if (NewYear != FPrevYearEnding)
            {
                FPrevYearEnding = NewYear;
                //TLogging.Log(String.Format("RefreshPeriods for Year {0}", newYear));
                RefreshPeriods(NewYear);

                // Apply the last good filter as we unwind the nesting
                AFilterString = FPrevFilter;
                return;
            }

            int NewPeriod = FcmbPeriod.GetSelectedInt32();

            if (NewYear == -1)
            {
                NewYear = FCurrentLedgerYear;

                WorkingFilter     = String.Format("{0}={1}", ABatchTable.GetBatchYearDBName(), NewYear);
                ShowingAllPeriods = true;
            }
            else
            {
                WorkingFilter = String.Format(
                    "{0}={1}",
                    ABatchTable.GetBatchYearDBName(), NewYear);

                if (NewPeriod == 0)  //All periods for year
                {
                    //Nothing to add to filter
                    ShowingAllPeriods = true;
                }
                else if (NewPeriod == -1)
                {
                    WorkingFilter += String.Format(" AND {0} >= {1}", ABatchTable.GetBatchPeriodDBName(), FCurrentLedgerPeriod);
                }
                else if (NewPeriod > 0)
                {
                    WorkingFilter += String.Format(" AND {0}={1}", ABatchTable.GetBatchPeriodDBName(), NewPeriod);
                }
            }

            if (!BatchYearIsLoaded(NewYear))
            {
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatch(FLedgerNumber, NewYear, NewPeriod));

                // Set the flag on the transaction tab to show the status dialog again when the transactions are loaded for a new year
                TFrmGLBatch glBatchForm = (TFrmGLBatch)FPetraUtilsObject.GetForm();
                glBatchForm.GetTransactionsControl().ShowStatusDialogOnLoad = true;
            }

            if (FrbtEditing.Checked)
            {
                StringHelper.JoinAndAppend(ref WorkingFilter, String.Format("{0}='{1}'",
                                                                            ABatchTable.GetBatchStatusDBName(),
                                                                            MFinanceConstants.BATCH_UNPOSTED),
                                           CommonJoinString.JOIN_STRING_SQL_AND);
            }
            else if (FrbtPosting.Checked)
            {
                StringHelper.JoinAndAppend(ref WorkingFilter,
                                           String.Format("({0}='{1}') AND ({2}={3}) AND ({2}<>0) AND (({4}=0) OR ({4}={2}))",
                                                         ABatchTable.GetBatchStatusDBName(),
                                                         MFinanceConstants.BATCH_UNPOSTED,
                                                         ABatchTable.GetBatchCreditTotalDBName(),
                                                         ABatchTable.GetBatchDebitTotalDBName(),
                                                         ABatchTable.GetBatchControlTotalDBName()),
                                           CommonJoinString.JOIN_STRING_SQL_AND);
            }
            else //(FrbtAll.Checked)
            {
            }

            FFilterFindPanelObject.FilterPanelControls.SetBaseFilter(WorkingFilter, FrbtAll.Checked && ShowingAllPeriods);
            FPrevBaseFilter = WorkingFilter;

            AFilterString = WorkingFilter;
            StringHelper.JoinAndAppend(ref AFilterString, AdditionalFilter, CommonJoinString.JOIN_STRING_SQL_AND);

            FPrevFilter = AFilterString;
        }
Ejemplo n.º 12
0
        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>
        /// 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);
        }
Ejemplo n.º 14
0
        /// <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(ARecurringBatchRow ARowToDelete, ref string ACompletionMessage)
        {
            //Assign default value(s)
            bool DeletionSuccessful = false;

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

            int BatchNumber = ARowToDelete.BatchNumber;

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

            BackupMainDS.Merge(FMainDS);

            if (ARowToDelete.RowState != DataRowState.Added)
            {
                //Reject any changes which may fail validation
                ARowToDelete.RejectChanges();
                ShowDetails(ARowToDelete);
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;

                ACompletionMessage = String.Format(Catalog.GetString("Batch no.: {0} deleted successfully."),
                                                   BatchNumber);

                // Delete the associated recurring transaction analysis attributes
                DataView viewRecurringTransAnalAttrib = new DataView(FMainDS.ARecurringTransAnalAttrib);
                viewRecurringTransAnalAttrib.RowFilter = String.Format("{0}={1} AND {2}={3}",
                                                                       ARecurringTransAnalAttribTable.GetLedgerNumberDBName(),
                                                                       FLedgerNumber,
                                                                       ARecurringTransAnalAttribTable.GetBatchNumberDBName(),
                                                                       BatchNumber);

                foreach (DataRowView row in viewRecurringTransAnalAttrib)
                {
                    row.Delete();
                }

                // Delete the associated recurring transactions
                DataView viewRecurringTransaction = new DataView(FMainDS.ARecurringTransaction);
                viewRecurringTransaction.RowFilter = String.Format("{0}={1} AND {2}={3}",
                                                                   ARecurringTransactionTable.GetLedgerNumberDBName(),
                                                                   FLedgerNumber,
                                                                   ARecurringTransactionTable.GetBatchNumberDBName(),
                                                                   BatchNumber);

                foreach (DataRowView row in viewRecurringTransaction)
                {
                    row.Delete();
                }

                // Delete the associated recurring journals
                DataView viewRecurringJournal = new DataView(FMainDS.ARecurringJournal);
                viewRecurringJournal.RowFilter = String.Format("{0}={1} AND {2}={3}",
                                                               ARecurringJournalTable.GetLedgerNumberDBName(),
                                                               FLedgerNumber,
                                                               ARecurringJournalTable.GetBatchNumberDBName(),
                                                               BatchNumber);

                foreach (DataRowView row in viewRecurringJournal)
                {
                    row.Delete();
                }

                // Delete the recurring batch row.
                ARowToDelete.Delete();

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

                //Revert to previous state
                FMainDS.Merge(BackupMainDS);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

            UpdateRecordNumberDisplay();

            return(DeletionSuccessful);
        }
        /// <summary>
        /// Method to cancel a specified journal
        /// </summary>
        /// <param name="AJournalRowToCancel">The row to cancel</param>
        /// <returns>True if the journal is cancelled.</returns>
        public bool CancelRow(GLBatchTDSAJournalRow AJournalRowToCancel)
        {
            bool CancellationSuccessful = false;

            if ((AJournalRowToCancel == null) || (AJournalRowToCancel.JournalStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return(false);
            }

            int  CurrentBatchNo   = AJournalRowToCancel.BatchNumber;
            int  CurrentJournalNo = AJournalRowToCancel.JournalNumber;
            bool CurrentJournalTransactionsLoadedAndCurrent = false;

            string CancelMessage     = string.Empty;
            string CompletionMessage = string.Empty;

            CancelMessage = String.Format(Catalog.GetString("Are you sure you want to cancel GL Journal {0} in Batch {1}?"),
                                          CurrentJournalNo,
                                          CurrentBatchNo);

            if ((MessageBox.Show(CancelMessage,
                                 Catalog.GetString("Confirm Cancel"),
                                 MessageBoxButtons.YesNo,
                                 MessageBoxIcon.Question,
                                 MessageBoxDefaultButton.Button2) != System.Windows.Forms.DialogResult.Yes))
            {
                return(false);
            }

            //Backup the Dataset for reversion purposes
            GLBatchTDS BackupMainDS = null;

            try
            {
                FMyForm.Cursor = Cursors.WaitCursor;

                //Backup the Dataset for reversion purposes
                BackupMainDS = (GLBatchTDS)FMainDS.GetChangesTyped(false);

                //Don't run an inactive fields check on this batch
                FMyForm.GetBatchControl().UpdateUnpostedBatchDictionary(CurrentBatchNo);

                //Check if current batch details are currently loaded
                CurrentJournalTransactionsLoadedAndCurrent = (FMyForm.GetTransactionsControl().FBatchNumber == CurrentBatchNo);

                //Save and check for inactive values in other unsaved Batches
                FPetraUtilsObject.SetChangedFlag();

                if (!FMyForm.SaveChangesManual(FMyForm.FCurrentGLBatchAction, false, !CurrentJournalTransactionsLoadedAndCurrent))
                {
                    FMyForm.GetBatchControl().UpdateUnpostedBatchDictionary();

                    CompletionMessage = String.Format(Catalog.GetString("Journal {0} in GL Batch {1} has not been cancelled."),
                                                      CurrentJournalNo,
                                                      CurrentBatchNo);

                    MessageBox.Show(CompletionMessage,
                                    Catalog.GetString("GL Journal Cancellation"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);

                    return(false);
                }

                //Remove any changes, which may cause validation issues, before cancelling
                FMyForm.GetJournalsControl().PrepareJournalDataForCancelling(CurrentBatchNo, CurrentJournalNo, true);

                if (CurrentJournalTransactionsLoadedAndCurrent)
                {
                    //Clear any transactions currently being edited in the Transaction Tab
                    FMyForm.GetTransactionsControl().ClearCurrentSelection(CurrentBatchNo);
                }

                //Delete transactions and attributes for current jouernal only
                FMyForm.GetTransactionsControl().DeleteTransactionData(CurrentBatchNo, CurrentJournalNo);

                //Edit current Journal
                decimal journalCreditTotal = AJournalRowToCancel.JournalCreditTotal;
                decimal journalDebitTotal  = AJournalRowToCancel.JournalDebitTotal;
                AJournalRowToCancel.BeginEdit();
                AJournalRowToCancel.JournalStatus         = MFinanceConstants.BATCH_CANCELLED;
                AJournalRowToCancel.LastTransactionNumber = 0;
                AJournalRowToCancel.JournalCreditTotal    = 0;
                AJournalRowToCancel.JournalDebitTotal     = 0;
                AJournalRowToCancel.EndEdit();

                //Edit current Batch
                ABatchRow CurrentBatchRow   = FMyForm.GetBatchControl().GetSelectedDetailRow();
                decimal   batchControlTotal = CurrentBatchRow.BatchControlTotal;
                CurrentBatchRow.BeginEdit();
                CurrentBatchRow.BatchCreditTotal  -= journalCreditTotal;
                CurrentBatchRow.BatchDebitTotal   -= journalDebitTotal;
                CurrentBatchRow.BatchControlTotal -= (batchControlTotal != 0 ? journalCreditTotal : 0);
                CurrentBatchRow.EndEdit();

                FPetraUtilsObject.SetChangedFlag();
                FMyForm.SaveChangesManual();

                CompletionMessage = String.Format(Catalog.GetString("Journal no.: {0} cancelled successfully."),
                                                  CurrentJournalNo);

                MessageBox.Show(CompletionMessage,
                                Catalog.GetString("Journal Cancelled"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);

                FMyForm.DisableTransactions();

                CancellationSuccessful = true;
            }
            catch (Exception ex)
            {
                //Revert to previous state
                if (BackupMainDS != null)
                {
                    FMainDS.RejectChanges();
                    FMainDS.Merge(BackupMainDS);

                    FMyForm.GetJournalsControl().ShowDetailsRefresh();
                }

                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                FMyForm.Cursor = Cursors.Default;
            }

            return(CancellationSuccessful);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Need to ensure that the Analysis Attributes grid has all the entries
        /// that are required for the selected account.
        /// There may or may not already be attribute assignments for this transaction.
        /// </summary>
        /// <param name="AGLBatchDS"></param>
        /// <param name="AGLSetupDS">Can be null.  If supplied the code will use this to discover the required attributes without making a trip to the server.
        /// Otherwise a server request is made.</param>
        /// <param name="AAccountCode"></param>
        /// <param name="ATransactionNumber"></param>
        /// <param name="ACheckBatchStatus"></param>
        /// <returns></returns>
        public bool TransAnalAttrRequiredUpdating(GLBatchTDS AGLBatchDS,
            GLSetupTDS AGLSetupDS,
            string AAccountCode,
            int ATransactionNumber,
            bool ACheckBatchStatus = true)
        {
            #region Validate Arguments

            if (AGLBatchDS == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString("Function:{0} - The GL Batch dataset is null!"),
                        Utilities.GetMethodName(true)));
            }
            else if (ACheckBatchStatus && ((AGLBatchDS.ABatch == null) || (AGLBatchDS.ABatch.Count == 0)))
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The GL Batch table in the dataset was required but is null or empty!"),
                        Utilities.GetMethodName(true)));
            }
            else if (AGLBatchDS.ATransAnalAttrib == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The GL Transaction Analysis Attributes table in the dataset is null or empty!"),
                        Utilities.GetMethodName(true)));
            }
            else if (AAccountCode.Length == 0)
            {
                return false;
            }
            else if (ATransactionNumber <= 0)
            {
                throw new ArgumentException(String.Format(Catalog.GetString("Function:{0} - The Transaction number must be greater than 0!"),
                        Utilities.GetMethodName(true)));
            }

            #endregion Validate Arguments

            try
            {
                if (ACheckBatchStatus)
                {
                    //Check Batch Status and return if not unposted
                    string batchFilter = String.Format("{0}={1}",
                        ABatchTable.GetBatchNumberDBName(),
                        FBatchNumber);

                    DataRow[] batchRows = AGLBatchDS.ABatch.Select(batchFilter);

                    #region Validate Data

                    if (batchRows.Length != 1)
                    {
                        throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                                    "Function:{0} - GL Batch number {1} does not exist in the table!"),
                                Utilities.GetMethodName(true),
                                FBatchNumber));
                    }

                    #endregion Validate Data

                    ABatchRow batchRow = (ABatchRow)batchRows[0];

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

                //See what analysis attribute codes are required for the specified account code in this ledger
                StringCollection requiredAnalAttrCodes = new StringCollection();
                StringCollection currentAnalAttrCodes = new StringCollection();
                StringCollection analAttrCodesToDelete = new StringCollection();
                StringCollection analAttrCodesToAdd = new StringCollection();

                if ((AGLSetupDS != null) && (AGLSetupDS.AAnalysisAttribute != null))
                {
                    // This makes use of the supplied GLSetupTDS
                    AGLSetupDS.AAnalysisAttribute.DefaultView.RowFilter = String.Format("{0}='{1}' And {2}=true",
                        AAnalysisAttributeTable.GetAccountCodeDBName(),
                        AAccountCode,
                        AAnalysisAttributeTable.GetActiveDBName());

                    foreach (DataRowView drv in AGLSetupDS.AAnalysisAttribute.DefaultView)
                    {
                        requiredAnalAttrCodes.Add(drv.Row[AAnalysisAttributeTable.ColumnAnalysisTypeCodeId].ToString());
                    }
                }
                else
                {
                    //The server call is needed
                    requiredAnalAttrCodes = TRemote.MFinance.Setup.WebConnectors.RequiredAnalysisAttributesForAccount(FLedgerNumber,
                        AAccountCode,
                        true);
                }

                //Populate current codes and which ones to add or delete
                // (Check if loading required)
                SetTransAnalAttributeDefaultView(AGLBatchDS, ATransactionNumber);

                if (AGLBatchDS.ATransAnalAttrib.DefaultView.Count == 0)
                {
                    AGLBatchDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransAnalAttribForJournal(FLedgerNumber, FBatchNumber, FJournalNumber));
                }

                foreach (DataRowView drv in AGLBatchDS.ATransAnalAttrib.DefaultView)
                {
                    ATransAnalAttribRow transAnalAttrRow = (ATransAnalAttribRow)drv.Row;

                    //Populate the current codes string collection
                    string analAttrCode = transAnalAttrRow.AnalysisTypeCode;
                    currentAnalAttrCodes.Add(analAttrCode);

                    if ((requiredAnalAttrCodes.Count == 0) || !requiredAnalAttrCodes.Contains(analAttrCode))
                    {
                        //Populate the invalid codes string collection
                        analAttrCodesToDelete.Add(analAttrCode);
                    }
                }

                foreach (string analAttrCode in requiredAnalAttrCodes)
                {
                    if (!currentAnalAttrCodes.Contains(analAttrCode))
                    {
                        //Populate the needed codes string collection
                        analAttrCodesToAdd.Add(analAttrCode);
                    }
                }

                //count collection sizes
                int codesNumToAdd = analAttrCodesToAdd.Count;
                int codesNumToDelete = analAttrCodesToDelete.Count;

                //Nothing to add or take away
                if ((codesNumToAdd == 0) && (codesNumToDelete == 0))
                {
                    //No difference detected
                    return false;
                }

                //Delete invalid ones
                if (codesNumToDelete > 0)
                {
                    foreach (DataRowView drv in AGLBatchDS.ATransAnalAttrib.DefaultView)
                    {
                        ATransAnalAttribRow attrRowCurrent = (ATransAnalAttribRow)drv.Row;

                        if (analAttrCodesToDelete.Contains(attrRowCurrent.AnalysisTypeCode))
                        {
                            attrRowCurrent.Delete();
                        }
                    }
                }

                //Add missing ones
                if (codesNumToAdd > 0)
                {
                    foreach (string analysisTypeCode in analAttrCodesToAdd)
                    {
                        ATransAnalAttribRow newRow = AGLBatchDS.ATransAnalAttrib.NewRowTyped(true);
                        newRow.LedgerNumber = FLedgerNumber;
                        newRow.BatchNumber = FBatchNumber;
                        newRow.JournalNumber = FJournalNumber;
                        newRow.TransactionNumber = ATransactionNumber;
                        newRow.AnalysisTypeCode = analysisTypeCode;
                        newRow.AccountCode = AAccountCode;
                        newRow.AnalysisAttributeValue = string.Empty;

                        AGLBatchDS.ATransAnalAttrib.Rows.Add(newRow);
                    }
                }
            }
            catch (Exception ex)
            {
                TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}",
                        Utilities.GetMethodSignature(),
                        Environment.NewLine,
                        ex.Message));
                throw ex;
            }

            return true;
        }
        /// <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);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Need to ensure that the Analysis Attributes grid has all the entries
        /// that are required for the selected account.
        /// There may or may not already be attribute assignments for this transaction.
        /// </summary>
        /// <param name="AGLBatchDS"></param>
        /// <param name="AAccountCode"></param>
        /// <param name="ATransactionNumber"></param>
        /// <returns></returns>
        public bool RecurringTransAnalAttrRequiredUpdating(GLBatchTDS AGLBatchDS,
            string AAccountCode,
            int ATransactionNumber)
        {
            #region Validate Arguments

            if (AGLBatchDS == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Recurring GL Batch dataset is null!"),
                        Utilities.GetMethodName(true)));
            }
            else if ((AGLBatchDS.ARecurringBatch == null) || (AGLBatchDS.ARecurringBatch.Count == 0))
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Recurring GL Batch table in the dataset is null or empty!"),
                        Utilities.GetMethodName(true)));
            }
            else if ((AGLBatchDS.ARecurringTransaction == null) || (AGLBatchDS.ARecurringTransaction.Count == 0))
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Recurring GL Transaction table in the dataset is null or empty!"),
                        Utilities.GetMethodName(true)));
            }
            else if (AGLBatchDS.ARecurringTransAnalAttrib == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Recurring GL Transaction Analysis Attributes table in the dataset is null or empty!"),
                        Utilities.GetMethodName(true)));
            }
            else if (AAccountCode.Length == 0)
            {
                return false;
            }
            else if (ATransactionNumber <= 0)
            {
                throw new ArgumentException(String.Format(Catalog.GetString("Function:{0} - The Transaction number must be greater than 0!"),
                        Utilities.GetMethodName(true)));
            }

            #endregion Validate Arguments

            try
            {
                //See what analysis attribute codes are required for the specified account code in this ledger
                StringCollection requiredAnalAttrCodes = new StringCollection();
                StringCollection currentAnalAttrCodes = new StringCollection();
                StringCollection analAttrCodesToDelete = new StringCollection();
                StringCollection analAttrCodesToAdd = new StringCollection();

                //The server call is needed
                requiredAnalAttrCodes = TRemote.MFinance.Setup.WebConnectors.RequiredAnalysisAttributesForAccount(FLedgerNumber,
                    AAccountCode,
                    true);

                //Populate current codes and which ones to add or delete
                // (Check if loading required)
                SetRecurringTransAnalAttributeDefaultView(AGLBatchDS, ATransactionNumber);

                //First check if loading required
                if (AGLBatchDS.ARecurringTransAnalAttrib.DefaultView.Count == 0)
                {
                    AGLBatchDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadARecurringTransAnalAttribForJournal(FLedgerNumber, FBatchNumber,
                            FJournalNumber));
                }

                foreach (DataRowView drv in AGLBatchDS.ARecurringTransAnalAttrib.DefaultView)
                {
                    ARecurringTransAnalAttribRow transAnalAttrRow = (ARecurringTransAnalAttribRow)drv.Row;

                    string analAttrCode = transAnalAttrRow.AnalysisTypeCode;

                    //Populate the current codes string collection
                    currentAnalAttrCodes.Add(analAttrCode);

                    if ((requiredAnalAttrCodes.Count == 0) || !requiredAnalAttrCodes.Contains(analAttrCode))
                    {
                        //Populate the invalid codes string collection
                        analAttrCodesToDelete.Add(analAttrCode);
                    }
                }

                foreach (string analAttrCode in requiredAnalAttrCodes)
                {
                    if (!currentAnalAttrCodes.Contains(analAttrCode))
                    {
                        //Populate the needed codes string collection
                        analAttrCodesToAdd.Add(analAttrCode);
                    }
                }

                //count collection sizes
                int codesNumToAdd = analAttrCodesToAdd.Count;
                int codesNumToDelete = analAttrCodesToDelete.Count;

                //Nothing to add or take away
                if ((codesNumToAdd == 0) && (codesNumToDelete == 0))
                {
                    //No difference detected
                    return false;
                }

                //Delete invalid ones
                if (codesNumToDelete > 0)
                {
                    foreach (DataRowView drv in AGLBatchDS.ARecurringTransAnalAttrib.DefaultView)
                    {
                        ARecurringTransAnalAttribRow attrRowCurrent = (ARecurringTransAnalAttribRow)drv.Row;

                        if (analAttrCodesToDelete.Contains(attrRowCurrent.AnalysisTypeCode))
                        {
                            attrRowCurrent.Delete();
                        }
                    }
                }

                //Add missing ones
                if (codesNumToAdd > 0)
                {
                    //Access the transaction row
                    string transFilter = String.Format("{0}={1} And {2}={3} And {4}={5}",
                        ARecurringTransactionTable.GetBatchNumberDBName(),
                        FBatchNumber,
                        ARecurringTransactionTable.GetJournalNumberDBName(),
                        FJournalNumber,
                        ARecurringTransactionTable.GetTransactionNumberDBName(),
                        ATransactionNumber);

                    DataRow[] transRows = AGLBatchDS.ARecurringTransaction.Select(transFilter);

                    #region Validate Data

                    if (transRows.Length != 1)
                    {
                        throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(
                                Catalog.GetString(
                                    "Function:{0} - Transaction number {1} in Recurring GL Batch {2} and Journal {3} does not exist in the table!"),
                                Utilities.GetMethodName(true),
                                FBatchNumber,
                                FJournalNumber,
                                ATransactionNumber));
                    }

                    #endregion Validate Data

                    ARecurringTransactionRow transRow = (ARecurringTransactionRow)transRows[0];

                    foreach (string analysisTypeCode in analAttrCodesToAdd)
                    {
                        ARecurringTransAnalAttribRow newRow = AGLBatchDS.ARecurringTransAnalAttrib.NewRowTyped(true);
                        newRow.LedgerNumber = FLedgerNumber;
                        newRow.BatchNumber = FBatchNumber;
                        newRow.JournalNumber = FJournalNumber;
                        newRow.TransactionNumber = ATransactionNumber;
                        newRow.AnalysisTypeCode = analysisTypeCode;
                        newRow.AccountCode = AAccountCode;
                        newRow.CostCentreCode = transRow.CostCentreCode;
                        newRow.AnalysisAttributeValue = string.Empty;

                        AGLBatchDS.ARecurringTransAnalAttrib.Rows.Add(newRow);
                    }
                }
            }
            catch (Exception ex)
            {
                TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}",
                        Utilities.GetMethodSignature(),
                        Environment.NewLine,
                        ex.Message));
                throw ex;
            }

            return true;
        }
Ejemplo n.º 19
0
        /// <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);
        }
Ejemplo n.º 20
0
        private void SubmitBatch(System.Object sender, EventArgs e)
        {
            if ((GetSelectedRowIndex() < 0) || (FPreviouslySelectedDetailRow == null))
            {
                MessageBox.Show(Catalog.GetString("Please select a Recurring Batch before submitting!"));
                return;
            }

            TFrmRecurringGLBatch       MainForm   = (TFrmRecurringGLBatch)ParentForm;
            TFrmStatusDialog           dlgStatus  = new TFrmStatusDialog(FPetraUtilsObject.GetForm());
            TFrmRecurringGLBatchSubmit SubmitForm = null;

            bool LoadDialogVisible = false;

            try
            {
                Cursor = Cursors.WaitCursor;
                MainForm.FCurrentGLBatchAction = TGLBatchEnums.GLBatchAction.SUBMITTING;

                dlgStatus.Show();
                LoadDialogVisible       = true;
                dlgStatus.Heading       = String.Format(Catalog.GetString("Recurring GL Batch {0}"), FSelectedBatchNumber);
                dlgStatus.CurrentStatus = Catalog.GetString("Loading journals and transactions ready for submitting...");

                if (!LoadAllBatchData())
                {
                    Cursor = Cursors.Default;
                    MessageBox.Show(Catalog.GetString("The Recurring GL Batch is empty!"),
                                    Catalog.GetString("Submit GL Batch"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Stop);

                    dlgStatus.Close();
                    LoadDialogVisible = false;
                    return;
                }

                dlgStatus.Close();
                LoadDialogVisible = false;

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

                //Save and check for inactive values
                if (FPetraUtilsObject.HasChanges)
                {
                    //Keep this conditional check separate from the one above so that it only gets called
                    // when necessary and doesn't result in the executon of the same method
                    if (!MainForm.SaveChangesManual(MainForm.FCurrentGLBatchAction))
                    {
                        return;
                    }
                }
                else
                {
                    //This has to be called here because if there are no changes then the DataSavingValidating
                    // method which calls the method below, will not run.
                    if (!MainForm.GetTransactionsControl().AllowInactiveFieldValues(FLedgerNumber,
                                                                                    FSelectedBatchNumber, MainForm.FCurrentGLBatchAction))
                    {
                        return;
                    }
                }

                if ((FPreviouslySelectedDetailRow.BatchControlTotal != 0) &&
                    (FPreviouslySelectedDetailRow.BatchDebitTotal != FPreviouslySelectedDetailRow.BatchControlTotal))
                {
                    MessageBox.Show(String.Format(Catalog.GetString(
                                                      "The recurring gl batch total ({0}) for batch {1} does not equal the hash total ({2})."),
                                                  FPreviouslySelectedDetailRow.BatchDebitTotal,
                                                  FPreviouslySelectedDetailRow.BatchNumber,
                                                  FPreviouslySelectedDetailRow.BatchControlTotal));

                    txtDetailBatchControlTotal.Focus();
                    txtDetailBatchControlTotal.SelectAll();
                    return;
                }

                SubmitForm = new TFrmRecurringGLBatchSubmit(FPetraUtilsObject.GetForm());

                ParentForm.ShowInTaskbar = false;

                GLBatchTDS submitRecurringDS = (GLBatchTDS)FMainDS.Clone();
                int        currentBatch      = FPreviouslySelectedDetailRow.BatchNumber;

                submitRecurringDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadARecurringBatchAndRelatedTables(FLedgerNumber, FSelectedBatchNumber));

                SubmitForm.SubmitMainDS = submitRecurringDS;
                SubmitForm.ShowDialog();
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                if (LoadDialogVisible)
                {
                    dlgStatus.Close();
                    LoadDialogVisible = false;
                }

                if (SubmitForm != null)
                {
                    SubmitForm.Dispose();
                    ParentForm.ShowInTaskbar = true;
                }

                MainForm.FCurrentGLBatchAction = TGLBatchEnums.GLBatchAction.NONE;
                Cursor = Cursors.Default;
            }

            if (FPetraUtilsObject.HasChanges)
            {
                // save first, then submit
                if (!((TFrmRecurringGLBatch)ParentForm).SaveChanges())
                {
                    // saving failed, therefore do not try to post
                    MessageBox.Show(Catalog.GetString(
                                        "The recurring batch was not submitted due to problems during saving; ") + Environment.NewLine +
                                    Catalog.GetString("Please fix the batch first and then submit it."),
                                    Catalog.GetString("Submit Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
        }
Ejemplo n.º 21
0
        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;
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Method to cancel a specified batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The row to cancel</param>
        /// <param name="ABatchDescriptionTextBox">Pass a reference to a TextBox that is used to display the batch description text.  This is required
        /// to ensure that validation passes when the cancelled batch is saved.</param>
        /// <returns></returns>
        public bool CancelBatch(ABatchRow ACurrentBatchRow, TextBox ABatchDescriptionTextBox)
        {
            if ((ACurrentBatchRow == null) || !FMyForm.SaveChanges())
            {
                return(false);
            }

            int CurrentBatchNumber = ACurrentBatchRow.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))
            {
                try
                {
                    //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.LoadATransactionForBatch(FLedgerNumber, CurrentBatchNumber));
                    FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransAnalAttribForBatch(FLedgerNumber, CurrentBatchNumber));

                    //Delete transactions
                    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.EndEdit();
                        }
                    }

                    // Edit the batch row
                    ACurrentBatchRow.BeginEdit();

                    //Ensure validation passes
                    if (ACurrentBatchRow.BatchDescription.Length == 0)
                    {
                        ABatchDescriptionTextBox.Text = " ";
                    }

                    ACurrentBatchRow.BatchCreditTotal  = 0;
                    ACurrentBatchRow.BatchDebitTotal   = 0;
                    ACurrentBatchRow.BatchControlTotal = 0;
                    ACurrentBatchRow.BatchStatus       = MFinanceConstants.BATCH_CANCELLED;

                    ACurrentBatchRow.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);

                        return(true);
                    }
                    else
                    {
                        // saving failed, therefore do not try to post
                        MessageBox.Show(Catalog.GetString(
                                            "The batch has been cancelled but there were problems during saving; ") + Environment.NewLine +
                                        Catalog.GetString("Please try and save the cancellation immediately."),
                                        Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            return(false);
        }
        /// <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>
        /// 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);
        }
        private void ProcessNewlyAddedJournalRowForDeletion(int AJournalNumberToDelete)
        {
            GLBatchTDS BackupDS = (GLBatchTDS)FMainDS.Copy();

            BackupDS.Merge(FMainDS);

            try
            {
                // Delete the associated recurring transaction analysis attributes
                DataView attributesDV = new DataView(FMainDS.ARecurringTransAnalAttrib);
                attributesDV.RowFilter = string.Format("{0}={1} And {2}={3}",
                                                       ARecurringTransAnalAttribTable.GetBatchNumberDBName(),
                                                       FBatchNumber,
                                                       ARecurringTransAnalAttribTable.GetJournalNumberDBName(),
                                                       AJournalNumberToDelete
                                                       );

                foreach (DataRowView attrDRV in attributesDV)
                {
                    ARecurringTransAnalAttribRow attrRow = (ARecurringTransAnalAttribRow)attrDRV.Row;
                    attrRow.Delete();
                }

                // Delete the associated recurring transactions
                DataView transactionsDV = new DataView(FMainDS.ARecurringTransaction);
                transactionsDV.RowFilter = String.Format("{0}={1} And {2}={3}",
                                                         ARecurringTransactionTable.GetBatchNumberDBName(),
                                                         FBatchNumber,
                                                         ARecurringTransactionTable.GetJournalNumberDBName(),
                                                         AJournalNumberToDelete
                                                         );

                foreach (DataRowView transDRV in transactionsDV)
                {
                    ARecurringTransactionRow tranRow = (ARecurringTransactionRow)transDRV.Row;
                    tranRow.Delete();
                }

                // Delete the recurring journal
                DataView journalDV = new DataView(FMainDS.ARecurringJournal);
                journalDV.RowFilter = String.Format("{0}={1} And {2}={3}",
                                                    ARecurringJournalTable.GetBatchNumberDBName(),
                                                    FBatchNumber,
                                                    ARecurringJournalTable.GetJournalNumberDBName(),
                                                    AJournalNumberToDelete
                                                    );

                foreach (DataRowView journalDRV in journalDV)
                {
                    ARecurringJournalRow jrnlRow = (ARecurringJournalRow)journalDRV.Row;
                    jrnlRow.Delete();
                }

                //Renumber the journals, transactions and attributes
                DataView attributesDV2 = new DataView(FMainDS.ARecurringTransAnalAttrib);
                attributesDV2.RowFilter = string.Format("{0}={1} And {2}>{3}",
                                                        ARecurringTransAnalAttribTable.GetBatchNumberDBName(),
                                                        FBatchNumber,
                                                        ARecurringTransAnalAttribTable.GetJournalNumberDBName(),
                                                        AJournalNumberToDelete);
                attributesDV2.Sort = String.Format("{0} ASC", ARecurringTransAnalAttribTable.GetJournalNumberDBName());

                foreach (DataRowView attrDRV in attributesDV2)
                {
                    ARecurringTransAnalAttribRow attrRow = (ARecurringTransAnalAttribRow)attrDRV.Row;
                    attrRow.JournalNumber--;
                }

                DataView transactionsDV2 = new DataView(FMainDS.ARecurringTransaction);
                transactionsDV2.RowFilter = string.Format("{0}={1} And {2}>{3}",
                                                          ARecurringTransactionTable.GetBatchNumberDBName(),
                                                          FBatchNumber,
                                                          ARecurringTransactionTable.GetJournalNumberDBName(),
                                                          AJournalNumberToDelete);
                transactionsDV2.Sort = String.Format("{0} ASC", ARecurringTransactionTable.GetJournalNumberDBName());

                foreach (DataRowView transDRV in transactionsDV2)
                {
                    ARecurringTransactionRow tranRow = (ARecurringTransactionRow)transDRV.Row;
                    tranRow.JournalNumber--;
                }

                DataView journalDV2 = new DataView(FMainDS.ARecurringJournal);
                journalDV2.RowFilter = string.Format("{0}={1} And {2}>{3}",
                                                     ARecurringJournalTable.GetBatchNumberDBName(),
                                                     FBatchNumber,
                                                     ARecurringJournalTable.GetJournalNumberDBName(),
                                                     AJournalNumberToDelete);
                journalDV2.Sort = String.Format("{0} ASC", ARecurringJournalTable.GetJournalNumberDBName());

                foreach (DataRowView jrnlDRV in journalDV2)
                {
                    ARecurringJournalRow jrnlRow = (ARecurringJournalRow)jrnlDRV.Row;
                    jrnlRow.JournalNumber--;
                }
            }
            catch (Exception ex)
            {
                FMainDS.Merge(BackupDS);

                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
        }
        /// <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);
            }
        }