Beispiel #1
0
        /// <summary>
        /// make sure the correct journal number is assigned and the batch.lastJournal is updated
        /// </summary>
        /// <param name="ANewRow"></param>
        public void NewRowManual(ref GLBatchTDSAJournalRow ANewRow)
        {
            if ((ANewRow == null) || (FLedgerNumber == -1))
            {
                return;
            }

            ALedgerRow LedgerRow =
                ((ALedgerTable)TDataCache.TMFinance.GetCacheableFinanceTable(
                     TCacheableFinanceTablesEnum.LedgerDetails, FLedgerNumber))[0];

            ANewRow.LedgerNumber  = FBatchRow.LedgerNumber;
            ANewRow.BatchNumber   = FBatchRow.BatchNumber;
            ANewRow.JournalNumber = ++FBatchRow.LastJournal;

            // manually created journals are all GL
            ANewRow.SubSystemCode       = MFinanceConstants.SUB_SYSTEM_GL;
            ANewRow.TransactionTypeCode = MFinanceConstants.STANDARD_JOURNAL;

            ANewRow.TransactionCurrency    = LedgerRow.BaseCurrency;
            ANewRow.ExchangeRateToBase     = 1;
            ANewRow.DateEffective          = FBatchRow.DateEffective;
            ANewRow.JournalPeriod          = FBatchRow.BatchPeriod;
            ANewRow.JournalDebitTotalBase  = 0.0M;
            ANewRow.JournalCreditTotalBase = 0.0M;
        }
Beispiel #2
0
        /// <summary>
        /// Calculate the base amount for the transactions, and update the totals for the journals and the current batch
        /// </summary>
        /// <param name="AMainDS"></param>
        /// <param name="ACurrentBatch"></param>
        public static void UpdateTotalsOfBatch(ref GLBatchTDS AMainDS,
                                               ABatchRow ACurrentBatch)
        {
            decimal BatchDebitTotal  = 0.0m;
            decimal BatchCreditTotal = 0.0m;

            DataView jnlDataView = new DataView(AMainDS.AJournal);

            jnlDataView.RowFilter = String.Format("{0}={1}",
                                                  AJournalTable.GetBatchNumberDBName(),
                                                  ACurrentBatch.BatchNumber);

            foreach (DataRowView journalView in jnlDataView)
            {
                GLBatchTDSAJournalRow journalRow = (GLBatchTDSAJournalRow)journalView.Row;

                UpdateTotalsOfJournal(ref AMainDS, ref journalRow);

                BatchDebitTotal  += journalRow.JournalDebitTotal;
                BatchCreditTotal += journalRow.JournalCreditTotal;
            }

            if ((ACurrentBatch.BatchDebitTotal != BatchDebitTotal) ||
                (ACurrentBatch.BatchCreditTotal != BatchCreditTotal))
            {
                ACurrentBatch.BatchDebitTotal  = BatchDebitTotal;
                ACurrentBatch.BatchCreditTotal = BatchCreditTotal;
            }
        }
