Exemple #1
0
        private void GetLedgerInfo(out DateTime APeriodStartDate, out DateTime APeriodEndDate,
                                   out string AForexGainsLossesAccount, TDataBase ADataBase)
        {
            ALedgerTable LedgerTable = null;

            TDataBase db = DBAccess.Connect("GetLedgerInfo", ADataBase);

            TDBTransaction Transaction = new TDBTransaction();

            DateTime PeriodStartDate         = DateTime.Today;
            DateTime PeriodEndDate           = DateTime.Today;
            string   ForexGainsLossesAccount = String.Empty;

            db.ReadTransaction(ref Transaction,
                               delegate
            {
                LedgerTable = ALedgerAccess.LoadByPrimaryKey(FLedgerNumber, Transaction);

                ForexGainsLossesAccount = LedgerTable[0].ForexGainsLossesAccount;

                TFinancialYear.GetStartAndEndDateOfPeriod(FLedgerNumber, LedgerTable[0].CurrentPeriod, out PeriodStartDate, out PeriodEndDate, Transaction);
            });

            AForexGainsLossesAccount = ForexGainsLossesAccount;
            APeriodStartDate         = PeriodStartDate;
            APeriodEndDate           = PeriodEndDate;
        }
        private static Int32 FindFinancialYearByDate(Int32 ALedgerNumber, DateTime ADate)
        {
            Int32    yearDateBelongsTo = 99;
            DateTime yearStartDate     = DateTime.Today;

            TDBTransaction transaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.Serializable, ref transaction,
                                                                      delegate
            {
                ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, transaction);

                if (LedgerTable.Count == 0)
                {
                    return;
                }

                ALedgerRow LedgerRow = (ALedgerRow)LedgerTable.Rows[0];
                yearDateBelongsTo    = LedgerRow.CurrentFinancialYear;

                AAccountingPeriodTable AccPeriodTable = AAccountingPeriodAccess.LoadViaALedger(ALedgerNumber, transaction);

                if (AccPeriodTable.Count == 0)
                {
                    return;
                }

                //Find earliest start date (don't assume PK order)
                AAccountingPeriodRow AccPeriodRow = null;

                for (int i = 0; i < AccPeriodTable.Count; i++)
                {
                    DateTime currentStartDate;

                    AccPeriodRow     = (AAccountingPeriodRow)AccPeriodTable.Rows[i];
                    currentStartDate = AccPeriodRow.PeriodStartDate;

                    if (i > 0)
                    {
                        if (yearStartDate > currentStartDate)
                        {
                            yearStartDate = currentStartDate;
                        }
                    }
                    else
                    {
                        yearStartDate = currentStartDate;
                    }
                }

                //Find the correct year
                while (ADate < yearStartDate)
                {
                    ADate = ADate.AddYears(1);
                    yearDateBelongsTo--;
                }
            });     // Get NewOrExisting AutoReadTransaction
            //Set the year to return
            return(yearDateBelongsTo);
        } // Find FinancialYear ByDate
        //
        // This will be called if the Fast Reports Wrapper loaded OK.
        // Returns True if the data apparently loaded OK and the report should be printed.
        private bool LoadReportData(TRptCalculator ACalc)
        {
            String RootCostCentre = "[" + FLedgerNumber + "]";

            ACalc.AddParameter("param_cost_centre_code", new TVariant(RootCostCentre));

            // I need to get the name of the current ledger..

            ALedgerTable LedgerTbl = TRemote.MFinance.AP.WebConnectors.GetLedgerInfo(FLedgerNumber);

            Boolean IsClosed = false;

            if (LedgerTbl.Rows.Count > 0)
            {
                ALedgerRow LedgerRow = LedgerTbl[0];
                //
                // I want to tell the user whether the selected period is closed
                // (although they probably know already...)
                Int32 SelPeriod = ACalc.GetParameters().GetParameter("param_end_period_i").value.ToInt32();
                Int32 SelYear   = ACalc.GetParameters().GetParameter("param_year_i").value.ToInt32();

                if ((SelYear < LedgerRow.CurrentFinancialYear) || (SelPeriod < LedgerRow.CurrentPeriod))
                {
                    IsClosed = true;
                }
            }

            String LedgerName = TRemote.MFinance.Reporting.WebConnectors.GetLedgerName(FLedgerNumber);

            ACalc.AddStringParameter("param_ledger_name", LedgerName);
            ACalc.AddParameter("param_period_closed", IsClosed);

            return(FPetraUtilsObject.FFastReportsPlugin.LoadReportData("TrialBalance", false, new string[] { "TrialBalance" }, ACalc, this, false));
        }
        /// <summary>
        /// build an XML document which includes all ledgers etc.
        /// </summary>
        public static XmlNode BuildNavigationXml(bool ADontUseDefaultLedger = false)
        {
            TYml2Xml    parser       = new TYml2Xml(TAppSettingsManager.GetValue("UINavigation.File"));
            XmlDocument UINavigation = parser.ParseYML2XML();

            ALedgerTable AvailableLedgers = new ALedgerTable();

            if (UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE1))
            {
                AvailableLedgers = TRemote.MFinance.Setup.WebConnectors.GetAvailableLedgers();
            }

            XmlNode OpenPetraNode   = UINavigation.FirstChild.NextSibling.FirstChild;
            XmlNode SearchBoxesNode = OpenPetraNode.FirstChild;
            XmlNode MainMenuNode    = SearchBoxesNode.NextSibling;

            if (TFormsList.GSingletonForms.Count == 0)      // There is no need to re-record all Singleton screens if this was already done once
            {
                RecordAllSingletonScreens(MainMenuNode);
            }

            AddNavigationForEachLedger(MainMenuNode, AvailableLedgers, ADontUseDefaultLedger);

            if (UserInfo.GUserInfo.IsInModule("PTNRUSER") && UserInfo.GUserInfo.IsInModule("CONFERENCE"))
            {
                AddConferenceInformation(MainMenuNode);
            }

            return(MainMenuNode);
        }
Exemple #5
0
        public static Boolean GetCurrentPeriodDates(Int32 ALedgerNumber,
                                                    out DateTime AStartDateCurrentPeriod,
                                                    out DateTime AEndDateCurrentPeriod)
        {
            DateTime       startDate   = new DateTime();
            DateTime       endDate     = new DateTime();
            TDBTransaction Transaction = new TDBTransaction();
            TDataBase      db          = DBAccess.Connect("GetCurrentPeriodDates");

            db.ReadTransaction(
                ref Transaction,
                delegate
            {
                ALedgerTable ledgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);
                AAccountingPeriodTable accountingPeriodTable = AAccountingPeriodAccess.LoadByPrimaryKey(ALedgerNumber,
                                                                                                        ledgerTable[0].CurrentPeriod,
                                                                                                        Transaction);
                startDate = accountingPeriodTable[0].PeriodStartDate;
                endDate   = accountingPeriodTable[0].PeriodEndDate;
            });

            db.CloseDBConnection();

            AStartDateCurrentPeriod = startDate;
            AEndDateCurrentPeriod   = endDate;
            return(true);
        }
Exemple #6
0
        /// <summary>
        /// create a new batch with a consecutive batch number in the ledger
        /// for call inside a server function
        /// for performance reasons submitting (save the data in the database) is done later (not here)
        /// </summary>
        /// <param name="MainDS"></param>
        /// <param name="Transaction"></param>
        /// <param name="LedgerTable"></param>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ADateEffective"></param>
        /// <param name="AForceEffectiveDateToFit"></param>
        /// <returns>the new gift batch row</returns>
        public static AGiftBatchRow CreateANewGiftBatchRow(ref GiftBatchTDS MainDS,
                                                           ref TDBTransaction Transaction,
                                                           ref ALedgerTable LedgerTable,
                                                           Int32 ALedgerNumber,
                                                           DateTime ADateEffective,
                                                           bool AForceEffectiveDateToFit = true)
        {
            AGiftBatchRow NewRow = MainDS.AGiftBatch.NewRowTyped(true);

            NewRow.LedgerNumber = ALedgerNumber;
            LedgerTable[0].LastGiftBatchNumber++;
            NewRow.BatchNumber = LedgerTable[0].LastGiftBatchNumber;
            Int32 BatchYear, BatchPeriod;

            // if DateEffective is outside the range of open periods, use the most fitting date
            TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber,
                                                      ref ADateEffective,
                                                      out BatchYear,
                                                      out BatchPeriod,
                                                      Transaction,
                                                      AForceEffectiveDateToFit);
            NewRow.BatchYear          = BatchYear;
            NewRow.BatchPeriod        = BatchPeriod;
            NewRow.GlEffectiveDate    = ADateEffective;
            NewRow.ExchangeRateToBase = 1.0M;
            NewRow.BatchDescription   = "PLEASE ENTER A DESCRIPTION";
            NewRow.BankAccountCode    = TLedgerInfo.GetDefaultBankAccount(ALedgerNumber);
            NewRow.BankCostCentre     = TLedgerInfo.GetStandardCostCentre(ALedgerNumber);
            NewRow.CurrencyCode       = LedgerTable[0].BaseCurrency;
            MainDS.AGiftBatch.Rows.Add(NewRow);
            return(NewRow);
        }
        public static System.DateTime GetPeriodEndDate(Int32 ALedgerNumber, System.Int32 AYear, System.Int32 ADiffPeriod,
                                                       System.Int32 APeriod, TDataBase ADataBase)
        {
            System.Int32 RealYear       = 0;
            System.Int32 RealPeriod     = 0;
            System.Type  typeofTable    = null;
            TCacheable   CachePopulator = new TCacheable();
            DateTime     ReturnValue    = DateTime.Now;

            GetRealPeriod(ALedgerNumber, ADiffPeriod, AYear, APeriod, out RealPeriod, out RealYear);
            DataTable UntypedTable = CachePopulator.GetCacheableTable(TCacheableFinanceTablesEnum.AccountingPeriodList,
                                                                      "",
                                                                      false,
                                                                      ALedgerNumber,
                                                                      out typeofTable, ADataBase);
            AAccountingPeriodTable CachedDataTable = (AAccountingPeriodTable)UntypedTable;

            CachedDataTable.DefaultView.RowFilter = AAccountingPeriodTable.GetAccountingPeriodNumberDBName() + " = " + RealPeriod;

            if (CachedDataTable.DefaultView.Count > 0)
            {
                ReturnValue = ((AAccountingPeriodRow)CachedDataTable.DefaultView[0].Row).PeriodEndDate;

                ALedgerTable Ledger = (ALedgerTable)CachePopulator.GetCacheableTable(TCacheableFinanceTablesEnum.LedgerDetails,
                                                                                     "",
                                                                                     false,
                                                                                     ALedgerNumber,
                                                                                     out typeofTable, ADataBase);

                ReturnValue = ReturnValue.AddYears(RealYear - Ledger[0].CurrentFinancialYear);
            }

            return(ReturnValue);
        }
        /// create new AP info
        public static AApDocumentRow CreateNewAPInfo(Int64 APartnerKey, ref AccountsPayableTDS AMainDS)
        {
            ALedgerTable LedgerTable = ALedgerAccess.LoadAll(DBAccess.GDBAccessObj.Transaction);

            AMainDS = TAPTransactionWebConnector.CreateAApDocument(((ALedgerRow)LedgerTable.Rows[0]).LedgerNumber, APartnerKey, true);

            // Create a new RecurringGiftBatch
            AApDocumentRow Document = AMainDS.AApDocument[0];

            Document.DocumentCode     = "TEST";
            Document.CreditNoteFlag   = false;
            Document.DateIssued       = DateTime.Today;
            Document.DateEntered      = DateTime.Today;
            Document.TotalAmount      = 0;
            Document.CurrencyCode     = "EUR";
            Document.LastDetailNumber = 0;

            // Create a new RecurringGift record
            AApSupplierRow ApSupplierRow = AMainDS.AApSupplier.NewRowTyped();

            ApSupplierRow.PartnerKey   = APartnerKey;
            ApSupplierRow.CurrencyCode = "EUR";
            AMainDS.AApSupplier.Rows.Add(ApSupplierRow);

            return(Document);
        }
