コード例 #1
0
 void CheckFCacheInitialised()
 {
     if ((FCacheDS == null) && (FLedgerNumber >= 0))
     {
         FCacheDS = TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, FActiveOnly);
     }
 }
コード例 #2
0
        /// <summary>
        /// Main method for saving the screen data.
        /// Stores the settings for all the pages, since everything shares the same FMainDS
        /// </summary>
        private TSubmitChangesResult StoreManualCode(ref GLSetupTDS ASubmitChanges, out TVerificationResultCollection AVerificationResult)
        {
            AVerificationResult = null;

            // save ledger settings now
            // Note:  a_ledger_init_flag records are automatically added/removed on server side for the following
            //           based on the values in the a_ledger table
            // * suspense account flag: "SUSP-ACCT"
            // * budget flag: "BUDGET"
            // * branch processing: "BRANCH-PROCESS" (this is a new flag for OpenPetra)
            // * base currency: "CURRENCY"
            // * international currency: "INTL-CURRENCY" (this is a new flag for OpenPetra)
            // * current period (start of ledger date): CURRENT-PERIOD
            // * calendar settings: CAL
            // But the 'AP require approval before posting' flag is set in this GUI on the AP tab by setting the a_ledger_init_flag row directly
            //  (because there is no column in a_ledger for this option - it only exists in a_ledger_init_flag table)

            TSubmitChangesResult res = TRemote.MFinance.Setup.WebConnectors.SaveLedgerSettings(FLedgerNumber,
                                                                                               FCalendarStartDate,
                                                                                               ref ASubmitChanges);

            TDataCache.TMFinance.RefreshCacheableFinanceTable(TCacheableFinanceTablesEnum.LedgerDetails, FLedgerNumber);

            return(res);
        }
コード例 #3
0
        /// <summary>
        /// Show all the data (Account Code and description)
        /// </summary>
        public void PopulateListView(GLSetupTDS MainDS, Int32 LedgerNumber, String SelectedHierarchy)
        {
//            FLedgerNumber = LedgerNumber;
//            FSelectedHierarchy = SelectedHierarchy;

            FDataView              = new DataView(MainDS.AAccount);
            FDataView.Sort         = "a_account_code_c";
            FDataView.AllowNew     = false;
            grdAccounts.DataSource = new DevAge.ComponentModel.BoundDataView(FDataView);

            grdAccounts.Columns.Clear();
            grdAccounts.AddTextColumn(Catalog.GetString("Code"), MainDS.AAccount.ColumnAccountCode);
            grdAccounts.AddTextColumn(Catalog.GetString("Descr"), MainDS.AAccount.ColumnAccountCodeShortDesc);
//          grdAccounts.AddCurrencyColumn(Catalog.GetString("YTD Actual"), MainDS.AAccount.ColumnYtdActualBase);
//          grdAccounts.AddCurrencyColumn(Catalog.GetString("Foreign"), MainDS.AAccount.ColumnYtdActualForeign);

            if (FSelectedAccount != null)
            {
                this.SelectedAccount = FSelectedAccount;
            }
            else
            {
                grdAccounts.SelectRowInGrid(0);
            }
        }
コード例 #4
0
        /// <summary>
        /// Load CostCentre hierarchy from the dataset into the tree view
        /// </summary>
        public void PopulateTreeView(GLSetupTDS MainDS)
        {
            FDuringInitialisation = true;
            trvCostCentres.BeginUpdate();
            trvCostCentres.Nodes.Clear();

            // find the root cost centre
            MainDS.ACostCentre.DefaultView.RowFilter =
                ACostCentreTable.GetCostCentreToReportToDBName() + " IS NULL";

            DataView view = new DataView(MainDS.ACostCentre);

            view.Sort = ACostCentreTable.GetCostCentreCodeDBName();

            InsertNodeIntoTreeView(null,
                                   view,
                                   (ACostCentreRow)MainDS.ACostCentre.DefaultView[0].Row);

            MainDS.ACostCentre.DefaultView.RowFilter = "";

            trvCostCentres.EndUpdate();

            this.trvCostCentres.BeforeSelect += TreeViewBeforeSelect;
            this.trvCostCentres.AfterSelect  += TreeViewAfterSelect;
            trvCostCentres.EndUpdate();

            FDuringInitialisation = false;

            if (trvCostCentres.Nodes.Count > 0)
            {
                SelectNodeByName(trvCostCentres.Nodes[0].Name); // Select the first item
            }
        }
コード例 #5
0
 /// <summary>
 /// Show all the data (CostCentre Code and description)
 /// </summary>
 public void PopulateListView(GLSetupTDS MainDS)
 {
     FDataView                 = new DataView(MainDS.ACostCentre);
     FDataView.Sort            = "a_cost_centre_code_c";
     FDataView.AllowNew        = false;
     grdCostCentres.DataSource = new DevAge.ComponentModel.BoundDataView(FDataView);
     grdCostCentres.Columns.Clear();
     grdCostCentres.AddTextColumn("Code", MainDS.ACostCentre.ColumnCostCentreCode);
     grdCostCentres.AddTextColumn("Name", MainDS.ACostCentre.ColumnCostCentreName);
     grdCostCentres.AutoResizeGrid();
 }
コード例 #6
0
        /// <summary>
        /// Show ledger info data from given data set
        /// </summary>
        /// <param name="ADataSet">The data set for which details will be shown</param>
        private void ShowData(GLSetupTDS ADataSet)
        {
            ALedgerRow           LedgerRow;
            AAccountingPeriodRow AccountingPeriodRow;
            DataRow TempRow;

            if ((ADataSet == null) ||
                (ADataSet.ALedger.Count == 0))
            {
                return;
            }

            LedgerRow = (ALedgerRow)ADataSet.ALedger.Rows[0];

            cmbBaseCurrency.SetSelectedString(LedgerRow.BaseCurrency, -1);
            cmbIntlCurrency.SetSelectedString(LedgerRow.IntlCurrency, -1);

            txtAccountingPeriods.NumberValueInt = LedgerRow.NumberOfAccountingPeriods;

            if (LedgerRow.CalendarMode)
            {
                txtCalendarMode.Text = Catalog.GetString("Monthly");
            }
            else
            {
                txtCalendarMode.Text = Catalog.GetString("Non-Monthly");
            }

            txtCurrencyRevaluation.Text      = LedgerRow.ForexGainsLossesAccount;
            txtCurrentPeriod.NumberValueInt  = LedgerRow.CurrentPeriod;
            txtForwardPeriods.NumberValueInt = LedgerRow.NumberFwdPostingPeriods;

            TempRow = ADataSet.AAccountingPeriod.Rows.Find(new object[] { LedgerRow.LedgerNumber,
                                                                          LedgerRow.CurrentPeriod });

            if (TempRow != null)
            {
                AccountingPeriodRow     = (AAccountingPeriodRow)TempRow;
                dtpPeriodStartDate.Date = AccountingPeriodRow.PeriodStartDate.Date;
                dtpPeriodEndDate.Date   = AccountingPeriodRow.PeriodEndDate.Date;
            }

            TempRow = ADataSet.AAccountingPeriod.Rows.Find(new object[] { LedgerRow.LedgerNumber,
                                                                          LedgerRow.CurrentPeriod + LedgerRow.NumberFwdPostingPeriods });

            if (TempRow != null)
            {
                AccountingPeriodRow         = (AAccountingPeriodRow)TempRow;
                dtpPostingAllowedUntil.Date = AccountingPeriodRow.PeriodEndDate.Date;
            }

            chkSuspenseAccounts.Checked = LedgerRow.SuspenseAccountFlag;
            chkBudgetControl.Checked    = LedgerRow.BudgetControlFlag;
        }
コード例 #7
0
        private DataTable GetAccountListTable(TDBTransaction AReadTransaction, System.Int32 ALedgerNumber, string ATableName)
        {
            StringCollection FieldList = new StringCollection();

            FieldList.Add(AAccountTable.GetLedgerNumberDBName());
            FieldList.Add(AAccountTable.GetAccountCodeDBName());
            FieldList.Add(AAccountTable.GetAccountTypeDBName());
            FieldList.Add(AAccountTable.GetAccountCodeShortDescDBName());
            FieldList.Add(AAccountTable.GetAccountActiveFlagDBName());
            FieldList.Add(AAccountTable.GetPostingStatusDBName());
            FieldList.Add(AAccountTable.GetForeignCurrencyFlagDBName());
            FieldList.Add(AAccountTable.GetForeignCurrencyCodeDBName());
            GLSetupTDS TempDS = new GLSetupTDS();

            AAccountAccess.LoadViaALedger(TempDS, ALedgerNumber, FieldList, AReadTransaction);

            // load AAccountProperty and set the BankAccountFlag
            AAccountPropertyAccess.LoadViaALedger(TempDS, ALedgerNumber, AReadTransaction);

            foreach (AAccountPropertyRow accProp in TempDS.AAccountProperty.Rows)
            {
                if ((accProp.PropertyCode == MFinanceConstants.ACCOUNT_PROPERTY_BANK_ACCOUNT) && (accProp.PropertyValue == "true"))
                {
                    TempDS.AAccount.DefaultView.RowFilter = String.Format("{0}='{1}'",
                                                                          AAccountTable.GetAccountCodeDBName(),
                                                                          accProp.AccountCode);
                    GLSetupTDSAAccountRow acc = (GLSetupTDSAAccountRow)TempDS.AAccount.DefaultView[0].Row;
                    acc.BankAccountFlag = true;
                    TempDS.AAccount.DefaultView.RowFilter = "";
                }
            }

            // not currently needed as an Account is only a Bank Account if it has a 'Bank Account' Account Property
            // load AAccountHierarchyDetails and check if this account reports to the CASH account

            /*AAccountHierarchyDetailAccess.LoadViaAAccountHierarchy(TempDS,
             *  ALedgerNumber,
             *  MFinanceConstants.ACCOUNT_HIERARCHY_STANDARD,
             *  AReadTransaction);
             *
             * TLedgerInfo ledgerInfo = new TLedgerInfo(ALedgerNumber);
             * TGetAccountHierarchyDetailInfo accountHierarchyTools = new TGetAccountHierarchyDetailInfo(ledgerInfo);
             * List <string>children = accountHierarchyTools.GetChildren(MFinanceConstants.CASH_ACCT);
             *
             * foreach (GLSetupTDSAAccountRow account in TempDS.AAccount.Rows)
             * {
             *  if (children.Contains(account.AccountCode))
             *  {
             *      account.CashAccountFlag = true;
             *  }
             * }*/

            return(TempDS.AAccount);
        }
コード例 #8
0
        public void Init()
        {
            TPetraServerConnector.Connect("../../etc/TestServer.config");

            // These will be our test ledger numbers
            FTestLedgerList.AddRange(new int[] { 9997, 9998, 9999 });

            // Load existing data
            FMainDS = new GLSetupTDS();

            try
            {
                TDBTransaction transaction = new TDBTransaction();
                TDataBase      db          = DBAccess.Connect("Init");
                db.ReadTransaction(
                    ref transaction,
                    delegate
                {
                    ALedgerAccess.LoadAll(FMainDS, transaction);
                });

                // Check that our test rows are not in the database already
                if (!FindTestRows(FTestLedgerList))
                {
                    // Get the initial number of available ledgers
                    FInitialLedgerCount = TGLSetupWebConnector.GetAvailableLedgers().DefaultView.Count;

                    bool SubmitOK = true;
                    db.WriteTransaction(
                        ref transaction,
                        ref SubmitOK,
                        delegate
                    {
                        // Add our test rows
                        AddTestRow(FTestLedgerList[0], "NUnitTestLedger1", false);
                        AddTestRow(FTestLedgerList[1], "NUnitTestLedger2", true, "JPY");
                        AddTestRow(FTestLedgerList[2], "NUnitTestLedger2", true);

                        // Save these new rows
                        ALedgerAccess.SubmitChanges(FMainDS.ALedger, transaction);
                        FMainDS.AcceptChanges();
                    });

                    FInitSucceeded = true;
                }
            }
            catch (Exception ex)
            {
                FInitExceptionMessage = ex.Message;
            }
        }
コード例 #9
0
        /// <summary>
        /// Show all the data (Account Code and description)
        /// </summary>
        public void PopulateListView(GLSetupTDS MainDS, Int32 LedgerNumber, String SelectedHierarchy)
        {
//            FLedgerNumber = LedgerNumber;
//            FSelectedHierarchy = SelectedHierarchy;

            FDataView              = new DataView(MainDS.AAccount);
            FDataView.Sort         = "a_account_code_c";
            FDataView.AllowNew     = false;
            grdAccounts.DataSource = new DevAge.ComponentModel.BoundDataView(FDataView);
            grdAccounts.Columns.Clear();
            grdAccounts.AddTextColumn("Code", MainDS.AAccount.ColumnAccountCode);
            grdAccounts.AddTextColumn("Descr", MainDS.AAccount.ColumnAccountCodeShortDesc);
            grdAccounts.AutoResizeGrid();
        }