Beispiel #3
0
        /// <summary>
        /// Update the specified Journal's LastTransaction number. Assumes all necessary data is loaded for Journal
        /// </summary>
        /// <param name="AMainDS">ATransactions are filtered on current journal</param>
        /// <param name="ACurrentJournal"></param>
        /// <returns>false if no change to journal totals</returns>
        public static bool UpdateJournalLastTransaction(ref GLBatchTDS AMainDS,
                                                        ref GLBatchTDSAJournalRow ACurrentJournal)
        {
            #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 (ACurrentJournal == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                                                                                         "Function:{0} - The Journal row does not exist or is empty!"),
                                                                                     Utilities.GetMethodName(true)));
            }
            else if (ACurrentJournal.JournalStatus != MFinanceConstants.BATCH_UNPOSTED)
            {
                TLogging.Log(String.Format("Function:{0} - Tried to update totals for non-Unposted Batch:{1} and Journal:{2}",
                                           Utilities.GetMethodName(true),
                                           ACurrentJournal.BatchNumber,
                                           ACurrentJournal.JournalNumber));
                return(false);
            }

            #endregion Validate Arguments

            bool RowUpdated = false;

            int ActualLastTransNumber = 0;

            DataView TransDV = new DataView(AMainDS.ATransaction);
            TransDV.RowFilter = String.Format("{0}={1} And {2}={3}",
                                              ATransactionTable.GetBatchNumberDBName(),
                                              ACurrentJournal.BatchNumber,
                                              ATransactionTable.GetJournalNumberDBName(),
                                              ACurrentJournal.JournalNumber);

            TransDV.Sort = String.Format("{0} DESC",
                                         ATransactionTable.GetTransactionNumberDBName());

            foreach (DataRowView drv in TransDV)
            {
                ATransactionRow transRow = (ATransactionRow)drv.Row;

                //Run once only
                ActualLastTransNumber = transRow.TransactionNumber;
                break;
            }

            if (ACurrentJournal.LastTransactionNumber != ActualLastTransNumber)
            {
                ACurrentJournal.BeginEdit();
                ACurrentJournal.LastTransactionNumber = ActualLastTransNumber;
                ACurrentJournal.EndEdit();
                RowUpdated = true;
            }

            return(RowUpdated);
        }
        /// <summary>
        /// Re-show the specified row
        /// </summary>
        /// <param name="AModifiedJournalRow"></param>
        /// <param name="ARedisplay"></param>
        public void UndoModifiedJournalRow(GLBatchTDSAJournalRow AModifiedJournalRow, bool ARedisplay)
        {
            //Check if new row or not
            if (AModifiedJournalRow.RowState == DataRowState.Added)
            {
                return;
            }

            AModifiedJournalRow.RejectChanges();

            if (ARedisplay)
            {
                ShowDetails(AModifiedJournalRow);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Calculate the base amount for the transactions, and update the totals for the journals and the current batch
        ///   Assumes that all transactions for the journal are already loaded.
        /// </summary>
        /// <param name="AMainDS"></param>
        /// <param name="ACurrentBatch"></param>
        /// <param name="ACurrentJournal"></param>
        public static void UpdateTotalsOfBatchForJournal(ref GLBatchTDS AMainDS,
                                                         ABatchRow ACurrentBatch, GLBatchTDSAJournalRow ACurrentJournal)
        {
            //Save current values
            decimal JournalDebitTotal  = ACurrentJournal.JournalDebitTotal;
            decimal JournalCreditTotal = ACurrentJournal.JournalCreditTotal;

            bool JournalUpdated;

            UpdateTotalsOfJournal(ref AMainDS, ref ACurrentJournal, out JournalUpdated);

            if (JournalUpdated)
            {
                //Subtract old amounts
                ACurrentBatch.BatchDebitTotal  -= JournalDebitTotal;
                ACurrentBatch.BatchCreditTotal -= JournalCreditTotal;
                //Add updated Journals amounts
                ACurrentBatch.BatchDebitTotal  += ACurrentJournal.JournalDebitTotal;
                ACurrentBatch.BatchCreditTotal += ACurrentJournal.JournalCreditTotal;
            }
        }
Beispiel #6
0
        /// <summary>
        /// Switch to the given tab
        /// </summary>
        /// <param name="ATab"></param>
        /// <param name="AAllowRepeatEvent"></param>
        public void SelectTab(TGLBatchEnums.eGLTabs ATab, bool AAllowRepeatEvent = false)
        {
            //Between the tab changing and seleted events changes are incorrectly detected on Journal controls
            // TODO: find cause but use this field for now
            if (!FChangesDetected && FPetraUtilsObject.HasChanges)
            {
                FPetraUtilsObject.DisableSaveButton();
            }
            else if (FChangesDetected && !FPetraUtilsObject.HasChanges)
            {
                FChangesDetected = false;
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;

                if (ATab == TGLBatchEnums.eGLTabs.Batches)
                {
                    if ((FPreviouslySelectedTab == TGLBatchEnums.eGLTabs.Batches) && !AAllowRepeatEvent)
                    {
                        //Repeat event
                        return;
                    }

                    FPreviouslySelectedTab = TGLBatchEnums.eGLTabs.Batches;

                    this.tabGLBatch.SelectedTab = this.tpgBatches;
                    this.tpgJournals.Enabled    = (ucoBatches.GetSelectedDetailRow() != null);
                    this.tabGLBatch.TabStop     = this.tpgJournals.Enabled;

                    if (this.tpgTransactions.Enabled)
                    {
                        this.ucoTransactions.CancelChangesToFixedBatches();
                        this.ucoJournals.CancelChangesToFixedBatches();
                    }

                    ucoBatches.AutoEnableTransTabForBatch();
                    ucoBatches.SetInitialFocus();
                }
                else if (ATab == TGLBatchEnums.eGLTabs.Journals)
                {
                    if ((FPreviouslySelectedTab == TGLBatchEnums.eGLTabs.Journals) && !AAllowRepeatEvent)
                    {
                        //Repeat event
                        return;
                    }

                    if (this.tpgJournals.Enabled)
                    {
                        FPreviouslySelectedTab = TGLBatchEnums.eGLTabs.Journals;

                        this.tabGLBatch.SelectedTab = this.tpgJournals;

                        LoadJournals(ucoBatches.GetSelectedDetailRow());

                        this.tpgTransactions.Enabled =
                            (ucoJournals.GetSelectedDetailRow() != null && ucoJournals.GetSelectedDetailRow().JournalStatus !=
                             MFinanceConstants.BATCH_CANCELLED);

                        this.ucoJournals.UpdateHeaderTotals(ucoBatches.GetSelectedDetailRow());
                    }
                }
                else if (ATab == TGLBatchEnums.eGLTabs.Transactions)
                {
                    if ((FPreviouslySelectedTab == TGLBatchEnums.eGLTabs.Transactions) && !AAllowRepeatEvent)
                    {
                        //Repeat event
                        return;
                    }

                    if (this.tpgTransactions.Enabled)
                    {
                        ABatchRow batchRow = ucoBatches.GetSelectedDetailRow();

                        string loadingMessage      = string.Empty;
                        bool   batchWasPreviousTab = (FPreviouslySelectedTab == TGLBatchEnums.eGLTabs.Batches);

                        FPreviouslySelectedTab = TGLBatchEnums.eGLTabs.Transactions;

                        // Note!! This call may result in this (SelectTab) method being called again (but no new transactions will be loaded the second time)
                        this.tabGLBatch.SelectedTab = this.tpgTransactions;

                        if (batchWasPreviousTab)
                        {
                            //This only happens when the user clicks from Batch to Transactions,
                            //  which is only allowed when one journal exists

                            //Need to make sure that the Journal is loaded
                            LoadJournals(batchRow);
                        }

                        GLBatchTDSAJournalRow journalRow = ucoJournals.GetSelectedDetailRow();

                        if ((batchRow == null) || batchRow.IsBatchStatusNull())
                        {
                            loadingMessage = Catalog.GetString(
                                "There has been a problem loading the batch, please reselect the Batch tab and batch again and then retry.");
                        }
                        else if ((journalRow == null) || journalRow.IsJournalStatusNull())
                        {
                            loadingMessage = Catalog.GetString(
                                "There has been a problem loading the journals, please reselect the Batch tab and then the Journal tab and then retry.");
                        }

                        if (loadingMessage.Length == 0)
                        {
                            LoadTransactions(journalRow.BatchNumber,
                                             batchRow.BatchStatus,
                                             journalRow.JournalNumber,
                                             journalRow.JournalStatus,
                                             journalRow.TransactionCurrency,
                                             batchWasPreviousTab);

                            //Warn if missing International Exchange Rate
                            WarnAboutMissingIntlExchangeRate = true;
                            GetInternationalCurrencyExchangeRate();
                        }
                        else
                        {
                            MessageBox.Show(loadingMessage,
                                            "View Transactions",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Warning);
                        }
                    }
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
                this.Refresh();
            }
        }
Beispiel #7
0
        /// <summary>
        /// Re-show the specified row
        /// </summary>
        /// <param name="ACurrentBatch"></param>
        /// <param name="AJournalToCancel"></param>
        /// <param name="ARedisplay"></param>
        public void PrepareJournalDataForCancelling(Int32 ACurrentBatch, Int32 AJournalToCancel, Boolean ARedisplay)
        {
            //This code will only be called when the Journal tab is active.

            DataView JournalDV   = new DataView(FMainDS.AJournal);
            DataView TransDV     = new DataView(FMainDS.ATransaction);
            DataView TransAnalDV = new DataView(FMainDS.ATransAnalAttrib);

            JournalDV.RowFilter = String.Format("{0}={1} And {2}={3}",
                                                AJournalTable.GetBatchNumberDBName(),
                                                ACurrentBatch,
                                                AJournalTable.GetJournalNumberDBName(),
                                                AJournalToCancel);

            TransDV.RowFilter = String.Format("{0}={1} And {2}={3}",
                                              ATransactionTable.GetBatchNumberDBName(),
                                              ACurrentBatch,
                                              ATransactionTable.GetJournalNumberDBName(),
                                              AJournalToCancel);

            TransAnalDV.RowFilter = String.Format("{0}={1} And {2}={3}",
                                                  ATransAnalAttribTable.GetBatchNumberDBName(),
                                                  ACurrentBatch,
                                                  ATransAnalAttribTable.GetJournalNumberDBName(),
                                                  AJournalToCancel);

            //Work from lowest level up
            if (TransAnalDV.Count > 0)
            {
                TransAnalDV.Sort = String.Format("{0}, {1}",
                                                 ATransAnalAttribTable.GetTransactionNumberDBName(),
                                                 ATransAnalAttribTable.GetAnalysisTypeCodeDBName());

                foreach (DataRowView drv in TransAnalDV)
                {
                    ATransAnalAttribRow transAnalRow = (ATransAnalAttribRow)drv.Row;

                    if (transAnalRow.RowState == DataRowState.Added)
                    {
                        //Do nothing
                    }
                    else if (transAnalRow.RowState != DataRowState.Unchanged)
                    {
                        transAnalRow.RejectChanges();
                    }
                }
            }

            if (TransDV.Count > 0)
            {
                TransDV.Sort = String.Format("{0}", ATransactionTable.GetTransactionNumberDBName());

                foreach (DataRowView drv in TransDV)
                {
                    ATransactionRow transRow = (ATransactionRow)drv.Row;

                    if (transRow.RowState == DataRowState.Added)
                    {
                        //Do nothing
                    }
                    else if (transRow.RowState != DataRowState.Unchanged)
                    {
                        transRow.RejectChanges();
                    }
                }
            }

            if (JournalDV.Count > 0)
            {
                GLBatchTDSAJournalRow journalRow = (GLBatchTDSAJournalRow)JournalDV[0].Row;

                //No need to check for Added state as new journals are always saved
                // on creation
                if (journalRow.RowState != DataRowState.Unchanged)
                {
                    journalRow.RejectChanges();
                }

                if (ARedisplay)
                {
                    ShowDetails(journalRow);
                }
            }

            if (TransDV.Count == 0)
            {
                //Load all related data for journal ready to delete/cancel
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransactionAndRelatedTablesForJournal(FLedgerNumber, ACurrentBatch,
                                                                                                           AJournalToCancel));
            }
        }
Beispiel #8
0
        /// <summary>
        /// Update the specified Journal's LastTransaction number. Assumes all necessary data is loaded for Journal
        /// </summary>
        /// <param name="AMainDS">ATransactions are filtered on current journal</param>
        /// <param name="ACurrentJournal"></param>
        /// <returns>false if no change to journal totals</returns>
        public static bool UpdateJournalLastTransaction(ref GLBatchTDS AMainDS,
            ref GLBatchTDSAJournalRow ACurrentJournal)
        {
            #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 (ACurrentJournal == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Journal row does not exist or is empty!"),
                        Utilities.GetMethodName(true)));
            }
            else if (ACurrentJournal.JournalStatus != MFinanceConstants.BATCH_UNPOSTED)
            {
                TLogging.Log(String.Format("Function:{0} - Tried to update totals for non-Unposted Batch:{1} and Journal:{2}",
                        Utilities.GetMethodName(true),
                        ACurrentJournal.BatchNumber,
                        ACurrentJournal.JournalNumber));
                return false;
            }

            #endregion Validate Arguments

            bool RowUpdated = false;

            int ActualLastTransNumber = 0;

            DataView TransDV = new DataView(AMainDS.ATransaction);
            TransDV.RowFilter = String.Format("{0}={1} And {2}={3}",
                ATransactionTable.GetBatchNumberDBName(),
                ACurrentJournal.BatchNumber,
                ATransactionTable.GetJournalNumberDBName(),
                ACurrentJournal.JournalNumber);

            TransDV.Sort = String.Format("{0} DESC",
                ATransactionTable.GetTransactionNumberDBName());

            foreach (DataRowView drv in TransDV)
            {
                ATransactionRow transRow = (ATransactionRow)drv.Row;

                //Run once only
                ActualLastTransNumber = transRow.TransactionNumber;
                break;
            }

            if (ACurrentJournal.LastTransactionNumber != ActualLastTransNumber)
            {
                ACurrentJournal.LastTransactionNumber = ActualLastTransNumber;
                RowUpdated = true;
            }

            return RowUpdated;
        }