Exemple #9
0
        public static Boolean GetCurrentPeriodDates(Int32 ALedgerNumber,
                                                    out DateTime AStartDateCurrentPeriod,
                                                    out DateTime AEndDateCurrentPeriod)
        {
            DateTime       startDate   = new DateTime();
            DateTime       endDate     = new DateTime();
            TDBTransaction Transaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                      TEnforceIsolationLevel.eilMinimum,
                                                                      ref Transaction,
                                                                      delegate
            {
                ALedgerTable ledgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);
                AAccountingPeriodTable accountingPeriodTable = AAccountingPeriodAccess.LoadByPrimaryKey(ALedgerNumber,
                                                                                                        ledgerTable[0].CurrentPeriod,
                                                                                                        Transaction);
                startDate = accountingPeriodTable[0].PeriodStartDate;
                endDate   = accountingPeriodTable[0].PeriodEndDate;
            });

            AStartDateCurrentPeriod = startDate;
            AEndDateCurrentPeriod   = endDate;
            return(true);
        }
Exemple #10
0
        /// <summary>
        /// create a new batch with a consecutive batch number in the ledger
        /// for call inside a server function
        /// for performance reasons submitting (save the data in the database) is done later (not here)
        /// </summary>
        /// <param name="MainDS"></param>
        /// <param name="Transaction"></param>
        /// <param name="LedgerTable"></param>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ADateEffective"></param>
        /// <param name="AForceEffectiveDateToFit"></param>
        /// <returns>the new gift batch row</returns>
        public static AGiftBatchRow CreateANewGiftBatchRow(ref GiftBatchTDS MainDS,
            ref TDBTransaction Transaction,
            ref ALedgerTable LedgerTable,
            Int32 ALedgerNumber,
            DateTime ADateEffective,
            bool AForceEffectiveDateToFit = true)
        {
            AGiftBatchRow NewRow = MainDS.AGiftBatch.NewRowTyped(true);

            NewRow.LedgerNumber = ALedgerNumber;
            LedgerTable[0].LastGiftBatchNumber++;
            NewRow.BatchNumber = LedgerTable[0].LastGiftBatchNumber;
            Int32 BatchYear, BatchPeriod;
            // if DateEffective is outside the range of open periods, use the most fitting date
            TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber,
                ref ADateEffective,
                out BatchYear,
                out BatchPeriod,
                Transaction,
                AForceEffectiveDateToFit);
            NewRow.BatchYear = BatchYear;
            NewRow.BatchPeriod = BatchPeriod;
            NewRow.GlEffectiveDate = ADateEffective;
            NewRow.ExchangeRateToBase = 1.0M;
            NewRow.BatchDescription = "PLEASE ENTER A DESCRIPTION";
            NewRow.BankAccountCode = TLedgerInfo.GetDefaultBankAccount(ALedgerNumber);
            NewRow.BankCostCentre = TLedgerInfo.GetStandardCostCentre(ALedgerNumber);
            NewRow.CurrencyCode = LedgerTable[0].BaseCurrency;
            MainDS.AGiftBatch.Rows.Add(NewRow);
            return NewRow;
        }
Exemple #11
0
        /// <summary>
        /// build an XML document which includes all ledgers etc.
        /// </summary>
        public static XmlNode BuildNavigationXml(bool ADontUseDefaultLedger = false)
        {
            string UINavigationFile = TAppSettingsManager.GetValue("UINavigation.File");

            if (!File.Exists(UINavigationFile))
            {
                throw new Exception("cannot find file " + UINavigationFile);
            }

            TYml2Xml    parser       = new TYml2Xml(UINavigationFile);
            XmlDocument UINavigation = parser.ParseYML2XML();

            ALedgerTable AvailableLedgers = new ALedgerTable();

            if (UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE1))
            {
                AvailableLedgers = TGLSetupWebConnector.GetAvailableLedgers();
            }

            XmlNode OpenPetraNode = UINavigation.FirstChild.NextSibling.FirstChild;
            XmlNode MainMenuNode  = OpenPetraNode.FirstChild;

            AddNavigationForEachLedger(MainMenuNode, AvailableLedgers, ADontUseDefaultLedger);

            return(MainMenuNode);
        }
        public static Int32 GetNumberOfPeriods(
            System.Int32 ALedgerNumber)
        {
            Int32 returnValue = 0;

            bool newTransaction = false;

            try
            {
                TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.Serializable, out newTransaction);

                ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);

                returnValue = LedgerTable[0].NumberOfAccountingPeriods;
            }
            finally
            {
                if (newTransaction)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }
            }

            return(returnValue);
        }
Exemple #13
0
        public static Boolean GetCurrentPostingRangeDates(Int32 ALedgerNumber,
                                                          out DateTime AStartDateCurrentPeriod,
                                                          out DateTime AEndDateLastForwardingPeriod)
        {
            DateTime       StartDateCurrentPeriod      = new DateTime();
            DateTime       EndDateLastForwardingPeriod = new DateTime();
            TDBTransaction Transaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                      TEnforceIsolationLevel.eilMinimum,
                                                                      ref Transaction,
                                                                      delegate
            {
                ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);
                AAccountingPeriodTable AccountingPeriodTable = AAccountingPeriodAccess.LoadByPrimaryKey(ALedgerNumber,
                                                                                                        LedgerTable[0].CurrentPeriod,
                                                                                                        Transaction);

                StartDateCurrentPeriod = AccountingPeriodTable[0].PeriodStartDate;

                AccountingPeriodTable = AAccountingPeriodAccess.LoadByPrimaryKey(ALedgerNumber,
                                                                                 LedgerTable[0].CurrentPeriod + LedgerTable[0].NumberFwdPostingPeriods,
                                                                                 Transaction);
                EndDateLastForwardingPeriod = AccountingPeriodTable[0].PeriodEndDate;
            });

            AStartDateCurrentPeriod      = StartDateCurrentPeriod;
            AEndDateLastForwardingPeriod = EndDateLastForwardingPeriod;

            return(true);
        }
        public static System.DateTime GetPeriodEndDate(Int32 ALedgerNumber, System.Int32 AYear, System.Int32 ADiffPeriod, System.Int32 APeriod)
        {
            System.Int32 RealYear       = 0;
            System.Int32 RealPeriod     = 0;
            System.Type  typeofTable    = null;
            TCacheable   CachePopulator = new TCacheable();
            DateTime     ReturnValue    = DateTime.Now;

            GetRealPeriod(ALedgerNumber, ADiffPeriod, AYear, APeriod, out RealPeriod, out RealYear);
            DataTable CachedDataTable = CachePopulator.GetCacheableTable(TCacheableFinanceTablesEnum.AccountingPeriodList,
                                                                         "",
                                                                         false,
                                                                         ALedgerNumber,
                                                                         out typeofTable);
            string whereClause = AAccountingPeriodTable.GetLedgerNumberDBName() + " = " + ALedgerNumber.ToString() + " and " +
                                 AAccountingPeriodTable.GetAccountingPeriodNumberDBName() + " = " + RealPeriod.ToString();

            DataRow[] filteredRows = CachedDataTable.Select(whereClause);

            if (filteredRows.Length > 0)
            {
                ReturnValue = ((AAccountingPeriodRow)filteredRows[0]).PeriodEndDate;

                ALedgerTable Ledger = (ALedgerTable)CachePopulator.GetCacheableTable(TCacheableFinanceTablesEnum.LedgerDetails,
                                                                                     "",
                                                                                     false,
                                                                                     ALedgerNumber,
                                                                                     out typeofTable);

                ReturnValue = ReturnValue.AddYears(RealYear - Ledger[0].CurrentFinancialYear);
            }

            return(ReturnValue);
        }
        public static bool GetAccountingYearPeriodByDate(Int32 ALedgerNumber,
                                                         DateTime ADate,
                                                         out Int32 AYearNumber,
                                                         out Int32 APeriodNumber)
        {
            bool  newTransaction;
            Int32 CurrentFinancialYear;

            //Set the year to return
            AYearNumber = FindFinancialYearByDate(ALedgerNumber, ADate);

            if (AYearNumber == 99)
            {
                AYearNumber   = 0;
                APeriodNumber = 0;
                return(false);
            }

            TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.Serializable, out newTransaction);

            ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);

            CurrentFinancialYear = ((ALedgerRow)LedgerTable.Rows[0]).CurrentFinancialYear;

            AAccountingPeriodTable AccPeriodTableTmp = new AAccountingPeriodTable();
            AAccountingPeriodRow   TemplateRow       = AccPeriodTableTmp.NewRowTyped(false);

            TemplateRow.LedgerNumber    = ALedgerNumber;
            TemplateRow.PeriodStartDate = ADate.AddYears(CurrentFinancialYear - AYearNumber);
            TemplateRow.PeriodEndDate   = ADate.AddYears(CurrentFinancialYear - AYearNumber);

            StringCollection operators = StringHelper.InitStrArr(new string[] { "=", "<=", ">=" });

            AAccountingPeriodTable AccountingPeriodTable = AAccountingPeriodAccess.LoadUsingTemplate(TemplateRow,
                                                                                                     operators,
                                                                                                     null,
                                                                                                     Transaction);

            if ((AccountingPeriodTable == null) || (AccountingPeriodTable.Count == 0))
            {
                if (newTransaction)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }

                APeriodNumber = 0;
                return(false);
            }

            AAccountingPeriodRow AccountingPeriodRow = (AAccountingPeriodRow)AccountingPeriodTable.Rows[0];

            APeriodNumber = AccountingPeriodRow.AccountingPeriodNumber;

            if (newTransaction)
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
            }

            return(true);
        }
        public static bool GetCurrentPostingRangeDates(Int32 ALedgerNumber,
                                                       out DateTime AStartDateCurrentPeriod,
                                                       out DateTime AEndDateLastForwardingPeriod)
        {
            bool newTransaction = false;

            TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.Serializable, out newTransaction);

            ALedgerTable           LedgerTable           = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);
            AAccountingPeriodTable AccountingPeriodTable = AAccountingPeriodAccess.LoadByPrimaryKey(ALedgerNumber,
                                                                                                    LedgerTable[0].CurrentPeriod,
                                                                                                    Transaction);

            AStartDateCurrentPeriod = AccountingPeriodTable[0].PeriodStartDate;

            AccountingPeriodTable = AAccountingPeriodAccess.LoadByPrimaryKey(ALedgerNumber,
                                                                             LedgerTable[0].CurrentPeriod + LedgerTable[0].NumberFwdPostingPeriods,
                                                                             Transaction);
            AEndDateLastForwardingPeriod = AccountingPeriodTable[0].PeriodEndDate;

            if (newTransaction)
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
            }

            return(true);
        }