コード例 #10
0
        private TSubmitChangesResult StoreManualCode(ref GLSetupTDS ASubmitTDS, out TVerificationResultCollection AVerificationResult)
        {
            //
            // I'll warn the user if they have created analysis Types with no values:

            String EmptyTypesWarning = "";

            //
            // If the user has added a new type, I want to show her a warning if she didn't also add at least one value for the new type.

            if (ASubmitTDS.AAnalysisType != null)
            {
                foreach (AAnalysisTypeRow TypeRow in ASubmitTDS.AAnalysisType.Rows)
                {
                    if (TypeRow.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    Boolean NoValuesProvided = true;

                    if (ASubmitTDS.AFreeformAnalysis != null)
                    {
                        ASubmitTDS.AFreeformAnalysis.DefaultView.RowFilter =
                            String.Format("a_analysis_type_code_c='{0}'", TypeRow["a_analysis_type_code_c"]);
                        NoValuesProvided = ASubmitTDS.AFreeformAnalysis.DefaultView.Count == 0;
                    }

                    if (NoValuesProvided)
                    {
                        if (EmptyTypesWarning != "")
                        {
                            EmptyTypesWarning += "\r\n";
                        }

                        EmptyTypesWarning +=
                            String.Format(Catalog.GetString("Type {0} has no values, and therefore it cannot yet be applied to any account."),
                                          TypeRow["a_analysis_type_code_c"]);
                    }
                }
            }

            if (EmptyTypesWarning != "")
            {
                MessageBox.Show(EmptyTypesWarning, Catalog.GetString("Empty Analysis Types"), MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            return(TRemote.MFinance.Setup.WebConnectors.SaveGLSetupTDS(FLedgerNumber, ref ASubmitTDS, out AVerificationResult));
        }
コード例 #11
0
        /// <summary>
        /// link the fields in the current ledger
        /// </summary>
        /// <param name="AFieldCSVFile"></param>
        public static void GenerateFieldsFinanceOnly(string AFieldCSVFile)
        {
            XmlDocument doc = TCsv2Xml.ParseCSV2Xml(AFieldCSVFile, ",");

            XmlNode RecordNode = doc.FirstChild.NextSibling.FirstChild;

            GLSetupTDS GLSetupDS = new GLSetupTDS();

            PCountryTable CountryTable = null;

            TDBTransaction Transaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                      TEnforceIsolationLevel.eilMinimum,
                                                                      ref Transaction,
                                                                      delegate
            {
                CountryTable = PCountryAccess.LoadAll(Transaction);
            });

            while (RecordNode != null)
            {
                long   id          = 100 + Convert.ToInt64(TXMLParser.GetAttribute(RecordNode, "id"));
                string CountryCode = TXMLParser.GetAttribute(RecordNode, "Name");
                string UnitName    = ((PCountryRow)CountryTable.Rows.Find(CountryCode)).CountryName;
                Int64  PartnerKey  = id * 1000000;

                // create cost centre
                ACostCentreRow CostCentreRow = GLSetupDS.ACostCentre.NewRowTyped();
                CostCentreRow.LedgerNumber         = FLedgerNumber;
                CostCentreRow.CostCentreCode       = (id * 100).ToString("0000");
                CostCentreRow.CostCentreName       = UnitName;
                CostCentreRow.CostCentreToReportTo = MFinanceConstants.INTER_LEDGER_HEADING;
                CostCentreRow.CostCentreType       = MFinanceConstants.FOREIGN_CC_TYPE;
                GLSetupDS.ACostCentre.Rows.Add(CostCentreRow);

                // create foreign ledger, cost centre link validledgernumber
                AValidLedgerNumberRow ValidLedgerNumber = GLSetupDS.AValidLedgerNumber.NewRowTyped();
                ValidLedgerNumber.LedgerNumber        = FLedgerNumber;
                ValidLedgerNumber.PartnerKey          = PartnerKey;
                ValidLedgerNumber.CostCentreCode      = CostCentreRow.CostCentreCode;
                ValidLedgerNumber.IltProcessingCentre = Convert.ToInt64(MFinanceConstants.ICH_COST_CENTRE) * 10000;
                GLSetupDS.AValidLedgerNumber.Rows.Add(ValidLedgerNumber);

                RecordNode = RecordNode.NextSibling;
            }

            GLSetupTDSAccess.SubmitChanges(GLSetupDS);
        }
コード例 #12
0
        private void InsertNodeIntoTreeView(GLSetupTDS MainDS,
                                            Int32 LedgerNumber,
                                            TreeNode AParent,
                                            DataView view,
                                            AAccountHierarchyDetailRow ADetailRow)
        {
            GLSetupTDSAAccountRow AccountRow = (GLSetupTDSAAccountRow)MainDS.AAccount.Rows.Find(
                new object[] { LedgerNumber, ADetailRow.ReportingAccountCode });

            TreeNode Child = new TreeNode();


            AccountNodeDetails NodeTag = AccountNodeDetails.AddNewAccount(Child, AccountRow, ADetailRow);

            NodeTag.IsNew = (ADetailRow.RowState == DataRowState.Added);

            SetNodeLabel(AccountRow, Child);

            if (AParent == null)
            {
                trvAccounts.Nodes.Add(Child);
            }
            else
            {
                InsertInOrder(AParent, Child);
            }

            // Now add the children of this node:
            view.RowFilter =
                AAccountHierarchyDetailTable.GetAccountHierarchyCodeDBName() + " = '" + ADetailRow.AccountHierarchyCode + "' AND " +
                AAccountHierarchyDetailTable.GetAccountCodeToReportToDBName() + " = '" + ADetailRow.ReportingAccountCode + "'";

            if (view.Count > 0)
            {
                // An account cannot be deleted if it has children.
                NodeTag.CanDelete       = false;
                NodeTag.Msg             = Catalog.GetString("Child accounts must be deleted first.");
                NodeTag.CanHaveChildren = true;

                foreach (DataRowView rowView in view)
                {
                    AAccountHierarchyDetailRow accountDetail = (AAccountHierarchyDetailRow)rowView.Row;
                    InsertNodeIntoTreeView(MainDS, LedgerNumber, Child, view, accountDetail);
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// Initialize values
        /// </summary>
        public void InitializeManualCode()
        {
            cmbBaseCurrency.Enabled        = false;
            cmbIntlCurrency.Enabled        = false;
            txtAccountingPeriods.Enabled   = false;
            txtCalendarMode.Enabled        = false;
            txtCurrencyRevaluation.Enabled = false;
            txtCurrentPeriod.Enabled       = false;
            txtForwardPeriods.Enabled      = false;
            dtpPeriodStartDate.Enabled     = false;
            dtpPeriodEndDate.Enabled       = false;
            dtpPostingAllowedUntil.Enabled = false;
            chkSuspenseAccounts.Enabled    = false;
            chkBudgetControl.Enabled       = false;

            FMainDS = new GLSetupTDS();
        }
コード例 #14
0
        /// <summary>
        /// Initialize values
        /// </summary>
        public void InitializeManualCode()
        {
            cmbBaseCurrency.Enabled = false;
            cmbIntlCurrency.Enabled = false;
            txtAccountingPeriods.Enabled = false;
            txtCalendarMode.Enabled = false;
            txtCurrencyRevaluation.Enabled = false;
            txtCurrentPeriod.Enabled = false;
            txtForwardPeriods.Enabled = false;
            dtpPeriodStartDate.Enabled = false;
            dtpPeriodEndDate.Enabled = false;
            dtpPostingAllowedUntil.Enabled = false;
            chkSuspenseAccounts.Enabled = false;
            chkBudgetControl.Enabled = false;

            FMainDS = new GLSetupTDS();
        }
コード例 #15
0
        /// <summary>
        /// load the batches into the grid
        /// </summary>
        /// <param name="ALedgerNumber"></param>
        public void LoadBatches(Int32 ALedgerNumber)
        {
            //FBatchesLoaded = false;
            InitialiseControls();

            FLedgerNumber = ALedgerNumber;

            if ((FPetraUtilsObject == null) || FPetraUtilsObject.SuppressChangeDetection)
            {
                return;
            }

            FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadARecurringBatch(FLedgerNumber, TFinanceBatchFilterEnum.fbfAll));

            if (FCacheDS == null)
            {
                FCacheDS = TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, false);
            }

            btnNew.Enabled = true;

            FPreviouslySelectedDetailRow = null;
            grdDetails.DataSource        = new DevAge.ComponentModel.BoundDataView(FMainDS.ARecurringBatch.DefaultView);

            if (grdDetails.Rows.Count > 1)
            {
                SelectRowInGrid(1);
                ((TFrmRecurringGLBatch)this.ParentForm).EnableJournals();
                AutoEnableTransTabForBatch();
            }
            else
            {
                ClearControls();
                ((TFrmRecurringGLBatch)this.ParentForm).DisableJournals();
                ((TFrmRecurringGLBatch)this.ParentForm).DisableTransactions();
            }

            //Load all analysis attribute values
            ShowData();

            UpdateChangeableStatus();
            UpdateRecordNumberDisplay();
            SetAccountCostCentreTableVariables();

            //FBatchesLoaded = true;
        }
コード例 #16
0
        public void Init()
        {
            TPetraServerConnector.Connect("../../etc/TestServer.config");

            // These will be our test ledger numbers
            FTestLedgerList.AddRange(new int[] { 9997, 9998, 9999 });

            // Load existing data
            FMainDS = new GLSetupTDS();

            try
            {
                TDBTransaction transaction = null;
                DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                    TEnforceIsolationLevel.eilMinimum,
                    ref transaction,
                    delegate
                    {
                        ALedgerAccess.LoadAll(FMainDS, transaction);
                    });

                // Check that our test rows are not in the database already
                if (!FindTestRows(FTestLedgerList))
                {
                    // Get the initial number of available ledgers
                    FInitialLedgerCount = TGLSetupWebConnector.GetAvailableLedgers().DefaultView.Count;

                    // Add our test rows
                    AddTestRow(FTestLedgerList[0], "NUnitTestLedger1", false);
                    AddTestRow(FTestLedgerList[1], "NUnitTestLedger2", true, "JPY");
                    AddTestRow(FTestLedgerList[2], "NUnitTestLedger2", true);

                    // Save these new rows
                    ALedgerAccess.SubmitChanges(FMainDS.ALedger, null);
                    FMainDS.AcceptChanges();

                    FInitSucceeded = true;
                }
            }
            catch (Exception ex)
            {
                FInitExceptionMessage = ex.Message;
            }
        }
コード例 #17
0
        public void Init()
        {
            TPetraServerConnector.Connect("../../etc/TestServer.config");

            // These will be our test ledger numbers
            FTestLedgerList.AddRange(new int[] { 9997, 9998, 9999 });

            // Load existing data
            FMainDS = new GLSetupTDS();

            try
            {
                TDBTransaction transaction = null;
                DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                          TEnforceIsolationLevel.eilMinimum,
                                                                          ref transaction,
                                                                          delegate
                {
                    ALedgerAccess.LoadAll(FMainDS, transaction);
                });

                // Check that our test rows are not in the database already
                if (!FindTestRows(FTestLedgerList))
                {
                    // Get the initial number of available ledgers
                    FInitialLedgerCount = TGLSetupWebConnector.GetAvailableLedgers().DefaultView.Count;

                    // Add our test rows
                    AddTestRow(FTestLedgerList[0], "NUnitTestLedger1", false);
                    AddTestRow(FTestLedgerList[1], "NUnitTestLedger2", true, "JPY");
                    AddTestRow(FTestLedgerList[2], "NUnitTestLedger2", true);

                    // Save these new rows
                    ALedgerAccess.SubmitChanges(FMainDS.ALedger, null);
                    FMainDS.AcceptChanges();

                    FInitSucceeded = true;
                }
            }
            catch (Exception ex)
            {
                FInitExceptionMessage = ex.Message;
            }
        }
コード例 #18
0
        /// <summary>
        /// Implementation of the logic for setting the filter string for the accounts list screen
        /// </summary>
        /// <param name="AFilterString">The desired filter string</param>
        /// <param name="AMainDataSet">The data set</param>
        public void ApplyFilterManual(ref string AFilterString, GLSetupTDS AMainDataSet)
        {
            string filter = String.Empty;

            if (FFilterTxtCostCentreCode.Text != String.Empty)
            {
                StringHelper.JoinAndAppend(ref filter,
                    String.Format("({0} LIKE '%{1}%')", AMainDataSet.ACostCentre.ColumnCostCentreCode, FFilterTxtCostCentreCode.Text),
                    CommonJoinString.JOIN_STRING_SQL_AND);
            }

            if (FFilterCmbCostCentreType.Text != String.Empty)
            {
                StringHelper.JoinAndAppend(ref filter,
                    String.Format("({0} LIKE '{1}')", AMainDataSet.ACostCentre.ColumnCostCentreType, FFilterCmbCostCentreType.Text),
                    CommonJoinString.JOIN_STRING_SQL_AND);
            }

            if (FFilterTxtCostCentreName.Text != String.Empty)
            {
                StringHelper.JoinAndAppend(ref filter,
                    String.Format("({0} LIKE '%{1}%')", AMainDataSet.ACostCentre.ColumnCostCentreName, FFilterTxtCostCentreName.Text),
                    CommonJoinString.JOIN_STRING_SQL_AND);
            }

            if (FFilterChkActive.CheckState != CheckState.Indeterminate)
            {
                if (FFilterChkActive.Checked)
                {
                    StringHelper.JoinAndAppend(ref filter,
                        String.Format("({0}=1)", AMainDataSet.ACostCentre.ColumnCostCentreActiveFlag),
                        CommonJoinString.JOIN_STRING_SQL_AND);
                }
                else
                {
                    StringHelper.JoinAndAppend(ref filter,
                        String.Format("({0}=0 OR {0} IS NULL)", AMainDataSet.ACostCentre.ColumnCostCentreActiveFlag),
                        CommonJoinString.JOIN_STRING_SQL_AND);
                }
            }

            AFilterString = filter;
        }
コード例 #19
0
        /// <summary>
        /// Implementation of the logic for setting the filter string for the accounts list screen
        /// </summary>
        /// <param name="AFilterString">The desired filter string</param>
        /// <param name="AMainDataSet">The data set</param>
        public void ApplyFilterManual(ref string AFilterString, GLSetupTDS AMainDataSet)
        {
            string filter = String.Empty;

            if (FFilterTxtCostCentreCode.Text != String.Empty)
            {
                StringHelper.JoinAndAppend(ref filter,
                                           String.Format("({0} LIKE '%{1}%')", AMainDataSet.ACostCentre.ColumnCostCentreCode, FFilterTxtCostCentreCode.Text),
                                           CommonJoinString.JOIN_STRING_SQL_AND);
            }

            if (FFilterCmbCostCentreType.Text != String.Empty)
            {
                StringHelper.JoinAndAppend(ref filter,
                                           String.Format("({0} LIKE '{1}')", AMainDataSet.ACostCentre.ColumnCostCentreType, FFilterCmbCostCentreType.Text),
                                           CommonJoinString.JOIN_STRING_SQL_AND);
            }

            if (FFilterTxtCostCentreName.Text != String.Empty)
            {
                StringHelper.JoinAndAppend(ref filter,
                                           String.Format("({0} LIKE '%{1}%')", AMainDataSet.ACostCentre.ColumnCostCentreName, FFilterTxtCostCentreName.Text),
                                           CommonJoinString.JOIN_STRING_SQL_AND);
            }

            if (FFilterChkActive.CheckState != CheckState.Indeterminate)
            {
                if (FFilterChkActive.Checked)
                {
                    StringHelper.JoinAndAppend(ref filter,
                                               String.Format("({0}=1)", AMainDataSet.ACostCentre.ColumnCostCentreActiveFlag),
                                               CommonJoinString.JOIN_STRING_SQL_AND);
                }
                else
                {
                    StringHelper.JoinAndAppend(ref filter,
                                               String.Format("({0}=0 OR {0} IS NULL)", AMainDataSet.ACostCentre.ColumnCostCentreActiveFlag),
                                               CommonJoinString.JOIN_STRING_SQL_AND);
                }
            }

            AFilterString = filter;
        }
コード例 #20
0
ファイル: GenerateLedger.cs プロジェクト: weiplanet/openpetra
        /// update the current ledger with new number of forward posting periods, and different start date for the calendar
        public static void UpdateLedger(DateTime ACalendarStartDate)
        {
            GLSetupTDS InspectDS = new GLSetupTDS();

            TDataBase db = DBAccess.Connect("UpdateLedger");

            TDBTransaction Transaction = new TDBTransaction();

            db.ReadTransaction(ref Transaction,
                               delegate
            {
                ALedgerAccess.LoadByPrimaryKey(InspectDS, FLedgerNumber, Transaction);
            });

            db.CloseDBConnection();

            InspectDS.ALedger[0].NumberFwdPostingPeriods = FNumberOfFwdPostingPeriods;

            TGLSetupWebConnector.SaveLedgerSettings(FLedgerNumber, ACalendarStartDate, ref InspectDS);
        }
コード例 #21
0
        /// <summary>
        /// Load account hierarchy from the dataset into the tree view
        /// </summary>
        public void PopulateTreeView(GLSetupTDS MainDS, Int32 LedgerNumber, String SelectedHierarchy)
        {
            FParentForm.SetSelectedAccount(null);
            FDuringInitialisation = true;
            trvAccounts.BeginUpdate();
            trvAccounts.Nodes.Clear();

            // TODO: select account hierarchy
            AAccountHierarchyRow accountHierarchy = (AAccountHierarchyRow)MainDS.AAccountHierarchy.Rows.Find(new object[] { LedgerNumber,
                                                                                                                            SelectedHierarchy });

            if (accountHierarchy != null)
            {
                // find the BALSHT account that is reporting to the root account
                MainDS.AAccountHierarchyDetail.DefaultView.RowFilter =
                    AAccountHierarchyDetailTable.GetAccountHierarchyCodeDBName() + " = '" + SelectedHierarchy + "' AND " +
                    AAccountHierarchyDetailTable.GetAccountCodeToReportToDBName() + " = '" + accountHierarchy.RootAccountCode + "'";

                DataView view = new DataView(MainDS.AAccountHierarchyDetail);
                view.Sort = AAccountHierarchyDetailTable.GetReportOrderDBName() + ", " + AAccountHierarchyDetailTable.GetReportingAccountCodeDBName();
                InsertNodeIntoTreeView(MainDS, LedgerNumber, null, view,
                                       (AAccountHierarchyDetailRow)MainDS.AAccountHierarchyDetail.DefaultView[0].Row);
            }

            // reset filter so that the defaultview can be used for finding accounts (eg. when adding new account)
            MainDS.AAccountHierarchyDetail.DefaultView.RowFilter = "";
            trvAccounts.EndUpdate();

            FDuringInitialisation = false;

            if (trvAccounts.Nodes.Count > 0)
            {
                SelectNodeByName(trvAccounts.Nodes[0].Name); // Select the first (BAL SHT) item
            }

            this.trvAccounts.BeforeSelect +=
                new System.Windows.Forms.TreeViewCancelEventHandler(this.TreeViewBeforeSelect);
            this.trvAccounts.AfterSelect +=
                new System.Windows.Forms.TreeViewEventHandler(this.TreeViewAfterSelect);
        }
コード例 #22
0
        private TSubmitChangesResult StoreManualCode(ref GLSetupTDS ASubmitDS, out TVerificationResultCollection AVerificationResult)
        {
            //
            // The Controls might not have changed, but if they have, this will make the tree look right:
            FPetraUtilsObject_ControlChanged(null);

            //
            // I'll look through and check whether any of the cost centres still have "NEWCOSTCENTRE"..
            //
            if (CheckForInvalidCostCentre())
            {
                AVerificationResult = null;
                FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataErrorOccured);
                return TSubmitChangesResult.scrInfoNeeded;
            }

            ucoCostCentreTree.MarkAllNodesCommitted();
            TSubmitChangesResult ServerResult =
                TRemote.MFinance.Setup.WebConnectors.SaveGLSetupTDS(FLedgerNumber, ref ASubmitDS, out AVerificationResult);
            TDataCache.TMFinance.RefreshCacheableFinanceTable(Shared.TCacheableFinanceTablesEnum.CostCentreList, FLedgerNumber);
            return ServerResult;
        }
コード例 #23
0
        private TSubmitChangesResult StoreManualCode(ref GLSetupTDS ASubmitDS, out TVerificationResultCollection AVerificationResult)
        {
            //
            // I need to remove any AnalysisAttribute records that are still set to "Unassigned"
            //
            if ((ASubmitDS.AAnalysisAttribute != null) && (ASubmitDS.AAnalysisAttribute.Rows.Count > 0))
            {
                for (int Idx = ASubmitDS.AAnalysisAttribute.Rows.Count - 1; Idx >= 0; Idx--)
                {
                    AAnalysisAttributeRow Row = ASubmitDS.AAnalysisAttribute[Idx];

                    if ((Row.RowState != DataRowState.Deleted) && (Row.AnalysisTypeCode.IndexOf("Unassigned") == 0))
                    {
                        Row.Delete();
                    }
                }
            }

            //
            // I'll take this opportunity to remove any similar records in my own TDS
            //
            for (int Idx = FMainDS.AAnalysisAttribute.Rows.Count - 1; Idx >= 0; Idx--)
            {
                AAnalysisAttributeRow Row = FMainDS.AAnalysisAttribute[Idx];

                if ((Row.RowState != DataRowState.Deleted) && (Row.AnalysisTypeCode.IndexOf("Unassigned") == 0))
                {
                    Row.Delete();
                }
            }

            ucoAccountsTree.MarkAllNodesCommitted();
            TSubmitChangesResult ServerResult =
                TRemote.MFinance.Setup.WebConnectors.SaveGLSetupTDS(FLedgerNumber, ref ASubmitDS, out AVerificationResult);

            TDataCache.TMFinance.RefreshCacheableFinanceTable(Shared.TCacheableFinanceTablesEnum.AccountList, FLedgerNumber);
            return(ServerResult);
        }
コード例 #24
0
ファイル: GL.Setup.cs プロジェクト: js1987/openpetragit
        public static GLSetupTDS LoadLedgerInfo(Int32 ALedgerNumber)
        {
            GLSetupTDS MainDS = new GLSetupTDS();

            TDBTransaction Transaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                TEnforceIsolationLevel.eilMinimum,
                ref Transaction,
                delegate
                {
                    ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction);
                    AAccountingSystemParameterAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction);
                    AAccountingPeriodAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                });

            // Accept row changes here so that the Client gets 'unmodified' rows
            MainDS.AcceptChanges();

            // Remove all Tables that were not filled with data before remoting them.
            MainDS.RemoveEmptyTables();

            return MainDS;
        }
コード例 #25
0
        /// <summary>
        /// Posts a batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The data row corresponding to the batch to post</param>
        /// <param name="AEffectiveDate">The effective date for the batch</param>
        /// <param name="AStartDateCurrentPeriod">The earliest postable date</param>
        /// <param name="AEndDateLastForwardingPeriod">The latest postable date</param>
        /// <returns>
        /// True if the batch was successfully posted
        /// </returns>
        public bool PostBatch(ABatchRow ACurrentBatchRow,
                              DateTime AEffectiveDate,
                              DateTime AStartDateCurrentPeriod,
                              DateTime AEndDateLastForwardingPeriod)
        {
            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return(false);
            }

            int CurrentBatchNumber = ACurrentBatchRow.BatchNumber;

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

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

            //Load all Batch data
            FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAndRelatedTables(FLedgerNumber, CurrentBatchNumber));

            if (FCacheDS == null)
            {
                FCacheDS = TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, false);
            }

            if (FAccountTable == null)
            {
                SetAccountCostCentreTableVariables();
            }

            if ((AEffectiveDate.Date < AStartDateCurrentPeriod) || (AEffectiveDate.Date > AEndDateLastForwardingPeriod))
            {
                MessageBox.Show(String.Format(Catalog.GetString(
                                                  "The Date Effective is outside the periods available for posting. Enter a date between {0:d} and {1:d}."),
                                              AStartDateCurrentPeriod,
                                              AEndDateLastForwardingPeriod));

                return(false);
            }

            // check that a corportate exchange rate exists
            FMyForm.WarnAboutMissingIntlExchangeRate = true;

            if (FMyForm.GetInternationalCurrencyExchangeRate() == 0)
            {
                return(false);
            }

            if ((MessageBox.Show(String.Format(Catalog.GetString("Are you sure you want to post GL batch {0}?"),
                                               CurrentBatchNumber),
                                 Catalog.GetString("Question"),
                                 MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) != System.Windows.Forms.DialogResult.Yes))
            {
                return(false);
            }

            TVerificationResultCollection Verifications = new TVerificationResultCollection();

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                Thread postingThread = new Thread(() => PostGLBatch(CurrentBatchNumber, out Verifications));
                postingThread.SetApartmentState(ApartmentState.STA);

                using (TProgressDialog dialog = new TProgressDialog(postingThread))
                {
                    dialog.ShowDialog();
                }

                if (TVerificationHelper.ResultsContainErrorCode(Verifications, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                {
                    TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                }
                else if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications))
                {
                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    StringBuilder errorMessages = new StringBuilder();
                    int           counter       = 0;

                    errorMessages.AppendLine(Catalog.GetString("________________________GL Posting Errors________________________"));
                    errorMessages.AppendLine();

                    foreach (TVerificationResult verif in Verifications)
                    {
                        counter++;
                        errorMessages.AppendLine(counter.ToString("000") + " - " + verif.ResultText);
                        errorMessages.AppendLine();
                    }

                    extendedMessageBox.ShowDialog(errorMessages.ToString(),
                                                  Catalog.GetString("Post Batch Error"),
                                                  string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);
                }
                else
                {
                    MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"),
                                    Catalog.GetString("Success"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }

                // refresh the grid, to reflect that the batch has been posted (or even maybe had been posted by another user)
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAndRelatedTables(FLedgerNumber, CurrentBatchNumber));

                // make sure that the current dataset is clean,
                // otherwise the next save would try to modify the posted batch, even though no values have been changed
                FMainDS.AcceptChanges();

                // Ensure these tabs will ask the server for updates
                FMyForm.GetTransactionsControl().ClearCurrentSelection();
                FMyForm.GetJournalsControl().ClearCurrentSelection();

                FMyUserControl.UpdateDisplay();
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }

            return(true);
        }