Beispiel #9
0
        /// <summary>
        /// Update the specified Batch's LastJournal number. Assumes all necessary data is loaded for Batch
        /// </summary>
        /// <param name="AMainDS"></param>
        /// <param name="ACurrentBatchRow"></param>
        /// <returns>false if no change to batch totals</returns>
        public static bool UpdateBatchLastJournal(ref GLBatchTDS AMainDS,
                                                  ref ABatchRow ACurrentBatchRow)
        {
            #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 (ACurrentBatchRow == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                                                                                         "Function:{0} - The GL Batch data row is null!"),
                                                                                     Utilities.GetMethodName(true)));
            }
            else if (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)
            {
                TLogging.Log(String.Format("Function:{0} - Tried to update totals for non-Unposted Batch:{1}",
                                           Utilities.GetMethodName(true),
                                           ACurrentBatchRow.BatchNumber));
                return(false);
            }

            #endregion Validate Arguments

            bool RowUpdated = false;
            int  ActualLastJournalNumber = 0;

            DataView JournalDV = new DataView(AMainDS.AJournal);

            JournalDV.RowFilter = String.Format("{0}={1}",
                                                AJournalTable.GetBatchNumberDBName(),
                                                ACurrentBatchRow.BatchNumber);

            //Highest Journal number first
            JournalDV.Sort = String.Format("{0} DESC",
                                           AJournalTable.GetJournalNumberDBName());

            foreach (DataRowView journalView in JournalDV)
            {
                GLBatchTDSAJournalRow journalRow = (GLBatchTDSAJournalRow)journalView.Row;

                //Run once only
                if (ActualLastJournalNumber == 0)
                {
                    ActualLastJournalNumber = journalRow.JournalNumber;
                }

                if (UpdateJournalLastTransaction(ref AMainDS, ref journalRow))
                {
                    RowUpdated = true;
                }
            }

            if (ACurrentBatchRow.LastJournal != ActualLastJournalNumber)
            {
                ACurrentBatchRow.LastJournal = ActualLastJournalNumber;
                RowUpdated = true;
            }

            return(RowUpdated);
        }
        /// <summary>
        /// make sure the correct journal number is assigned and the batch.lastJournal is updated
        /// </summary>
        /// <param name="ANewRow"></param>
        public void NewRowManual(ref GLBatchTDSAJournalRow ANewRow)
        {
            if ((ANewRow == null) || (FLedgerNumber == -1))
            {
                return;
            }

            ALedgerRow LedgerRow =
                ((ALedgerTable)TDataCache.TMFinance.GetCacheableFinanceTable(
                     TCacheableFinanceTablesEnum.LedgerDetails, FLedgerNumber))[0];

            ANewRow.LedgerNumber = FBatchRow.LedgerNumber;
            ANewRow.BatchNumber = FBatchRow.BatchNumber;
            ANewRow.JournalNumber = ++FBatchRow.LastJournal;

            // manually created journals are all GL
            ANewRow.SubSystemCode = MFinanceConstants.SUB_SYSTEM_GL;
            ANewRow.TransactionTypeCode = MFinanceConstants.STANDARD_JOURNAL;

            ANewRow.TransactionCurrency = LedgerRow.BaseCurrency;
            ANewRow.ExchangeRateToBase = 1;
            ANewRow.DateEffective = FBatchRow.DateEffective;
            ANewRow.JournalPeriod = FBatchRow.BatchPeriod;
            ANewRow.JournalDebitTotalBase = 0.0M;
            ANewRow.JournalCreditTotalBase = 0.0M;
        }
        /// <summary>
        /// Import a batch from a spreadsheet
        /// </summary>
        /// <param name="ACSVDataFileName"></param>
        /// <param name="ALatestTransactionDate"></param>
        /// <returns></returns>
        public bool ImportFromSpreadsheet(out string ACSVDataFileName, out DateTime ALatestTransactionDate)
        {
            ALatestTransactionDate = DateTime.MinValue;
            ACSVDataFileName       = String.Empty;

            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Title  = Catalog.GetString("Import transactions from spreadsheet file");
            dialog.Filter = Catalog.GetString("Spreadsheet files (*.csv)|*.csv");

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string   directory          = Path.GetDirectoryName(dialog.FileName);
                string[] ymlFiles           = Directory.GetFiles(directory, "*.yml");
                string   definitionFileName = String.Empty;

                if (ymlFiles.Length == 1)
                {
                    definitionFileName = ymlFiles[0];
                }
                else
                {
                    // show another open file dialog for the description file
                    OpenFileDialog dialogDefinitionFile = new OpenFileDialog();
                    dialogDefinitionFile.Title  = Catalog.GetString("Please select a yml file that describes the content of the spreadsheet");
                    dialogDefinitionFile.Filter = Catalog.GetString("Data description files (*.yml)|*.yml");

                    if (dialogDefinitionFile.ShowDialog() == DialogResult.OK)
                    {
                        definitionFileName = dialogDefinitionFile.FileName;
                    }
                }

                if (File.Exists(definitionFileName))
                {
                    TYml2Xml    parser              = new TYml2Xml(definitionFileName);
                    XmlDocument dataDescription     = parser.ParseYML2XML();
                    XmlNode     RootNode            = TXMLParser.FindNodeRecursive(dataDescription.DocumentElement, "RootNode");
                    Int32       FirstTransactionRow = TXMLParser.GetIntAttribute(RootNode, "FirstTransactionRow");
                    string      DefaultCostCentre   = TXMLParser.GetAttribute(RootNode, "CostCentre");

                    FMyUserControl.CreateNewABatch();
                    GLBatchTDSAJournalRow NewJournal = FMainDS.AJournal.NewRowTyped(true);
                    FMyForm.GetJournalsControl().NewRowManual(ref NewJournal);
                    FMainDS.AJournal.Rows.Add(NewJournal);
                    NewJournal.TransactionCurrency = TXMLParser.GetAttribute(RootNode, "Currency");

                    if (Path.GetExtension(dialog.FileName).ToLower() == ".csv")
                    {
                        ACSVDataFileName = dialog.FileName;

                        CreateBatchFromCSVFile(dialog.FileName,
                                               RootNode,
                                               NewJournal,
                                               FirstTransactionRow,
                                               DefaultCostCentre,
                                               out ALatestTransactionDate);

                        return(true);
                    }
                }
            }

            return(false);
        }
        /// <summary>
        /// load the transactions into the grid
        /// </summary>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ABatchNumber"></param>
        /// <param name="AJournalNumber"></param>
        /// <param name="ACurrencyCode"></param>
        /// <param name="AFromBatchTab"></param>
        /// <param name="ABatchStatus"></param>
        /// <param name="AJournalStatus"></param>
        /// <returns>True if new GL transactions were loaded, false if transactions had been loaded already.</returns>
        public bool LoadTransactions(Int32 ALedgerNumber,
            Int32 ABatchNumber,
            Int32 AJournalNumber,
            string ACurrencyCode,
            bool AFromBatchTab = false,
            string ABatchStatus = MFinanceConstants.BATCH_UNPOSTED,
            string AJournalStatus = MFinanceConstants.BATCH_UNPOSTED)
        {
            bool DifferentBatchSelected = false;

            FLoadCompleted = false;
            FBatchRow = GetBatchRow();
            FJournalRow = GetJournalRow();
            FIsUnposted = (FBatchRow.BatchStatus == MFinanceConstants.BATCH_UNPOSTED);

            if (FLedgerNumber == -1)
            {
                InitialiseControls();
            }

            //Check if the same batch is selected, so no need to apply filter
            if ((FLedgerNumber == ALedgerNumber) && (FBatchNumber == ABatchNumber) && (FJournalNumber == AJournalNumber)
                && (FTransactionCurrency == ACurrencyCode) && (FBatchStatus == ABatchStatus) && (FJournalStatus == AJournalStatus)
                && (FMainDS.ATransaction.DefaultView.Count > 0))
            {
                //Same as previously selected
                if (FIsUnposted && (GetSelectedRowIndex() > 0))
                {
                    if (AFromBatchTab)
                    {
                        SelectRowInGrid(GetSelectedRowIndex());
                    }
                    else
                    {
                        GetDetailsFromControls(GetSelectedDetailRow());
                    }
                }

                FLoadCompleted = true;
            }
            else
            {
                // A new ledger/batch
                DifferentBatchSelected = true;
                bool requireControlSetup = (FLedgerNumber == -1) || (FTransactionCurrency != ACurrencyCode);

                FLedgerNumber = ALedgerNumber;
                FBatchNumber = ABatchNumber;
                FJournalNumber = AJournalNumber;
                FTransactionNumber = -1;
                FTransactionCurrency = ACurrencyCode;

                FPreviouslySelectedDetailRow = null;
                grdDetails.SuspendLayout();
                //Empty grids before filling them
                grdDetails.DataSource = null;
                grdAnalAttributes.DataSource = null;

                FBatchStatus = ABatchStatus;
                FJournalStatus = AJournalStatus;

                // This sets the main part of the filter but excluding the additional items set by the user GUI
                // It gets the right sort order
                SetTransactionDefaultView();

                //Load from server if necessary
                if (FMainDS.ATransaction.DefaultView.Count == 0)
                {
                    FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransactionATransAnalAttrib(ALedgerNumber, ABatchNumber, AJournalNumber));
                }

                // We need to call this because we have not called ShowData(), which would have set it.  This differs from the Gift screen.
                grdDetails.DataSource = new DevAge.ComponentModel.BoundDataView(FMainDS.ATransaction.DefaultView);

                // Now we set the full filter
                FFilterAndFindObject.ApplyFilter();

                if (grdAnalAttributes.Columns.Count == 1)
                {
                    grdAnalAttributes.SpecialKeys = GridSpecialKeys.Default | GridSpecialKeys.Tab;

                    FcmbAnalAttribValues = new SourceGrid.Cells.Editors.ComboBox(typeof(string));
                    FcmbAnalAttribValues.EnableEdit = true;
                    FcmbAnalAttribValues.EditableMode = EditableMode.Focus;
                    grdAnalAttributes.AddTextColumn(Catalog.GetString("Value"),
                        FMainDS.ATransAnalAttrib.Columns[ATransAnalAttribTable.GetAnalysisAttributeValueDBName()], 150,
                        FcmbAnalAttribValues);
                    FcmbAnalAttribValues.Control.SelectedValueChanged += new EventHandler(this.AnalysisAttributeValueChanged);

                    grdAnalAttributes.Columns[0].Width = 99;
                }

                FAnalysisAttributesLogic = new TAnalysisAttributes(FLedgerNumber, FBatchNumber, FJournalNumber);

                FAnalysisAttributesLogic.SetTransAnalAttributeDefaultView(FMainDS, FActiveOnly);
                FMainDS.ATransAnalAttrib.DefaultView.AllowNew = false;
                grdAnalAttributes.DataSource = new DevAge.ComponentModel.BoundDataView(FMainDS.ATransAnalAttrib.DefaultView);
                grdAnalAttributes.SetHeaderTooltip(0, Catalog.GetString("Type"));
                grdAnalAttributes.SetHeaderTooltip(1, Catalog.GetString("Value"));

                // if this form is readonly or batch is posted, then we need all account and cost centre codes, because old codes might have been used
                bool ActiveOnly = (this.Enabled && FIsUnposted);

                if (requireControlSetup || (FActiveOnly != ActiveOnly))
                {
                    FActiveOnly = ActiveOnly;

                    //Load all analysis attribute values
                    if (FCacheDS == null)
                    {
                        FCacheDS = TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, FActiveOnly);
                    }

                    SetupExtraGridFunctionality();

                    TFinanceControls.InitialiseAccountList(ref cmbDetailAccountCode, FLedgerNumber,
                        true, false, ActiveOnly, false, ACurrencyCode, true);
                    TFinanceControls.InitialiseCostCentreList(ref cmbDetailCostCentreCode, FLedgerNumber, true, false, ActiveOnly, false);
                }

                UpdateTransactionTotals();
                grdDetails.ResumeLayout();
                FLoadCompleted = true;
            }

            ShowData();
            SelectRowInGrid(1);
            ShowDetails(); //Needed because of how currency is handled

            UpdateChangeableStatus();
            UpdateRecordNumberDisplay();
            FFilterAndFindObject.SetRecordNumberDisplayProperties();

            return DifferentBatchSelected;
        }