Exemple #17
0
        private void RunOnceOnActivationManual()
        {
            // Set the Tag for the checkbox since we don't want changes to the checkbox to look like we have to save the data
            this.chkHideOthers.Tag = MCommon.MCommonResourcestrings.StrCtrlSuppressChangeDetection;

            // Activate events we will use in manual code
            this.txtDetailRateOfExchange.TextChanged +=
                new System.EventHandler(this.txtDetailRateOfExchange_TextChanged);

            // These Leave events are all fired before validation updates the row
            // This is important because we need to suggest a new date/rate depending on the selection made
            //  and so we need to be able to check on the existence of specific rows in the data table before they get updated on validation
            this.cmbDetailFromCurrencyCode.Leave +=
                new System.EventHandler(this.CurrencyCodeComboBox_Leave);
            this.cmbDetailToCurrencyCode.Leave +=
                new System.EventHandler(this.CurrencyCodeComboBox_Leave);
            this.dtpDetailDateEffectiveFrom.Leave +=
                new EventHandler(dtpDetailDateEffectiveFrom_Leave);

            this.btnInvertExchangeRate.Click +=
                new System.EventHandler(this.InvertExchangeRate);
            this.chkHideOthers.CheckedChanged +=
                new EventHandler(chkHideOthers_CheckedChanged);

            FPetraUtilsObject.DataSavingStarted += new TDataSavingStartHandler(FPetraUtilsObject_DataSavingStarted);

            if (baseCurrencyOfLedger == null)
            {
                // Have a last attempt at deciding what the base currency is...
                // What ledgers does the user have access to??
                ALedgerTable ledgers    = TRemote.MFinance.Setup.WebConnectors.GetAvailableLedgers();
                DataView     ledgerView = ledgers.DefaultView;
                ledgerView.RowFilter = "a_ledger_status_l = 1";     // Only view 'in use' ledgers

                if (ledgerView.Count > 0)
                {
                    // There is at least one - so default to the currency of the first one
                    baseCurrencyOfLedger = ((ALedgerRow)ledgerView.Table.Rows[0]).BaseCurrency;
                }
            }

            DataView myView = FMainDS.ACorporateExchangeRate.DefaultView;

            myView.Sort = ACorporateExchangeRateTable.GetToCurrencyCodeDBName() + ", " +
                          ACorporateExchangeRateTable.GetFromCurrencyCodeDBName() + ", " +
                          ACorporateExchangeRateTable.GetDateEffectiveFromDBName() + " DESC";
            myView.RowFilter = "";

            if (myView.Count > 0)
            {
                // We have to use this construct because simple ShoWDetails requires two cursor down keypresses to move the cursor
                // because we have changed the row filter.
                grdDetails.Selection.Focus(new SourceGrid.Position(1, 0), false);
                ShowDetails();
            }
            else
            {
                ShowDetails(null);
            }
        }
        /// create new AP info
        public static AApDocumentRow CreateNewAPInfo(Int64 APartnerKey, ref AccountsPayableTDS AMainDS, TDataBase ADataBase = null)
        {
            TDataBase      db          = DBAccess.Connect("CreateNewAPInfo", ADataBase);
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            ALedgerTable LedgerTable = ALedgerAccess.LoadAll(Transaction);

            AMainDS = TAPTransactionWebConnector.CreateAApDocument(((ALedgerRow)LedgerTable.Rows[0]).LedgerNumber, APartnerKey, true, db);

            // Create a new RecurringGiftBatch
            AApDocumentRow Document = AMainDS.AApDocument[0];

            Document.DocumentCode     = "TEST";
            Document.CreditNoteFlag   = false;
            Document.DateIssued       = DateTime.Today;
            Document.DateEntered      = DateTime.Today;
            Document.TotalAmount      = 0;
            Document.CurrencyCode     = "EUR";
            Document.LastDetailNumber = 0;

            // Create a new RecurringGift record
            AApSupplierRow ApSupplierRow = AMainDS.AApSupplier.NewRowTyped();

            ApSupplierRow.PartnerKey   = APartnerKey;
            ApSupplierRow.CurrencyCode = "EUR";
            AMainDS.AApSupplier.Rows.Add(ApSupplierRow);

            Transaction.Commit();

            return(Document);
        }
        /// <summary>
        /// Get the start and end date of the given period in the given year
        /// </summary>
        public static bool GetStartAndEndDateOfPeriod(Int32 ALedgerNumber,
                                                      Int32 AYear,
                                                      Int32 APeriodNumber,
                                                      out DateTime APeriodStartDate,
                                                      out DateTime APeriodEndDate,
                                                      TDBTransaction ATransaction)
        {
            #region Validate Arguments

            if (ALedgerNumber <= 0)
            {
                throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString(
                                                                                       "Function:{0} - The Ledger number must be greater than 0!"),
                                                                                   Utilities.GetMethodName(true)), ALedgerNumber);
            }

            // ATransaction can be null
            //else if (ATransaction == null)
            //{
            //    throw new EFinanceSystemDBTransactionNullException(String.Format(Catalog.GetString(
            //                "Function:{0} - Database Transaction must not be NULL!"),
            //            Utilities.GetMethodName(true)));
            //}

            #endregion Validate Arguments

            // invalid period
            if (APeriodNumber == -1)
            {
                APeriodStartDate = DateTime.MinValue;
                APeriodEndDate   = DateTime.MaxValue;
                return(false);
            }

            AAccountingPeriodTable AccPeriodTable = AAccountingPeriodAccess.LoadByPrimaryKey(ALedgerNumber, APeriodNumber, ATransaction);

            #region Validate Data

            if ((AccPeriodTable == null) || (AccPeriodTable.Count == 0))
            {
                throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString(
                                                                                           "Function:{0} - Accounting Period data for period {1} in Ledger number {2} does not exist or could not be accessed!"),
                                                                                       Utilities.GetMethodName(true),
                                                                                       APeriodNumber,
                                                                                       ALedgerNumber));
            }

            #endregion Validate Data

            AAccountingPeriodRow AccPeriodRow = (AAccountingPeriodRow)AccPeriodTable.Rows[0];
            ALedgerTable         LedgerTable  = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, ATransaction);
            Int32 currentYear = LedgerTable[0].CurrentFinancialYear;
            Int32 yearsAgo    = currentYear - AYear;

            APeriodStartDate = AccPeriodRow.PeriodStartDate.AddYears(0 - yearsAgo);
            APeriodEndDate   = AccPeriodRow.PeriodEndDate.AddYears(0 - yearsAgo);

            return(true);
        }
Exemple #20
0
        private Boolean LoadReportData(TRptCalculator ACalc)
        {
            ArrayList reportParam = ACalc.GetParameters().Elems;

            Dictionary <String, TVariant> paramsDictionary = new Dictionary <string, TVariant>();

            foreach (Shared.MReporting.TParameter p in reportParam)
            {
                if (p.name.StartsWith("param") && (p.name != "param_calculation") && !paramsDictionary.ContainsKey(p.name))
                {
                    paramsDictionary.Add(p.name, p.value);
                }
            }

            // get data for this report
            DataSet ReportDataSet = TRemote.MReporting.WebConnectors.GetOneYearMonthGivingDataSet(paramsDictionary);

            if (TRemote.MReporting.WebConnectors.DataTableGenerationWasCancelled() || this.IsDisposed)
            {
                return(false);
            }

            // if no recipients
            if (ReportDataSet.Tables["Recipients"] == null)
            {
                FPetraUtilsObject.WriteToStatusBar("No recipients found for this report period.");
                return(false);
            }

            // register datatables with the report
            FPetraUtilsObject.FFastReportsPlugin.RegisterData(ReportDataSet.Tables["Recipients"], "Recipients");
            FPetraUtilsObject.FFastReportsPlugin.RegisterData(ReportDataSet.Tables["Donors"], "Donors");

            //
            // My report doesn't need a ledger row - only the name of the ledger. And I need the currency formatter..
            String       LedgerName         = TRemote.MFinance.Reporting.WebConnectors.GetLedgerName(FLedgerNumber);
            ALedgerTable LedgerDetailsTable = (ALedgerTable)TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.LedgerDetails,
                                                                                                          FLedgerNumber);
            ALedgerRow Row = LedgerDetailsTable[0];

            ACalc.AddStringParameter("param_ledger_name", LedgerName);
            String CurrencyName = (cmbCurrency.SelectedItem.ToString() == "Base") ? Row.BaseCurrency : Row.IntlCurrency;

            ACalc.AddStringParameter("param_currency_name", CurrencyName);

            ACalc.AddStringParameter("param_currency_formatter", "0,0.000");

            Boolean HasData = ReportDataSet.Tables["Recipients"].Rows.Count > 0;

            if (!HasData)
            {
                MessageBox.Show(Catalog.GetString(
                                    "No Recipients found."), "Recipient Gift Statement");
            }

            return(HasData);
        }
        private void RunOnceOnActivationManual()
        {
            ALedgerTable ledgers = TRemote.MFinance.Setup.WebConnectors.GetAvailableLedgers();

            if (ledgers.Count > 0)
            {
                FLedgerBaseCurrency = ledgers[0].BaseCurrency;
            }
        }
Exemple #22
0
        public static bool GetAccountingYearPeriodByDate(Int32 ALedgerNumber,
                                                         DateTime ADate,
                                                         out Int32 AYearNumber,
                                                         out Int32 APeriodNumber)
        {
            Int32 CurrentFinancialYear;

            //Set the year to return
            Int32 YearNumber = FindFinancialYearByDate(ALedgerNumber, ADate);

            AYearNumber = YearNumber;

            if (AYearNumber == 99)
            {
                AYearNumber   = 0;
                APeriodNumber = 0;
                return(false);
            }

            Int32 PeriodNumber = 0;

            TDBTransaction transaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.Serializable, ref transaction,
                                                                      delegate
            {
                ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, transaction);

                CurrentFinancialYear = ((ALedgerRow)LedgerTable.Rows[0]).CurrentFinancialYear;

                AAccountingPeriodTable AccPeriodTableTmp = new AAccountingPeriodTable();
                AAccountingPeriodRow TemplateRow         = AccPeriodTableTmp.NewRowTyped(false);

                TemplateRow.LedgerNumber    = ALedgerNumber;
                TemplateRow.PeriodStartDate = ADate.AddYears(CurrentFinancialYear - YearNumber);
                TemplateRow.PeriodEndDate   = ADate.AddYears(CurrentFinancialYear - YearNumber);

                StringCollection operators = StringHelper.InitStrArr(new string[] { "=", "<=", ">=" });

                AAccountingPeriodTable AccountingPeriodTable = AAccountingPeriodAccess.LoadUsingTemplate(TemplateRow,
                                                                                                         operators,
                                                                                                         null,
                                                                                                         transaction);

                if (AccountingPeriodTable.Count == 0)
                {
                    return;
                }

                AAccountingPeriodRow AccountingPeriodRow = (AAccountingPeriodRow)AccountingPeriodTable.Rows[0];

                PeriodNumber = AccountingPeriodRow.AccountingPeriodNumber;
            });

            APeriodNumber = PeriodNumber;
            return(true);
        } // Get AccountingYear Period ByDate
        //
        // This will be called if the Fast Reports Wrapper loaded OK.
        // Returns True if the data apparently loaded OK and the report should be printed.
        private bool LoadReportData(TRptCalculator ACalc)
        {
            ArrayList reportParam = ACalc.GetParameters().Elems;

            Dictionary <String, TVariant> paramsDictionary = new Dictionary <string, TVariant>();

            foreach (Shared.MReporting.TParameter p in reportParam)
            {
                if (p.name.StartsWith("param") && (p.name != "param_calculation") && (!paramsDictionary.ContainsKey(p.name)))
                {
                    paramsDictionary.Add(p.name, p.value);
                }
            }

            String RootCostCentre = "[" + FLedgerNumber + "]";

            paramsDictionary.Add("param_cost_centre_code", new TVariant(RootCostCentre));

            DataTable ReportTable = TRemote.MReporting.WebConnectors.GetReportDataTable("TrialBalance", paramsDictionary);

            if (ReportTable == null)
            {
                FPetraUtilsObject.WriteToStatusBar("Report Cancelled.");
                return(false);
            }

            FPetraUtilsObject.FFastReportsPlugin.RegisterData(ReportTable, "TrialBalance");

            //
            // I need to get the name of the current ledger..

            ALedgerTable LedgerTbl = TRemote.MFinance.AP.WebConnectors.GetLedgerInfo(FLedgerNumber);

            String  LedgerName = "";
            Boolean IsClosed   = false;

            if (LedgerTbl.Rows.Count > 0)
            {
                ALedgerRow LedgerRow = LedgerTbl[0];
                LedgerName = LedgerRow.LedgerName;
                //
                // I want to tell the user whether the selected period is closed
                // (although they probably know already...)
                Int32 SelPeriod = ACalc.GetParameters().GetParameter("param_end_period_i").value.ToInt32();
                Int32 SelYear   = ACalc.GetParameters().GetParameter("param_year_i").value.ToInt32();

                if ((SelYear < LedgerRow.CurrentFinancialYear) || (SelPeriod < LedgerRow.CurrentPeriod))
                {
                    IsClosed = true;
                }
            }

            ACalc.AddStringParameter("param_ledger_name", LedgerName);
            ACalc.AddParameter("param_period_closed", IsClosed);

            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="ALedgerNumber"></param>
        /// <param name="APaymentNumber"></param>
        public void ReloadPayment(Int32 ALedgerNumber, Int32 APaymentNumber)
        {
            FMainDS       = TRemote.MFinance.AP.WebConnectors.LoadAPPayment(ALedgerNumber, APaymentNumber);
            FLedgerNumber = FMainDS.AApPayment[0].LedgerNumber;
            ALedgerTable Tbl = TRemote.MFinance.AP.WebConnectors.GetLedgerInfo(FLedgerNumber);

            FLedgerRow = Tbl[0];
            ShowData(FMainDS.AApSupplier[0]);
        }
Exemple #25
0
        /// create a new gift batch using some of the details of an existing gift batch
        private static AGiftBatchRow CreateNewGiftBatch(
            Int32 ALedgerNumber,
            Int32 ABatchNumber,
            DateTime ADateEffective,
            GiftAdjustmentFunctionEnum AFunction,
            ref GiftBatchTDS AMainDS,
            ref ALedgerTable ALedgerTable,
            TDBTransaction ATransaction)
        {
            AGiftBatchRow ReturnValue;

            AGiftBatchAccess.LoadByPrimaryKey(AMainDS, ALedgerNumber, ABatchNumber, ATransaction);

            AGiftBatchRow oldGiftBatch = AMainDS.AGiftBatch[0];

            TGiftBatchFunctions.CreateANewGiftBatchRow(ref AMainDS, ref ATransaction, ref ALedgerTable, ALedgerNumber, ADateEffective);
            ReturnValue = AMainDS.AGiftBatch[1];
            ReturnValue.BankAccountCode     = oldGiftBatch.BankAccountCode;
            ReturnValue.BankCostCentre      = oldGiftBatch.BankCostCentre;
            ReturnValue.CurrencyCode        = oldGiftBatch.CurrencyCode;
            ReturnValue.ExchangeRateToBase  = oldGiftBatch.ExchangeRateToBase;
            ReturnValue.MethodOfPaymentCode = oldGiftBatch.MethodOfPaymentCode;
            ReturnValue.HashTotal           = 0;

            if (ReturnValue.MethodOfPaymentCode.Length == 0)
            {
                ReturnValue.SetMethodOfPaymentCodeNull();
            }

            ReturnValue.BankCostCentre = oldGiftBatch.BankCostCentre;
            ReturnValue.GiftType       = oldGiftBatch.GiftType;

            if (AFunction.Equals(GiftAdjustmentFunctionEnum.AdjustGift))
            {
                ReturnValue.BatchDescription = Catalog.GetString("Gift Adjustment");
            }
            else if (AFunction.Equals(GiftAdjustmentFunctionEnum.AdjustGiftBatch))
            {
                ReturnValue.BatchDescription = Catalog.GetString("Gift Batch Adjustment");
            }
            else if (AFunction.Equals(GiftAdjustmentFunctionEnum.FieldAdjust))
            {
                ReturnValue.BatchDescription = Catalog.GetString("Gift Adjustment (Field Change)");
            }
            else if (AFunction.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust))
            {
                ReturnValue.BatchDescription = Catalog.GetString("Gift Adjustment (Tax Deductible Pct Change)");
            }
            else
            {
                ReturnValue.BatchDescription = Catalog.GetString("Reverse Gift");
            }

            return(ReturnValue);
        }