コード例 #26
0
ファイル: GL.Setup.cs プロジェクト: Davincier/openpetra
        public static AFreeformAnalysisTable LoadAFreeformAnalysis(Int32 ALedgerNumber)
        {
            GLSetupTDS MainDS = new GLSetupTDS();

            TDBTransaction Transaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                TEnforceIsolationLevel.eilMinimum,
                ref Transaction,
                delegate
                {
                    AFreeformAnalysisAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                });

            // Accept row changes here so that the Client gets 'unmodified' rows
            MainDS.AcceptChanges();

            // Remove all Tables that were not filled with data before remoting them.
            MainDS.RemoveEmptyTables();
            AFreeformAnalysisTable myAT = MainDS.AFreeformAnalysis;
            return myAT;
        }
コード例 #27
0
        private TSubmitChangesResult StoreManualCode(ref GLSetupTDS ASubmitDS, out TVerificationResultCollection AVerificationResult)
        {
            //
            // I need to remove any AnalysisAttribute records that are still set to "Unassigned"
            //
            if ((ASubmitDS.AAnalysisAttribute != null) && (ASubmitDS.AAnalysisAttribute.Rows.Count > 0))
            {
                for (int Idx = ASubmitDS.AAnalysisAttribute.Rows.Count - 1; Idx >= 0; Idx--)
                {
                    AAnalysisAttributeRow Row = ASubmitDS.AAnalysisAttribute[Idx];

                    if ((Row.RowState != DataRowState.Deleted) && (Row.AnalysisTypeCode.IndexOf("Unassigned") == 0))
                    {
                        Row.Delete();
                    }
                }
            }

            //
            // I'll take this opportunity to remove any similar records in my own TDS
            //
            for (int Idx = FMainDS.AAnalysisAttribute.Rows.Count - 1; Idx >= 0; Idx--)
            {
                AAnalysisAttributeRow Row = FMainDS.AAnalysisAttribute[Idx];

                if ((Row.RowState != DataRowState.Deleted) && (Row.AnalysisTypeCode.IndexOf("Unassigned") == 0))
                {
                    Row.Delete();
                }
            }

            ucoAccountsTree.MarkAllNodesCommitted();
            TSubmitChangesResult ServerResult =
                TRemote.MFinance.Setup.WebConnectors.SaveGLSetupTDS(FLedgerNumber, ref ASubmitDS, out AVerificationResult);
            TDataCache.TMFinance.RefreshCacheableFinanceTable(Shared.TCacheableFinanceTablesEnum.AccountList, FLedgerNumber);
            return ServerResult;
        }
コード例 #28
0
        /// <summary>
        /// generate the units
        /// </summary>
        /// <param name="AFieldCSVFile"></param>
        public static void GenerateFields(string AFieldCSVFile)
        {
            XmlDocument doc = TCsv2Xml.ParseCSVFile2Xml(AFieldCSVFile, ",");

            XmlNode RecordNode = doc.FirstChild.NextSibling.FirstChild;

            PartnerImportExportTDS PartnerDS = new PartnerImportExportTDS();
            GLSetupTDS             GLSetupDS = new GLSetupTDS();

            PCountryTable CountryTable = null;

            TDBTransaction Transaction = new TDBTransaction();

            DBAccess.ReadTransaction(
                ref Transaction,
                delegate
            {
                CountryTable = PCountryAccess.LoadAll(Transaction);
            });

            while (RecordNode != null)
            {
                PUnitRow UnitRow = PartnerDS.PUnit.NewRowTyped();
                long     id      = 100 + Convert.ToInt64(TXMLParser.GetAttribute(RecordNode, "id"));
                UnitRow.PartnerKey = id * 1000000;
                string CountryCode = TXMLParser.GetAttribute(RecordNode, "Name");
                UnitRow.UnitName     = ((PCountryRow)CountryTable.Rows.Find(CountryCode)).CountryName;
                UnitRow.UnitTypeCode = "F";
                PartnerDS.PUnit.Rows.Add(UnitRow);

                PPartnerRow PartnerRow = PartnerDS.PPartner.NewRowTyped();
                PartnerRow.PartnerKey       = UnitRow.PartnerKey;
                PartnerRow.PartnerShortName = UnitRow.UnitName;
                PartnerRow.PartnerClass     = MPartnerConstants.PARTNERCLASS_UNIT;
                PartnerRow.StatusCode       = MPartnerConstants.PARTNERSTATUS_ACTIVE;
                PartnerDS.PPartner.Rows.Add(PartnerRow);

                // add empty location so that the partner can be found in the Partner Find screen
                PPartnerLocationRow PartnerLocationRow = PartnerDS.PPartnerLocation.NewRowTyped();
                PartnerLocationRow.PartnerKey  = UnitRow.PartnerKey;
                PartnerLocationRow.LocationKey = 0;
                PartnerLocationRow.SiteKey     = 0;
                PartnerDS.PPartnerLocation.Rows.Add(PartnerLocationRow);

                // create unit hierarchy
                UmUnitStructureRow UnitStructureRow = PartnerDS.UmUnitStructure.NewRowTyped();
                UnitStructureRow.ParentUnitKey = 1000000;
                UnitStructureRow.ChildUnitKey  = UnitRow.PartnerKey;
                PartnerDS.UmUnitStructure.Rows.Add(UnitStructureRow);

                // create special type
                PPartnerTypeRow PartnerTypeRow = PartnerDS.PPartnerType.NewRowTyped();
                PartnerTypeRow.PartnerKey = UnitRow.PartnerKey;
                PartnerTypeRow.TypeCode   = MPartnerConstants.PARTNERTYPE_LEDGER;
                PartnerDS.PPartnerType.Rows.Add(PartnerTypeRow);

                // create cost centre
                ACostCentreRow CostCentreRow = GLSetupDS.ACostCentre.NewRowTyped();
                CostCentreRow.LedgerNumber         = FLedgerNumber;
                CostCentreRow.CostCentreCode       = (id * 100).ToString("0000");
                CostCentreRow.CostCentreName       = UnitRow.UnitName;
                CostCentreRow.CostCentreToReportTo = MFinanceConstants.INTER_LEDGER_HEADING;
                CostCentreRow.CostCentreType       = MFinanceConstants.FOREIGN_CC_TYPE;
                GLSetupDS.ACostCentre.Rows.Add(CostCentreRow);

                // create foreign ledger, cost centre link validledgernumber
                AValidLedgerNumberRow ValidLedgerNumber = GLSetupDS.AValidLedgerNumber.NewRowTyped();
                ValidLedgerNumber.LedgerNumber        = FLedgerNumber;
                ValidLedgerNumber.PartnerKey          = UnitRow.PartnerKey;
                ValidLedgerNumber.CostCentreCode      = CostCentreRow.CostCentreCode;
                ValidLedgerNumber.IltProcessingCentre = Convert.ToInt64(MFinanceConstants.ICH_COST_CENTRE) * 10000;
                GLSetupDS.AValidLedgerNumber.Rows.Add(ValidLedgerNumber);

                RecordNode = RecordNode.NextSibling;
            }

            PartnerImportExportTDSAccess.SubmitChanges(PartnerDS);

            GLSetupTDSAccess.SubmitChanges(GLSetupDS);
        }
コード例 #29
0
ファイル: GL.Validation.cs プロジェクト: Davincier/openpetra
        /// <summary>
        /// Validates the GL Journal 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="AGLSetupDSRef">A GLSetupTDS reference with a populated ATransactionTypeTable.  A reference to this DataSet is REQUIRED when importing - optional otherwise</param>
        /// <param name="ACurrencyTableRef">A reference to the Currency table.  A reference to this table is REQUIRED when importing - optional otherwise</param>
        /// <param name="ACorporateExchangeTableRef">Corporate exchange rate table.  A reference to this table is REQUIRED when importing - optional otherwise</param>
        /// <param name="ABaseCurrency">Ledger base currency.  Required when importing</param>
        /// <param name="AIntlCurrency">Ledger international currency.  Required when importing</param>
        /// <returns>True if the validation found no data validation errors, otherwise false.</returns>
        public static bool ValidateGLJournalManual(object AContext, AJournalRow ARow,
            ref TVerificationResultCollection AVerificationResultCollection, TValidationControlsDict AValidationControlsDict,
            GLSetupTDS AGLSetupDSRef = null,
            ACurrencyTable ACurrencyTableRef = null,
            ACorporateExchangeRateTable ACorporateExchangeTableRef = null,
            String ABaseCurrency = null,
            String AIntlCurrency = null)
        {
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TScreenVerificationResult VerificationResult;
            string ValidationContext;
            int VerifResultCollAddedCount = 0;

            // Don't validate deleted or posted DataRows
            if ((ARow.RowState == DataRowState.Deleted) || (ARow.JournalStatus == MFinanceConstants.BATCH_POSTED))
            {
                return true;
            }

            bool isImporting = AContext.ToString().Contains("Importing");

            // 'Exchange Rate' must be greater than 0
            ValidationColumn = ARow.Table.Columns[AJournalTable.ColumnExchangeRateToBaseId];
            ValidationContext = ARow.JournalNumber.ToString() + " of Batch Number: " + ARow.BatchNumber.ToString();

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                VerificationResult = (TScreenVerificationResult)TNumericalChecks.IsPositiveDecimal(ARow.ExchangeRateToBase,
                    ValidationControlsData.ValidationControlLabel + (isImporting ? String.Empty : " of Journal Number: " + ValidationContext.ToString()),
                    AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                // Handle addition/removal to/from TVerificationResultCollection
                if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn, true))
                {
                    VerifResultCollAddedCount++;
                }

                // Exchange rate must be 1.00 if the currency is the base ledger currency
                if ((ABaseCurrency != null)
                    && (!ARow.IsExchangeRateToBaseNull())
                    && (ARow.TransactionCurrency == ABaseCurrency)
                    && (ARow.ExchangeRateToBase != 1.00m))
                {
                    if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext,
                            new TVerificationResult(ValidationContext,
                                Catalog.GetString("A journal in the ledger base currency must have exchange rate of 1.00."),
                                TResultSeverity.Resv_Critical),
                            ValidationColumn))
                    {
                        VerifResultCollAddedCount++;
                    }
                }
            }

            // Transaction currency must be valid
            bool isValidTransactionCurrency = true;

            if (isImporting && (ACurrencyTableRef != null))
            {
                ValidationColumn = ARow.Table.Columns[AJournalTable.ColumnTransactionCurrencyId];

                if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    ACurrencyRow foundRow = (ACurrencyRow)ACurrencyTableRef.Rows.Find(ARow.TransactionCurrency);
                    isValidTransactionCurrency = (foundRow != null);

                    if ((foundRow == null)
                        && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                            AContext,
                            new TVerificationResult(ValidationContext,
                                String.Format(Catalog.GetString("'{0}' is not a valid currency."), ARow.TransactionCurrency),
                                TResultSeverity.Resv_Critical),
                            ValidationColumn))
                    {
                        VerifResultCollAddedCount++;
                    }
                }
            }

            if ((ACorporateExchangeTableRef != null) && isValidTransactionCurrency && (ABaseCurrency != null) && (AIntlCurrency != null)
                && !ARow.IsDateEffectiveNull() && (ABaseCurrency != AIntlCurrency))
            {
                // For ledgers where the base currency and intl currency differ there must be a corporate exchange rate to the international currency
                ValidationColumn = ARow.Table.Columns[AJournalTable.ColumnTransactionCurrencyId];
                ValidationContext = ARow.JournalNumber.ToString() + " of Batch Number: " + ARow.BatchNumber.ToString();

                if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    DateTime firstOfMonth;

                    if (TSharedFinanceValidationHelper.GetFirstDayOfAccountingPeriod(ARow.LedgerNumber,
                            ARow.DateEffective, out firstOfMonth))
                    {
                        ACorporateExchangeRateRow foundRow = (ACorporateExchangeRateRow)ACorporateExchangeTableRef.Rows.Find(
                            new object[] { ABaseCurrency, AIntlCurrency, firstOfMonth });

                        if ((foundRow == null)
                            && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                AContext,
                                new TVerificationResult(ValidationContext,
                                    String.Format(Catalog.GetString(
                                            "There is no Corporate Exchange Rate defined for '{0}' to '{1}' for the month starting on '{2}'."),
                                        ABaseCurrency, AIntlCurrency,
                                        StringHelper.DateToLocalizedString(firstOfMonth)),
                                    TResultSeverity.Resv_Noncritical),
                                ValidationColumn))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }
                }
            }

            // Sub-system code must exist in the transaction type table
            if (isImporting && (AGLSetupDSRef.ATransactionType != null))
            {
                ValidationColumn = ARow.Table.Columns[AJournalTable.ColumnSubSystemCodeId];

                if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    ATransactionTypeRow foundRow = (ATransactionTypeRow)AGLSetupDSRef.ATransactionType.Rows.Find(
                        new object[] { ARow.LedgerNumber, ARow.SubSystemCode, ARow.TransactionTypeCode });

                    if ((foundRow == null)
                        && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                            AContext,
                            new TVerificationResult(ValidationContext,
                                String.Format(Catalog.GetString(
                                        "The combination of Transaction Type of '{0}' and Sub-system Code of '{1}' is not valid for journals in Ledger {2}."),
                                    ARow.TransactionTypeCode, ARow.SubSystemCode, ARow.LedgerNumber),
                                TResultSeverity.Resv_Critical),
                            ValidationColumn))
                    {
                        VerifResultCollAddedCount++;
                    }
                }
            }

            // Journal description must not be null
            if (isImporting)
            {
                ValidationColumn = ARow.Table.Columns[AJournalTable.ColumnJournalDescriptionId];

                if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    if ((ARow.JournalDescription == null) || (ARow.JournalDescription.Length == 0))
                    {
                        if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                AContext,
                                new TVerificationResult(ValidationContext,
                                    Catalog.GetString("The journal description must not be empty."),
                                    TResultSeverity.Resv_Critical),
                                ValidationColumn))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }
                }
            }

            return VerifResultCollAddedCount == 0;
        }