Beispiel #13
0
        /// <summary>
        /// Update the totals for the current journal (no exchange rate calculation at this point)
        ///   and set LastTransactionNumber
        /// </summary>
        /// <param name="AMainDS">ATransactions are filtered on current journal</param>
        /// <param name="ACurrentJournal"></param>
        public static void UpdateTotalsOfJournal(ref GLBatchTDS AMainDS,
                                                 ref GLBatchTDSAJournalRow ACurrentJournal)
        {
            if (ACurrentJournal == null)
            {
                return;
            }

            int LastTransactionNumber = 0;

            decimal JournalDebitTotal      = 0.0M;
            decimal JournalDebitTotalBase  = 0.0M;
            decimal JournalCreditTotal     = 0.0M;
            decimal JournalCreditTotalBase = 0.0M;

            if (DBNull.Value.Equals(ACurrentJournal[GLBatchTDSAJournalTable.ColumnJournalDebitTotalBaseId]))
            {
                ACurrentJournal.JournalDebitTotalBase = 0;
            }

            if (DBNull.Value.Equals(ACurrentJournal[GLBatchTDSAJournalTable.ColumnJournalCreditTotalBaseId]))
            {
                ACurrentJournal.JournalCreditTotalBase = 0;
            }

            DataView TransDataView = new DataView(AMainDS.ATransaction);

            TransDataView.RowFilter = String.Format("{0}={1} And {2}={3}",
                                                    ATransactionTable.GetBatchNumberDBName(),
                                                    ACurrentJournal.BatchNumber,
                                                    ATransactionTable.GetJournalNumberDBName(),
                                                    ACurrentJournal.JournalNumber);

            TransDataView.Sort = string.Format("{0} DESC",
                                               ATransactionTable.GetTransactionNumberDBName());

            // transactions are filtered for this journal; add up the total amounts
            foreach (DataRowView drv in TransDataView)
            {
                ATransactionRow transRow = (ATransactionRow)drv.Row;

                //on first recursion
                if (transRow.TransactionNumber > LastTransactionNumber)
                {
                    //Sort order will ensure this is the highest trans number on first pass
                    LastTransactionNumber = transRow.TransactionNumber;
                }

                if (transRow.DebitCreditIndicator)
                {
                    JournalDebitTotal     += transRow.TransactionAmount;
                    JournalDebitTotalBase += transRow.AmountInBaseCurrency;
                }
                else
                {
                    JournalCreditTotal     += transRow.TransactionAmount;
                    JournalCreditTotalBase += transRow.AmountInBaseCurrency;
                }
            }

            if ((ACurrentJournal.JournalDebitTotal != JournalDebitTotal) ||
                (ACurrentJournal.JournalDebitTotalBase != JournalDebitTotalBase) ||
                (ACurrentJournal.JournalCreditTotal != JournalCreditTotal) ||
                (ACurrentJournal.JournalCreditTotalBase != JournalCreditTotalBase))
            {
                ACurrentJournal.JournalDebitTotal      = JournalDebitTotal;
                ACurrentJournal.JournalDebitTotalBase  = JournalDebitTotalBase;
                ACurrentJournal.JournalCreditTotal     = JournalCreditTotal;
                ACurrentJournal.JournalCreditTotalBase = JournalCreditTotalBase;
            }

            if (ACurrentJournal.LastTransactionNumber != LastTransactionNumber)
            {
                ACurrentJournal.LastTransactionNumber = LastTransactionNumber;
            }
        }
        private void ValidateDataDetailsManual(ATransactionRow ARow)
        {
            //Can be called from outside, so need to update fields
            FBatchRow = GetBatchRow();

            if (FBatchRow == null)
            {
                return;
            }

            FJournalRow = GetJournalRow();

            if (FJournalRow != null)
            {
                FJournalNumber = FJournalRow.JournalNumber;
                FJournalStatus = FJournalRow.JournalStatus;
            }

            FIsUnposted = (FBatchRow.BatchStatus == MFinanceConstants.BATCH_UNPOSTED);

            if ((ARow == null) || (FBatchRow.BatchNumber != ARow.BatchNumber) || !FIsUnposted)
            {
                return;
            }

            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;

            Control controlToPass = null;

            //Local validation
            if (((txtDebitAmount.NumberValueDecimal.Value == 0)
                 && (txtCreditAmount.NumberValueDecimal.Value == 0))
                || (txtDebitAmount.NumberValueDecimal.Value < 0))
            {
                controlToPass = txtDebitAmount;
            }
            else if (txtCreditAmount.NumberValueDecimal.Value < 0)
            {
                controlToPass = txtCreditAmount;
            }
            else if (TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_GLREFMANDATORY, "no") == "yes")
            {
                controlToPass = txtDetailReference;
            }
            else if ((VerificationResultCollection.Count == 1)
                     && (VerificationResultCollection[0].ResultCode == CommonErrorCodes.ERR_INVALIDNUMBER))
            {
                //The amount controls register as invalid even when value is correct. Need to reset
                //  Verifications accordingly.
                FPetraUtilsObject.VerificationResultCollection.Clear();
            }

            TSharedFinanceValidation_GL.ValidateGLDetailManual(this, FBatchRow, ARow, controlToPass, ref VerificationResultCollection,
                FValidationControlsDict);

            if ((FPreviouslySelectedDetailRow != null)
                && !FAnalysisAttributesLogic.AccountAnalysisAttributeCountIsCorrect(
                    FPreviouslySelectedDetailRow.TransactionNumber,
                    FPreviouslySelectedDetailRow.AccountCode,
                    FMainDS,
                    FIsUnposted))
            {
                DataColumn ValidationColumn;
                TVerificationResult VerificationResult = null;
                object ValidationContext;

                ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnAccountCodeId];
                ValidationContext = "unused because of OverrideResultText";

                // This code is only running because of failure, so cause an error to occur.
                VerificationResult = TStringChecks.StringMustNotBeEmpty("",
                    ValidationContext.ToString(),
                    this, ValidationColumn, null);
                VerificationResult.OverrideResultText(String.Format(
                        "A value must be entered for 'Analysis Attributes' for Account Code {0} in Transaction {1}.",
                        ARow.AccountCode,
                        ARow.TransactionNumber));

                // Handle addition/removal to/from TVerificationResultCollection
                VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn, true);
            }

            String ValueRequiredForType;

            if ((FPreviouslySelectedDetailRow != null)
                && !FAnalysisAttributesLogic.AccountAnalysisAttributesValuesExist(
                    FPreviouslySelectedDetailRow.TransactionNumber,
                    FPreviouslySelectedDetailRow.AccountCode,
                    FMainDS,
                    out ValueRequiredForType,
                    FIsUnposted))
            {
                DataColumn ValidationColumn;
                TVerificationResult VerificationResult = null;
                object ValidationContext;

                ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnAccountCodeId];
                ValidationContext = String.Format("Analysis code {0} for Account Code {1} in Transaction {2}",
                    ValueRequiredForType,
                    ARow.AccountCode,
                    ARow.TransactionNumber);

                // This code is only running because of failure, so cause an error to occur.
                VerificationResult = TStringChecks.StringMustNotBeEmpty("",
                    ValidationContext.ToString(),
                    this, ValidationColumn, null);

                // Handle addition/removal to/from TVerificationResultCollection
                VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn, true);
            }
        }