Exemple #26
0
        /// <summary>
        /// init the exchange rate, to avoid messages "Cannot find exchange rate for EUR USD"
        /// </summary>
        public static void InitExchangeRate()
        {
            TAccountPeriodInfo AccountingPeriodInfo =
                new TAccountPeriodInfo(FLedgerNumber, 1);
            ADailyExchangeRateTable dailyrates = new ADailyExchangeRateTable();
            ADailyExchangeRateRow   row        = dailyrates.NewRowTyped(true);

            row.DateEffectiveFrom = AccountingPeriodInfo.PeriodStartDate;
            row.TimeEffectiveFrom = 100;
            row.FromCurrencyCode  = "USD";
            row.ToCurrencyCode    = "EUR";
            row.RateOfExchange    = 1.34m;
            dailyrates.Rows.Add(row);
            row = dailyrates.NewRowTyped(true);
            row.DateEffectiveFrom = AccountingPeriodInfo.PeriodStartDate;
            row.TimeEffectiveFrom = 100;
            row.FromCurrencyCode  = "USD";
            row.ToCurrencyCode    = "GBP";
            row.RateOfExchange    = 1.57m;
            dailyrates.Rows.Add(row);

            if (!ADailyExchangeRateAccess.Exists(row.FromCurrencyCode, row.ToCurrencyCode, row.DateEffectiveFrom, row.TimeEffectiveFrom, null))
            {
                ADailyExchangeRateAccess.SubmitChanges(dailyrates, null);
            }

            ALedgerTable Ledger = ALedgerAccess.LoadByPrimaryKey(FLedgerNumber, null);

            for (int periodCounter = 1; periodCounter <= Ledger[0].NumberOfAccountingPeriods + Ledger[0].NumberFwdPostingPeriods; periodCounter++)
            {
                AccountingPeriodInfo = new TAccountPeriodInfo(FLedgerNumber, periodCounter);

                ACorporateExchangeRateTable corprates = new ACorporateExchangeRateTable();
                ACorporateExchangeRateRow   corprow   = corprates.NewRowTyped(true);
                corprow.DateEffectiveFrom = AccountingPeriodInfo.PeriodStartDate;
                corprow.TimeEffectiveFrom = 100;
                corprow.FromCurrencyCode  = "USD";
                corprow.ToCurrencyCode    = "EUR";
                corprow.RateOfExchange    = 1.34m;
                corprates.Rows.Add(corprow);
                corprow = corprates.NewRowTyped(true);
                corprow.DateEffectiveFrom = AccountingPeriodInfo.PeriodStartDate;
                corprow.TimeEffectiveFrom = 100;
                corprow.FromCurrencyCode  = "USD";
                corprow.ToCurrencyCode    = "GBP";
                corprow.RateOfExchange    = 1.57m;
                corprates.Rows.Add(corprow);

                if (!ACorporateExchangeRateAccess.Exists(corprow.FromCurrencyCode, corprow.ToCurrencyCode, corprow.DateEffectiveFrom, null))
                {
                    ACorporateExchangeRateAccess.SubmitChanges(corprates, null);
                }
            }
        }
Exemple #27
0
        /// <summary>
        /// Return the country code for the ledger with this key
        /// </summary>
        public static string GetCountryCodeFromLedger(TDBTransaction ATransaction, Int32 LedgerNumber)
        {
            ALedgerTable ledgerTable = ALedgerAccess.LoadByPrimaryKey((int)(DomainManager.GSiteKey / 1000000), ATransaction);

            if (ledgerTable.Rows.Count == 1)
            {
                return(ledgerTable[0].CountryCode);
            }

            // no Ledger row for this key, so return invalid country code
            return("99");
        }
        private void GetDataRow()
        {
            TDBTransaction Transaction = null;

            try
            {
                DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadUncommitted,
                                                                          TEnforceIsolationLevel.eilMinimum,
                                                                          ref Transaction,
                                                                          delegate
                {
                    FLedgerTbl = ALedgerAccess.LoadAll(Transaction);     // FLedgerTbl is static - this refreshes *any and all* TLedgerInfo objects.

                    #region Validate Data 1

                    if ((FLedgerTbl == null) || (FLedgerTbl.Count == 0))
                    {
                        throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString(
                                                                                                   "Function:{0} - The Ledger table is empty or could not be accessed!"),
                                                                                               Utilities.GetMethodName(true)));
                    }

                    #endregion Validate Data 1

                    FMyDataView           = new DataView(FLedgerTbl);
                    FMyDataView.RowFilter = String.Format("{0} = {1}", ALedgerTable.GetLedgerNumberDBName(), FLedgerNumber);     //a_ledger_number_i

                    #region Validate Data 2

                    if (FMyDataView.Count == 0)
                    {
                        throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString(
                                                                                                   "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"),
                                                                                               Utilities.GetMethodName(true),
                                                                                               FLedgerNumber));
                    }

                    #endregion Validate Data 2

                    FLedgerRow = (ALedgerRow)FMyDataView[0].Row;     // More than one TLedgerInfo object may point to this same row.
                });
            }
            catch (Exception ex)
            {
                TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}",
                                           Utilities.GetMethodSignature(),
                                           Environment.NewLine,
                                           ex.Message));
                throw ex;
            }
        }
        /// <summary>
        /// Set which payments should be paid; initialises the data of this screen
        /// </summary>
        /// <param name="ADataset"></param>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ADocumentsToPay"></param>
        /// <returns>true if there's something to pay</returns>
        public bool AddDocumentsToPayment(AccountsPayableTDS ADataset, Int32 ALedgerNumber, List <Int32> ADocumentsToPay)
        {
            FMainDS       = ADataset;
            FLedgerNumber = ALedgerNumber;
            ALedgerTable Tbl = TRemote.MFinance.AP.WebConnectors.GetLedgerInfo(FLedgerNumber);

            FLedgerRow = Tbl[0];

            if (FMainDS.AApPayment == null)
            {
                FMainDS.Merge(new AccountsPayableTDSAApPaymentTable()); // Because of these lines, AddDocumentsToPayment may only be called once per payment.
            }
            else
            {
                FMainDS.AApPayment.Clear();
            }

            if (FMainDS.AApDocumentPayment == null)
            {
                FMainDS.Merge(new AccountsPayableTDSAApDocumentPaymentTable());
            }
            else
            {
                FMainDS.AApDocumentPayment.Clear();
            }

            // I want to check that it'll be OK to pay these documents:
            for (Int32 Idx = ADocumentsToPay.Count - 1; Idx >= 0; Idx--)
            {
                Int32 DocId = ADocumentsToPay[Idx];
                AccountsPayableTDS tempDs = TRemote.MFinance.AP.WebConnectors.LoadAApDocument(ALedgerNumber, DocId);

                if (!ApDocumentCanPay(tempDs, tempDs.AApDocument[0]))
                {
                    ADocumentsToPay.Remove(DocId);
                }
            }

            if (ADocumentsToPay.Count == 0)
            {
                return(false);
            }

            TRemote.MFinance.AP.WebConnectors.CreatePaymentTableEntries(ref FMainDS, ALedgerNumber, ADocumentsToPay);
            chkPrintRemittance.Checked = true;
            chkClaimDiscount.Enabled   = false;
            chkPrintCheque.Enabled     = false;
            chkPrintLabel.Enabled      = false;
            ShowDataManual();
            return(true);
        }