コード例 #30
0
        private TSubmitChangesResult StoreManualCode(ref GLSetupTDS ASubmitTDS, out TVerificationResultCollection AVerificationResult)
        {
            //
            // I'll warn the user if they have created analysis Types with no values:

            String EmptyTypesWarning = "";

            //
            // If the user has added a new type, I want to show her a warning if she didn't also add at least one value for the new type.

            if (ASubmitTDS.AAnalysisType != null)
            {
                foreach (AAnalysisTypeRow TypeRow in ASubmitTDS.AAnalysisType.Rows)
                {
                    if (TypeRow.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    Boolean NoValuesProvided = true;

                    if (ASubmitTDS.AFreeformAnalysis != null)
                    {
                        ASubmitTDS.AFreeformAnalysis.DefaultView.RowFilter =
                            String.Format("a_analysis_type_code_c='{0}'", TypeRow["a_analysis_type_code_c"]);
                        NoValuesProvided = ASubmitTDS.AFreeformAnalysis.DefaultView.Count == 0;
                    }

                    if (NoValuesProvided)
                    {
                        if (EmptyTypesWarning != "")
                        {
                            EmptyTypesWarning += "\r\n";
                        }

                        EmptyTypesWarning +=
                            String.Format(Catalog.GetString("Type {0} has no values, and therefore it cannot yet be applied to any account."),
                                TypeRow["a_analysis_type_code_c"]);
                    }
                }
            }

            if (EmptyTypesWarning != "")
            {
                MessageBox.Show(EmptyTypesWarning, Catalog.GetString("Empty Analysis Types"), MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            return TRemote.MFinance.Setup.WebConnectors.SaveGLSetupTDS(FLedgerNumber, ref ASubmitTDS, out AVerificationResult);
        }
コード例 #31
0
        private DataTable GetAccountListTable(TDBTransaction AReadTransaction, System.Int32 ALedgerNumber, string ATableName)
        {
            StringCollection FieldList = new StringCollection();

            FieldList.Add(AAccountTable.GetLedgerNumberDBName());
            FieldList.Add(AAccountTable.GetAccountCodeDBName());
            FieldList.Add(AAccountTable.GetAccountTypeDBName());
            FieldList.Add(AAccountTable.GetAccountCodeShortDescDBName());
            FieldList.Add(AAccountTable.GetAccountActiveFlagDBName());
            FieldList.Add(AAccountTable.GetPostingStatusDBName());
            FieldList.Add(AAccountTable.GetForeignCurrencyFlagDBName());
            FieldList.Add(AAccountTable.GetForeignCurrencyCodeDBName());
            GLSetupTDS TempDS = new GLSetupTDS();
            AAccountAccess.LoadViaALedger(TempDS, ALedgerNumber, FieldList, AReadTransaction);

            // load AAccountProperty and set the BankAccountFlag
            AAccountPropertyAccess.LoadViaALedger(TempDS, ALedgerNumber, AReadTransaction);

            foreach (AAccountPropertyRow accProp in TempDS.AAccountProperty.Rows)
            {
                if ((accProp.PropertyCode == MFinanceConstants.ACCOUNT_PROPERTY_BANK_ACCOUNT) && (accProp.PropertyValue == "true"))
                {
                    TempDS.AAccount.DefaultView.RowFilter = String.Format("{0}='{1}'",
                        AAccountTable.GetAccountCodeDBName(),
                        accProp.AccountCode);
                    GLSetupTDSAAccountRow acc = (GLSetupTDSAAccountRow)TempDS.AAccount.DefaultView[0].Row;
                    acc.BankAccountFlag = true;
                    TempDS.AAccount.DefaultView.RowFilter = "";
                }
            }

            // not currently needed as an Account is only a Bank Account if it has a 'Bank Account' Account Property
            // load AAccountHierarchyDetails and check if this account reports to the CASH account

            /*AAccountHierarchyDetailAccess.LoadViaAAccountHierarchy(TempDS,
             *  ALedgerNumber,
             *  MFinanceConstants.ACCOUNT_HIERARCHY_STANDARD,
             *  AReadTransaction);
             *
             * TLedgerInfo ledgerInfo = new TLedgerInfo(ALedgerNumber);
             * TGetAccountHierarchyDetailInfo accountHierarchyTools = new TGetAccountHierarchyDetailInfo(ledgerInfo);
             * List <string>children = accountHierarchyTools.GetChildren(MFinanceConstants.CASH_ACCT);
             *
             * foreach (GLSetupTDSAAccountRow account in TempDS.AAccount.Rows)
             * {
             *  if (children.Contains(account.AccountCode))
             *  {
             *      account.CashAccountFlag = true;
             *  }
             * }*/

            return TempDS.AAccount;
        }
コード例 #32
0
        public static bool RunFirstSetup(
            string AUserID,
            string AFirstName,
            string ALastName,
            string ALanguageCode,
            string AEmailAddress,
            List <string> AInitialModulePermissions,
            string AInitialPassword,
            Int64 ASiteKey,
            bool AEnableSelfSignup,
            out TVerificationResultCollection AVerificationResult)
        {
            bool result = true;

            AVerificationResult = new TVerificationResultCollection();
            TVerificationResult           VerificationResult           = null;
            TVerificationResultCollection VerificationResultCollection = new TVerificationResultCollection();

            if (AInitialPassword != String.Empty)
            {
                // check if password is valid, it meets the criteria
                if (!TSharedSysManValidation.CheckPasswordQuality(AInitialPassword, out VerificationResult))
                {
                    AVerificationResult.Add(VerificationResult);
                    return(false);
                }
            }

            result = TMaintenanceWebConnector.SaveUserAndModulePermissions(
                AUserID, AFirstName, ALastName, AEmailAddress, ALanguageCode,
                false, false, false, AInitialModulePermissions, 0,
                out VerificationResultCollection);

            if (result != false)
            {
                TDBTransaction t        = new TDBTransaction();
                TDataBase      db       = DBAccess.Connect("RunFirstSetup");
                bool           SubmitOK = false;

                db.WriteTransaction(ref t,
                                    ref SubmitOK,
                                    delegate
                {
                    if (AInitialPassword != String.Empty)
                    {
                        result = TMaintenanceWebConnector.SetUserPassword(AUserID, AInitialPassword, false, false,
                                                                          String.Empty, String.Empty, out VerificationResultCollection);
                    }
                    else
                    {
                        // TODO send welcoming Email, with link for setting the password
                    }

                    if (result)
                    {
                        TSystemDefaults defaults = new TSystemDefaults(db);
                        defaults.SetSystemDefault(SharedConstants.SYSDEFAULT_SITEKEY, ASiteKey.ToString(), db);
                        defaults.SetSystemDefault(SharedConstants.SYSDEFAULT_SELFSIGNUPENABLED, AEnableSelfSignup.ToString(), db);

                        GLSetupTDS GLMainDS = new GLSetupTDS();
                        SubmitOK            = TGLSetupWebConnector.CreateSite(ref GLMainDS, "Default Site", ASiteKey, t);

                        if (SubmitOK)
                        {
                            GLSetupTDSAccess.SubmitChanges(GLMainDS, db, t);
                        }
                    }
                });

                db.CloseDBConnection();
            }

            if (!result)
            {
                if (VerificationResultCollection.HasCriticalErrors)
                {
                    AVerificationResult = VerificationResultCollection;
                }
                else
                {
                    AVerificationResult.Add(VerificationResult);
                }
            }

            return(result);
        }
コード例 #33
0
        public static GLSetupTDS LoadAAnalysisAttributes(Int32 ALedgerNumber, Boolean AActiveOnly = false)
        {
            #region Validate Arguments

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

            #endregion Validate Arguments

            GLSetupTDS MainDS = new GLSetupTDS();
            TDBTransaction Transaction = null;

            try
            {
                DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                    TEnforceIsolationLevel.eilMinimum,
                    ref Transaction,
                    delegate
                    {
                        AAnalysisTypeAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);

                        if (!AActiveOnly)
                        {
                            AFreeformAnalysisAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                            AAnalysisAttributeAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                        }
                        else
                        {
                            AFreeformAnalysisTable FFTable = new AFreeformAnalysisTable();
                            AFreeformAnalysisRow TemplateFFRow = FFTable.NewRowTyped(false);
                            TemplateFFRow.LedgerNumber = ALedgerNumber;
                            TemplateFFRow.Active = true;
                            AFreeformAnalysisAccess.LoadUsingTemplate(MainDS, TemplateFFRow, Transaction);

                            AAnalysisAttributeTable AATable = new AAnalysisAttributeTable();
                            AAnalysisAttributeRow TemplateAARow = AATable.NewRowTyped(false);
                            TemplateAARow.LedgerNumber = ALedgerNumber;
                            TemplateAARow.Active = true;
                            AAnalysisAttributeAccess.LoadUsingTemplate(MainDS, TemplateAARow, Transaction);
                        }
                    });

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

            return MainDS;
        }
コード例 #34
0
        /// <summary>
        /// Show ledger info data from given data set
        /// </summary>
        /// <param name="ADataSet">The data set for which details will be shown</param>
        private void ShowData(GLSetupTDS ADataSet)
        {
            ALedgerRow LedgerRow;
            AAccountingPeriodRow AccountingPeriodRow;
            DataRow TempRow;

            if ((ADataSet == null)
                || (ADataSet.ALedger.Count == 0))
            {
                return;
            }

            LedgerRow = (ALedgerRow)ADataSet.ALedger.Rows[0];

            cmbBaseCurrency.SetSelectedString(LedgerRow.BaseCurrency, -1);
            cmbIntlCurrency.SetSelectedString(LedgerRow.IntlCurrency, -1);

            txtAccountingPeriods.NumberValueInt = LedgerRow.NumberOfAccountingPeriods;

            if (LedgerRow.CalendarMode)
            {
                txtCalendarMode.Text = Catalog.GetString("Monthly");
            }
            else
            {
                txtCalendarMode.Text = Catalog.GetString("Non-Monthly");
            }

            txtCurrencyRevaluation.Text = LedgerRow.ForexGainsLossesAccount;
            txtCurrentPeriod.NumberValueInt = LedgerRow.CurrentPeriod;
            txtForwardPeriods.NumberValueInt = LedgerRow.NumberFwdPostingPeriods;

            TempRow = ADataSet.AAccountingPeriod.Rows.Find(new object[] { LedgerRow.LedgerNumber,
                                                                          LedgerRow.CurrentPeriod });

            if (TempRow != null)
            {
                AccountingPeriodRow = (AAccountingPeriodRow)TempRow;
                dtpPeriodStartDate.Date = AccountingPeriodRow.PeriodStartDate.Date;
                dtpPeriodEndDate.Date = AccountingPeriodRow.PeriodEndDate.Date;
            }

            TempRow = ADataSet.AAccountingPeriod.Rows.Find(new object[] { LedgerRow.LedgerNumber,
                                                                          LedgerRow.CurrentPeriod + LedgerRow.NumberFwdPostingPeriods });

            if (TempRow != null)
            {
                AccountingPeriodRow = (AAccountingPeriodRow)TempRow;
                dtpPostingAllowedUntil.Date = AccountingPeriodRow.PeriodEndDate.Date;
            }

            chkSuspenseAccounts.Checked = LedgerRow.SuspenseAccountFlag;
            chkBudgetControl.Checked = LedgerRow.BudgetControlFlag;
        }
コード例 #35
0
        /// <summary>
        /// Load CostCentre hierarchy from the dataset into the tree view
        /// </summary>
        public void PopulateTreeView(GLSetupTDS MainDS)
        {
            FDuringInitialisation = true;
            trvCostCentres.BeginUpdate();
            trvCostCentres.Nodes.Clear();

            // find the root cost centre
            MainDS.ACostCentre.DefaultView.RowFilter =
                ACostCentreTable.GetCostCentreToReportToDBName() + " IS NULL";

            DataView view = new DataView(MainDS.ACostCentre);
            view.Sort = ACostCentreTable.GetCostCentreCodeDBName();

            InsertNodeIntoTreeView(null,
                view,
                (ACostCentreRow)MainDS.ACostCentre.DefaultView[0].Row);

            MainDS.ACostCentre.DefaultView.RowFilter = "";

            trvCostCentres.EndUpdate();

            this.trvCostCentres.BeforeSelect += TreeViewBeforeSelect;
            this.trvCostCentres.AfterSelect += TreeViewAfterSelect;
            trvCostCentres.EndUpdate();

            FDuringInitialisation = false;

            if (trvCostCentres.Nodes.Count > 0)
            {
                SelectNodeByName(trvCostCentres.Nodes[0].Name); // Select the first item
            }
        }
コード例 #36
0
        /// <summary>
        /// Show all the data (CostCentre Code and description)
        /// </summary>
        public void PopulateListView(GLSetupTDS MainDS, Int32 LedgerNumber)
        {
//          FLedgerNumber = LedgerNumber;

            FDataView = new DataView(MainDS.ACostCentre);
            FDataView.Sort = "a_cost_centre_code_c";
            FDataView.AllowNew = false;
            grdCostCentres.DataSource = new DevAge.ComponentModel.BoundDataView(FDataView);
            grdCostCentres.Columns.Clear();
            grdCostCentres.AddTextColumn("Code", MainDS.ACostCentre.ColumnCostCentreCode);
            grdCostCentres.AddTextColumn("Name", MainDS.ACostCentre.ColumnCostCentreName);
            grdCostCentres.AutoResizeGrid();
        }
コード例 #37
0
        /// <summary>
        /// Main method for saving the screen data.
        /// Stores the settings for all the pages, since everything shares the same FMainDS
        /// </summary>
        private TSubmitChangesResult StoreManualCode(ref GLSetupTDS ASubmitChanges, out TVerificationResultCollection AVerificationResult)
        {
            AVerificationResult = null;

            // save ledger settings now
            // Note:  a_ledger_init_flag records are automatically added/removed on server side for the following
            //           based on the values in the a_ledger table
            // * suspense account flag: "SUSP-ACCT"
            // * budget flag: "BUDGET"
            // * branch processing: "BRANCH-PROCESS" (this is a new flag for OpenPetra)
            // * base currency: "CURRENCY"
            // * international currency: "INTL-CURRENCY" (this is a new flag for OpenPetra)
            // * current period (start of ledger date): CURRENT-PERIOD
            // * calendar settings: CAL
            // But the 'AP require approval before posting' flag is set in this GUI on the AP tab by setting the a_ledger_init_flag row directly
            //  (because there is no column in a_ledger for this option - it only exists in a_ledger_init_flag table)

            TSubmitChangesResult res = TRemote.MFinance.Setup.WebConnectors.SaveLedgerSettings(FLedgerNumber,
                FCalendarStartDate,
                ref ASubmitChanges);
            TDataCache.TMFinance.RefreshCacheableFinanceTable(TCacheableFinanceTablesEnum.LedgerDetails, FLedgerNumber);

            return res;
        }
コード例 #38
0
        /// <summary>
        /// Validates the GL Journal 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="AGLSetupDSRef">A GLSetupTDS reference with a populated ATransactionTypeTable.  A reference to this DataSet is REQUIRED when importing - optional otherwise</param>
        /// <param name="ACurrencyTableRef">A reference to the Currency table.  A reference to this table is REQUIRED when importing - optional otherwise</param>
        /// <param name="ACorporateExchangeTableRef">Corporate exchange rate table.  A reference to this table is REQUIRED when importing - optional otherwise</param>
        /// <param name="ABaseCurrency">Ledger base currency.  Required when importing</param>
        /// <param name="AIntlCurrency">Ledger international currency.  Required when importing</param>
        /// <returns>True if the validation found no data validation errors, otherwise false.</returns>
        public static bool ValidateGLJournalManual(object AContext, AJournalRow ARow,
                                                   ref TVerificationResultCollection AVerificationResultCollection,
                                                   GLSetupTDS AGLSetupDSRef         = null,
                                                   ACurrencyTable ACurrencyTableRef = null,
                                                   ACorporateExchangeRateTable ACorporateExchangeTableRef = null,
                                                   String ABaseCurrency = null,
                                                   String AIntlCurrency = null)
        {
            DataColumn ValidationColumn;
            TScreenVerificationResult VerificationResult;
            string ValidationContext;
            int    VerifResultCollAddedCount = 0;

            // Don't validate deleted or posted DataRows
            if ((ARow.RowState == DataRowState.Deleted) || (ARow.JournalStatus == MFinanceConstants.BATCH_POSTED))
            {
                return(true);
            }

            bool isImporting = AContext.ToString().Contains("Importing");

            // 'Exchange Rate' must be greater than 0
            ValidationColumn  = ARow.Table.Columns[AJournalTable.ColumnExchangeRateToBaseId];
            ValidationContext = ARow.JournalNumber.ToString() + " of Batch Number: " + ARow.BatchNumber.ToString();

            if (true)
            {
                VerificationResult = (TScreenVerificationResult)TNumericalChecks.IsPositiveDecimal(ARow.ExchangeRateToBase,
                                                                                                   String.Empty + (isImporting ? String.Empty : " of Journal Number: " + ValidationContext.ToString()),
                                                                                                   AContext, ValidationColumn);

                // Handle addition/removal to/from TVerificationResultCollection
                if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult))
                {
                    VerifResultCollAddedCount++;
                }

                // Exchange rate must be 1.00 if the currency is the base ledger currency
                if ((ABaseCurrency != null) &&
                    (!ARow.IsExchangeRateToBaseNull()) &&
                    (ARow.TransactionCurrency == ABaseCurrency) &&
                    (ARow.ExchangeRateToBase != 1.00m))
                {
                    if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext,
                                                                              new TVerificationResult(ValidationContext,
                                                                                                      Catalog.GetString("A journal in the ledger base currency must have exchange rate of 1.00."),
                                                                                                      TResultSeverity.Resv_Critical)))
                    {
                        VerifResultCollAddedCount++;
                    }
                }
            }

            // Transaction currency must be valid
            bool isValidTransactionCurrency = true;

            if (isImporting && (ACurrencyTableRef != null))
            {
                ValidationColumn = ARow.Table.Columns[AJournalTable.ColumnTransactionCurrencyId];

                if (true)
                {
                    ACurrencyRow foundRow = (ACurrencyRow)ACurrencyTableRef.Rows.Find(ARow.TransactionCurrency);
                    isValidTransactionCurrency = (foundRow != null);

                    if ((foundRow == null) &&
                        AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                            AContext,
                            new TVerificationResult(ValidationContext,
                                                    String.Format(Catalog.GetString("'{0}' is not a valid currency."), ARow.TransactionCurrency),
                                                    TResultSeverity.Resv_Critical)))
                    {
                        VerifResultCollAddedCount++;
                    }
                }
            }

            if ((ACorporateExchangeTableRef != null) && isValidTransactionCurrency && (ABaseCurrency != null) && (AIntlCurrency != null) &&
                !ARow.IsDateEffectiveNull() && (ABaseCurrency != AIntlCurrency))
            {
                // For ledgers where the base currency and intl currency differ there must be a corporate exchange rate to the international currency
                ValidationColumn  = ARow.Table.Columns[AJournalTable.ColumnTransactionCurrencyId];
                ValidationContext = ARow.JournalNumber.ToString() + " of Batch Number: " + ARow.BatchNumber.ToString();

                if (true)
                {
                    DateTime firstOfMonth;

                    if (TSharedFinanceValidationHelper.GetFirstDayOfAccountingPeriod(ARow.LedgerNumber,
                                                                                     ARow.DateEffective, out firstOfMonth))
                    {
                        ACorporateExchangeRateRow foundRow = (ACorporateExchangeRateRow)ACorporateExchangeTableRef.Rows.Find(
                            new object[] { ABaseCurrency, AIntlCurrency, firstOfMonth });

                        if ((foundRow == null) &&
                            AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                AContext,
                                new TVerificationResult(ValidationContext,
                                                        String.Format(Catalog.GetString(
                                                                          "There is no Corporate Exchange Rate defined for '{0}' to '{1}' for the month starting on '{2}'."),
                                                                      ABaseCurrency, AIntlCurrency,
                                                                      StringHelper.DateToLocalizedString(firstOfMonth)),
                                                        TResultSeverity.Resv_Noncritical)))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }
                }
            }

            // Sub-system code must exist in the transaction type table
            if (isImporting && (AGLSetupDSRef.ATransactionType != null))
            {
                ValidationColumn = ARow.Table.Columns[AJournalTable.ColumnSubSystemCodeId];

                if (true)
                {
                    ATransactionTypeRow foundRow = (ATransactionTypeRow)AGLSetupDSRef.ATransactionType.Rows.Find(
                        new object[] { ARow.LedgerNumber, ARow.SubSystemCode, ARow.TransactionTypeCode });

                    if ((foundRow == null) &&
                        AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                            AContext,
                            new TVerificationResult(ValidationContext,
                                                    String.Format(Catalog.GetString(
                                                                      "The combination of Transaction Type of '{0}' and Sub-system Code of '{1}' is not valid for journals in Ledger {2}."),
                                                                  ARow.TransactionTypeCode, ARow.SubSystemCode, ARow.LedgerNumber),
                                                    TResultSeverity.Resv_Critical)))
                    {
                        VerifResultCollAddedCount++;
                    }
                }
            }

            // Journal description must not be null
            if (isImporting)
            {
                ValidationColumn = ARow.Table.Columns[AJournalTable.ColumnJournalDescriptionId];

                if (true)
                {
                    if ((ARow.JournalDescription == null) || (ARow.JournalDescription.Length == 0))
                    {
                        if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                AContext,
                                new TVerificationResult(ValidationContext,
                                                        Catalog.GetString("The journal description must not be empty."),
                                                        TResultSeverity.Resv_Critical)))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }
                }
            }

            return(VerifResultCollAddedCount == 0);
        }