Beispiel #15
0
        private static bool UpdateJournalTotals(ref GLBatchTDS AMainDS,
            ref GLBatchTDSAJournalRow ACurrentJournal)
        {
            #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 (ACurrentJournal == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Journal row does not exist or is empty!"),
                        Utilities.GetMethodName(true)));
            }
            else if (ACurrentJournal.JournalStatus != MFinanceConstants.BATCH_UNPOSTED)
            {
                TLogging.Log(String.Format("Function:{0} - Tried to update totals for non-Unposted Batch:{1} and Journal:{2}",
                        Utilities.GetMethodName(true),
                        ACurrentJournal.BatchNumber,
                        ACurrentJournal.JournalNumber));
                return false;
            }

            #endregion Validate Arguments

            bool AmountsUpdated = false;

            decimal JournalDebitTotal = 0.0M;
            decimal JournalDebitTotalBase = 0.0M;
            decimal JournalCreditTotal = 0.0M;
            decimal JournalCreditTotalBase = 0.0M;

            if (ACurrentJournal.IsJournalDebitTotalBaseNull()) //DBNull.Value.Equals(ACurrentJournal[GLBatchTDSAJournalTable.ColumnJournalDebitTotalBaseId])
            {
                ACurrentJournal.JournalDebitTotalBase = 0;
                AmountsUpdated = true;
            }

            if (ACurrentJournal.IsJournalCreditTotalBaseNull()) //DBNull.Value.Equals(ACurrentJournal[GLBatchTDSAJournalTable.ColumnJournalCreditTotalBaseId])
            {
                ACurrentJournal.JournalCreditTotalBase = 0;
                AmountsUpdated = true;
            }

            DataView TransDV = new DataView(AMainDS.ATransaction);
            TransDV.RowFilter = String.Format("{0}={1} And {2}={3}",
                ATransactionTable.GetBatchNumberDBName(),
                ACurrentJournal.BatchNumber,
                ATransactionTable.GetJournalNumberDBName(),
                ACurrentJournal.JournalNumber);

            if ((TransDV.Count == 0) && (ACurrentJournal.LastTransactionNumber > 0))
            {
                //do not update totals as no transactions loaded as yet so no need to update journal total
                return AmountsUpdated;
            }

            // transactions are filtered for this journal; add up the total amounts
            foreach (DataRowView drv in TransDV)
            {
                ATransactionRow transRow = (ATransactionRow)drv.Row;

                if (transRow.DebitCreditIndicator)
                {
                    JournalDebitTotal += transRow.TransactionAmount;
                    JournalDebitTotalBase += transRow.AmountInBaseCurrency;
                }
                else
                {
                    JournalCreditTotal += transRow.TransactionAmount;
                    JournalCreditTotalBase += transRow.AmountInBaseCurrency;
                }
            }

            if ((ACurrentJournal.JournalDebitTotal != JournalDebitTotal)
                || (ACurrentJournal.JournalDebitTotalBase != JournalDebitTotalBase)
                || (ACurrentJournal.JournalCreditTotal != JournalCreditTotal)
                || (ACurrentJournal.JournalCreditTotalBase != JournalCreditTotalBase))
            {
                ACurrentJournal.JournalDebitTotal = JournalDebitTotal;
                ACurrentJournal.JournalDebitTotalBase = JournalDebitTotalBase;
                ACurrentJournal.JournalCreditTotal = JournalCreditTotal;
                ACurrentJournal.JournalCreditTotalBase = JournalCreditTotalBase;
                AmountsUpdated = true;
            }

            return AmountsUpdated;
        }
        /// <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)
        {
            //Assign default value(s)
            bool CancellationSuccessful = false;

            if (AJournalRowToCancel == null)
            {
                return(CancellationSuccessful);
            }

            int CurrentBatchNumber   = AJournalRowToCancel.BatchNumber;
            int CurrentJournalNumber = AJournalRowToCancel.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, 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 = (AJournalRowToCancel.RowState == DataRowState.Added);

            if (!RowToDeleteIsNew)
            {
                //Remove any changes, which may cause validation issues, before cancelling
                FMyForm.GetJournalsControl().UndoModifiedJournalRow(AJournalRowToCancel, true);

                if (!(FMyForm.SaveChanges()))
                {
                    MessageBox.Show(Catalog.GetString("Error in trying to save prior to cancelling current journal!"),
                                    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 Journals etc for current Batch
                FMainDS.ATransAnalAttrib.Clear();
                FMainDS.ATransaction.Clear();

                //Load data afresh
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransactionATransAnalAttrib(FLedgerNumber, CurrentBatchNumber,
                                                                                                 CurrentJournalNumber));
                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();
                }

                //Edit current Journal
                AJournalRowToCancel.BeginEdit();

                AJournalRowToCancel.JournalStatus         = MFinanceConstants.BATCH_CANCELLED;
                AJournalRowToCancel.LastTransactionNumber = 0;

                //Edit current Batch
                ABatchRow CurrentBatchRow = FMyForm.GetBatchControl().GetSelectedDetailRow();

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

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

                AJournalRowToCancel.JournalCreditTotal = 0;
                AJournalRowToCancel.JournalDebitTotal  = 0;

                AJournalRowToCancel.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();

                    CancellationSuccessful = true;
                }
                else
                {
                    // saving failed
                    throw new Exception(Catalog.GetString("The journal failed to save after being cancelled! Reopen the form and retry."));
                }
            }
            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);
        }
        /// <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);
        }
        /// <summary>
        /// Re-show the specified row
        /// </summary>
        /// <param name="AModifiedJournalRow"></param>
        /// <param name="ARedisplay"></param>
        public void UndoModifiedJournalRow(GLBatchTDSAJournalRow AModifiedJournalRow, bool ARedisplay)
        {
            //Check if new row or not
            if (AModifiedJournalRow.RowState == DataRowState.Added)
            {
                return;
            }

            AModifiedJournalRow.RejectChanges();

            if (ARedisplay)
            {
                ShowDetails(AModifiedJournalRow);
            }
        }
        /// <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)
        {
            //Assign default value(s)
            bool CancellationSuccessful = false;

            if (AJournalRowToCancel == null)
            {
                return CancellationSuccessful;
            }

            int CurrentBatchNumber = AJournalRowToCancel.BatchNumber;
            int CurrentJournalNumber = AJournalRowToCancel.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, 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 = (AJournalRowToCancel.RowState == DataRowState.Added);

            if (!RowToDeleteIsNew)
            {
                //Remove any changes, which may cause validation issues, before cancelling
                FMyForm.GetJournalsControl().UndoModifiedJournalRow(AJournalRowToCancel, true);

                if (!(FMyForm.SaveChanges()))
                {
                    MessageBox.Show(Catalog.GetString("Error in trying to save prior to cancelling current journal!"),
                        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 Journals etc for current Batch
                FMainDS.ATransAnalAttrib.Clear();
                FMainDS.ATransaction.Clear();

                //Load data afresh
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransactionATransAnalAttrib(FLedgerNumber, CurrentBatchNumber,
                        CurrentJournalNumber));
                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();
                }

                //Edit current Journal
                AJournalRowToCancel.BeginEdit();

                AJournalRowToCancel.JournalStatus = MFinanceConstants.BATCH_CANCELLED;
                AJournalRowToCancel.LastTransactionNumber = 0;

                //Edit current Batch
                ABatchRow CurrentBatchRow = FMyForm.GetBatchControl().GetSelectedDetailRow();

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

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

                AJournalRowToCancel.JournalCreditTotal = 0;
                AJournalRowToCancel.JournalDebitTotal = 0;

                AJournalRowToCancel.EndEdit();

                //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();

                    CancellationSuccessful = true;
                }
                else
                {
                    // saving failed
                    throw new Exception(Catalog.GetString("The journal failed to save after being cancelled! Reopen the form and retry."));
                }
            }
            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;
        }