Exemple #30
0
        /// <summary>
        /// Get Data Row
        /// </summary>
        private void GetDataRow()
        {
            TDBTransaction Transaction = new TDBTransaction();

            try
            {
                TDataBase db = DBAccess.Connect("LedgerInfo.GetDataRow", FDataBase);
                db.ReadTransaction(
                    ref Transaction,
                    delegate
                {
                    //Reload all ledgers each time
                    FLedgerTbl = ALedgerAccess.LoadAll(Transaction);     // FLedgerTbl is static - this refreshes *any and all* TLedgerInfo objects.

                    #region Validate Data 1

                    if ((FLedgerTbl == null) || (FLedgerTbl.Count == 0))
                    {
                        throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString(
                                                                                                   "Function:{0} - The Ledger table is empty or could not be accessed!"),
                                                                                               Utilities.GetMethodName(true)));
                    }

                    #endregion Validate Data 1
                    FMyDataView           = new DataView(FLedgerTbl);
                    FMyDataView.RowFilter = String.Format("{0} = {1}", ALedgerTable.GetLedgerNumberDBName(), FLedgerNumber);     //a_ledger_number_i

                    #region Validate Data 2
                    if (FMyDataView.Count == 0)
                    {
                        throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString(
                                                                                                   "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"),
                                                                                               Utilities.GetMethodName(true),
                                                                                               FLedgerNumber));
                    }
                    #endregion Validate Data 2

                    FLedgerRow = (FMyDataView.Count == 0?null:(ALedgerRow)FMyDataView[0].Row);
                });

                if (FDataBase == null)
                {
                    db.CloseDBConnection();
                }
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
        }
        public static Int32 GetNumberOfPeriods(Int32 ALedgerNumber)
        {
            Int32          returnValue = 0;
            TDBTransaction transaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.Serializable, ref transaction,
                                                                      delegate
            {
                ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, transaction);
                returnValue = LedgerTable[0].NumberOfAccountingPeriods;
            });

            return(returnValue);
        }
        private void GetDataRow()
        {
            bool NewTransaction = false;

            try
            {
                TDBTransaction transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadUncommitted,
                    TEnforceIsolationLevel.eilMinimum,
                    out NewTransaction);

                FLedgerTbl = ALedgerAccess.LoadAll(transaction); // FLedgerTbl is static - this refreshes *any and all* TLedgerInfo objects.
                MyView = new DataView(FLedgerTbl);
                MyView.RowFilter = "a_ledger_number_i = " + ledgerNumber;
                FLedgerRow = (ALedgerRow)MyView[0].Row; // More than one TLedgerInfo object may point to this same row.
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }
            }
        }
        /// <summary>
        /// build an XML document which includes all ledgers etc.
        /// </summary>
        public static XmlNode BuildNavigationXml(bool ADontUseDefaultLedger = false)
        {
            TYml2Xml parser = new TYml2Xml(TAppSettingsManager.GetValue("UINavigation.File"));
            XmlDocument UINavigation = parser.ParseYML2XML();

            // look for plugin UINavigation files, for development mode in the OpenPetra source code working tree
            string PluginsPath = "../../csharp/ICT/Petra/Plugins";

            if (!Directory.Exists(PluginsPath))
            {
                // in Production, we can have extension yml UINavigation files for the plugins too
                PluginsPath = "Plugins";
            }

            if (Directory.Exists(PluginsPath))
            {
                MergePluginUINavigation(PluginsPath, ref UINavigation);
            }

            ALedgerTable AvailableLedgers = new ALedgerTable();

            if (UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE1))
            {
                AvailableLedgers = TRemote.MFinance.Setup.WebConnectors.GetAvailableLedgers();
            }

            XmlNode OpenPetraNode = UINavigation.FirstChild.NextSibling.FirstChild;
            XmlNode SearchBoxesNode = OpenPetraNode.FirstChild;
            XmlNode MainMenuNode = SearchBoxesNode.NextSibling;

            if (TFormsList.GSingletonForms.Count == 0)      // There is no need to re-record all Singleton screens if this was already done once
            {
                RecordAllSingletonScreens(MainMenuNode);
            }

            AddNavigationForEachLedger(MainMenuNode, AvailableLedgers, ADontUseDefaultLedger);

            if (UserInfo.GUserInfo.IsInModule("PTNRUSER") && UserInfo.GUserInfo.IsInModule("CONFERENCE"))
            {
                AddConferenceInformation(MainMenuNode);
            }

            return MainMenuNode;
        }
        private void GetDataRow()
        {
            TDBTransaction Transaction = null;

            try
            {
                DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadUncommitted,
                    TEnforceIsolationLevel.eilMinimum,
                    ref Transaction,
                    delegate
                    {
                        FLedgerTbl = ALedgerAccess.LoadAll(Transaction); // FLedgerTbl is static - this refreshes *any and all* TLedgerInfo objects.

                        #region Validate Data 1

                        if ((FLedgerTbl == null) || (FLedgerTbl.Count == 0))
                        {
                            throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString(
                                        "Function:{0} - The Ledger table is empty or could not be accessed!"),
                                    Utilities.GetMethodName(true)));
                        }

                        #endregion Validate Data 1

                        FMyDataView = new DataView(FLedgerTbl);
                        FMyDataView.RowFilter = String.Format("{0} = {1}", ALedgerTable.GetLedgerNumberDBName(), FLedgerNumber); //a_ledger_number_i

                        #region Validate Data 2

                        if (FMyDataView.Count == 0)
                        {
                            throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString(
                                        "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"),
                                    Utilities.GetMethodName(true),
                                    FLedgerNumber));
                        }

                        #endregion Validate Data 2

                        FLedgerRow = (ALedgerRow)FMyDataView[0].Row; // More than one TLedgerInfo object may point to this same row.
                    });
            }
            catch (Exception ex)
            {
                TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}",
                        Utilities.GetMethodSignature(),
                        Environment.NewLine,
                        ex.Message));
                throw ex;
            }
        }
        private void RunOnceOnActivationManual()
        {
            // Set the Tag for the checkbox since we don't want changes to the checkbox to look like we have to save the data
            this.chkHideOthers.Tag = MCommon.MCommonResourcestrings.StrCtrlSuppressChangeDetection;

            // Activate events we will use in manual code
            this.txtDetailRateOfExchange.TextChanged +=
                new System.EventHandler(this.txtDetailRateOfExchange_TextChanged);

            // These Leave events are all fired before validation updates the row
            // This is important because we need to suggest a new date/rate depending on the selection made
            //  and so we need to be able to check on the existence of specific rows in the data table before they get updated on validation
            this.cmbDetailFromCurrencyCode.Leave +=
                new System.EventHandler(this.CurrencyCodeComboBox_Leave);
            this.cmbDetailToCurrencyCode.Leave +=
                new System.EventHandler(this.CurrencyCodeComboBox_Leave);
            this.dtpDetailDateEffectiveFrom.Leave +=
                new EventHandler(dtpDetailDateEffectiveFrom_Leave);

            this.btnInvertExchangeRate.Click +=
                new System.EventHandler(this.InvertExchangeRate);
            this.chkHideOthers.CheckedChanged +=
                new EventHandler(chkHideOthers_CheckedChanged);

            FPetraUtilsObject.DataSavingStarted += new TDataSavingStartHandler(FPetraUtilsObject_DataSavingStarted);

            // What ledgers does the user have access to??
            FAvailableLedgers = TRemote.MFinance.Setup.WebConnectors.GetAvailableLedgers();
            DataView ledgerView = FAvailableLedgers.DefaultView;
            ledgerView.RowFilter = "a_ledger_status_l = 1";     // Only view 'in use' ledgers

            for (int i = 0; i < ledgerView.Count; i++)
            {
                // Have a last attempt at deciding what the base currency is...
                if (baseCurrencyOfLedger == null)
                {
                    // we default to the first one we find
                    baseCurrencyOfLedger = ((ALedgerRow)ledgerView[i].Row).BaseCurrency;
                }

                if (intlCurrencyOfLedger == null)
                {
                    // we default to the first one we find
                    intlCurrencyOfLedger = ((ALedgerRow)ledgerView[i].Row).IntlCurrency;
                }

                // Get the accounting periods for this ledger
                AAccountingPeriodTable periods = (AAccountingPeriodTable)TDataCache.TMFinance.GetCacheableFinanceTable(
                    TCacheableFinanceTablesEnum.AccountingPeriodList,
                    ((ALedgerRow)ledgerView[i].Row).LedgerNumber);

                if ((periods != null) && (periods.Rows.Count > 0))
                {
                    int firstDay = ((AAccountingPeriodRow)periods.Rows[0]).PeriodStartDate.Day;

                    if ((FAlternativeFirstDayInMonth == 1) && (firstDay != 1))
                    {
                        // Now we have an alternative first day of month
                        FAlternativeFirstDayInMonth = firstDay;
                    }
                    else if ((FAlternativeFirstDayInMonth != 1) && (firstDay != 1) && (firstDay != FAlternativeFirstDayInMonth))
                    {
                        // Ooops.  Now we seem to have more than one alternative first day of month.
                        // We can't cope with that level of complexity!
                        FAlternativeFirstDayInMonth = 0;
                    }
                }
            }

            DataView myView = FMainDS.ACorporateExchangeRate.DefaultView;
            myView.Sort = ACorporateExchangeRateTable.GetToCurrencyCodeDBName() + ", " +
                          ACorporateExchangeRateTable.GetFromCurrencyCodeDBName() + ", " +
                          ACorporateExchangeRateTable.GetDateEffectiveFromDBName() + " DESC";
            myView.RowFilter = "";

            if (myView.Count > 0)
            {
                // We have to use this construct because simple ShoWDetails requires two cursor down keypresses to move the cursor
                // because we have changed the row filter.
                grdDetails.Selection.Focus(new SourceGrid.Position(1, 0), false);
                ShowDetails();
            }
            else
            {
                ShowDetails(null);
            }
        }