コード例 #39
0
ファイル: GL.Importing.cs プロジェクト: Davincier/openpetra
        } // Import GL Transactions

        private void ImportGLTransactionsInner(Int32 ALedgerNumber,
            Int32 ARowNumber,
            ref GLBatchTDS AMainDS,
            ref GLSetupTDS ASetupDS,
            ref ABatchRow ANewBatchRow,
            ref AJournalRow ANewJournalRow,
            decimal AIntlRateFromBase,
            ref TDBTransaction ATransaction,
            ref string AImportMessage,
            ref TVerificationResultCollection AMessages,
            ref TValidationControlsDict AValidationControlsDictTransaction)
        {
            AImportMessage = Catalog.GetString("Parsing a transaction line.");
            string strIgnoreAnalysisTypeAndValue = Catalog.GetString(" The analysis type/value pair will be ignored.");

            GLBatchTDSATransactionRow NewTransaction = AMainDS.ATransaction.NewRowTyped(true);

            NewTransaction.LedgerNumber = ANewJournalRow.LedgerNumber;
            NewTransaction.BatchNumber = ANewJournalRow.BatchNumber;
            NewTransaction.JournalNumber = ANewJournalRow.JournalNumber;
            NewTransaction.TransactionNumber = ++ANewJournalRow.LastTransactionNumber;

            AMainDS.ATransaction.Rows.Add(NewTransaction);

            int preParseMessageCount = AMessages.Count;
            int nonCriticalErrorCount = 0;

            string costCentreCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Cost centre"),
                AMainDS.ATransaction.ColumnCostCentreCode, ARowNumber, AMessages, AValidationControlsDictTransaction).ToUpper();

            string accountCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Account code"),
                AMainDS.ATransaction.ColumnAccountCode, ARowNumber, AMessages, AValidationControlsDictTransaction).ToUpper();

            // This might add a non-critical error
            int msgCount = AMessages.Count;
            TCommonImport.FixAccountCodes(ALedgerNumber, ARowNumber, ref accountCode, ASetupDS.AAccount,
                ref costCentreCode, ASetupDS.ACostCentre, AMessages);
            nonCriticalErrorCount = AMessages.Count - msgCount;

            NewTransaction.CostCentreCode = costCentreCode;
            NewTransaction.AccountCode = accountCode;

            NewTransaction.Narrative = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Narrative"),
                AMainDS.ATransaction.ColumnNarrative, ARowNumber, AMessages, AValidationControlsDictTransaction);

            NewTransaction.Reference = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Reference"),
                AMainDS.ATransaction.ColumnReference, ARowNumber, AMessages, AValidationControlsDictTransaction);

            DateTime TransactionDate = TCommonImport.ImportDate(ref FImportLine, FDelimiter, FCultureInfoDate, Catalog.GetString("Transaction date"),
                AMainDS.ATransaction.ColumnTransactionDate, ARowNumber, AMessages, AValidationControlsDictTransaction);

            decimal DebitAmount = TCommonImport.ImportDecimal(ref FImportLine, FDelimiter, FCultureInfoNumberFormat, Catalog.GetString("Debit amount"),
                AMainDS.ATransaction.ColumnTransactionAmount, ARowNumber, AMessages, AValidationControlsDictTransaction, "0");
            decimal CreditAmount =
                TCommonImport.ImportDecimal(ref FImportLine, FDelimiter, FCultureInfoNumberFormat, Catalog.GetString("Credit amount"),
                    AMainDS.ATransaction.ColumnTransactionAmount, ARowNumber, AMessages, AValidationControlsDictTransaction, "0");

            // The critical parsing is complete now
            bool hasParsingErrors = (AMessages.Count != (preParseMessageCount + nonCriticalErrorCount));

            for (int i = 0; i < 10; i++)
            {
                String analysisType = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Analysis Type") + "#" + i,
                    AMainDS.ATransAnalAttrib.ColumnAnalysisTypeCode, ARowNumber, AMessages, AValidationControlsDictTransaction).ToUpper();
                String analysisValue = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Analysis Value") + "#" + i,
                    AMainDS.ATransAnalAttrib.ColumnAnalysisAttributeValue, ARowNumber, AMessages, AValidationControlsDictTransaction);

                bool gotType = (analysisType != null) && (analysisType.Length > 0);
                bool gotValue = (analysisValue != null) && (analysisValue.Length > 0);

                if (gotType && !gotValue)
                {
                    // All analysis analysisType errors are non-critical
                    AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationWarningInLine, ARowNumber),
                            Catalog.GetString("Transaction analysis attributes must have an attribute value.") + strIgnoreAnalysisTypeAndValue,
                            TResultSeverity.Resv_Noncritical));
                }

                if (!hasParsingErrors)
                {
                    // The analysis data is only imported if all corresponding values are there:
                    // Errors are recorded on-the-fly but are marked as non-critical
                    if (gotType && gotValue)
                    {
                        DataRow atrow = ASetupDS.AAnalysisType.Rows.Find(new Object[] { NewTransaction.LedgerNumber, analysisType });
                        DataRow afrow = ASetupDS.AFreeformAnalysis.Rows.Find(new Object[] { NewTransaction.LedgerNumber, analysisType, analysisValue });
                        AAnalysisAttributeRow anrow = (AAnalysisAttributeRow)ASetupDS.AAnalysisAttribute.Rows.Find(
                            new Object[] { NewTransaction.LedgerNumber, analysisType, NewTransaction.AccountCode });

                        bool isActive = (anrow != null) && anrow.Active;

                        if ((atrow != null) && (afrow != null) && isActive)
                        {
                            ATransAnalAttribRow NewTransAnalAttrib = AMainDS.ATransAnalAttrib.NewRowTyped(true);
                            NewTransAnalAttrib.LedgerNumber = NewTransaction.LedgerNumber;
                            NewTransAnalAttrib.BatchNumber = NewTransaction.BatchNumber;
                            NewTransAnalAttrib.JournalNumber = NewTransaction.JournalNumber;
                            NewTransAnalAttrib.TransactionNumber = NewTransaction.TransactionNumber;
                            NewTransAnalAttrib.AnalysisTypeCode = analysisType;
                            NewTransAnalAttrib.AnalysisAttributeValue = analysisValue;
                            NewTransAnalAttrib.AccountCode = NewTransaction.AccountCode;
                            AMainDS.ATransAnalAttrib.Rows.Add(NewTransAnalAttrib);
                        }
                        else
                        {
                            // All analysis analysisType errors are non-critical
                            if (atrow == null)
                            {
                                AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationWarningInLine, ARowNumber),
                                        String.Format(Catalog.GetString("Unknown transaction analysis attribute '{0}'."),
                                            analysisType) + strIgnoreAnalysisTypeAndValue,
                                        TResultSeverity.Resv_Noncritical));
                            }
                            else if (afrow == null)
                            {
                                AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationWarningInLine, ARowNumber),
                                        String.Format(Catalog.GetString("Unknown transaction analysis value '{0}' for type '{1}'."),
                                            analysisValue, analysisType) + strIgnoreAnalysisTypeAndValue,
                                        TResultSeverity.Resv_Noncritical));
                            }
                            else if (!isActive)
                            {
                                if (anrow == null)
                                {
                                    AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationWarningInLine, ARowNumber),
                                            String.Format(Catalog.GetString(
                                                    "Transaction analysis type/value '{0}'/'{1}' is not associated with account '{2}'."),
                                                analysisType, analysisValue, NewTransaction.AccountCode) + strIgnoreAnalysisTypeAndValue,
                                            TResultSeverity.Resv_Noncritical));
                                }
                                else
                                {
                                    AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationWarningInLine, ARowNumber),
                                            String.Format(Catalog.GetString("Transaction analysis type/value '{0}'/'{1}' is no longer active."),
                                                analysisType, analysisValue) + strIgnoreAnalysisTypeAndValue,
                                            TResultSeverity.Resv_Noncritical));
                                }
                            }
                        }
                    }
                }
            }

            if (!hasParsingErrors)
            {
                NewTransaction.TransactionDate = TransactionDate;

                if ((DebitAmount == 0) && (CreditAmount == 0))
                {
                    AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationErrorInLine, ARowNumber),
                            Catalog.GetString("Either the debit amount or the credit amount must be greater than 0."), TResultSeverity.Resv_Critical));
                }

                if ((DebitAmount < 0) || (CreditAmount < 0))
                {
                    AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationErrorInLine, ARowNumber),
                            Catalog.GetString("Negative amount specified - debits and credits must be positive."), TResultSeverity.Resv_Critical));
                }

                if ((DebitAmount != 0) && (CreditAmount != 0))
                {
                    AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationErrorInLine, ARowNumber),
                            Catalog.GetString("Transactions cannot have values for both debit and credit amounts."), TResultSeverity.Resv_Critical));
                }

                if (DebitAmount != 0)
                {
                    NewTransaction.DebitCreditIndicator = true;
                    NewTransaction.TransactionAmount = DebitAmount;
                }
                else
                {
                    NewTransaction.DebitCreditIndicator = false;
                    NewTransaction.TransactionAmount = CreditAmount;
                }

                NewTransaction.AmountInBaseCurrency = GLRoutines.Divide(NewTransaction.TransactionAmount, ANewJournalRow.ExchangeRateToBase);

                // If we know the international currency exchange rate we can set the value for the transaction amount
                if (AIntlRateFromBase > 0.0m)
                {
                    NewTransaction.AmountInIntlCurrency = GLRoutines.Divide(NewTransaction.AmountInBaseCurrency, AIntlRateFromBase, 2);
                }

                // Now we can start validation
                int messageCountBeforeValidate = AMessages.Count;

                // Do our standard gift batch validation checks on this row
                AImportMessage = Catalog.GetString("Validating the transaction data");
                ATransactionValidation.Validate(this, NewTransaction, ref AMessages, AValidationControlsDictTransaction);

                // And do the additional manual ones
                AImportMessage = Catalog.GetString("Additional validation of the transaction data");
                TSharedFinanceValidation_GL.ValidateGLDetailManual(this,
                    ANewBatchRow,
                    NewTransaction,
                    null,
                    ref AMessages,
                    AValidationControlsDictTransaction,
                    ASetupDS.ACostCentre,
                    ASetupDS.AAccount);

                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 (NewTransaction.TransactionAmount <= 0.0m)
                {
                    // We will have a validation message that will duplicate one we already have and may not really make sense in the context
                    //  of separate credit and debit amounts
                    for (int i = messageCountBeforeValidate; i < AMessages.Count; i++)
                    {
                        TVerificationResult msg = (TVerificationResult)AMessages[i];

                        if (msg.ResultText.Contains(Catalog.GetString("Debit amount")) || msg.ResultText.Contains(Catalog.GetString("Credit amount")))
                        {
                            AMessages.RemoveAt(i);
                            break;
                        }
                    }
                }
            }
        }
コード例 #40
0
        /// <summary>
        /// Need to ensure that the Analysis Attributes grid has all the entries
        /// that are required for the selected account.
        /// There may or may not already be attribute assignments for this transaction.
        /// </summary>
        /// <param name="AGLBatchDS"></param>
        /// <param name="AGLSetupDS">Can be null.  If supplied the code will use this data set to work out the required analysis attributes
        /// without a need to make a server call.  If not supplied the code will make a separate server call for each transaction row.  This may take several seconds.</param>
        /// <param name="ATransactionNumbers"></param>
        public void ReconcileTransAnalysisAttributes(GLBatchTDS AGLBatchDS, GLSetupTDS AGLSetupDS, out string ATransactionNumbers)
        {
            #region Validate Arguments

            if (AGLBatchDS == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString("Function:{0} - The GL Batch dataset is null!"),
                        Utilities.GetMethodName(true)));
            }
            else if (AGLSetupDS == null)
            {
                AGLSetupDS = (GLSetupTDS)TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, false);
            }
            else if ((AGLSetupDS.AAnalysisAttribute == null) || (AGLSetupDS.AAnalysisAttribute.Count == 0))
            {
                AGLSetupDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, false));
            }

            #endregion Validate Arguments

            ATransactionNumbers = string.Empty;

            foreach (DataRowView drv in AGLBatchDS.ATransaction.DefaultView)
            {
                ATransactionRow tr = (ATransactionRow)drv.Row;

                if (TransAnalAttrRequiredUpdating(AGLBatchDS, AGLSetupDS, tr.AccountCode, tr.TransactionNumber))
                {
                    ATransactionNumbers += tr.TransactionNumber.ToString() + ", ";
                }
            }
        }
コード例 #41
0
        /// <summary>
        /// Posts a batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The data row corresponding to the batch to post</param>
        /// <param name="AEffectiveDate">The effective date for the batch</param>
        /// <param name="AStartDateCurrentPeriod">The earliest postable date</param>
        /// <param name="AEndDateLastForwardingPeriod">The latest postable date</param>
        /// <param name="AInactiveValuesWarningOnGLPosting">Warn of inactive values</param>
        /// <returns>
        /// True if the batch was successfully posted
        /// </returns>
        public bool PostBatch(ABatchRow ACurrentBatchRow,
                              DateTime AEffectiveDate,
                              DateTime AStartDateCurrentPeriod,
                              DateTime AEndDateLastForwardingPeriod,
                              bool AInactiveValuesWarningOnGLPosting = true)
        {
            bool RetVal = false;

            if (!SaveBatchForPosting())
            {
                return(RetVal);
            }

            //Load all Batch data
            FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAndContent(FLedgerNumber, ACurrentBatchRow.BatchNumber));

            if (FCacheDS == null)
            {
                FCacheDS = TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, false);
            }

            if (FAccountTable == null)
            {
                SetAccountCostCentreTableVariables();
            }

            //Check for inactive values
            int NumInactiveValues = 0;

            if (AInactiveValuesWarningOnGLPosting && !AllowInactiveFieldValues(ACurrentBatchRow.BatchNumber, out NumInactiveValues))
            {
                return(RetVal);
            }

            bool PostWithInactiveValues = (NumInactiveValues > 0);


            // TODO: display progress of posting
            TVerificationResultCollection Verifications;

            int CurrentBatchNumber = ACurrentBatchRow.BatchNumber;

            if ((AEffectiveDate.Date < AStartDateCurrentPeriod) || (AEffectiveDate.Date > AEndDateLastForwardingPeriod))
            {
                MessageBox.Show(String.Format(Catalog.GetString(
                                                  "The Date Effective is outside the periods available for posting. Enter a date between {0:d} and {1:d}."),
                                              AStartDateCurrentPeriod,
                                              AEndDateLastForwardingPeriod));

                return(RetVal);
            }

            // check that a corportate exchange rate exists
            FMyForm.WarnAboutMissingIntlExchangeRate = true;

            if (FMyForm.GetInternationalCurrencyExchangeRate() == 0)
            {
                return(false);
            }

            if (PostWithInactiveValues ||
                (MessageBox.Show(String.Format(Catalog.GetString("Are you sure you want to post GL batch {0}?"),
                                               CurrentBatchNumber),
                                 Catalog.GetString("Question"),
                                 MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes))
            {
                try
                {
                    Cursor.Current = Cursors.WaitCursor;

                    if (!TRemote.MFinance.GL.WebConnectors.PostGLBatch(FLedgerNumber, CurrentBatchNumber, out Verifications))
                    {
                        string ErrorMessages = String.Empty;

                        foreach (TVerificationResult verif in Verifications)
                        {
                            ErrorMessages += "[" + verif.ResultContext + "] " +
                                             verif.ResultTextCaption + ": " +
                                             verif.ResultText + Environment.NewLine;
                        }

                        System.Windows.Forms.MessageBox.Show(ErrorMessages, Catalog.GetString("Posting failed"),
                                                             MessageBoxButtons.OK,
                                                             MessageBoxIcon.Error);
                    }
                    else
                    {
                        //I don't need to call this directly, because the server calls it:
                        //TFrmGLBatch.PrintPostingRegister(FLedgerNumber, CurrentBatchNumber);

                        // TODO: print reports on successfully posted batch
                        MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"),
                                        Catalog.GetString("Success"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);

                        // refresh the grid, to reflect that the batch has been posted
                        FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAndContent(FLedgerNumber, CurrentBatchNumber));

                        // make sure that the current dataset is clean,
                        // otherwise the next save would try to modify the posted batch, even though no values have been changed
                        FMainDS.AcceptChanges();

                        // Ensure these tabs will ask the server for updates
                        FMyForm.GetJournalsControl().ClearCurrentSelection();
                        FMyForm.GetTransactionsControl().ClearCurrentSelection();

                        FMyUserControl.UpdateDisplay();

                        RetVal = true;
                    }
                }
                catch (Exception ex)
                {
                    string msg = (String.Format(Catalog.GetString("Unexpected error occurred during the posting of GL Batch {0}!{1}{1}{2}{1}{1}{3}"),
                                                CurrentBatchNumber,
                                                Environment.NewLine,
                                                ex.Message,
                                                ex.InnerException != null?ex.InnerException.Message:String.Empty));

                    TLogging.LogException(ex, Utilities.GetMethodSignature());
                    MessageBox.Show(msg, "Post GL Batch Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }

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

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

            #endregion Validate Arguments

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

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

                    #region Validate Data

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

                    #endregion Validate Data

                    ABatchRow batchRow = (ABatchRow)batchRows[0];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return true;
        }
コード例 #43
0
        /// <summary>
        /// load the batches into the grid
        /// </summary>
        /// <param name="ALedgerNumber"></param>
        public void LoadBatches(Int32 ALedgerNumber)
        {
            //FBatchesLoaded = false;
            InitialiseControls();

            FLedgerNumber = ALedgerNumber;

            if ((FPetraUtilsObject == null) || FPetraUtilsObject.SuppressChangeDetection)
            {
                return;
            }

            FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadARecurringBatch(FLedgerNumber, TFinanceBatchFilterEnum.fbfAll));

            if (FCacheDS == null)
            {
                FCacheDS = TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, false);
            }

            btnNew.Enabled = true;

            FPreviouslySelectedDetailRow = null;
            grdDetails.DataSource = new DevAge.ComponentModel.BoundDataView(FMainDS.ARecurringBatch.DefaultView);

            if (grdDetails.Rows.Count > 1)
            {
                SelectRowInGrid(1);
                ((TFrmRecurringGLBatch) this.ParentForm).EnableJournals();
                AutoEnableTransTabForBatch();
            }
            else
            {
                ClearControls();
                ((TFrmRecurringGLBatch) this.ParentForm).DisableJournals();
                ((TFrmRecurringGLBatch) this.ParentForm).DisableTransactions();
            }

            //Load all analysis attribute values
            ShowData();

            UpdateChangeableStatus();
            UpdateRecordNumberDisplay();
            SetAccountCostCentreTableVariables();

            //FBatchesLoaded = true;
        }
コード例 #44
0
 void CheckFCacheInitialised()
 {
     if ((FCacheDS == null) && (FLedgerNumber >= 0))
     {
         FCacheDS = TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, FActiveOnly);
     }
 }
コード例 #45
0
        /// <summary>
        /// load the transactions into the grid
        /// </summary>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ABatchNumber"></param>
        /// <param name="AJournalNumber"></param>
        /// <param name="ACurrencyCode"></param>
        /// <param name="AFromBatchTab"></param>
        /// <param name="ABatchStatus"></param>
        /// <param name="AJournalStatus"></param>
        /// <returns>True if new GL transactions were loaded, false if transactions had been loaded already.</returns>
        public bool LoadTransactions(Int32 ALedgerNumber,
            Int32 ABatchNumber,
            Int32 AJournalNumber,
            string ACurrencyCode,
            bool AFromBatchTab = false,
            string ABatchStatus = MFinanceConstants.BATCH_UNPOSTED,
            string AJournalStatus = MFinanceConstants.BATCH_UNPOSTED)
        {
            TFrmStatusDialog dlgStatus = null;
            bool DifferentBatchSelected = false;

            FLoadCompleted = false;

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

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

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

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

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

            if (FirstRun)
            {
                FLedgerNumber = ALedgerNumber;
            }

            if (BatchChanged)
            {
                FBatchNumber = ABatchNumber;
            }

            if (BatchStatusChanged)
            {
                FBatchStatus = ABatchStatus;
            }

            if (JournalChanged)
            {
                FJournalNumber = AJournalNumber;
            }

            if (JournalStatusChanged)
            {
                FJournalStatus = AJournalStatus;
            }

            if (CurrencyChanged)
            {
                FTransactionCurrency = ACurrencyCode;
            }

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

            if (FirstRun)
            {
                InitialiseControls();
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;

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

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

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

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

                    FLoadCompleted = true;

                    return false;
                }

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

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

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

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

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

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

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

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

                FContainsSystemGenerated = false;

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

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

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

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

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

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

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

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

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

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

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

                    SetupExtraGridFunctionality();

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

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

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

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

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

                UpdateRecordNumberDisplay();
                FFilterAndFindObject.SetRecordNumberDisplayProperties();

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

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

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

                        FPetraUtilsObject.SetChangedFlag();
                    }
                }

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

                this.Cursor = Cursors.Default;
            }

            return DifferentBatchSelected;
        }