Beispiel #20
0
        /// <summary>
        /// Calculate the base amount for the transactions, and update the totals for the journals and the current batch
        ///   Assumes that all transactions for the journal are already loaded.
        /// </summary>
        /// <param name="AMainDS"></param>
        /// <param name="ACurrentBatch"></param>
        /// <param name="ACurrentJournal"></param>
        public static void UpdateTotalsOfBatchForJournal(ref GLBatchTDS AMainDS,
            ABatchRow ACurrentBatch, GLBatchTDSAJournalRow ACurrentJournal)
        {
            //Save current values
            decimal JournalDebitTotal = ACurrentJournal.JournalDebitTotal;
            decimal JournalCreditTotal = ACurrentJournal.JournalCreditTotal;

            bool JournalUpdated;

            UpdateTotalsOfJournal(ref AMainDS, ref ACurrentJournal, out JournalUpdated);

            if (JournalUpdated)
            {
                //Subtract old amounts
                ACurrentBatch.BatchDebitTotal -= JournalDebitTotal;
                ACurrentBatch.BatchCreditTotal -= JournalCreditTotal;
                //Add updated Journals amounts
                ACurrentBatch.BatchDebitTotal += ACurrentJournal.JournalDebitTotal;
                ACurrentBatch.BatchCreditTotal += ACurrentJournal.JournalCreditTotal;
            }
        }