Exemple #36
0
        /// <summary>
        /// build an XML document which includes all ledgers etc.
        /// </summary>
        public static XmlNode BuildNavigationXml(bool ADontUseDefaultLedger = false)
        {
            TYml2Xml parser = new TYml2Xml(TAppSettingsManager.GetValue("UINavigation.File"));
            XmlDocument UINavigation = parser.ParseYML2XML();

            ALedgerTable AvailableLedgers = new ALedgerTable();

            if (UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE1))
            {
                AvailableLedgers = TGLSetupWebConnector.GetAvailableLedgers();
            }

            XmlNode OpenPetraNode = UINavigation.FirstChild.NextSibling.FirstChild;
            XmlNode SearchBoxesNode = OpenPetraNode.FirstChild;
            XmlNode MainMenuNode = SearchBoxesNode.NextSibling;

            AddNavigationForEachLedger(MainMenuNode, AvailableLedgers, ADontUseDefaultLedger);

            return MainMenuNode;
        }
        /// <summary>
        /// Validates the Corporate Exchange Rates screen data.
        /// </summary>
        /// <param name="AContext">Context that describes where the data validation failed.</param>
        /// <param name="ARow">The <see cref="DataRow" /> which holds the the data against which the validation is run.</param>
        /// <param name="AVerificationResultCollection">Will be filled with any <see cref="TVerificationResult" /> items if
        /// data validation errors occur.</param>
        /// <param name="AValidationControlsDict">A <see cref="TValidationControlsDict" /> containing the Controls that
        /// display data that is about to be validated.</param>
        /// <param name="ALedgerTableRef">A reference to a ledger table that has contains the ledgers that a client has access to</param>
        /// <param name="AAlternativeFirstDayOfPeriod">An alternative day (apart from 1) that is the start of an accounting period
        /// for at least one of the availbale ledgers</param>
        public static void ValidateCorporateExchangeRate(object AContext, ACorporateExchangeRateRow ARow,
            ref TVerificationResultCollection AVerificationResultCollection, TValidationControlsDict AValidationControlsDict,
            ALedgerTable ALedgerTableRef, int AAlternativeFirstDayOfPeriod)
        {
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TVerificationResult VerificationResult;

            // Don't validate deleted DataRows
            if (ARow.RowState == DataRowState.Deleted)
            {
                return;
            }

            // RateOfExchange must be positive (definitely not zero because we can invert it)
            ValidationColumn = ARow.Table.Columns[ACorporateExchangeRateTable.ColumnRateOfExchangeId];

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                VerificationResult = TNumericalChecks.IsPositiveDecimal(ARow.RateOfExchange,
                    ValidationControlsData.ValidationControlLabel,
                    AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                // Handle addition/removal to/from TVerificationResultCollection
                AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
            }

            // Date must not be empty
            ValidationColumn = ARow.Table.Columns[ACorporateExchangeRateTable.ColumnDateEffectiveFromId];

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                VerificationResult = TDateChecks.IsNotUndefinedDateTime(ARow.DateEffectiveFrom,
                    ValidationControlsData.ValidationControlLabel,
                    true, AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                // Handle addition/removal to/from TVerificationResultCollection
                AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
            }

            // Date must be first of month or first day in accounting period of a ledger
            ValidationColumn = ARow.Table.Columns[ACorporateExchangeRateTable.ColumnDateEffectiveFromId];

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                VerificationResult = null;

                if (AAlternativeFirstDayOfPeriod != 0)
                {
                    // day must be either 1 or AAlternativeFirstDayOfPeriod
                    VerificationResult = TDateChecks.IsNotCorporateDateTime(ARow.DateEffectiveFrom,
                        ValidationControlsData.ValidationControlLabel,
                        AContext, ValidationColumn, ValidationControlsData.ValidationControl, AAlternativeFirstDayOfPeriod);
                }
                else
                {
                    // when the value is 0 we cannot do validation because there are too many alternatives!
                    // How complicated is this set of ledgers???
                }

                // Handle addition/removal to/from TVerificationResultCollection
                AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
            }

            if (AContext is System.Windows.Forms.Form || AContext is System.Windows.Forms.UserControl)
            {
                // These tests are for the GUI only
                ValidationColumn = ARow.Table.Columns[ACorporateExchangeRateTable.ColumnToCurrencyCodeId];

                if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    // One of the currencies should be the base currency of one of the ledgers
                    if ((ARow.RowState == DataRowState.Added) && (ALedgerTableRef != null))
                    {
                        // Only do this test on new rows
                        TScreenVerificationResult vr = null;
                        DataView fromView = new DataView(ALedgerTableRef, String.Format("{0}='{1}'",
                                ALedgerTable.GetBaseCurrencyDBName(), ARow.FromCurrencyCode), String.Empty, DataViewRowState.CurrentRows);

                        if (fromView.Count == 0)
                        {
                            DataView toView = new DataView(ALedgerTableRef, String.Format("{0}='{1}'",
                                    ALedgerTable.GetBaseCurrencyDBName(), ARow.ToCurrencyCode), String.Empty, DataViewRowState.CurrentRows);

                            if (toView.Count == 0)
                            {
                                vr = new TScreenVerificationResult(AContext, ValidationColumn,
                                    "One of the currencies should normally be a base currency for one of the Ledgers",
                                    ValidationControlsData.ValidationControl, TResultSeverity.Resv_Noncritical);
                            }
                        }

                        // Handle addition to/removal from TVerificationResultCollection
                        AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, vr, ValidationColumn);
                    }
                }
            }
        }
        /// <summary>
        /// Validates the Daily Exchange Rates screen data.
        /// </summary>
        /// <param name="AContext">Context that describes where the data validation failed.</param>
        /// <param name="ARow">The <see cref="DataRow" /> which holds the the data against which the validation is run.</param>
        /// <param name="AVerificationResultCollection">Will be filled with any <see cref="TVerificationResult" /> items if
        /// data validation errors occur.</param>
        /// <param name="AValidationControlsDict">A <see cref="TValidationControlsDict" /> containing the Controls that
        /// display data that is about to be validated.</param>
        /// <param name="AMinDateTime">The earliest allowable date.</param>
        /// <param name="AMaxDateTime">The latest allowable date.</param>
        /// <param name="AIgnoreZeroRateCheck">If true a zero rate will be allowed.  This will be the case when the Daily Exchange Rate screen is modal.</param>
        /// <param name="ALedgerTableRef">A ledger table containg the available ledgers and their base currencies</param>
        /// <param name="AEarliestAccountingPeriodStartDate">The earliest accounting period start date in all the active ledgers</param>
        /// <param name="ALatestAccountingPeriodEndDate">The latest accounting period end date in all the active ledgers</param>
        public static void ValidateDailyExchangeRate(object AContext,
            ADailyExchangeRateRow ARow,
            ref TVerificationResultCollection AVerificationResultCollection,
            TValidationControlsDict AValidationControlsDict,
            DateTime AMinDateTime,
            DateTime AMaxDateTime,
            bool AIgnoreZeroRateCheck,
            ALedgerTable ALedgerTableRef,
            DateTime AEarliestAccountingPeriodStartDate,
            DateTime ALatestAccountingPeriodEndDate)
        {
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TVerificationResult VerificationResult;

            // Don't validate deleted DataRows
            if (ARow.RowState == DataRowState.Deleted)
            {
                return;
            }

            // RateOfExchange must be positive (definitely not zero unless in modal mode)
            ValidationColumn = ARow.Table.Columns[ADailyExchangeRateTable.ColumnRateOfExchangeId];

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                if (AIgnoreZeroRateCheck)
                {
                    VerificationResult = TNumericalChecks.IsPositiveOrZeroDecimal(ARow.RateOfExchange,
                        ValidationControlsData.ValidationControlLabel,
                        AContext, ValidationColumn, ValidationControlsData.ValidationControl);
                }
                else
                {
                    VerificationResult = TNumericalChecks.IsPositiveDecimal(ARow.RateOfExchange,
                        ValidationControlsData.ValidationControlLabel,
                        AContext, ValidationColumn, ValidationControlsData.ValidationControl);
                }

                // Handle addition/removal to/from TVerificationResultCollection
                AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
            }

            // Date must not be empty and must be in range
            ValidationColumn = ARow.Table.Columns[ADailyExchangeRateTable.ColumnDateEffectiveFromId];

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                VerificationResult = TSharedValidationControlHelper.IsNotInvalidDate(ARow.DateEffectiveFrom,
                    ValidationControlsData.ValidationControlLabel, AVerificationResultCollection, true,
                    AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                // Handle addition to/removal from TVerificationResultCollection
                AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);

                if (VerificationResult == null)
                {
                    if ((AMinDateTime > DateTime.MinValue) && (AMaxDateTime < DateTime.MaxValue))
                    {
                        // Check that the date is in range
                        VerificationResult = TDateChecks.IsDateBetweenDates(ARow.DateEffectiveFrom,
                            AMinDateTime,
                            AMaxDateTime,
                            ValidationControlsData.ValidationControlLabel,
                            TDateBetweenDatesCheckType.dbdctUnspecific,
                            TDateBetweenDatesCheckType.dbdctUnspecific,
                            AContext,
                            ValidationColumn,
                            ValidationControlsData.ValidationControl);
                    }
                    else if (AMaxDateTime < DateTime.MaxValue)
                    {
                        VerificationResult = TDateChecks.FirstLesserOrEqualThanSecondDate(ARow.DateEffectiveFrom, AMaxDateTime,
                            ValidationControlsData.ValidationControlLabel, Ict.Common.StringHelper.DateToLocalizedString(AMaxDateTime),
                            AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                        if ((VerificationResult == null) && (ARow.RowState == DataRowState.Added)
                            && (AContext is System.Windows.Forms.Form || AContext is System.Windows.Forms.UserControl))
                        {
                            // even without a specific minimum date it should not be too far back
                            if (ARow.DateEffectiveFrom < AEarliestAccountingPeriodStartDate)
                            {
                                VerificationResult = new TScreenVerificationResult(AContext, ValidationColumn,
                                    Catalog.GetString(
                                        "The date is before the start of the earliest current accounting period of any active ledger."),
                                    ValidationControlsData.ValidationControl, TResultSeverity.Resv_Noncritical);
                            }
                        }
                    }
                    else if (AMinDateTime > DateTime.MinValue)
                    {
                        VerificationResult = TDateChecks.FirstGreaterOrEqualThanSecondDate(ARow.DateEffectiveFrom, AMinDateTime,
                            ValidationControlsData.ValidationControlLabel, Ict.Common.StringHelper.DateToLocalizedString(AMinDateTime),
                            AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                        if ((VerificationResult == null) && (ARow.RowState == DataRowState.Added)
                            && (AContext is System.Windows.Forms.Form || AContext is System.Windows.Forms.UserControl))
                        {
                            // even without a specific maximum date it should not be too far ahead
                            if (ARow.DateEffectiveFrom > ALatestAccountingPeriodEndDate)
                            {
                                VerificationResult = new TScreenVerificationResult(AContext, ValidationColumn,
                                    Catalog.GetString(
                                        "The date is after the end of the latest forwarding period of any active ledger."),
                                    ValidationControlsData.ValidationControl, TResultSeverity.Resv_Noncritical);
                            }
                        }
                    }
                    else if ((AMinDateTime == DateTime.MinValue) && (AMaxDateTime == DateTime.MaxValue)
                             && (ARow.RowState == DataRowState.Added)
                             && (AContext is System.Windows.Forms.Form || AContext is System.Windows.Forms.UserControl))
                    {
                        // even without a specific maximum date it should not be too far ahead
                        if (ARow.DateEffectiveFrom > ALatestAccountingPeriodEndDate)
                        {
                            VerificationResult = new TScreenVerificationResult(AContext, ValidationColumn,
                                Catalog.GetString(
                                    "The date is after the end of the latest forwarding period of any active ledger."),
                                ValidationControlsData.ValidationControl, TResultSeverity.Resv_Noncritical);
                        }
                        // even without a specific minimum date it should not be too far back
                        else if (ARow.DateEffectiveFrom < AEarliestAccountingPeriodStartDate)
                        {
                            VerificationResult = new TScreenVerificationResult(AContext, ValidationColumn,
                                Catalog.GetString(
                                    "The date is before the start of the earliest current accounting period of any active ledger."),
                                ValidationControlsData.ValidationControl, TResultSeverity.Resv_Noncritical);
                        }
                    }

                    // Handle addition to/removal from TVerificationResultCollection
                    AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
                }
            }

            // Time must not be negative (indicating an error)
            ValidationColumn = ARow.Table.Columns[ADailyExchangeRateTable.ColumnTimeEffectiveFromId];

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                VerificationResult = TTimeChecks.IsValidIntegerTime(ARow.TimeEffectiveFrom,
                    ValidationControlsData.ValidationControlLabel,
                    AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                // Handle addition to/removal from TVerificationResultCollection
                AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
            }

            if (AContext is System.Windows.Forms.Form || AContext is System.Windows.Forms.UserControl)
            {
                // These tests are for the GUI only
                ValidationColumn = ARow.Table.Columns[ADailyExchangeRateTable.ColumnToCurrencyCodeId];

                if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    // One of the currencies should be the base currency of one of the ledgers
                    if (ValidationControlsData.ValidationControl.Enabled && (ARow.RowState == DataRowState.Added))
                    {
                        // Only do this test if the To Currency ComboBox is enabled
                        TScreenVerificationResult vr = null;
                        DataView fromView = new DataView(ALedgerTableRef, String.Format("{0}='{1}'",
                                ALedgerTable.GetBaseCurrencyDBName(), ARow.FromCurrencyCode), String.Empty, DataViewRowState.CurrentRows);

                        if (fromView.Count == 0)
                        {
                            DataView toView = new DataView(ALedgerTableRef, String.Format("{0}='{1}'",
                                    ALedgerTable.GetBaseCurrencyDBName(), ARow.ToCurrencyCode), String.Empty, DataViewRowState.CurrentRows);

                            if (toView.Count == 0)
                            {
                                vr = new TScreenVerificationResult(AContext, ValidationColumn,
                                    "One of the currencies should normally be a base currency for one of the Ledgers",
                                    ValidationControlsData.ValidationControl, TResultSeverity.Resv_Noncritical);
                            }
                        }

                        // Handle addition to/removal from TVerificationResultCollection
                        AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, vr, ValidationColumn);
                    }
                }
            }
        }
Exemple #39
0
        /// <summary>
        /// create a new batch with a consecutive batch number in the ledger
        /// for call inside a server function
        /// for performance reasons submitting (save the data in the database) is done later (not here)
        /// </summary>
        /// <param name="AMainDS"></param>
        /// <param name="ATransaction"></param>
        /// <param name="ALedgerTbl"></param>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ADateEffective"></param>
        /// <param name="AForceEffectiveDateToFit"></param>
        /// <returns>the new gift batch row</returns>
        public static AGiftBatchRow CreateANewGiftBatchRow(ref GiftBatchTDS AMainDS,
            ref TDBTransaction ATransaction,
            ref ALedgerTable ALedgerTbl,
            Int32 ALedgerNumber,
            DateTime ADateEffective,
            bool AForceEffectiveDateToFit = true)
        {
            #region Validate Arguments

            if (AMainDS == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Gift Batch dataset is NULL!"),
                        Utilities.GetMethodName(true)));
            }
            else if (ATransaction == null)
            {
                throw new EFinanceSystemDBTransactionNullException(String.Format(Catalog.GetString(
                            "Function:{0} - Database Transaction must not be NULL!"),
                        Utilities.GetMethodName(true)));
            }
            else if ((ALedgerTbl == null) || (ALedgerTbl.Count == 0))
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Ledger table is NULL or is empty!"),
                        Utilities.GetMethodName(true)));
            }
            else if (ALedgerNumber <= 0)
            {
                throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString(
                            "Function:{0} - The Ledger number must be greater than 0!"),
                        Utilities.GetMethodName(true)), ALedgerNumber);
            }

            #endregion Validate Arguments

            AGiftBatchRow NewRow = null;

            try
            {
                NewRow = AMainDS.AGiftBatch.NewRowTyped(true);

                NewRow.LedgerNumber = ALedgerNumber;
                NewRow.BatchNumber = ++ALedgerTbl[0].LastGiftBatchNumber;
                Int32 BatchYear, BatchPeriod;
                // if DateEffective is outside the range of open periods, use the most fitting date
                TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber,
                    ref ADateEffective,
                    out BatchYear,
                    out BatchPeriod,
                    ATransaction,
                    AForceEffectiveDateToFit);

                NewRow.BatchYear = BatchYear;
                NewRow.BatchPeriod = BatchPeriod;
                NewRow.GlEffectiveDate = ADateEffective;
                NewRow.ExchangeRateToBase = 1.0M;
                NewRow.BatchDescription = "PLEASE ENTER A DESCRIPTION";
                NewRow.BankAccountCode = TLedgerInfo.GetDefaultBankAccount(ALedgerNumber);
                NewRow.BankCostCentre = TLedgerInfo.GetStandardCostCentre(ALedgerNumber);
                NewRow.CurrencyCode = ALedgerTbl[0].BaseCurrency;
                AMainDS.AGiftBatch.Rows.Add(NewRow);
            }
            catch (Exception ex)
            {
                TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}",
                        Utilities.GetMethodSignature(),
                        Environment.NewLine,
                        ex.Message));
                throw ex;
            }

            return NewRow;
        }