コード例 #46
0
        /// <summary>
        /// Stores the manual code.
        /// </summary>
        /// <param name="ASubmitDS">a submit ds.</param>
        /// <param name="AVerificationResult">a verification result.</param>
        /// <returns></returns>
        private TSubmitChangesResult StoreManualCode(ref GLSetupTDS ASubmitDS, out TVerificationResultCollection AVerificationResult)
        {
            //
            // I need to remove any AnalysisAttribute records that are still set to "Unassigned"
            //
            if ((ASubmitDS.AAnalysisAttribute != null) && (ASubmitDS.AAnalysisAttribute.Rows.Count > 0))
            {
                for (int Idx = ASubmitDS.AAnalysisAttribute.Rows.Count - 1; Idx >= 0; Idx--)
                {
                    AAnalysisAttributeRow Row = ASubmitDS.AAnalysisAttribute[Idx];

                    if ((Row.RowState != DataRowState.Deleted) && (Row.AnalysisTypeCode.IndexOf("Unassigned") == 0))
                    {
                        Row.Delete();
                    }
                }
            }

            //
            // I'll take this opportunity to remove any similar records in my own TDS
            //
            for (int Idx = FMainDS.AAnalysisAttribute.Rows.Count - 1; Idx >= 0; Idx--)
            {
                AAnalysisAttributeRow Row = FMainDS.AAnalysisAttribute[Idx];

                if ((Row.RowState != DataRowState.Deleted) && (Row.AnalysisTypeCode.IndexOf("Unassigned") == 0))
                {
                    Row.Delete();
                }
            }

            ucoAccountsTree.MarkAllNodesCommitted();
            TSubmitChangesResult ServerResult =
                TRemote.MFinance.Setup.WebConnectors.SaveGLSetupTDS(FLedgerNumber, ref ASubmitDS, out AVerificationResult);
            TDataCache.TMFinance.RefreshCacheableFinanceTable(Shared.TCacheableFinanceTablesEnum.AccountList, FLedgerNumber);

            if (ServerResult == TSubmitChangesResult.scrOK)
            {
                if ((FZeroForeignCurrencyBalances != null) && (FZeroForeignCurrencyBalances.Count > 0))
                {
                    Int32 Year = (Int32)TDataCache.TMFinance.GetCacheableFinanceTable(
                        TCacheableFinanceTablesEnum.LedgerDetails, FLedgerNumber).Rows[0][ALedgerTable.GetCurrentFinancialYearDBName()];

                    // Makes all foreign currency balances zero for the given accounts in the current ledger year for all posting cost centres
                    TRemote.MFinance.Setup.WebConnectors.ZeroForeignCurrencyBalances(FLedgerNumber, Year, FZeroForeignCurrencyBalances.ToArray());
                    FZeroForeignCurrencyBalances.Clear();
                }

                // Broadcast message to update partner's Partner Edit screen if open
                TFormsMessage BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcAccountsChanged);
                BroadcastMessage.SetMessageDataAccounts();
                TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);
            }

            return ServerResult;
        }
コード例 #47
0
ファイル: GL.Setup.cs プロジェクト: Davincier/openpetra
        public static GLSetupTDS LoadAccountHierarchies(Int32 ALedgerNumber)
        {
            #region Validate Arguments

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

            #endregion Validate Arguments

            GLSetupTDS MainDS = new GLSetupTDS();

            // create template for AGeneralLedgerMaster
            TCacheable CachePopulator = new TCacheable();

            System.Type TypeofTable = null;

            TDBTransaction Transaction = null;

            try
            {
                ALedgerTable ledger = (ALedgerTable)CachePopulator.GetCacheableTable(TCacheableFinanceTablesEnum.LedgerDetails,
                    "",
                    false,
                    ALedgerNumber,
                    out TypeofTable);

                #region Validate Data

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

                #endregion Validate Data

                int year = ledger[0].CurrentFinancialYear;
                string costCentreCode = "[" + ALedgerNumber + "]";

                AGeneralLedgerMasterRow template = new AGeneralLedgerMasterTable().NewRowTyped(false);
                template.LedgerNumber = ALedgerNumber;
                template.Year = year;
                template.CostCentreCode = costCentreCode;

                DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                    TEnforceIsolationLevel.eilMinimum,
                    ref Transaction,
                    delegate
                    {
                        ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction);
                        ACurrencyAccess.LoadAll(MainDS, Transaction);
                        AAccountHierarchyAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                        AAccountHierarchyDetailAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                        AAccountAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                        AAccountPropertyAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                        AAnalysisTypeAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                        AAnalysisAttributeAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                        AFreeformAnalysisAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                        AFeesReceivableAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                        AFeesPayableAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                        AGeneralLedgerMasterAccess.LoadUsingTemplate(MainDS, template, Transaction);
                        ASuspenseAccountAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                    });

                // set Account BankAccountFlag if there exists a property
                foreach (AAccountPropertyRow accProp in MainDS.AAccountProperty.Rows)
                {
                    if ((accProp.PropertyCode == MFinanceConstants.ACCOUNT_PROPERTY_BANK_ACCOUNT) && (accProp.PropertyValue == "true"))
                    {
                        MainDS.AAccount.DefaultView.RowFilter = String.Format("{0}='{1}'",
                            AAccountTable.GetAccountCodeDBName(),
                            accProp.AccountCode);
                        GLSetupTDSAAccountRow acc = (GLSetupTDSAAccountRow)MainDS.AAccount.DefaultView[0].Row;
                        acc.BankAccountFlag = true;
                        MainDS.AAccount.DefaultView.RowFilter = "";
                    }
                }

                // set Account SuspenseAccountFlag if there exists a property
                foreach (ASuspenseAccountRow suspenseAccountRow in MainDS.ASuspenseAccount.Rows)
                {
                    GLSetupTDSAAccountRow AccountRow =
                        (GLSetupTDSAAccountRow)MainDS.AAccount.Rows.Find(new object[] { ALedgerNumber, suspenseAccountRow.SuspenseAccountCode });
                    AccountRow.SuspenseAccountFlag = true;
                }

                // Don't include any AnalysisType for which there are no values set
                MainDS.AFreeformAnalysis.DefaultView.Sort = AFreeformAnalysisTable.GetAnalysisTypeCodeDBName(); // "a_analysis_type_code_c";

                foreach (AAnalysisTypeRow typeRow in MainDS.AAnalysisType.Rows)
                {
                    Int32 Idx = MainDS.AFreeformAnalysis.DefaultView.Find(typeRow.AnalysisTypeCode);

                    if (Idx < 0)
                    {
                        typeRow.Delete();
                    }
                }

                // add the YTD Actuals to each account
                foreach (AGeneralLedgerMasterRow generalLedgerMasterRow in MainDS.AGeneralLedgerMaster.Rows)
                {
                    GLSetupTDSAAccountRow AccountRow =
                        (GLSetupTDSAAccountRow)MainDS.AAccount.Rows.Find(new object[] { ALedgerNumber, generalLedgerMasterRow.AccountCode });
                    AccountRow.YtdActualBase = generalLedgerMasterRow.YtdActualBase;

                    if (AccountRow.ForeignCurrencyFlag)
                    {
                        AccountRow.YtdActualForeign = generalLedgerMasterRow.YtdActualForeign;
                    }
                }

                // Accept row changes here so that the Client gets 'unmodified' rows
                MainDS.AcceptChanges();

                // Remove all Tables that were not filled with data before remoting them.
                MainDS.RemoveEmptyTables();
            }
            catch (Exception ex)
            {
                TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}",
                        Utilities.GetMethodSignature(),
                        Environment.NewLine,
                        ex.Message));
                throw ex;
            }

            return MainDS;
        }
コード例 #48
0
ファイル: GL.Importing.cs プロジェクト: Davincier/openpetra
        } // Import GL Batches

        /// <summary>
        /// Wrapper for importing GL Transactions. Called from client side
        /// </summary>
        /// <param name="ARequestParams"></param>
        /// <param name="AImportString"></param>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ABatchNumber"></param>
        /// <param name="AJournalNumber"></param>
        /// <param name="AMessages"></param>
        /// <returns></returns>
        public bool ImportGLTransactions(
            Hashtable ARequestParams,
            String AImportString,
            Int32 ALedgerNumber,
            Int32 ABatchNumber,
            Int32 AJournalNumber,
            out TVerificationResultCollection AMessages)
        {
            string ImportMessage = Catalog.GetString("Initialising");

            TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(),
                Catalog.GetString("Importing GL Batches"),
                100);

            TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                Catalog.GetString("Initialising"),
                5);

            TVerificationResultCollection Messages = new TVerificationResultCollection();

            // fix for Mono issue with out parameter: https://bugzilla.xamarin.com/show_bug.cgi?id=28196
            AMessages = Messages;

            GLSetupTDS SetupDS = new GLSetupTDS();
            SetupDS.CaseSensitive = true;
            StringReader sr = new StringReader(AImportString);

            FDelimiter = (String)ARequestParams["Delimiter"];
            Int32 LedgerNumber = (Int32)ARequestParams["ALedgerNumber"];
            FDateFormatString = (String)ARequestParams["DateFormatString"];
            String NumberFormat = (String)ARequestParams["NumberFormat"];
            FNewLine = (String)ARequestParams["NewLine"];

            FCultureInfoNumberFormat = new CultureInfo(NumberFormat.Equals("American") ? "en-US" : "de-DE");
            FCultureInfoDate = new CultureInfo("en-GB");
            FCultureInfoDate.DateTimeFormat.ShortDatePattern = FDateFormatString;

            TDBTransaction Transaction = null;
            Int32 RowNumber = 0;
            Int32 InitialTextLength = AImportString.Length;
            Int32 TextProcessedLength = 0;
            Int32 PercentDone = 10;
            Int32 PreviousPercentDone = 0;
            bool submissionOK = false;
            Boolean CancelledByUser = false;

            // Create some validation dictionaries
            TValidationControlsDict ValidationControlsDictTransaction = new TValidationControlsDict();

            try
            {
                // This needs to be initialised because we will be calling the method
                TSharedFinanceValidationHelper.GetValidPostingDateRangeDelegate = @TFinanceServerLookups.GetCurrentPostingRangeDates;
                TSharedFinanceValidationHelper.GetValidPeriodDatesDelegate = @TAccountingPeriodsWebConnector.GetPeriodDates;

                DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref submissionOK,
                    delegate
                    {
                        // Construct our DataSet - we use all the journals for the batch so we can update the batch totals.
                        GLBatchTDS MainDS = new GLBatchTDS();
                        ABatchTable BatchTable = ABatchAccess.LoadByPrimaryKey(ALedgerNumber, ABatchNumber, Transaction);
                        MainDS.ABatch.Merge(BatchTable);
                        AJournalTable JournalTable = AJournalAccess.LoadViaABatch(ALedgerNumber, ABatchNumber, Transaction);
                        MainDS.AJournal.Merge(JournalTable);
                        ATransactionTable TransactionTable = ATransactionAccess.LoadViaABatch(ALedgerNumber, ABatchNumber, Transaction);
                        MainDS.ATransaction.Merge(TransactionTable);
                        ATransAnalAttribTable TransAnalAttributeTable = ATransAnalAttribAccess.LoadViaAJournal(ALedgerNumber,
                            ABatchNumber,
                            AJournalNumber,
                            Transaction);
                        MainDS.ATransAnalAttrib.Merge(TransAnalAttributeTable);
                        MainDS.AcceptChanges();

                        ABatchRow NewBatchRow = (ABatchRow)MainDS.ABatch.Rows.Find(new object[] { ALedgerNumber, ABatchNumber });
                        AJournalRow NewJournalRow = (AJournalRow)MainDS.AJournal.Rows.Find(new object[] { ALedgerNumber, ABatchNumber, AJournalNumber });

                        // Load supplementary tables that we are going to need for validation
                        ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);
                        AAnalysisTypeAccess.LoadViaALedger(SetupDS, LedgerNumber, Transaction);
                        AFreeformAnalysisAccess.LoadViaALedger(SetupDS, LedgerNumber, Transaction);
                        AAnalysisAttributeAccess.LoadViaALedger(SetupDS, LedgerNumber, Transaction);
                        ACostCentreAccess.LoadViaALedger(SetupDS, LedgerNumber, Transaction);
                        AAccountAccess.LoadViaALedger(SetupDS, LedgerNumber, Transaction);
                        ALedgerInitFlagAccess.LoadViaALedger(SetupDS, LedgerNumber, Transaction);

                        DateTime firstDayOfMonth;
                        decimal intlRateFromBase = -1.0m;

                        if (LedgerTable.Rows.Count > 0)
                        {
                            string intlCurrency = LedgerTable[0].IntlCurrency;
                            string baseCurrency = LedgerTable[0].BaseCurrency;

                            if (TSharedFinanceValidationHelper.GetFirstDayOfAccountingPeriod(LedgerNumber, NewJournalRow.DateEffective,
                                    out firstDayOfMonth))
                            {
                                intlRateFromBase =
                                    TExchangeRateTools.GetCorporateExchangeRate(baseCurrency, intlCurrency, firstDayOfMonth,
                                        NewJournalRow.DateEffective);
                            }

                            if (intlRateFromBase <= 0.0m)
                            {
                                Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, 1),
                                        String.Format(
                                            "There is no Corporate Exchange Rate for {0} to {1} applicable to the period {2} to {3}.  Please set up an appropriate rate and then import the data again.",
                                            baseCurrency,
                                            intlCurrency,
                                            StringHelper.DateToLocalizedString(firstDayOfMonth),
                                            StringHelper.DateToLocalizedString(NewJournalRow.DateEffective)),
                                        TResultSeverity.Resv_Critical));
                            }
                        }

                        ImportMessage = Catalog.GetString("Parsing first line");

                        // Go round a loop reading the file line by line
                        FImportLine = sr.ReadLine();

                        while (FImportLine != null)
                        {
                            RowNumber++;

                            TextProcessedLength += (FImportLine.Length + FNewLine.Length);
                            PercentDone = 10 + ((TextProcessedLength * 90) / InitialTextLength);

                            // skip empty lines and commented lines
                            if ((FImportLine.Trim().Length > 0) && !FImportLine.StartsWith("/*") && !FImportLine.StartsWith("#"))
                            {
                                int numberOfElements = StringHelper.GetCSVList(FImportLine, FDelimiter).Count + 1;

                                if (numberOfElements < 8)
                                {
                                    Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, RowNumber),
                                            Catalog.GetString("Wrong number of transaction columns.  Expected at least 8 columns."),
                                            TResultSeverity.Resv_Critical));

                                    FImportLine = sr.ReadLine();

                                    if (FImportLine != null)
                                    {
                                        TextProcessedLength += (FImportLine.Length + FNewLine.Length);
                                    }

                                    continue;
                                }

                                ImportGLTransactionsInner(LedgerNumber, RowNumber, ref MainDS, ref SetupDS, ref NewBatchRow, ref NewJournalRow,
                                    intlRateFromBase, ref Transaction, ref ImportMessage, ref Messages,
                                    ref ValidationControlsDictTransaction);
                            }  // if the CSV line qualifies

                            if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                            {
                                CancelledByUser = true;
                                break;
                            }

                            if (Messages.Count > 100)
                            {
                                // This probably means that it is a big file and the user has made the same mistake many times over
                                break;
                            }

                            // Update progress tracker every few percent
                            if ((PercentDone - PreviousPercentDone) > 3)
                            {
                                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                    String.Format(Catalog.GetString("Importing row {0}"), RowNumber),
                                    (PercentDone > 98) ? 98 : PercentDone);
                                PreviousPercentDone = PercentDone;
                            }

                            // Read the next line
                            FImportLine = sr.ReadLine();

                            if (FImportLine != null)
                            {
                                TextProcessedLength += (FImportLine.Length + FNewLine.Length);
                            }
                        }  // while CSV lines

                        if (CancelledByUser)
                        {
                            Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation,
                                    String.Format(Catalog.GetString("{0} messages reported."), Messages.Count), TResultSeverity.Resv_Info));
                            Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation,
                                    "The import was cancelled by the user.", TResultSeverity.Resv_Info));
                            return;
                        }

                        // Finished reading the file - did we have critical errors?
                        if (!TVerificationHelper.IsNullOrOnlyNonCritical(Messages))
                        {
                            TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                Catalog.GetString("Batch has critical errors"),
                                0);

                            if (FImportLine == null)
                            {
                                // We did reach the end of the file
                                Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation,
                                        Catalog.GetString(
                                            "Reached the end of file but errors occurred. When these errors are fixed the batch will import successfully."),
                                        TResultSeverity.Resv_Info));
                            }
                            else
                            {
                                // We gave up before the end
                                Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation,
                                        Catalog.GetString(
                                            "Stopped reading the file after generating more than 100 messages.  The file may contian more errors beyond the ones listed here."),
                                        TResultSeverity.Resv_Info));
                            }

                            // Do finally actions and then return false
                            return;
                        }

                        // Everything is ok, so we can do our finish actions


                        //Finally submit all our changes
                        ImportMessage = Catalog.GetString("Saving transactions");
                        ATransactionAccess.SubmitChanges(MainDS.ATransaction, Transaction);
                        MainDS.ATransaction.AcceptChanges();

                        ImportMessage = Catalog.GetString("Saving analysis attributes");
                        ATransAnalAttribAccess.SubmitChanges(MainDS.ATransAnalAttrib, Transaction);
                        MainDS.ATransAnalAttrib.AcceptChanges();

                        // update the totals of the batch that has just been imported
                        ImportMessage = Catalog.GetString("Saving changes to totals");
                        GLRoutines.UpdateBatchTotals(ref MainDS, ref NewBatchRow);

                        ImportMessage = Catalog.GetString("Saving journal totals");
                        AJournalAccess.SubmitChanges(MainDS.AJournal, Transaction);
                        MainDS.AJournal.AcceptChanges();

                        ImportMessage = Catalog.GetString("Saving batch totals");
                        ABatchAccess.SubmitChanges(MainDS.ABatch, Transaction);
                        MainDS.ABatch.AcceptChanges();

                        // Now we are done!!!
                        submissionOK = true;
                    }); // Begin Auto Transaction
            } // try
            catch (Exception ex)
            {
                // Parse the exception text for possible references to database foreign keys
                // Make the message more friendly in that case
                String friendlyExceptionText = MakeFriendlyFKExceptions(ex, "T");

                if (RowNumber > 0)
                {
                    // At least we made a start
                    string msg = ImportMessage;

                    if (friendlyExceptionText.Length > 0)
                    {
                        msg += FNewLine + friendlyExceptionText;
                    }

                    if (ImportMessage.StartsWith(Catalog.GetString("Saving ")))
                    {
                        // Do not display any specific line number because these errors occur outside the parsing loop
                        Messages.Add(new TVerificationResult(MCommonConstants.StrExceptionWhileSavingTransactions,
                                msg, TResultSeverity.Resv_Critical));
                    }
                    else
                    {
                        Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrExceptionWhileParsingLine, RowNumber),
                                msg, TResultSeverity.Resv_Critical));
                    }
                }
                else
                {
                    // We got an exception before we even started parsing the rows (getting a transaction?)
                    Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrExceptionWhileParsingLine, RowNumber),
                            friendlyExceptionText, TResultSeverity.Resv_Critical));
                }

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                    Catalog.GetString("Exception Occurred"),
                    0);
            }
            finally
            {
                sr.Close();

                if (submissionOK)
                {
                    TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                        Catalog.GetString("Gift batch import successful"),
                        100);
                }
                else
                {
                    Messages.Add(new TVerificationResult("Import information",
                            Catalog.GetString("None of the data from the import was saved."),
                            TResultSeverity.Resv_Critical));

                    TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                        Catalog.GetString("Data could not be saved."),
                        0);
                }

                TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
            } // end of 'finally'

            // Set our 'out' parameters
            AMessages = Messages;

            return submissionOK;
        } // Import GL Transactions