Beispiel #21
0
        /// <summary>
        /// Update the totals for the current journal (no exchange rate calculation at this point)
        ///   and set LastTransactionNumber
        /// </summary>
        /// <param name="AMainDS">ATransactions are filtered on current journal</param>
        /// <param name="ACurrentJournal"></param>
        public static void UpdateTotalsOfJournal(ref GLBatchTDS AMainDS,
            ref GLBatchTDSAJournalRow ACurrentJournal)
        {
            if (ACurrentJournal == null)
            {
                return;
            }

            int LastTransactionNumber = 0;

            decimal JournalDebitTotal = 0.0M;
            decimal JournalDebitTotalBase = 0.0M;
            decimal JournalCreditTotal = 0.0M;
            decimal JournalCreditTotalBase = 0.0M;

            if (DBNull.Value.Equals(ACurrentJournal[GLBatchTDSAJournalTable.ColumnJournalDebitTotalBaseId]))
            {
                ACurrentJournal.JournalDebitTotalBase = 0;
            }

            if (DBNull.Value.Equals(ACurrentJournal[GLBatchTDSAJournalTable.ColumnJournalCreditTotalBaseId]))
            {
                ACurrentJournal.JournalCreditTotalBase = 0;
            }

            DataView TransDataView = new DataView(AMainDS.ATransaction);

            TransDataView.RowFilter = String.Format("{0}={1} And {2}={3}",
                ATransactionTable.GetBatchNumberDBName(),
                ACurrentJournal.BatchNumber,
                ATransactionTable.GetJournalNumberDBName(),
                ACurrentJournal.JournalNumber);

            TransDataView.Sort = string.Format("{0} DESC",
                ATransactionTable.GetTransactionNumberDBName());

            // transactions are filtered for this journal; add up the total amounts
            foreach (DataRowView drv in TransDataView)
            {
                ATransactionRow transRow = (ATransactionRow)drv.Row;

                //on first recursion
                if (transRow.TransactionNumber > LastTransactionNumber)
                {
                    //Sort order will ensure this is the highest trans number on first pass
                    LastTransactionNumber = transRow.TransactionNumber;
                }

                if (transRow.DebitCreditIndicator)
                {
                    JournalDebitTotal += transRow.TransactionAmount;
                    JournalDebitTotalBase += transRow.AmountInBaseCurrency;
                }
                else
                {
                    JournalCreditTotal += transRow.TransactionAmount;
                    JournalCreditTotalBase += transRow.AmountInBaseCurrency;
                }
            }

            if ((ACurrentJournal.JournalDebitTotal != JournalDebitTotal)
                || (ACurrentJournal.JournalDebitTotalBase != JournalDebitTotalBase)
                || (ACurrentJournal.JournalCreditTotal != JournalCreditTotal)
                || (ACurrentJournal.JournalCreditTotalBase != JournalCreditTotalBase))
            {
                ACurrentJournal.JournalDebitTotal = JournalDebitTotal;
                ACurrentJournal.JournalDebitTotalBase = JournalDebitTotalBase;
                ACurrentJournal.JournalCreditTotal = JournalCreditTotal;
                ACurrentJournal.JournalCreditTotalBase = JournalCreditTotalBase;
            }

            if (ACurrentJournal.LastTransactionNumber != LastTransactionNumber)
            {
                ACurrentJournal.LastTransactionNumber = LastTransactionNumber;
            }
        }
        /// <summary>
        /// load the transactions into the grid
        /// </summary>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ABatchNumber"></param>
        /// <param name="AJournalNumber"></param>
        /// <param name="ACurrencyCode"></param>
        /// <param name="AFromBatchTab"></param>
        /// <param name="ABatchStatus"></param>
        /// <param name="AJournalStatus"></param>
        /// <returns>True if new GL transactions were loaded, false if transactions had been loaded already.</returns>
        public bool LoadTransactions(Int32 ALedgerNumber,
            Int32 ABatchNumber,
            Int32 AJournalNumber,
            string ACurrencyCode,
            bool AFromBatchTab = false,
            string ABatchStatus = MFinanceConstants.BATCH_UNPOSTED,
            string AJournalStatus = MFinanceConstants.BATCH_UNPOSTED)
        {
            TFrmStatusDialog dlgStatus = null;
            bool DifferentBatchSelected = false;

            FLoadCompleted = false;

            FBatchRow = GetBatchRow();
            FJournalRow = GetJournalRow();

            if ((FBatchRow == null) || (FJournalRow == null))
            {
                return false;
            }

            //FBatchNumber and FJournalNumber may have already been set outside
            //  so need to reset to previous value
            if ((txtBatchNumber.Text.Length > 0) && (FBatchNumber.ToString() != txtBatchNumber.Text))
            {
                FBatchNumber = Int32.Parse(txtBatchNumber.Text);
            }

            if ((txtJournalNumber.Text.Length > 0) && (FJournalNumber.ToString() != txtJournalNumber.Text))
            {
                FJournalNumber = Int32.Parse(txtJournalNumber.Text);
            }

            bool FirstRun = (FLedgerNumber != ALedgerNumber);
            bool BatchChanged = (FBatchNumber != ABatchNumber);
            bool BatchStatusChanged = (!BatchChanged && (FBatchStatus != ABatchStatus));
            bool JournalChanged = (BatchChanged || (FJournalNumber != AJournalNumber));
            bool JournalStatusChanged = (!JournalChanged && (FJournalStatus != AJournalStatus));
            bool CurrencyChanged = (FTransactionCurrency != ACurrencyCode);

            if (FirstRun)
            {
                FLedgerNumber = ALedgerNumber;
            }

            if (BatchChanged)
            {
                FBatchNumber = ABatchNumber;
            }

            if (BatchStatusChanged)
            {
                FBatchStatus = ABatchStatus;
            }

            if (JournalChanged)
            {
                FJournalNumber = AJournalNumber;
            }

            if (JournalStatusChanged)
            {
                FJournalStatus = AJournalStatus;
            }

            if (CurrencyChanged)
            {
                FTransactionCurrency = ACurrencyCode;
            }

            FIsUnposted = (FBatchRow.BatchStatus == MFinanceConstants.BATCH_UNPOSTED);

            if (FirstRun)
            {
                InitialiseControls();
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;

                //Check if the same batch and journal is selected, so no need to apply filter
                if (!FirstRun
                    && !BatchChanged
                    && !JournalChanged
                    && !BatchStatusChanged
                    && !JournalStatusChanged
                    && !CurrencyChanged
                    && (FMainDS.ATransaction.DefaultView.Count > 0))
                {
                    //Same as previously selected batch and journal

                    //Need to reconnect FPrev in some circumstances
                    if (FPreviouslySelectedDetailRow == null)
                    {
                        DataRowView rowView = (DataRowView)grdDetails.Rows.IndexToDataSourceRow(FPrevRowChangedRow);

                        if (rowView != null)
                        {
                            FPreviouslySelectedDetailRow = (GLBatchTDSATransactionRow)(rowView.Row);
                        }
                    }

                    if (FIsUnposted && (GetSelectedRowIndex() > 0))
                    {
                        if (AFromBatchTab)
                        {
                            SelectRowInGrid(GetSelectedRowIndex());
                        }
                        else
                        {
                            GetDetailsFromControls(FPreviouslySelectedDetailRow);
                        }
                    }

                    FLoadCompleted = true;

                    return false;
                }

                // Different batch selected
                DifferentBatchSelected = true;
                bool requireControlSetup = (FLedgerNumber == -1) || (FTransactionCurrency != ACurrencyCode);

                //Handle dialog
                dlgStatus = new TFrmStatusDialog(FPetraUtilsObject.GetForm());

                if (FShowStatusDialogOnLoad == true)
                {
                    dlgStatus.Show();
                    FShowStatusDialogOnLoad = false;
                    dlgStatus.Heading = String.Format(Catalog.GetString("Batch {0}, Journal {1}"), ABatchNumber, AJournalNumber);
                    dlgStatus.CurrentStatus = Catalog.GetString("Loading transactions ...");
                }

                FLedgerNumber = ALedgerNumber;
                FBatchNumber = ABatchNumber;
                FJournalNumber = AJournalNumber;
                FTransactionNumber = -1;
                FTransactionCurrency = ACurrencyCode;
                FBatchStatus = ABatchStatus;
                FJournalStatus = AJournalStatus;

                FPreviouslySelectedDetailRow = null;
                grdDetails.SuspendLayout();
                //Empty grids before filling them
                grdDetails.DataSource = null;
                grdAnalAttributes.DataSource = null;

                // This sets the main part of the filter but excluding the additional items set by the user GUI
                // It gets the right sort order
                SetTransactionDefaultView();

                //Set the Analysis attributes filter as well
                FAnalysisAttributesLogic = new TAnalysisAttributes(FLedgerNumber, FBatchNumber, FJournalNumber);
                FAnalysisAttributesLogic.SetTransAnalAttributeDefaultView(FMainDS);
                FMainDS.ATransAnalAttrib.DefaultView.AllowNew = false;

                //Load from server if necessary
                if (FMainDS.ATransaction.DefaultView.Count == 0)
                {
                    dlgStatus.CurrentStatus = Catalog.GetString("Requesting transactions from server...");
                    FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransactionATransAnalAttrib(ALedgerNumber, ABatchNumber, AJournalNumber));
                }
                else if (FMainDS.ATransAnalAttrib.DefaultView.Count == 0) // just in case transactions have been loaded in a separate process without analysis attributes
                {
                    dlgStatus.CurrentStatus = Catalog.GetString("Requesting analysis attributes from server...");
                    FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransAnalAttribForJournal(ALedgerNumber, ABatchNumber, AJournalNumber));
                }

                FContainsSystemGenerated = false;

                // check if any of the rows are system generated (i.e. reversals)
                foreach (DataRowView rv in FMainDS.ATransaction.DefaultView)
                {
                    if (((ATransactionRow)rv.Row).SystemGenerated)
                    {
                        FContainsSystemGenerated = true;
                        break;
                    }
                }

                // We need to call this because we have not called ShowData(), which would have set it.  This differs from the Gift screen.
                grdDetails.DataSource = new DevAge.ComponentModel.BoundDataView(FMainDS.ATransaction.DefaultView);

                // Now we set the full filter
                dlgStatus.CurrentStatus = Catalog.GetString("Selecting the records...");
                FFilterAndFindObject.ApplyFilter();

                dlgStatus.CurrentStatus = Catalog.GetString("Configuring analysis attributes ...");

                if (grdAnalAttributes.Columns.Count == 1)
                {
                    grdAnalAttributes.SpecialKeys = GridSpecialKeys.Default | GridSpecialKeys.Tab;

                    FcmbAnalAttribValues = new SourceGrid.Cells.Editors.ComboBox(typeof(string));
                    FcmbAnalAttribValues.EnableEdit = true;
                    FcmbAnalAttribValues.EditableMode = EditableMode.Focus;
                    grdAnalAttributes.AddTextColumn(Catalog.GetString("Value"),
                        FMainDS.ATransAnalAttrib.Columns[ATransAnalAttribTable.GetAnalysisAttributeValueDBName()], 150,
                        FcmbAnalAttribValues);
                    FcmbAnalAttribValues.Control.SelectedValueChanged += new EventHandler(this.AnalysisAttributeValueChanged);

                    grdAnalAttributes.Columns[0].Width = 99;
                }

                grdAnalAttributes.DataSource = new DevAge.ComponentModel.BoundDataView(FMainDS.ATransAnalAttrib.DefaultView);
                grdAnalAttributes.SetHeaderTooltip(0, Catalog.GetString("Type"));
                grdAnalAttributes.SetHeaderTooltip(1, Catalog.GetString("Value"));

                // if this form is readonly or batch is posted, then we need all account and cost centre codes, because old codes might have been used
                bool ActiveOnly = false; //(this.Enabled && FIsUnposted && !FContainsSystemGenerated);

                if (requireControlSetup || (FActiveOnly != ActiveOnly))
                {
                    FActiveOnly = ActiveOnly;

                    //Load all analysis attribute values
                    if (FCacheDS == null)
                    {
                        dlgStatus.CurrentStatus = Catalog.GetString("Loading analysis attributes ...");
                        FCacheDS = TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, FActiveOnly);
                    }

                    SetupExtraGridFunctionality();

                    dlgStatus.CurrentStatus = Catalog.GetString("Initialising accounts and cost centres ...");

                    // We suppress change detection because these are the correct values
                    // Then initialise our combo boxes for the correct account codes and cost centres
                    bool prevSuppressChangeDetection = FPetraUtilsObject.SuppressChangeDetection;
                    FPetraUtilsObject.SuppressChangeDetection = true;
                    TFinanceControls.InitialiseAccountList(ref cmbDetailAccountCode, FLedgerNumber,
                        true, false, ActiveOnly, false, ACurrencyCode, true);
                    TFinanceControls.InitialiseCostCentreList(ref cmbDetailCostCentreCode, FLedgerNumber, true, false, ActiveOnly, false);
                    FPetraUtilsObject.SuppressChangeDetection = prevSuppressChangeDetection;

                    cmbDetailCostCentreCode.AttachedLabel.Text = TFinanceControls.SELECT_VALID_COST_CENTRE;
                    cmbDetailAccountCode.AttachedLabel.Text = TFinanceControls.SELECT_VALID_ACCOUNT;
                }

                UpdateTransactionTotals();
                grdDetails.ResumeLayout();
                FLoadCompleted = true;

                ShowData();
                SelectRowInGrid(1);
                ShowDetails(); //Needed because of how currency is handled
                UpdateChangeableStatus();

                UpdateRecordNumberDisplay();
                FFilterAndFindObject.SetRecordNumberDisplayProperties();

                //Check for missing analysis attributes and their values
                if (FIsUnposted && (grdDetails.Rows.Count > 1))
                {
                    string updatedTransactions = string.Empty;

                    dlgStatus.CurrentStatus = Catalog.GetString("Checking analysis attributes ...");
                    FAnalysisAttributesLogic.ReconcileTransAnalysisAttributes(FMainDS, FCacheDS, out updatedTransactions);

                    if (updatedTransactions.Length > 0)
                    {
                        //Remove trailing comma
                        updatedTransactions = updatedTransactions.Remove(updatedTransactions.Length - 2);
                        MessageBox.Show(String.Format(Catalog.GetString(
                                    "Analysis Attributes have been updated in transaction(s): {0}.{1}{1}Remeber to set their values before posting!"),
                                updatedTransactions,
                                Environment.NewLine),
                            "Analysis Attributes",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information);

                        FPetraUtilsObject.SetChangedFlag();
                    }
                }

                RefreshAnalysisAttributesGrid();
            }
            catch (Exception ex)
            {
                TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}",
                        Utilities.GetMethodSignature(),
                        Environment.NewLine,
                        ex.Message));
                throw ex;
            }
            finally
            {
                if (dlgStatus != null)
                {
                    dlgStatus.Close();
                }

                this.Cursor = Cursors.Default;
            }

            return DifferentBatchSelected;
        }