Exemple #40
0
        /// <summary>
        /// create a new batch with a consecutive batch number in the ledger
        /// for call inside a server function
        /// for performance reasons submitting (save the data in the database) is done later (not here)
        /// </summary>
        /// <param name="MainDS"></param>
        /// <param name="Transaction"></param>
        /// <param name="LedgerTable"></param>
        /// <param name="ALedgerNumber"></param>
        /// <returns>the new gift batch row</returns>
        public static ARecurringGiftBatchRow CreateANewRecurringGiftBatchRow(ref GiftBatchTDS MainDS,
            ref TDBTransaction Transaction,
            ref ALedgerTable LedgerTable,
            Int32 ALedgerNumber)
        {
            GiftBatchTDS Temp = new GiftBatchTDS();

            ARecurringGiftBatchAccess.LoadViaALedger(Temp, LedgerTable[0].LedgerNumber, Transaction);

            DataView RecurringGiftBatchDV = new DataView(Temp.ARecurringGiftBatch);
            RecurringGiftBatchDV.RowFilter = string.Empty;
            RecurringGiftBatchDV.Sort = string.Format("{0} DESC",
                ARecurringGiftBatchTable.GetBatchNumberDBName());

            //Recurring batch numbers can be reused so check each time for current highest number
            if (RecurringGiftBatchDV.Count > 0)
            {
                LedgerTable[0].LastRecGiftBatchNumber = (int)(RecurringGiftBatchDV[0][ARecurringGiftBatchTable.GetBatchNumberDBName()]);
            }
            else
            {
                LedgerTable[0].LastRecGiftBatchNumber = 0;
            }

            ARecurringGiftBatchRow NewRow = MainDS.ARecurringGiftBatch.NewRowTyped(true);

            NewRow.LedgerNumber = ALedgerNumber;
            NewRow.BatchNumber = ++LedgerTable[0].LastRecGiftBatchNumber;
            NewRow.BatchDescription = Catalog.GetString("Please enter recurring batch description");
            NewRow.BankAccountCode = TLedgerInfo.GetDefaultBankAccount(ALedgerNumber);
            NewRow.BankCostCentre = TLedgerInfo.GetStandardCostCentre(ALedgerNumber);
            NewRow.CurrencyCode = LedgerTable[0].BaseCurrency;
            MainDS.ARecurringGiftBatch.Rows.Add(NewRow);
            return NewRow;
        }
Exemple #41
0
        private void ParseBatchLine(ref AGiftBatchRow AGiftBatch,
            ref TDBTransaction ATransaction,
            ref ALedgerTable ALedgerTable,
            ref string AImportMessage,
            int ARowNumber,
            TVerificationResultCollection AMessages,
            TValidationControlsDict AValidationControlsDictBatch,
            AAccountTable AValidationAccountTable,
            AAccountPropertyTable AValidationAccountPropertyTable,
            AAccountingPeriodTable AValidationAccountingPeriodTable,
            ACostCentreTable AValidationCostCentreTable,
            ACorporateExchangeRateTable AValidationCorporateExchTable,
            ACurrencyTable AValidationCurrencyTable)
        {
            // There are 8 elements to import (the last of which can be blank)
            string BatchDescription = ImportString(Catalog.GetString("Batch description"),
                FMainDS.AGiftBatch.ColumnBatchDescription, AValidationControlsDictBatch);
            string BankAccountCode = ImportString(Catalog.GetString("Bank account code"),
                FMainDS.AGiftBatch.ColumnBankAccountCode, AValidationControlsDictBatch).ToUpper();
            decimal HashTotal = ImportDecimal(Catalog.GetString("Hash total"),
                FMainDS.AGiftBatch.ColumnHashTotal, ARowNumber, AMessages, AValidationControlsDictBatch);
            DateTime GlEffectiveDate = ImportDate(Catalog.GetString("Effective Date"),
                FMainDS.AGiftBatch.ColumnGlEffectiveDate, ARowNumber, AMessages, AValidationControlsDictBatch);

            AImportMessage = "Creating new batch";

            // This call sets: BatchNumber, BatchYear, BatchPeriod, GlEffectiveDate, ExchangeRateToBase, BatchDescription, BankAccountCode
            //  BankCostCentre and CurrencyCode.  The effective date will NOT be modified.
            //  The first three are not validated because they should be ok by default
            AGiftBatch = TGiftBatchFunctions.CreateANewGiftBatchRow(ref FMainDS,
                ref ATransaction,
                ref ALedgerTable,
                FLedgerNumber,
                GlEffectiveDate,
                false);

            // Now we modify some of these in the light of the imported data
            AGiftBatch.BatchDescription = BatchDescription;
            AGiftBatch.BankAccountCode = BankAccountCode;
            AGiftBatch.HashTotal = HashTotal;
            AGiftBatch.CurrencyCode = ImportString(Catalog.GetString("Currency code"),
                FMainDS.AGiftBatch.ColumnCurrencyCode, AValidationControlsDictBatch);
            AGiftBatch.ExchangeRateToBase = ImportDecimal(Catalog.GetString("Exchange rate to base"),
                FMainDS.AGiftBatch.ColumnExchangeRateToBase, ARowNumber, AMessages, AValidationControlsDictBatch);

            AGiftBatch.BankCostCentre = ImportString(Catalog.GetString("Bank cost centre"),
                FMainDS.AGiftBatch.ColumnBankCostCentre, AValidationControlsDictBatch).ToUpper();
            AGiftBatch.GiftType = ImportString(Catalog.GetString("Gift type"),
                FMainDS.AGiftBatch.ColumnGiftType, AValidationControlsDictBatch);

            // If GiftType was empty, will default to GIFT
            // In all cases we ensure that the case entered by the user is converted to the case of our constants
            if ((AGiftBatch.GiftType == String.Empty) || (String.Compare(AGiftBatch.GiftType, MFinanceConstants.GIFT_TYPE_GIFT, true) == 0))
            {
                AGiftBatch.GiftType = MFinanceConstants.GIFT_TYPE_GIFT;
            }
            else if (String.Compare(AGiftBatch.GiftType, MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND, true) == 0)
            {
                AGiftBatch.GiftType = MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND;
            }
            else if (String.Compare(AGiftBatch.GiftType, MFinanceConstants.GIFT_TYPE_OTHER, true) == 0)
            {
                AGiftBatch.GiftType = MFinanceConstants.GIFT_TYPE_OTHER;
            }

            int messageCountBeforeValidate = AMessages.Count;

            // Do our standard gift batch validation checks on this row
            AImportMessage = Catalog.GetString("Validating the gift batch data");
            AGiftBatchValidation.Validate(this, AGiftBatch, ref AMessages, AValidationControlsDictBatch);

            // And do the additional manual ones
            AImportMessage = Catalog.GetString("Additional validation of the gift batch data");
            TSharedFinanceValidation_Gift.ValidateGiftBatchManual(this, AGiftBatch, ref AMessages, AValidationControlsDictBatch,
                AValidationAccountTable, AValidationCostCentreTable, AValidationAccountPropertyTable, AValidationAccountingPeriodTable,
                AValidationCorporateExchTable, AValidationCurrencyTable,
                FLedgerBaseCurrency, FLedgerIntlCurrency);

            for (int i = messageCountBeforeValidate; i < AMessages.Count; i++)
            {
                ((TVerificationResult)AMessages[i]).OverrideResultContext(String.Format(MCommonConstants.StrValidationErrorInLine, ARowNumber));

                if (AMessages[i] is TScreenVerificationResult)
                {
                    TVerificationResult downgrade = new TVerificationResult((TScreenVerificationResult)AMessages[i]);
                    AMessages.RemoveAt(i);
                    AMessages.Insert(i, downgrade);
                }
            }

            if (AGiftBatch.ExchangeRateToBase > 10000000)  // Huge numbers here indicate that the decimal comma/point is incorrect.
            {
                AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationErrorInLine, ARowNumber),
                        String.Format(Catalog.GetString("A huge exchange rate of {0} suggests a decimal point format problem."),
                            AGiftBatch.ExchangeRateToBase),
                        TResultSeverity.Resv_Noncritical));
            }
        }
        /// create a new gift batch using some of the details of an existing gift batch
        private static AGiftBatchRow CreateNewGiftBatch(Hashtable requestParams,
            ref GiftBatchTDS AMainDS,
            out DateTime ADateEffective,
            ref ALedgerTable ALedgerTable,
            TDBTransaction ATransaction)
        {
            AGiftBatchRow ReturnValue;

            Int32 LedgerNumber = (Int32)requestParams["ALedgerNumber"];

            ADateEffective = (DateTime)requestParams["GlEffectiveDate"];
            GiftAdjustmentFunctionEnum Function = (GiftAdjustmentFunctionEnum)requestParams["Function"];
            Int32 BatchNumber = (Int32)requestParams["BatchNumber"];

            AGiftBatchAccess.LoadByPrimaryKey(AMainDS, LedgerNumber, BatchNumber, ATransaction);

            AGiftBatchRow oldGiftBatch = AMainDS.AGiftBatch[0];
            TGiftBatchFunctions.CreateANewGiftBatchRow(ref AMainDS, ref ATransaction, ref ALedgerTable, LedgerNumber, ADateEffective);
            ReturnValue = AMainDS.AGiftBatch[1];
            ReturnValue.BankAccountCode = oldGiftBatch.BankAccountCode;
            ReturnValue.BankCostCentre = oldGiftBatch.BankCostCentre;
            ReturnValue.CurrencyCode = oldGiftBatch.CurrencyCode;
            ReturnValue.ExchangeRateToBase = oldGiftBatch.ExchangeRateToBase;
            ReturnValue.MethodOfPaymentCode = oldGiftBatch.MethodOfPaymentCode;
            ReturnValue.HashTotal = 0;

            if (ReturnValue.MethodOfPaymentCode.Length == 0)
            {
                ReturnValue.SetMethodOfPaymentCodeNull();
            }

            ReturnValue.BankCostCentre = oldGiftBatch.BankCostCentre;
            ReturnValue.GiftType = oldGiftBatch.GiftType;

            if (Function.Equals(GiftAdjustmentFunctionEnum.AdjustGift))
            {
                ReturnValue.BatchDescription = Catalog.GetString("Gift Adjustment");
            }
            else if (Function.Equals(GiftAdjustmentFunctionEnum.FieldAdjust))
            {
                ReturnValue.BatchDescription = Catalog.GetString("Gift Adjustment (Field Change)");
            }
            else if (Function.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust))
            {
                ReturnValue.BatchDescription = Catalog.GetString("Gift Adjustment (Tax Deductible Pct Change)");
            }
            else
            {
                ReturnValue.BatchDescription = Catalog.GetString("Reverse Gift");
            }

            return ReturnValue;
        }