コード例 #49
0
ファイル: GL.Setup.cs プロジェクト: Davincier/openpetra
        public static GLSetupTDS LoadLedgerInfo(Int32 ALedgerNumber)
        {
            #region Validate Arguments

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

            #endregion Validate Arguments

            GLSetupTDS MainDS = new GLSetupTDS();

            TDBTransaction Transaction = null;

            try
            {
                DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                    TEnforceIsolationLevel.eilMinimum,
                    ref Transaction,
                    delegate
                    {
                        ALedgerAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction);
                        AAccountingSystemParameterAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, Transaction);
                        AAccountingPeriodAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
                    });

                #region Validate Data

                if ((MainDS.ALedger == null) || (MainDS.ALedger.Count == 0))
                {
                    throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString(
                                "Function:{0} Ledger data for Ledger number {1} does not exist or could not be accessed!"),
                            Utilities.GetMethodName(true),
                            ALedgerNumber));
                }
                else if ((MainDS.AAccountingSystemParameter == null) || (MainDS.AAccountingSystemParameter.Count == 0))
                {
                    throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString(
                                "Function:{0} - Accounting System Parameter data for Ledger number {1} does not exist or could not be accessed!"),
                            Utilities.GetMethodName(true),
                            ALedgerNumber));
                }
                else if ((MainDS.AAccountingPeriod == null) || (MainDS.AAccountingPeriod.Count == 0))
                {
                    throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString(
                                "Function:{0} - Accounting Period data for Ledger number {1} does not exist or could not be accessed!"),
                            Utilities.GetMethodName(true),
                            ALedgerNumber));
                }

                #endregion Validate Data

                // Accept row changes here so that the Client gets 'unmodified' rows
                MainDS.AcceptChanges();

                // Remove all Tables that were not filled with data before remoting them.
                MainDS.RemoveEmptyTables();
            }
            catch (Exception ex)
            {
                TLogging.Log(String.Format("Method:{0} - Unexpected error!{1}{1}{2}",
                        Utilities.GetMethodSignature(),
                        Environment.NewLine,
                        ex.Message));
                throw ex;
            }

            return MainDS;
        }
コード例 #50
0
ファイル: GL.Importing.cs プロジェクト: Davincier/openpetra
        /// <summary>
        /// Import GL Batches data
        /// The data file contents from the client is sent as a string, imported in the database
        /// and committed immediately
        /// </summary>
        /// <param name="ARequestParams">Hashtable containing the given params </param>
        /// <param name="AImportString">Big parts of the export file as a simple String</param>
        /// <param name="AMessages">Additional messages to display in a messagebox</param>
        /// <returns>false if error</returns>
        public bool ImportGLBatches(
            Hashtable ARequestParams,
            String AImportString,
            out TVerificationResultCollection AMessages
            )
        {
            TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(),
                Catalog.GetString("Importing GL Batches"),
                100);

            TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                Catalog.GetString("Initialising"),
                5);

            TVerificationResultCollection Messages = new TVerificationResultCollection();

            // fix for Mono issue with out parameter: https://bugzilla.xamarin.com/show_bug.cgi?id=28196
            AMessages = Messages;

            GLBatchTDS MainDS = new GLBatchTDS();
            GLSetupTDS SetupDS = new GLSetupTDS();
            SetupDS.CaseSensitive = true;
            StringReader sr = new StringReader(AImportString);

            // Parse the supplied parameters
            FDelimiter = (String)ARequestParams["Delimiter"];
            Int32 LedgerNumber = (Int32)ARequestParams["ALedgerNumber"];
            FDateFormatString = (String)ARequestParams["DateFormatString"];
            String NumberFormat = (String)ARequestParams["NumberFormat"];
            FNewLine = (String)ARequestParams["NewLine"];

            // Set culture from parameters
            FCultureInfoNumberFormat = new CultureInfo(NumberFormat.Equals("American") ? "en-US" : "de-DE");
            FCultureInfoDate = new CultureInfo("en-GB");
            FCultureInfoDate.DateTimeFormat.ShortDatePattern = FDateFormatString;

            // Initialise our working variables
            Int32 InitialTextLength = AImportString.Length;
            Int32 PercentDone = 10;
            Int32 PreviousPercentDone = 0;
            ABatchRow NewBatch = null;
            AJournalRow NewJournal = null;
            int BatchPeriodNumber = -1;
            int BatchYearNr = -1;
            String ImportMessage = "";
            Int32 RowNumber = 0;
            decimal intlRateFromBase = -1.0m;
            Boolean gotFirstBatch = false;
            Boolean CancelledByUser = false;

            // Create some validation dictionaries
            TValidationControlsDict ValidationControlsDictBatch = new TValidationControlsDict();
            TValidationControlsDict ValidationControlsDictJournal = new TValidationControlsDict();
            TValidationControlsDict ValidationControlsDictTransaction = new TValidationControlsDict();

            // This needs to be initialised because we will be calling the method
            TSharedFinanceValidationHelper.GetValidPostingDateRangeDelegate = @TFinanceServerLookups.GetCurrentPostingRangeDates;
            TSharedFinanceValidationHelper.GetValidPeriodDatesDelegate = @TAccountingPeriodsWebConnector.GetPeriodDates;

            // Get a new transaction
            TDBTransaction transaction = null;
            Boolean submissionOK = false;
            DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref transaction, ref submissionOK,
                delegate
                {
                    try
                    {
                        // Load supplementary tables that we are going to need for validation
                        ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(LedgerNumber, transaction);
                        ACurrencyTable CurrencyTable = ACurrencyAccess.LoadAll(transaction);

                        AAnalysisTypeAccess.LoadViaALedger(SetupDS, LedgerNumber, transaction);
                        AFreeformAnalysisAccess.LoadViaALedger(SetupDS, LedgerNumber, transaction);
                        AAnalysisAttributeAccess.LoadViaALedger(SetupDS, LedgerNumber, transaction);
                        ACostCentreAccess.LoadViaALedger(SetupDS, LedgerNumber, transaction);
                        AAccountAccess.LoadViaALedger(SetupDS, LedgerNumber, transaction);
                        ALedgerInitFlagAccess.LoadViaALedger(SetupDS, LedgerNumber, transaction);
                        ATransactionTypeAccess.LoadViaALedger(SetupDS, LedgerNumber, transaction);

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

                        string LedgerBaseCurrency = LedgerTable[0].BaseCurrency;
                        string LedgerIntlCurrency = LedgerTable[0].IntlCurrency;
                        ACorporateExchangeRateTable CorporateExchangeRateTable =
                            ACorporateExchangeRateAccess.LoadViaACurrencyToCurrencyCode(LedgerIntlCurrency,
                                transaction);
                        ADailyExchangeRateTable DailyExchangeRateTable = ADailyExchangeRateAccess.LoadAll(transaction);

                        // Go round a loop reading the file line by line
                        ImportMessage = Catalog.GetString("Parsing first line");
                        FImportLine = sr.ReadLine();

                        Int32 TextProcessedLength = 0;

                        while (FImportLine != null)
                        {
                            RowNumber++;

                            TextProcessedLength += (FImportLine.Length + FNewLine.Length);
                            PercentDone = 10 + ((TextProcessedLength * 90) / InitialTextLength);

                            // skip empty lines and commented lines
                            if ((FImportLine.Trim().Length > 0) && !FImportLine.StartsWith("/*") && !FImportLine.StartsWith("#"))
                            {
                                int numberOfElements = StringHelper.GetCSVList(FImportLine, FDelimiter).Count;
                                int preParseMessageCount = Messages.Count;

                                // Read the row analysisType - there is no 'validation' on this so we can make the call with null parameters
                                string RowType =
                                    TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("row type"), null, RowNumber, Messages,
                                        null);

                                if (RowType == "B")
                                {
                                    ImportMessage = Catalog.GetString("Parsing a batch row");

                                    if (numberOfElements < 4)
                                    {
                                        Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, RowNumber),
                                                Catalog.GetString("Wrong number of batch columns.  Expected 4 columns."),
                                                TResultSeverity.Resv_Critical));

                                        FImportLine = sr.ReadLine();

                                        if (FImportLine != null)
                                        {
                                            TextProcessedLength += (FImportLine.Length + FNewLine.Length);
                                        }

                                        continue;
                                    }

                                    if (NewBatch != null)   // update the totals of the batch that has just been imported
                                    {
                                        GLRoutines.UpdateBatchTotals(ref MainDS, ref NewBatch);

                                        if (TVerificationHelper.IsNullOrOnlyNonCritical(Messages))
                                        {
                                            // Save the current batch and its components
                                            ImportMessage = Catalog.GetString("Saving batch");
                                            ABatchAccess.SubmitChanges(MainDS.ABatch, transaction);
                                            MainDS.ABatch.AcceptChanges();

                                            ImportMessage = Catalog.GetString("Saving gift");
                                            AJournalAccess.SubmitChanges(MainDS.AJournal, transaction);
                                            MainDS.AJournal.AcceptChanges();

                                            ImportMessage = Catalog.GetString("Saving giftdetails");
                                            ATransactionAccess.SubmitChanges(MainDS.ATransaction, transaction);
                                            MainDS.ATransaction.AcceptChanges();
                                        }
                                    }

                                    ImportMessage = Catalog.GetString("Starting new batch");
                                    gotFirstBatch = true;
                                    NewBatch = MainDS.ABatch.NewRowTyped(true);
                                    NewBatch.LedgerNumber = LedgerNumber;
                                    LedgerTable[0].LastBatchNumber++;
                                    NewBatch.BatchNumber = LedgerTable[0].LastBatchNumber;
                                    NewBatch.BatchPeriod = LedgerTable[0].CurrentPeriod;
                                    MainDS.ABatch.Rows.Add(NewBatch);
                                    NewJournal = null;
                                    intlRateFromBase = -1.0m;

                                    NewBatch.BatchDescription =
                                        TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Batch description"),
                                            MainDS.ABatch.ColumnBatchDescription, RowNumber, Messages, ValidationControlsDictBatch);

                                    NewBatch.BatchControlTotal =
                                        TCommonImport.ImportDecimal(ref FImportLine, FDelimiter, FCultureInfoNumberFormat,
                                            Catalog.GetString("Batch hash value"),
                                            MainDS.ABatch.ColumnBatchControlTotal, RowNumber, Messages, ValidationControlsDictBatch);
                                    NewBatch.DateEffective =
                                        TCommonImport.ImportDate(ref FImportLine, FDelimiter, FCultureInfoDate,
                                            Catalog.GetString("Batch effective date"),
                                            MainDS.ABatch.ColumnDateEffective, RowNumber, Messages, ValidationControlsDictBatch);

                                    if (Messages.Count == preParseMessageCount)
                                    {
                                        if (TFinancialYear.IsValidPostingPeriod(LedgerNumber,
                                                NewBatch.DateEffective,
                                                out BatchPeriodNumber,
                                                out BatchYearNr,
                                                transaction))
                                        {
                                            NewBatch.BatchYear = BatchYearNr;
                                            NewBatch.BatchPeriod = BatchPeriodNumber;
                                        }
                                        else
                                        {
                                            Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationErrorInLine,
                                                        RowNumber),
                                                    String.Format(Catalog.GetString(
                                                            "The effective date [{0}] of the imported batch is not in an open period."),
                                                        StringHelper.DateToLocalizedString(NewBatch.DateEffective)), TResultSeverity.Resv_Critical));
                                        }

                                        int messageCountBeforeValidate = Messages.Count;

                                        // Validate using the standard validation
                                        ImportMessage = Catalog.GetString("Validating the batch data");
                                        ABatchValidation.Validate(this, NewBatch, ref Messages, ValidationControlsDictBatch);

                                        // Now do the additional manual validation
                                        ImportMessage = Catalog.GetString("Additional validation of the batch data");
                                        TSharedFinanceValidation_GL.ValidateGLBatchManual(this, NewBatch, ref Messages, ValidationControlsDictBatch);

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

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

                                        if ((NewBatch.BatchDescription == null)   // raise error if empty batch description is imported
                                            || (NewBatch.BatchDescription == ""))
                                        {
                                            Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationErrorInLine,
                                                        RowNumber),
                                                    Catalog.GetString("The batch description must not be empty."), TResultSeverity.Resv_Critical));
                                        }
                                    }
                                }
                                else if (RowType == "J")
                                {
                                    ImportMessage = Catalog.GetString("Parsing a journal row");

                                    if (numberOfElements < 7)
                                    {
                                        Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, RowNumber),
                                                Catalog.GetString("Wrong number of journal columns.  Expected 7 columns."),
                                                TResultSeverity.Resv_Critical));

                                        FImportLine = sr.ReadLine();

                                        if (FImportLine != null)
                                        {
                                            TextProcessedLength += (FImportLine.Length + FNewLine.Length);
                                        }

                                        continue;
                                    }

                                    if (NewBatch == null)
                                    {
                                        Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, RowNumber),
                                                Catalog.GetString(
                                                    "Expected a Batch line, but found a Journal. Will create a dummy working batch for the current period."),
                                                TResultSeverity.Resv_Critical));

                                        // in order to carry on we will make a dummy batch and force the date to fit
                                        NewBatch = MainDS.ABatch.NewRowTyped(true);
                                        NewBatch.LedgerNumber = LedgerNumber;
                                        LedgerTable[0].LastBatchNumber++;
                                        NewBatch.BatchNumber = LedgerTable[0].LastBatchNumber;
                                        NewBatch.BatchPeriod = LedgerTable[0].CurrentPeriod;
                                        MainDS.ABatch.Rows.Add(NewBatch);
                                    }

                                    NewJournal = MainDS.AJournal.NewRowTyped(true);
                                    NewJournal.LedgerNumber = NewBatch.LedgerNumber;
                                    NewJournal.BatchNumber = NewBatch.BatchNumber;
                                    NewJournal.JournalNumber = NewBatch.LastJournal + 1;
                                    NewJournal.SubSystemCode = MFinanceConstants.SUB_SYSTEM_GL;
                                    NewJournal.TransactionTypeCode = MFinanceConstants.STANDARD_JOURNAL;
                                    NewJournal.TransactionCurrency = LedgerBaseCurrency;
                                    NewJournal.ExchangeRateToBase = 1;
                                    NewJournal.DateEffective = NewBatch.DateEffective;
                                    NewJournal.JournalPeriod = NewBatch.BatchPeriod;
                                    intlRateFromBase = -1.0m;
                                    NewBatch.LastJournal++;

                                    MainDS.AJournal.Rows.Add(NewJournal);

                                    NewJournal.JournalDescription =
                                        TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Journal description"),
                                            MainDS.AJournal.ColumnJournalDescription, RowNumber, Messages, ValidationControlsDictJournal);

                                    NewJournal.SubSystemCode =
                                        TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Journal sub system code"),
                                            MainDS.AJournal.ColumnSubSystemCode, RowNumber, Messages, ValidationControlsDictJournal).ToUpper();
                                    NewJournal.TransactionTypeCode =
                                        TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Journal transaction type"),
                                            MainDS.AJournal.ColumnTransactionTypeCode, RowNumber, Messages, ValidationControlsDictJournal).ToUpper();
                                    NewJournal.TransactionCurrency =
                                        TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Journal transaction currency"),
                                            MainDS.AJournal.ColumnTransactionCurrency, RowNumber, Messages, ValidationControlsDictJournal).ToUpper();
                                    NewJournal.ExchangeRateToBase =
                                        TCommonImport.ImportDecimal(ref FImportLine, FDelimiter, FCultureInfoNumberFormat,
                                            Catalog.GetString("Journal exchange rate"),
                                            MainDS.AJournal.ColumnExchangeRateToBase, RowNumber, Messages, ValidationControlsDictJournal);
                                    NewJournal.DateEffective =
                                        TCommonImport.ImportDate(ref FImportLine, FDelimiter, FCultureInfoDate,
                                            Catalog.GetString("Journal effective date"),
                                            MainDS.AJournal.ColumnDateEffective, RowNumber, Messages, ValidationControlsDictJournal);

                                    if (Messages.Count == preParseMessageCount)
                                    {
                                        int messageCountBeforeValidate = Messages.Count;

                                        // Validate using the standard validation
                                        ImportMessage = Catalog.GetString("Validating the journal data");
                                        AJournalValidation.Validate(this, NewJournal, ref Messages, ValidationControlsDictJournal);

                                        // Now do the additional manual validation
                                        ImportMessage = Catalog.GetString("Additional validation of the journal data");
                                        TSharedFinanceValidation_GL.ValidateGLJournalManual(this, NewJournal, ref Messages,
                                            ValidationControlsDictJournal, SetupDS, CurrencyTable,
                                            CorporateExchangeRateTable, LedgerBaseCurrency, LedgerIntlCurrency);

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

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

                                        // If this batch is in my base currency,
                                        // the ExchangeRateToBase must be 1:
                                        if ((NewJournal.TransactionCurrency == LedgerBaseCurrency)
                                            && (NewJournal.ExchangeRateToBase != 1.0m))
                                        {
                                            Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationErrorInLine,
                                                        RowNumber),
                                                    Catalog.GetString("Journal in base currency must have exchange rate of 1.00."),
                                                    TResultSeverity.Resv_Critical));
                                        }

                                        //
                                        // The DateEffective might be different to that of the Batch,
                                        // but it must be in the same accounting period.
                                        Int32 journalYear;
                                        Int32 journalPeriod;
                                        DateTime journalDate = NewJournal.DateEffective;

                                        TFinancialYear.GetLedgerDatePostingPeriod(LedgerNumber, ref journalDate,
                                            out journalYear, out journalPeriod, transaction, false);

                                        if ((journalYear != BatchYearNr) || (journalPeriod != BatchPeriodNumber))
                                        {
                                            Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationErrorInLine,
                                                        RowNumber),
                                                    String.Format(Catalog.GetString(
                                                            "The journal effective date {0} is not in the same period as the batch date {1}."),
                                                        journalDate.ToShortDateString(), NewBatch.DateEffective.ToShortDateString()),
                                                    TResultSeverity.Resv_Critical));
                                        }

                                        if (TVerificationHelper.IsNullOrOnlyNonCritical(Messages))
                                        {
                                            // Get a Corporate Exchange Rate for international currency
                                            // Validation will have ensured that we have a corporate rate for intl currency
                                            // at least for the first day of the accounting period.
                                            // (There may possibly be others between then and the effective date)
                                            DateTime firstDayOfMonth;

                                            if (TSharedFinanceValidationHelper.GetFirstDayOfAccountingPeriod(LedgerNumber, NewJournal.DateEffective,
                                                    out firstDayOfMonth))
                                            {
                                                intlRateFromBase =
                                                    TExchangeRateTools.GetCorporateExchangeRate(LedgerBaseCurrency, LedgerIntlCurrency,
                                                        firstDayOfMonth,
                                                        NewJournal.DateEffective);

                                                if (intlRateFromBase <= 0.0m)
                                                {
                                                    // This should never happen (see above)
                                                    Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine,
                                                                RowNumber),
                                                            String.Format(
                                                                "There is no Corporate Exchange Rate for {0} to {1} applicable to the period {2} to {3}.  Please set up an appropriate rate and then import the data again.",
                                                                LedgerBaseCurrency,
                                                                LedgerIntlCurrency,
                                                                StringHelper.DateToLocalizedString(firstDayOfMonth),
                                                                StringHelper.DateToLocalizedString(NewJournal.DateEffective)),
                                                            TResultSeverity.Resv_Critical));
                                                }
                                            }
                                        }

                                        if (TVerificationHelper.IsNullOrOnlyNonCritical(Messages))
                                        {
                                            // This row passes validation so we can do final actions if the batch is not in the ledger currency
                                            if (NewJournal.TransactionCurrency != LedgerBaseCurrency)
                                            {
                                                // we need to create a daily exchange rate pair for the transaction date
                                                // start with To Ledger currency
                                                if (UpdateDailyExchangeRateTable(DailyExchangeRateTable, NewJournal.TransactionCurrency,
                                                        LedgerBaseCurrency,
                                                        NewJournal.ExchangeRateToBase, NewJournal.DateEffective))
                                                {
                                                    Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportInformationForLine,
                                                                RowNumber),
                                                            String.Format(Catalog.GetString(
                                                                    "An exchange rate of {0} for '{1}' to '{2}' on {3} will be added to the Daily Exchange Rate table after a successful import."),
                                                                NewJournal.ExchangeRateToBase,
                                                                NewJournal.TransactionCurrency,
                                                                LedgerBaseCurrency,
                                                                StringHelper.DateToLocalizedString(NewJournal.DateEffective)),
                                                            TResultSeverity.Resv_Info));
                                                }

                                                // Now the inverse for From Ledger currency
                                                decimal inverseRate = Math.Round(1 / NewJournal.ExchangeRateToBase, 10);

                                                UpdateDailyExchangeRateTable(DailyExchangeRateTable, LedgerBaseCurrency,
                                                    NewJournal.TransactionCurrency,
                                                    inverseRate, NewJournal.DateEffective);
                                            }
                                        }
                                    }
                                }
                                else if (RowType == "T")
                                {
                                    ImportMessage = Catalog.GetString("Parsing a transaction row");
                                    bool skipThisLine = false;

                                    if (numberOfElements < 8)
                                    {
                                        Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, RowNumber),
                                                Catalog.GetString("Wrong number of transaction columns.  Expected at least 8 columns."),
                                                TResultSeverity.Resv_Critical));
                                        skipThisLine = true;
                                    }

                                    if (NewJournal == null)
                                    {
                                        Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, RowNumber),
                                                Catalog.GetString("Expected a Journal row but found a Transaction row."),
                                                TResultSeverity.Resv_Critical));
                                        skipThisLine = true;
                                    }

                                    if (skipThisLine)
                                    {
                                        FImportLine = sr.ReadLine();

                                        if (FImportLine != null)
                                        {
                                            TextProcessedLength += (FImportLine.Length + FNewLine.Length);
                                        }

                                        continue;
                                    }

                                    ImportGLTransactionsInner(LedgerNumber, RowNumber, ref MainDS, ref SetupDS, ref NewBatch, ref NewJournal,
                                        intlRateFromBase, ref transaction, ref ImportMessage, ref Messages,
                                        ref ValidationControlsDictTransaction);
                                }
                                else
                                {
                                    if ((NewBatch == null) && !gotFirstBatch)
                                    {
                                        string msg = Catalog.GetString(
                                            "Expecting a Row Type definition. Valid types are 'B', 'J' or 'T'. Maybe you are opening a 'Transactions' file.");
                                        msg +=
                                            Catalog.GetString(
                                                "  You need to be on the 'Transactions' Tab to import transaction-only data into an existing batch.");
                                        msg += Catalog.GetString("  Alternatively you may have selected the wrong Field Delimiter.");
                                        msg += Catalog.GetString("  Choose a delimiter that shows multiple columns in the preview window.");
                                        Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, RowNumber),
                                                msg,
                                                TResultSeverity.Resv_Critical));
                                        break;
                                    }
                                    else
                                    {
                                        Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrParsingErrorInLine, RowNumber),
                                                String.Format(Catalog.GetString(
                                                        "'{0}' is not a valid Row Type. Valid types are 'B', 'J' or 'T'."),
                                                    RowType),
                                                TResultSeverity.Resv_Critical));
                                    }
                                }
                            }  // if the CSV line qualifies

                            if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                            {
                                CancelledByUser = true;
                                break;
                            }

                            if (Messages.Count > 100)
                            {
                                // This probably means that it is a big file and the user has made the same mistake many times over
                                break;
                            }

                            // Update progress tracker every few percent
                            if ((PercentDone - PreviousPercentDone) > 3)
                            {
                                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                    String.Format(Catalog.GetString("Importing row {0}"), RowNumber),
                                    (PercentDone > 98) ? 98 : PercentDone);
                                PreviousPercentDone = PercentDone;
                            }

                            // Read the next line
                            FImportLine = sr.ReadLine();

                            if (FImportLine != null)
                            {
                                TextProcessedLength += (FImportLine.Length + FNewLine.Length);
                            }
                        }  // while CSV lines

                        if (CancelledByUser)
                        {
                            Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation,
                                    String.Format(Catalog.GetString("{0} messages reported."), Messages.Count), TResultSeverity.Resv_Info));
                            Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation,
                                    "The import was cancelled by the user.", TResultSeverity.Resv_Info));
                            return;
                        }

                        // Finished reading the file - did we have critical errors?
                        if (!TVerificationHelper.IsNullOrOnlyNonCritical(Messages))
                        {
                            TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                Catalog.GetString("Batch has critical errors"),
                                0);

                            // Record error count
                            Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation,
                                    String.Format(Catalog.GetString("{0} messages reported."), Messages.Count), TResultSeverity.Resv_Info));

                            if (FImportLine == null)
                            {
                                // We did reach the end of the file
                                Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation,
                                        Catalog.GetString(
                                            "Reached the end of file but errors occurred. When these errors are fixed the batch will import successfully."),
                                        TResultSeverity.Resv_Info));
                            }
                            else
                            {
                                // We gave up before the end
                                if (Messages.Count > 100)
                                {
                                    Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation,
                                            Catalog.GetString(
                                                "Stopped reading the file after generating more than 100 messages.  The file may contain more errors beyond the ones listed here."),
                                            TResultSeverity.Resv_Info));
                                }
                                else
                                {
                                    Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation,
                                            Catalog.GetString(
                                                "Stopped reading the file. Please check you are using a GL Batch Import file and have chosen the correct Field Delimiter."),
                                            TResultSeverity.Resv_Info));
                                }
                            }

                            // Do the 'finally' actions and return false
                            return;
                        }

                        // Everything is ok, so we can do our finish actions

                        // Save all pending changes (last xxx number is updated)
                        ImportMessage = Catalog.GetString("Saving daily exchange rate data");
                        ADailyExchangeRateAccess.SubmitChanges(DailyExchangeRateTable, transaction);
                        DailyExchangeRateTable.AcceptChanges();

                        ImportMessage = Catalog.GetString("Saving changes to Ledger table");
                        ALedgerAccess.SubmitChanges(LedgerTable, transaction);
                        LedgerTable.AcceptChanges();

                        // Update totals of final batch
                        ImportMessage = Catalog.GetString("Saving changes to batch totals");

                        if (NewBatch != null)
                        {
                            GLRoutines.UpdateBatchTotals(ref MainDS, ref NewBatch);
                        }

                        ImportMessage = Catalog.GetString("Saving changes to batch");
                        ABatchAccess.SubmitChanges(MainDS.ABatch, transaction);
                        MainDS.ABatch.AcceptChanges();
                        ImportMessage = Catalog.GetString("Saving changes to journal");
                        AJournalAccess.SubmitChanges(MainDS.AJournal, transaction);
                        MainDS.AJournal.AcceptChanges();
                        ImportMessage = Catalog.GetString("Saving changes to transactions");
                        ATransactionAccess.SubmitChanges(MainDS.ATransaction, transaction);
                        MainDS.ATransaction.AcceptChanges();

                        // Now we are done!!!
                        submissionOK = true;
                    } // try
                    catch (Exception ex)
                    {
                        // Parse the exception text for possible references to database foreign keys
                        // Make the message more friendly in that case
                        string friendlyExceptionText = MakeFriendlyFKExceptions(ex);

                        if (RowNumber > 0)
                        {
                            // At least we made a start
                            string msg = ImportMessage;

                            if (friendlyExceptionText.Length > 0)
                            {
                                msg += FNewLine + friendlyExceptionText;
                            }

                            if (ImportMessage.StartsWith(Catalog.GetString("Saving ")))
                            {
                                // Do not display any specific line number because these errors occur outside the parsing loop
                                Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrExceptionWhileSavingBatch,
                                            NewBatch.BatchDescription),
                                        msg, TResultSeverity.Resv_Critical));
                            }
                            else
                            {
                                Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrExceptionWhileParsingLine, RowNumber),
                                        msg, TResultSeverity.Resv_Critical));
                            }
                        }
                        else
                        {
                            // We got an exception before we even started parsing the rows (getting a transaction?)
                            Messages.Add(new TVerificationResult(String.Format(MCommonConstants.StrExceptionWhileParsingLine, RowNumber),
                                    friendlyExceptionText, TResultSeverity.Resv_Critical));
                        }

                        TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                            Catalog.GetString("Exception Occurred"),
                            0);
                    } // catch
                    finally
                    {
                        sr.Close();

                        if (submissionOK)
                        {
                            TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Gift batch import successful"),
                                100);
                        }
                        else
                        {
                            Messages.Add(new TVerificationResult(MCommonConstants.StrImportInformation,
                                    Catalog.GetString("None of the data from the import was saved."),
                                    TResultSeverity.Resv_Critical));

                            TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                Catalog.GetString("Data could not be saved."),
                                0);
                        }

                        TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                    } // end of 'finally'
                }); // Begin Auto Transaction


            // Set our 'out' parameters
            AMessages = Messages;

            return submissionOK;
        } // Import GL Batches