Beispiel #23
0
        /// <summary>
        /// Calculate the base amount for the transactions, and update the totals for the journals and the current batch
        ///   This assumes that all relevant data has already been loaded
        /// </summary>
        /// <param name="AMainDS"></param>
        /// <param name="ACurrentBatchRow"></param>
        /// <param name="ACurrentJournalNumber"></param>
        /// <returns>false if no change to batch totals</returns>
        public static bool UpdateBatchTotals(ref GLBatchTDS AMainDS,
                                             ref ABatchRow ACurrentBatchRow, Int32 ACurrentJournalNumber = 0)
        {
            #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 (ACurrentBatchRow == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                                                                                         "Function:{0} - The GL Batch data row is null!"),
                                                                                     Utilities.GetMethodName(true)));
            }
            else if (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)
            {
                TLogging.Log(String.Format("Function:{0} - Tried to update totals for non-Unposted Batch:{1}",
                                           Utilities.GetMethodName(true),
                                           ACurrentBatchRow.BatchNumber));
                return(false);
            }

            #endregion Validate Arguments

            bool AmountsUpdated = false;

            decimal BatchDebitTotal  = 0.0m;
            decimal BatchCreditTotal = 0.0m;

            DataView JournalDV = new DataView(AMainDS.AJournal);

            JournalDV.RowFilter = String.Format("{0}={1}",
                                                AJournalTable.GetBatchNumberDBName(),
                                                ACurrentBatchRow.BatchNumber);

            foreach (DataRowView journalView in JournalDV)
            {
                GLBatchTDSAJournalRow journalRow = (GLBatchTDSAJournalRow)journalView.Row;

                if (((ACurrentJournalNumber > 0) && (ACurrentJournalNumber == journalRow.JournalNumber)) ||
                    (ACurrentJournalNumber == 0))
                {
                    if ((UpdateJournalTotals(ref AMainDS, ref journalRow)))
                    {
                        AmountsUpdated = true;
                    }
                }

                BatchDebitTotal  += journalRow.JournalDebitTotal;
                BatchCreditTotal += journalRow.JournalCreditTotal;
            }

            if ((ACurrentBatchRow.BatchDebitTotal != BatchDebitTotal) ||
                (ACurrentBatchRow.BatchCreditTotal != BatchCreditTotal))
            {
                ACurrentBatchRow.BatchDebitTotal  = BatchDebitTotal;
                ACurrentBatchRow.BatchCreditTotal = BatchCreditTotal;
                AmountsUpdated = true;
            }

            return(AmountsUpdated);
        }
        /// <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);
        }
Beispiel #25
0
        private static bool UpdateJournalTotals(ref GLBatchTDS AMainDS,
                                                ref GLBatchTDSAJournalRow ACurrentJournal)
        {
            #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 (ACurrentJournal == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                                                                                         "Function:{0} - The Journal row does not exist or is empty!"),
                                                                                     Utilities.GetMethodName(true)));
            }
            else if (ACurrentJournal.JournalStatus != MFinanceConstants.BATCH_UNPOSTED)
            {
                TLogging.Log(String.Format("Function:{0} - Tried to update totals for non-Unposted Batch:{1} and Journal:{2}",
                                           Utilities.GetMethodName(true),
                                           ACurrentJournal.BatchNumber,
                                           ACurrentJournal.JournalNumber));
                return(false);
            }

            #endregion Validate Arguments

            bool AmountsUpdated = false;

            decimal JournalDebitTotal      = 0.0M;
            decimal JournalDebitTotalBase  = 0.0M;
            decimal JournalCreditTotal     = 0.0M;
            decimal JournalCreditTotalBase = 0.0M;

            if (ACurrentJournal.IsJournalDebitTotalBaseNull()) //DBNull.Value.Equals(ACurrentJournal[GLBatchTDSAJournalTable.ColumnJournalDebitTotalBaseId])
            {
                ACurrentJournal.JournalDebitTotalBase = 0;
                AmountsUpdated = true;
            }

            if (ACurrentJournal.IsJournalCreditTotalBaseNull()) //DBNull.Value.Equals(ACurrentJournal[GLBatchTDSAJournalTable.ColumnJournalCreditTotalBaseId])
            {
                ACurrentJournal.JournalCreditTotalBase = 0;
                AmountsUpdated = true;
            }

            DataView TransDV = new DataView(AMainDS.ATransaction);
            TransDV.RowFilter = String.Format("{0}={1} And {2}={3}",
                                              ATransactionTable.GetBatchNumberDBName(),
                                              ACurrentJournal.BatchNumber,
                                              ATransactionTable.GetJournalNumberDBName(),
                                              ACurrentJournal.JournalNumber);

            if ((TransDV.Count == 0) && (ACurrentJournal.LastTransactionNumber > 0))
            {
                //do not update totals as no transactions loaded as yet so no need to update journal total
                return(AmountsUpdated);
            }

            // transactions are filtered for this journal; add up the total amounts
            foreach (DataRowView drv in TransDV)
            {
                ATransactionRow transRow = (ATransactionRow)drv.Row;

                if (transRow.DebitCreditIndicator)
                {
                    JournalDebitTotal     += transRow.TransactionAmount;
                    JournalDebitTotalBase += transRow.AmountInBaseCurrency;
                }
                else
                {
                    JournalCreditTotal     += transRow.TransactionAmount;
                    JournalCreditTotalBase += transRow.AmountInBaseCurrency;
                }
            }

            if ((ACurrentJournal.JournalDebitTotal != JournalDebitTotal) ||
                (ACurrentJournal.JournalDebitTotalBase != JournalDebitTotalBase) ||
                (ACurrentJournal.JournalCreditTotal != JournalCreditTotal) ||
                (ACurrentJournal.JournalCreditTotalBase != JournalCreditTotalBase))
            {
                ACurrentJournal.JournalDebitTotal      = JournalDebitTotal;
                ACurrentJournal.JournalDebitTotalBase  = JournalDebitTotalBase;
                ACurrentJournal.JournalCreditTotal     = JournalCreditTotal;
                ACurrentJournal.JournalCreditTotalBase = JournalCreditTotalBase;
                AmountsUpdated = true;
            }

            return(AmountsUpdated);
        }
Beispiel #26
0
        public static void UpdateTotalsOfJournal(ref GLBatchTDS AMainDS,
            GLBatchTDSAJournalRow ACurrentJournal)
        {
            if (ACurrentJournal == null)
            {
                return;
            }

            if ((ACurrentJournal.ExchangeRateToBase == 0.0m)
                && (ACurrentJournal.TransactionTypeCode != CommonAccountingTransactionTypesEnum.REVAL.ToString()))
            {
                throw new Exception(String.Format("Batch {0} Journal {1} has invalid exchange rate to base",
                        ACurrentJournal.BatchNumber,
                        ACurrentJournal.JournalNumber));
            }

            ACurrentJournal.JournalDebitTotal = 0.0M;
            ACurrentJournal.JournalDebitTotalBase = 0.0M;
            ACurrentJournal.JournalCreditTotal = 0.0M;
            ACurrentJournal.JournalCreditTotalBase = 0.0M;

            DataView trnsDataView = new DataView(AMainDS.ATransaction);

            trnsDataView.RowFilter = String.Format("{0} = {1} And {2} = {3}",
                ATransactionTable.GetBatchNumberDBName(),
                ACurrentJournal.BatchNumber,
                ATransactionTable.GetJournalNumberDBName(),
                ACurrentJournal.JournalNumber);

            // transactions are filtered for this journal; add up the total amounts
            foreach (DataRowView v in trnsDataView)
            {
                ATransactionRow r = (ATransactionRow)v.Row;

                // recalculate the amount in base currency

                if (ACurrentJournal.TransactionTypeCode != CommonAccountingTransactionTypesEnum.REVAL.ToString())
                {
                    r.AmountInBaseCurrency = GLRoutines.Divide(r.TransactionAmount, ACurrentJournal.ExchangeRateToBase);
                }

                if (r.DebitCreditIndicator)
                {
                    ACurrentJournal.JournalDebitTotal += r.TransactionAmount;
                    ACurrentJournal.JournalDebitTotalBase += r.AmountInBaseCurrency;
                }
                else
                {
                    ACurrentJournal.JournalCreditTotal += r.TransactionAmount;
                    ACurrentJournal.JournalCreditTotalBase += r.AmountInBaseCurrency;
                }
            }
        }
        /// <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, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == 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;
        }