Exemple #43
0
        /// <summary>
        /// create a new batch with a consecutive batch number in the ledger
        /// for call inside a server function
        /// for performance reasons submitting (save the data in the database) is done later (not here)
        /// </summary>
        /// <param name="AMainDS"></param>
        /// <param name="ATransaction"></param>
        /// <param name="ALedgerTbl"></param>
        /// <param name="ALedgerNumber"></param>
        /// <returns>the new gift batch row</returns>
        public static ARecurringGiftBatchRow CreateANewRecurringGiftBatchRow(ref GiftBatchTDS AMainDS,
            ref TDBTransaction ATransaction,
            ref ALedgerTable ALedgerTbl,
            Int32 ALedgerNumber)
        {
            #region Validate Arguments

            if (AMainDS == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Gift Batch dataset is NULL!"),
                        Utilities.GetMethodName(true)));
            }
            else if (ATransaction == null)
            {
                throw new EFinanceSystemDBTransactionNullException(String.Format(Catalog.GetString(
                            "Function:{0} - Database Transaction must not be NULL!"),
                        Utilities.GetMethodName(true)));
            }
            else if ((ALedgerTbl == null) || (ALedgerTbl.Count == 0))
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Ledger table is NULL or is empty!"),
                        Utilities.GetMethodName(true)));
            }
            else if (ALedgerNumber <= 0)
            {
                throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString(
                            "Function:{0} - The Ledger number must be greater than 0!"),
                        Utilities.GetMethodName(true)), ALedgerNumber);
            }

            #endregion Validate Arguments

            GiftBatchTDS Temp = new GiftBatchTDS();

            ARecurringGiftBatchAccess.LoadViaALedger(Temp, ALedgerNumber, ATransaction);

            DataView RecurringGiftBatchDV = new DataView(Temp.ARecurringGiftBatch);
            RecurringGiftBatchDV.RowFilter = string.Empty;
            RecurringGiftBatchDV.Sort = string.Format("{0} DESC",
                ARecurringGiftBatchTable.GetBatchNumberDBName());

            //Recurring batch numbers can be reused so check each time for current highest number
            if (RecurringGiftBatchDV.Count > 0)
            {
                ALedgerTbl[0].LastRecGiftBatchNumber = (int)(RecurringGiftBatchDV[0][ARecurringGiftBatchTable.GetBatchNumberDBName()]);
            }
            else
            {
                ALedgerTbl[0].LastRecGiftBatchNumber = 0;
            }

            ARecurringGiftBatchRow NewRow = AMainDS.ARecurringGiftBatch.NewRowTyped(true);

            NewRow.LedgerNumber = ALedgerNumber;
            NewRow.BatchNumber = ++ALedgerTbl[0].LastRecGiftBatchNumber;
            NewRow.BatchDescription = Catalog.GetString("Please enter recurring batch description");
            NewRow.BankAccountCode = TLedgerInfo.GetDefaultBankAccount(ALedgerNumber);
            NewRow.BankCostCentre = TLedgerInfo.GetStandardCostCentre(ALedgerNumber);
            NewRow.CurrencyCode = ALedgerTbl[0].BaseCurrency;
            AMainDS.ARecurringGiftBatch.Rows.Add(NewRow);
            return NewRow;
        }
        private static void AddNavigationForEachLedger(XmlNode AMenuNode, ALedgerTable AAvailableLedgers, bool ADontUseDefaultLedger)
        {
            XmlNode childNode = AMenuNode.FirstChild;
            int PotentialCurrentLedger;
            ALedgerRow ProcessedLedger;
            XmlAttribute enabledAttribute;
            bool LedgersAvailableToUserCreatedInThisIteration = false;

            //Iterate through all children nodes of the node
            while (childNode != null)
            {
                if (TXMLParser.GetAttribute(childNode, "DependsOnLedger").ToLower() == "true")
                {
                    // If there is more than one Ledger in the system, show a 'Select Ledger' Collapsible Panel with a Task (=LinkLabel)
                    // for each Ledger.
                    if (AAvailableLedgers.Rows.Count > 1)
                    {
                        LedgersAvailableToUserCreatedInThisIteration = false;
                        AAvailableLedgers.DefaultView.Sort = ALedgerTable.GetLedgerNumberDBName() + " ASC";

                        FMultiLedgerSite = true;

                        // Create 'Select Ledger' Node
                        XmlAttribute LabelAttributeLedger = childNode.OwnerDocument.CreateAttribute("Label");
                        XmlElement SelLedgerElmnt = childNode.OwnerDocument.CreateElement("SelectLedger");
                        XmlNode SelectLedgerNode = childNode.AppendChild(SelLedgerElmnt);
                        SelectLedgerNode.Attributes.Append(LabelAttributeLedger);
                        SelectLedgerNode.Attributes["Label"].Value = Catalog.GetString("Select Ledger");

                        // Create 1..n 'Ledger xyz' Nodes
                        foreach (DataRowView Drv in AAvailableLedgers.DefaultView)
                        {
                            ProcessedLedger = (ALedgerRow)Drv.Row;

                            XmlElement SpecificLedgerElmnt = childNode.OwnerDocument.CreateElement("Ledger" + ProcessedLedger.LedgerNumber);
                            XmlNode SpecificLedgerNode = SelectLedgerNode.AppendChild(SpecificLedgerElmnt);
                            XmlAttribute LabelAttributeSpecificLedger = childNode.OwnerDocument.CreateAttribute("Label");
                            SpecificLedgerNode.Attributes.Append(LabelAttributeSpecificLedger);
                            XmlAttribute ledgerNumberAttribute = childNode.OwnerDocument.CreateAttribute("LedgerNumber");
                            ledgerNumberAttribute.Value = ProcessedLedger.LedgerNumber.ToString();
                            SpecificLedgerNode.Attributes.Append(ledgerNumberAttribute);
                            XmlAttribute ledgerNameAttribute = childNode.OwnerDocument.CreateAttribute("LedgerName");
                            ledgerNameAttribute.Value = ProcessedLedger.LedgerName;
                            SpecificLedgerNode.Attributes.Append(ledgerNameAttribute);

                            if (ProcessedLedger.LedgerName != String.Empty)
                            {
                                SpecificLedgerNode.Attributes["Label"].Value = String.Format(Catalog.GetString(
                                        "Ledger {0} (#{1})"), ProcessedLedger.LedgerName, ProcessedLedger.LedgerNumber);
                            }
                            else
                            {
                                SpecificLedgerNode.Attributes["Label"].Value = String.Format(Catalog.GetString(
                                        "Ledger #{0}"), ProcessedLedger.LedgerNumber);
                            }

                            // Check access permission for Ledger
                            if (!HasAccessPermission(SpecificLedgerNode, UserInfo.GUserInfo.UserID, true))
                            {
                                enabledAttribute = childNode.OwnerDocument.CreateAttribute("Enabled");
                                enabledAttribute.Value = "false";
                                SpecificLedgerNode.Attributes.Append(enabledAttribute);
                            }
                            else
                            {
                                if (FLedgersAvailableToUser == null)
                                {
                                    // (Re-)Calculate which Ledgers the user has access to
                                    FLedgersAvailableToUser = new List <string>();
                                    LedgersAvailableToUserCreatedInThisIteration = true;
                                }

                                if (LedgersAvailableToUserCreatedInThisIteration)
                                {
                                    // Add Ledger to the List of Ledgers that are available to the user
                                    if (!FLedgersAvailableToUser.Contains(FormatLedgerNumberForModuleAccess(ProcessedLedger.LedgerNumber)))
                                    {
                                        FLedgersAvailableToUser.Add(FormatLedgerNumberForModuleAccess(ProcessedLedger.LedgerNumber));
                                    }
                                }
                            }
                        }

                        if ((LedgersAvailableToUserCreatedInThisIteration)
                            || (FLedgersAvailableToUser == null))
                        {
                            if (!ADontUseDefaultLedger)
                            {
                                // Set the 'Current Ledger' to the users' Default Ledger, or if he/she hasn't got one, to the first Ledger of the Site.
                                PotentialCurrentLedger = TUserDefaults.GetInt32Default(TUserDefaults.FINANCE_DEFAULT_LEDGERNUMBER,
                                    ((ALedgerRow)AAvailableLedgers.DefaultView[0].Row).LedgerNumber);

                                if ((FLedgersAvailableToUser != null)
                                    && (FLedgersAvailableToUser.Contains(FormatLedgerNumberForModuleAccess(PotentialCurrentLedger))))
                                {
                                    FCurrentLedger = PotentialCurrentLedger;
                                }
                                else
                                {
                                    if (FLedgersAvailableToUser != null)
                                    {
                                        FCurrentLedger = Convert.ToInt32(FLedgersAvailableToUser[0].Substring(6));    // Skip "LEDGER"
                                    }
                                    else   // = no Ledgers available to the user at all!
                                    {
                                        FCurrentLedger = TLstFolderNavigation.LEDGERNUMBER_NO_ACCESS_TO_ANY_LEDGER;
                                    }
                                }
                            }
                        }
                    }
                    else if (AAvailableLedgers.Rows.Count == 1)
                    {
                        // Dynamically add Attribute 'SkipThisLevel' to the next child, which would be the child for the Collapsible Panel,
                        // which we don't need/want for a 'Single Ledger' Site!
                        XmlAttribute LabelSkipCollapsibleLevel = childNode.OwnerDocument.CreateAttribute("SkipThisLevel");
                        childNode.ChildNodes[0].Attributes.Append(LabelSkipCollapsibleLevel);
                        childNode.ChildNodes[0].Attributes["SkipThisLevel"].Value = "true";

                        // Check access permission for Ledger
                        if (UserInfo.GUserInfo.IsInModule(FormatLedgerNumberForModuleAccess(AAvailableLedgers[0].LedgerNumber)))
                        {
                            // Set the 'Current Ledger' to the only Ledger of the Site.
                            FCurrentLedger = AAvailableLedgers[0].LedgerNumber;
                        }
                        else   // = no Ledgers available to the user at all!
                        {
                            FCurrentLedger = TLstFolderNavigation.LEDGERNUMBER_NO_ACCESS_TO_ANY_LEDGER;
                        }
                    }
                    else   // = no Ledgers available to the user at all!
                    {
                        FCurrentLedger = TLstFolderNavigation.LEDGERNUMBER_NO_ACCESS_TO_ANY_LEDGER;
                    }

                    childNode = childNode.NextSibling;
                }
                else
                {
                    // Recurse into deeper levels!
                    AddNavigationForEachLedger(childNode, AAvailableLedgers, ADontUseDefaultLedger);

                    childNode = childNode.NextSibling;
                }
            }
        }
Exemple #45
0
 private static void LoadAll()
 {
     ALedger = new ALedgerTable();
     SerialisableDS.LoadAll(ALedger, ALedgerTable.GetTableDBName());
 }
        /// <summary>
        /// build an XML document which includes all ledgers etc.
        /// </summary>
        public static XmlNode BuildNavigationXml(bool ADontUseDefaultLedger = false)
        {
            TYml2Xml parser = new TYml2Xml(TAppSettingsManager.GetValue("UINavigation.File"));
            XmlDocument UINavigation = parser.ParseYML2XML();

            ALedgerTable AvailableLedgers = new ALedgerTable();

            if (UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE1))
            {
                AvailableLedgers = TRemote.MFinance.Setup.WebConnectors.GetAvailableLedgers();
            }

            XmlNode OpenPetraNode = UINavigation.FirstChild.NextSibling.FirstChild;
            XmlNode SearchBoxesNode = OpenPetraNode.FirstChild;
            XmlNode MainMenuNode = SearchBoxesNode.NextSibling;

            if (TFormsList.GSingletonForms.Count == 0)      // There is no need to re-record all Singleton screens if this was already done once
            {
                RecordAllSingletonScreens(MainMenuNode);
            }

            AddNavigationForEachLedger(MainMenuNode, AvailableLedgers, ADontUseDefaultLedger);

            if (UserInfo.GUserInfo.IsInModule("PTNRUSER") && UserInfo.GUserInfo.IsInModule("CONFERENCE"))
            {
                AddConferenceInformation(MainMenuNode);
            }

            return MainMenuNode;
        }