コード例 #51
0
        public static GLSetupTDS LoadAAnalysisAttributes(Int32 ALedgerNumber, Boolean AActiveOnly = false)
        {
            GLSetupTDS CacheDS = new GLSetupTDS();
            bool NewTransaction;
            TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted, out NewTransaction);

            AAnalysisTypeAccess.LoadAll(CacheDS, Transaction);

            if (!AActiveOnly)
            {
                AFreeformAnalysisAccess.LoadViaALedger(CacheDS, ALedgerNumber, Transaction);
                AAnalysisAttributeAccess.LoadViaALedger(CacheDS, ALedgerNumber, Transaction);
            }
            else
            {
                AFreeformAnalysisTable FFTable = new AFreeformAnalysisTable();
                AFreeformAnalysisRow TemplateFFRow = FFTable.NewRowTyped(false);
                TemplateFFRow.LedgerNumber = ALedgerNumber;
                TemplateFFRow.Active = true;

                AFreeformAnalysisAccess.LoadUsingTemplate(CacheDS, TemplateFFRow, Transaction);

                AAnalysisAttributeTable AATable = new AAnalysisAttributeTable();
                AAnalysisAttributeRow TemplateAARow = AATable.NewRowTyped(false);
                TemplateAARow.LedgerNumber = ALedgerNumber;
                TemplateAARow.Active = true;

                AAnalysisAttributeAccess.LoadUsingTemplate(CacheDS, TemplateAARow, Transaction);
            }

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

            return CacheDS;
        }
コード例 #52
0
        /// <summary>
        /// Load account hierarchy from the dataset into the tree view
        /// </summary>
        public void PopulateTreeView(GLSetupTDS MainDS, Int32 LedgerNumber, String SelectedHierarchy)
        {
            FParentForm.SetSelectedAccount(null);
            FDuringInitialisation = true;
            trvAccounts.BeginUpdate();
            trvAccounts.Nodes.Clear();

            // TODO: select account hierarchy
            AAccountHierarchyRow accountHierarchy = (AAccountHierarchyRow)MainDS.AAccountHierarchy.Rows.Find(new object[] { LedgerNumber,
                                                                                                                            SelectedHierarchy });

            if (accountHierarchy != null)
            {
                // find the BALSHT account that is reporting to the root account
                MainDS.AAccountHierarchyDetail.DefaultView.RowFilter =
                    AAccountHierarchyDetailTable.GetAccountHierarchyCodeDBName() + " = '" + SelectedHierarchy + "' AND " +
                    AAccountHierarchyDetailTable.GetAccountCodeToReportToDBName() + " = '" + accountHierarchy.RootAccountCode + "'";

                DataView view = new DataView(MainDS.AAccountHierarchyDetail);
                view.Sort = AAccountHierarchyDetailTable.GetReportOrderDBName() + ", " + AAccountHierarchyDetailTable.GetReportingAccountCodeDBName();
                InsertNodeIntoTreeView(MainDS, LedgerNumber, null, view,
                    (AAccountHierarchyDetailRow)MainDS.AAccountHierarchyDetail.DefaultView[0].Row);
            }

            // reset filter so that the defaultview can be used for finding accounts (eg. when adding new account)
            MainDS.AAccountHierarchyDetail.DefaultView.RowFilter = "";
            trvAccounts.EndUpdate();

            FDuringInitialisation = false;

            if (trvAccounts.Nodes.Count > 0)
            {
                SelectNodeByName(trvAccounts.Nodes[0].Name); // Select the first (BAL SHT) item
            }

            this.trvAccounts.BeforeSelect +=
                new System.Windows.Forms.TreeViewCancelEventHandler(this.TreeViewBeforeSelect);
            this.trvAccounts.AfterSelect +=
                new System.Windows.Forms.TreeViewEventHandler(this.TreeViewAfterSelect);
        }
コード例 #53
0
        private void InsertNodeIntoTreeView(GLSetupTDS MainDS,
            Int32 LedgerNumber,
            TreeNode AParent,
            DataView view,
            AAccountHierarchyDetailRow ADetailRow)
        {
            AAccountRow AccountRow = (AAccountRow)MainDS.AAccount.Rows.Find(
                new object[] { LedgerNumber, ADetailRow.ReportingAccountCode });

            TreeNode Child = new TreeNode();


            AccountNodeDetails NodeTag = AccountNodeDetails.AddNewAccount(Child, AccountRow, ADetailRow);

            NodeTag.IsNew = false;

            SetNodeLabel(AccountRow, Child);

            if (AParent == null)
            {
                trvAccounts.Nodes.Add(Child);
            }
            else
            {
                InsertInOrder(AParent, Child);
            }

            // Now add the children of this node:
            view.RowFilter =
                AAccountHierarchyDetailTable.GetAccountHierarchyCodeDBName() + " = '" + ADetailRow.AccountHierarchyCode + "' AND " +
                AAccountHierarchyDetailTable.GetAccountCodeToReportToDBName() + " = '" + ADetailRow.ReportingAccountCode + "'";

            if (view.Count > 0)
            {
                // An account cannot be deleted if it has children.
                NodeTag.CanDelete = false;
                NodeTag.Msg = Catalog.GetString("Child accounts must be deleted first.");
                NodeTag.CanHaveChildren = true;

                foreach (DataRowView rowView in view)
                {
                    AAccountHierarchyDetailRow accountDetail = (AAccountHierarchyDetailRow)rowView.Row;
                    InsertNodeIntoTreeView(MainDS, LedgerNumber, Child, view, accountDetail);
                }
            }
        }
コード例 #54
0
        /// <summary>
        /// load the transactions into the grid
        /// </summary>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ABatchNumber"></param>
        /// <param name="AJournalNumber"></param>
        /// <param name="ACurrencyCode"></param>
        /// <param name="AFromBatchTab"></param>
        /// <returns>True if new GL transactions were loaded, false if transactions had been loaded already.</returns>
        public bool LoadRecurringTransactions(Int32 ALedgerNumber,
            Int32 ABatchNumber,
            Int32 AJournalNumber,
            string ACurrencyCode,
            bool AFromBatchTab = false)
        {
            bool DifferentBatchSelected = false;
            bool HadChangesFromTheStart = FPetraUtilsObject.HasChanges;

            FLoadCompleted = false;
            FBatchRow = GetRecurringBatchRow();
            FJournalRow = GetRecurringJournalRow();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    SetupExtraGridFunctionality();

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

                // This modifies the content of the text boxes that display the totals.  This is not a user change.
                bool prev = FPetraUtilsObject.SuppressChangeDetection;
                FPetraUtilsObject.SuppressChangeDetection = true;
                UpdateTransactionTotals();
                FPetraUtilsObject.SuppressChangeDetection = prev;

                grdDetails.ResumeLayout();
                FLoadCompleted = true;
            }

            //Check for incorrect Exchange rate to base (mainly for existing Petra data)
            foreach (DataRowView drv in FMainDS.ARecurringTransaction.DefaultView)
            {
                ARecurringTransactionRow rtr = (ARecurringTransactionRow)drv.Row;

                if (rtr.ExchangeRateToBase == 0)
                {
                    rtr.ExchangeRateToBase = 1;
                    FPetraUtilsObject.HasChanges = true;
                }
            }

            if (FPetraUtilsObject.HasChanges && !HadChangesFromTheStart)
            {
                // This means we updated the transaction totals.  We will save them behind the scenes since there were no other changes when we started
                ((TFrmRecurringGLBatch)ParentForm).SaveChanges();
                FMainDS.ARecurringTransaction.AcceptChanges();
            }

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

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

            return DifferentBatchSelected;
        }