Ejemplo n.º 1
0
        public void ForeignCurrencySupplier_ExpectDocumentPostingPayingAndReversingWorking()
        {
            //
            // Arrange
            //
            decimal APAccountBalanceBefore;
            decimal BankAccountBefore;
            decimal RevalAccountBefore;
            TVerificationResultCollection VerificationResult;
            int PaymentNumber;

            List <int> DocumentIDs;
            AAPInfos   APInfos;

            CommonNUnitFunctions.ResetDatabase();
            TPetraServerConnector.Connect();

            TDataBase      db          = DBAccess.Connect("ForeignCurrencySupplier_ExpectDocumentPostingPayingAndReversingWorking");
            TDBTransaction transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // Post and pay a document with a foreign currency supplier
            APInfos = PostAndPayForeignSupplierAPDocument("Test Reverse", out PaymentNumber, out DocumentIDs,
                                                          out APAccountBalanceBefore, out BankAccountBefore, out RevalAccountBefore, db);

            transaction.Commit();
            transaction = db.BeginTransaction(IsolationLevel.Serializable);

            //
            // Act: Immediately "un-pay" and "un-post" this invoice!
            //
            VerificationResult = ReversePayment(PaymentNumber, APInfos.PeriodEndDate, DocumentIDs, APInfos.ApDS, db);
            CommonNUnitFunctions.EnsureNullOrEmptyVerificationResult(VerificationResult);   // Guard Assert

            transaction.Commit();
            transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // Save the current amount on the AP account
            decimal APAccountBalanceAfter = new TGet_GLM_Info(FLedgerNumber,
                                                              APInfos.ApAccountCode, APInfos.CostCentreCode, db).YtdActual;
            decimal BankAccountAfter = new TGet_GLM_Info(FLedgerNumber,
                                                         APInfos.BankAccount, APInfos.CostCentreCode, db).YtdForeign;
            decimal RevalAccountAfter = new TGet_GLM_Info(FLedgerNumber,
                                                          APInfos.ForexGainsLossesAccount, APInfos.CostCentreCode, db).YtdActual;

            //
            // Primary Assert: Reversal OK?
            //
            // Now I can see whether anything is left over by all these
            // various transactions, that should have added up to 0.
            // Check the amount on the AP account
            Assert.AreEqual(APAccountBalanceBefore, APAccountBalanceAfter, "After paying then reversing, the AP account should be as before.");
            Assert.AreEqual(BankAccountBefore, BankAccountAfter, "After paying then reversing, the Bank account should be as before.");
            Assert.AreEqual(
                Math.Round(RevalAccountAfter, 2),
                Math.Round(RevalAccountBefore, 2),
                "After paying then reversing, the Forex Gains/Losses Account account should be as before.");

            transaction.Commit();
        }
Ejemplo n.º 2
0
        public void TestSaveNewPartnerWithExistingLocation()
        {
            TDataBase               db          = DBAccess.Connect("TestSaveNewPartnerWithExistingLocation");
            TDBTransaction          Transaction = db.BeginTransaction(IsolationLevel.Serializable);
            TPartnerEditUIConnector connector   = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            PPartnerRow PartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);

            TCreateTestPartnerData.CreateNewLocation(PartnerRow.PartnerKey, MainDS);

            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);

            Transaction.Commit();

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving:");

            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "saving the first partner with a location");

            Int32 LocationKey = MainDS.PLocation[0].LocationKey;

            MainDS = new PartnerEditTDS();

            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            PartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);

            PPartnerLocationRow PartnerLocationRow = MainDS.PPartnerLocation.NewRowTyped();

            PartnerLocationRow.SiteKey     = DomainManager.GSiteKey;
            PartnerLocationRow.PartnerKey  = PartnerRow.PartnerKey;
            PartnerLocationRow.LocationKey = LocationKey;
            MainDS.PPartnerLocation.Rows.Add(PartnerLocationRow);

            ResponseDS = new PartnerEditTDS();

            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Transaction.Commit();

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving:");

            TDBTransaction ReadTransaction = new TDBTransaction();

            db.ReadTransaction(
                ref ReadTransaction,
                delegate
            {
                PPartnerTable PartnerAtAddress = PPartnerAccess.LoadViaPLocation(
                    DomainManager.GSiteKey, LocationKey, ReadTransaction);
                Assert.AreEqual(2, PartnerAtAddress.Rows.Count, "there should be two partners at this location");
            });
        }
Ejemplo n.º 3
0
        public void SimpleDocument_ExpectPostingAndPayingWorking()
        {
            //
            // Arrange
            //
            decimal Amount = 399.0m;
            decimal APAccountBalanceBefore;
            decimal ABankAccountBefore;
            decimal AExpAccountBefore;
            TVerificationResultCollection VerificationResult;

            List <int> DocumentIDs;
            int        PaymentNumber;
            AAPInfos   APInfos;

            CommonNUnitFunctions.ResetDatabase();
            TPetraServerConnector.Connect();

            TDataBase      db          = DBAccess.Connect("SimpleDocument_ExpectPostingAndPayingWorking");
            TDBTransaction transaction = db.BeginTransaction(IsolationLevel.Serializable);

            APInfos = PostSimpleAPDocument(Amount, "Test", "Detail Item", out APAccountBalanceBefore, out ABankAccountBefore,
                                           out AExpAccountBefore, out DocumentIDs, db);

            transaction.Commit();
            transaction = db.BeginTransaction(IsolationLevel.Serializable);

            //
            // Act: Pay the AP document
            //
            VerificationResult = PayAPDocument(APInfos.ApDS.AApDocument[0].ApDocumentId, Amount,
                                               APInfos.BankAccount, APInfos.CurrencyCode, APInfos.PeriodEndDate, out PaymentNumber, null, db);
            CommonNUnitFunctions.EnsureNullOrEmptyVerificationResult(VerificationResult);   // Guard Assert

            transaction.Commit();

            // Save the current amount on the AP account
            decimal APAccountBalanceAfter = new TGet_GLM_Info(FLedgerNumber,
                                                              APInfos.ApAccountCode, APInfos.CostCentreCode, db).YtdActual;
            decimal BankAccountAfter = new TGet_GLM_Info(FLedgerNumber,
                                                         APInfos.BankAccount, APInfos.CostCentreCode, db).YtdActual;

            //
            // Primary Assert: Paying OK?
            //
            // Check the amount on the AP account
            Assert.AreEqual(0.0m, APAccountBalanceAfter - APAccountBalanceBefore, "after paying the invoice, the AP account should be cleared");
            Assert.AreEqual((-1.0m) * Amount, BankAccountAfter - ABankAccountBefore, "after paying the invoice, the bank account should be credited");
        }
        /// <summary>
        /// Determines which address is the 'Best Address' of a Partner, and returns the PPartnerLocation record which is the
        /// 'Best Address'.
        /// </summary>
        /// <remarks>There are two similar shared Methods in Namespace Ict.Petra.Server.MPartner.Common.Calculations,
        /// both called 'DetermineBestAddress' which work by passing in the PartnerLocations of a Partner in an Argument
        /// and which return a <see cref="TLocationPK" />. As those Methods don't access the database, these Methods
        /// can be used client-side as well!</remarks>
        /// <param name="APartnerKey">PartnerKey of the Partner whose addresses should be checked.</param>
        /// <param name="APartnerLocationDR">PPartnerLocation Record that is the record that is the Location of the 'Best Address'.</param>
        /// <param name="ADataBase">An instantiated <see cref="TDataBase" /> object, or null (default = null). If null
        /// gets passed then the Method executes DB commands with a new Database connection</param>
        /// <returns>A <see cref="TLocationPK" /> which points to the 'Best Address'. If no 'Best Address' was found,
        /// SiteKey and LocationKey of this instance will be both -1.</returns>
        public static TLocationPK DetermineBestAddress(Int64 APartnerKey, out PPartnerLocationRow APartnerLocationDR,
                                                       TDataBase ADataBase = null)
        {
            TLocationPK           ReturnValue = new TLocationPK();
            PPartnerLocationTable PartnerLocationDT;
            Boolean NewTransaction;

            TDataBase      db = DBAccess.Connect("DetermineBestAddress", ADataBase);
            TDBTransaction ReadTransaction = db.GetNewOrExistingTransaction(
                MCommonConstants.CACHEABLEDT_ISOLATIONLEVEL,
                out NewTransaction);

            try
            {
                PartnerLocationDT = PPartnerLocationAccess.LoadViaPPartner(APartnerKey, ReadTransaction);
                ReturnValue       = Ict.Petra.Server.MPartner.Common.Calculations.DetermineBestAddress(PartnerLocationDT);

                APartnerLocationDR = (PPartnerLocationRow)PartnerLocationDT.Rows.Find(new object[]
                                                                                      { APartnerKey, ReturnValue.SiteKey, ReturnValue.LocationKey });
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "ServerCalculations.DetermineBestAddress: commited own transaction.");
                }
            }

            return(ReturnValue);
        }
Ejemplo n.º 5
0
        public void TestModifyGiftBatch()
        {
            TDataBase      db = DBAccess.Connect("test");
            TDBTransaction t  = db.BeginTransaction(IsolationLevel.Serializable);

            GiftBatchTDS MainDS;

            ALedgerAccess.LoadAll(MainDS, t);

            MainDS.ALedger[0].LastGiftBatchNumber++;

            AGiftBatchRow batch = MainDS.AGiftBatch.NewRowTyped();

            batch.LedgerNumber    = MainDS.ALedger[0].LedgerNumber;
            batch.BatchNumber     = MainDS.ALedger[0].LastGiftBatchNumber;
            batch.BankAccountCode = "6000";
            batch.BatchYear       = 1;
            batch.BatchPeriod     = 1;
            batch.CurrencyCode    = "EUR";
            batch.BankCostCentre  = MainDS.ALedger[0].LedgerNumber.ToString() + "00";
            batch.LastGiftNumber  = 2;
            MainDS.AGiftBatch.Rows.Add(batch);

            AGiftRow gift = MainDS.AGift.NewRowTyped();

            gift.LedgerNumber          = batch.LedgerNumber;
            gift.BatchNumber           = batch.BatchNumber;
            gift.GiftTransactionNumber = 1;
            MainDS.AGift.Rows.Add(gift);

            gift = MainDS.AGift.NewRowTyped();
            gift.LedgerNumber          = batch.LedgerNumber;
            gift.BatchNumber           = batch.BatchNumber;
            gift.GiftTransactionNumber = 2;
            gift.LastDetailNumber      = 1;
            MainDS.AGift.Rows.Add(gift);

            AGiftDetailRow giftdetail = MainDS.AGiftDetail.NewRowTyped();

            giftdetail.LedgerNumber          = gift.LedgerNumber;
            giftdetail.BatchNumber           = gift.BatchNumber;
            giftdetail.GiftTransactionNumber = gift.GiftTransactionNumber;
            giftdetail.DetailNumber          = 1;
            giftdetail.MotivationGroupCode   = "GIFT";
            giftdetail.MotivationDetailCode  = "SUPPORT";
            MainDS.AGiftDetail.Rows.Add(giftdetail);

            MainDS.SubmitChanges(t);
            t.Commit();

            // now delete the first gift, and fix the gift detail of the second gift
            t = db.BeginTransaction(IsolationLevel.Serializable);
            MainDS.AGift.Rows.RemoveAt(0);
            MainDS.AGift[0].GiftTransactionNumber       = 1;
            MainDS.AGiftDetail[0].GiftTransactionNumber = 1;
            MainDS.AGiftBatch[0].LastGiftNumber         = 1;

            MainDS.SubmitChanges(t);
            g.Commit();
        }
Ejemplo n.º 6
0
        /// create a new church
        public static PPartnerRow CreateNewChurchPartner(PartnerEditTDS AMainDS, TDataBase ADataBase = null)
        {
            PPartnerRow    PartnerRow  = CreateNewPartner(AMainDS, ADataBase);
            TDataBase      db          = DBAccess.Connect("CreateNewChurchPartner", ADataBase);
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // make sure denomination "UNKNOWN" exists as this is the default value
            if (!PDenominationAccess.Exists("UNKNOWN", Transaction))
            {
                PDenominationTable DenominationTable = new PDenominationTable();
                PDenominationRow   DenominationRow   = DenominationTable.NewRowTyped();
                DenominationRow.DenominationCode = "UNKNOWN";
                DenominationRow.DenominationName = "Unknown";
                DenominationTable.Rows.Add(DenominationRow);
                PDenominationAccess.SubmitChanges(DenominationTable, Transaction);
                Transaction.Commit();
            }
            else
            {
                Transaction.Rollback();
            }

            PartnerRow.PartnerClass     = MPartnerConstants.PARTNERCLASS_CHURCH;
            PartnerRow.PartnerShortName = PartnerRow.PartnerKey.ToString() + ", TestChurch";

            PChurchRow ChurchRow = AMainDS.PChurch.NewRowTyped();

            ChurchRow.PartnerKey       = PartnerRow.PartnerKey;
            ChurchRow.ChurchName       = "TestChurch";
            ChurchRow.DenominationCode = "UNKNOWN";
            AMainDS.PChurch.Rows.Add(ChurchRow);

            return(PartnerRow);
        }
Ejemplo n.º 7
0
        public void TestSaveNewPartnerWithLocation()
        {
            TDataBase               db          = DBAccess.Connect("TestSaveNewPartnerWithLocation");
            TDBTransaction          Transaction = db.BeginTransaction(IsolationLevel.Serializable);
            TPartnerEditUIConnector connector   = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            PPartnerRow PartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);

            TCreateTestPartnerData.CreateNewLocation(PartnerRow.PartnerKey, MainDS);

            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);

            Transaction.Commit();

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving:");

            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "TPartnerEditUIConnector SubmitChanges return value");

            // check the location key for this partner. should not be negative
            Assert.AreEqual(1, MainDS.PPartnerLocation.Rows.Count, "TPartnerEditUIConnector SubmitChanges returns one location");
            Assert.Greater(MainDS.PPartnerLocation[0].LocationKey, 0, "TPartnerEditUIConnector SubmitChanges returns valid location key");
        }
Ejemplo n.º 8
0
        /// create new AP info
        public static AApDocumentRow CreateNewAPInfo(Int64 APartnerKey, ref AccountsPayableTDS AMainDS, TDataBase ADataBase = null)
        {
            TDataBase      db          = DBAccess.Connect("CreateNewAPInfo", ADataBase);
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            ALedgerTable LedgerTable = ALedgerAccess.LoadAll(Transaction);

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

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

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

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

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

            Transaction.Commit();

            return(Document);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="AErrorCode"></param>
        /// <param name="AContext"></param>
        /// <param name="AMessageLine1"></param>
        /// <param name="AMessageLine2"></param>
        /// <param name="AMessageLine3"></param>
        /// <param name="AUserID"></param>
        /// <param name="AProcessID"></param>
        public void AddErrorLogEntry(String AErrorCode,
                                     String AContext,
                                     String AMessageLine1,
                                     String AMessageLine2,
                                     String AMessageLine3,
                                     String AUserID,
                                     Int32 AProcessID)
        {
            SErrorLogTable ErrorLogTable;
            SErrorLogRow   NewErrorLogRow;
            DateTime       ErrorLogDateTime;
            String         Context;

            ErrorLogTable    = new SErrorLogTable();
            NewErrorLogRow   = ErrorLogTable.NewRowTyped(false);
            ErrorLogDateTime = DateTime.Now;

            if (AContext != "")
            {
                Context = AContext;
            }
            else
            {
                Context = UNKNOWN_CONTEXT;
            }

            // Set DataRow values
            NewErrorLogRow.ErrorCode     = AErrorCode;
            NewErrorLogRow.UserId        = AUserID.ToUpper();
            NewErrorLogRow.Date          = ErrorLogDateTime;
            NewErrorLogRow.Time          = Conversions.DateTimeToInt32Time(ErrorLogDateTime);
            NewErrorLogRow.ReleaseNumber = TSrvSetting.ApplicationVersion.ToString();
            NewErrorLogRow.FileName      = Context;
            NewErrorLogRow.ProcessId     = AProcessID.ToString();
            NewErrorLogRow.MessageLine1  = AMessageLine1;
            NewErrorLogRow.MessageLine2  = AMessageLine2;
            NewErrorLogRow.MessageLine3  = AMessageLine3;
            ErrorLogTable.Rows.Add(NewErrorLogRow);

            TDataBase      db = DBAccess.Connect("AddErrorLogEntry");
            TDBTransaction WriteTransaction = db.BeginTransaction(IsolationLevel.Serializable);

            // Save DataRow
            try
            {
                SErrorLogAccess.SubmitChanges(ErrorLogTable, WriteTransaction);

                WriteTransaction.Commit();
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured during the saving of the Error Log:" + Environment.NewLine + Exc.ToString());

                WriteTransaction.Rollback();

                throw;
            }
        }
Ejemplo n.º 10
0
        private static void CreateOptionTypes()
        {
            TDataBase      db          = DBAccess.Connect("CreateOptionTypes");
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            bool RowsToAdd = false;

            string[, ] OptionTypes = new string[, ]
            {
                {
                    "ADD_ACCOMM_COST_FOR_TOTAL", "Add accommodation costs to get total costs"
                },
                {
                    "COST_PER_DAY", "Calculate conference cost per day"
                },
                {
                    "COST_PER_NIGHT", "Calculate conference cost per night"
                }
            };

            try
            {
                PcConferenceOptionTypeTable OptionTypeTable = PcConferenceOptionTypeAccess.LoadAll(Transaction);

                for (int i = 0; i < 3; i++)
                {
                    if (OptionTypeTable.Rows.Find(new object[] { OptionTypes[i, 0] }) == null)
                    {
                        PcConferenceOptionTypeRow NewRow = OptionTypeTable.NewRowTyped(false);
                        NewRow.OptionTypeCode        = OptionTypes[i, 0];
                        NewRow.OptionTypeDescription = OptionTypes[i, 1];
                        NewRow.UnassignableFlag      = false;
                        NewRow.DeletableFlag         = false;

                        OptionTypeTable.Rows.Add(NewRow);

                        RowsToAdd = true;
                    }
                }

                if (RowsToAdd)
                {
                    // add any new rows to database
                    PcConferenceOptionTypeAccess.SubmitChanges(OptionTypeTable, Transaction);
                }

                Transaction.Commit();
                TLogging.LogAtLevel(7, "TConferenceDataReaderWebConnector.CreateOptionTypes: commit own transaction.");
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured during the creation of option types:" + Environment.NewLine + Exc.ToString());

                Transaction.Rollback();

                throw;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Passes data as a Typed DataSet to the Supplier Edit Screen
        /// </summary>
        public AccountsPayableTDS GetData(Int64 APartnerKey)
        {
            TDBTransaction ReadTransaction;

            // create the DataSet that will later be passed to the Client
            AccountsPayableTDS MainDS = new AccountsPayableTDS();

            ReadTransaction = FDataBase.BeginTransaction(IsolationLevel.RepeatableRead, 5);

            try
            {
                try
                {
                    // Supplier
                    AApSupplierAccess.LoadByPrimaryKey(MainDS, APartnerKey, ReadTransaction);

                    if (MainDS.AApSupplier.Rows.Count == 0)
                    {
                        // Supplier does not exist
                        throw new Exception("supplier does not exist");
                    }
                }
                catch (Exception Exp)
                {
                    ReadTransaction.Rollback();
                    ReadTransaction = new TDBTransaction();
                    TLogging.Log("TSupplierEditUIConnector.LoadData exception: " + Exp.ToString(), TLoggingType.ToLogfile);
                    TLogging.Log(Exp.StackTrace, TLoggingType.ToLogfile);
                    throw;
                }
            }
            finally
            {
                if (ReadTransaction != null)
                {
                    ReadTransaction.Commit();
                }
            }

            // 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);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Determines which address is the 'Best Address' of a Partner, and returns the PLocation record which the
        /// 'Best Address' is pointing to.
        /// </summary>
        /// <remarks>There are two similar shared Methods in Namespace Ict.Petra.Server.MPartner.Common.Calculations,
        /// both called 'DetermineBestAddress' which work by passing in the PartnerLocations of a Partner in an Argument
        /// and which return a <see cref="TLocationPK" />. As those Methods don't access the database, these Methods
        /// can be used client-side as well!</remarks>
        /// <param name="APartnerKey">PartnerKey of the Partner whose addresses should be checked.</param>
        /// <param name="APartnerLocationDR">PPartnerLocation Record that is the record that is the Location of the 'Best Address'.</param>
        /// <param name="ALocationDR">PLocation Record that the 'Best Address' is pointing to.</param>
        /// <param name="ADataBase">An instantiated <see cref="TDataBase" /> object, or null (default = null). If null
        /// gets passed then the Method executes DB commands with a new Database connection</param>
        /// <returns>A <see cref="TLocationPK" /> which points to the 'Best Address'. If no 'Best Address' was found,
        /// SiteKey and LocationKey of this instance will be both -1.</returns>
        public static TLocationPK DetermineBestAddress(Int64 APartnerKey, out PPartnerLocationRow APartnerLocationDR,
                                                       out PLocationRow ALocationDR, TDataBase ADataBase = null)
        {
            PLocationTable LocationDT;
            TLocationPK    BestLocation = new TLocationPK();
            Boolean        NewTransaction;

            APartnerLocationDR = null;
            ALocationDR        = null;

            BestLocation = DetermineBestAddress(APartnerKey, out APartnerLocationDR);

            TDataBase      db = DBAccess.Connect("DetermineBestAddress", ADataBase);
            TDBTransaction ReadTransaction = db.GetNewOrExistingTransaction(
                MCommonConstants.CACHEABLEDT_ISOLATIONLEVEL,
                out NewTransaction);

            try
            {
                LocationDT = PLocationAccess.LoadByPrimaryKey(BestLocation.SiteKey, BestLocation.LocationKey, ReadTransaction);

                if (LocationDT.Rows.Count > 0)
                {
                    ALocationDR = LocationDT[0];
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "ServerCalculations.DetermineBestAddress: commited own transaction.");
                }
            }

            return(BestLocation);
        }
Ejemplo n.º 13
0
        public void ForeignCurrencySupplier_ExpectDocumentPostingAndPayingWorking()
        {
            //
            // Arrange
            //
            int PaymentNumber;

            List <int> DocumentIDs;
            decimal    APAccountBalanceBefore;
            decimal    BankAccountBefore;
            decimal    RevalAccountBefore;

            CommonNUnitFunctions.ResetDatabase();
            TPetraServerConnector.Connect();

            TDataBase      db          = DBAccess.Connect("ForeignCurrencySupplier_ExpectDocumentPostingPayingAndReversingWorking");
            TDBTransaction transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // Act and Assert: both encapsulated in the method that gets called!
            PostAndPayForeignSupplierAPDocument("Test", out PaymentNumber, out DocumentIDs,
                                                out APAccountBalanceBefore, out BankAccountBefore, out RevalAccountBefore, db);

            transaction.Commit();
        }
Ejemplo n.º 14
0
        public void TestDeleteBank()
        {
            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;
            String               TextMessage;
            Boolean              CanDeletePartner;
            PPartnerRow          BankPartnerRow;
            TSubmitChangesResult result;
            Int64 PartnerKey;

            TDataBase               db          = DBAccess.Connect("TestDeleteBank");
            TDBTransaction          Transaction = db.BeginTransaction(IsolationLevel.Serializable);
            TPartnerEditUIConnector connector   = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            BankPartnerRow = TCreateTestPartnerData.CreateNewBankPartner(MainDS, db);
            result         = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create bank record");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // check if Bank partner can be deleted (still needs to be possible at this point)
            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(BankPartnerRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(CanDeletePartner);

            // set up details (e.g. bank account) for this Bank so deletion is not allowed
            PBankingDetailsTable BankingDetailsTable = new PBankingDetailsTable();
            PBankingDetailsRow   BankingDetailsRow   = BankingDetailsTable.NewRowTyped();

            BankingDetailsRow.BankKey           = BankPartnerRow.PartnerKey;
            BankingDetailsRow.BankingType       = 0;
            BankingDetailsRow.BankingDetailsKey = Convert.ToInt32(TSequenceWebConnector.GetNextSequence(TSequenceNames.seq_bank_details, db));
            BankingDetailsTable.Rows.Add(BankingDetailsRow);

            Transaction.Commit();

            bool SubmitOK = false;

            db.WriteTransaction(ref Transaction, ref SubmitOK,
                                delegate
            {
                PBankingDetailsAccess.SubmitChanges(BankingDetailsTable, Transaction);
                SubmitOK = true;
            });

            // now deletion must not be possible since a bank account is set up for the bank
            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(BankPartnerRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(!CanDeletePartner);

            // now test actual deletion of venue partner
            BankPartnerRow = TCreateTestPartnerData.CreateNewBankPartner(MainDS, db);
            PartnerKey     = BankPartnerRow.PartnerKey;
            result         = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create bank partner for deletion");

            // check if Venue record is being deleted
            Assert.IsTrue(TPartnerWebConnector.DeletePartner(PartnerKey, out VerificationResult, db));

            // check that Bank record is really deleted
            Assert.IsTrue(!TPartnerServerLookups.VerifyPartner(PartnerKey));
        }
Ejemplo n.º 15
0
        public void TestDeletePerson()
        {
            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;
            String               TextMessage;
            Boolean              CanDeletePartner;
            PPartnerRow          FamilyPartnerRow;
            PPartnerRow          UnitPartnerRow;
            PPersonRow           PersonRow;
            TSubmitChangesResult result;
            Int64 PartnerKey;

            TDataBase               db          = DBAccess.Connect("TestDeleteFamily");
            TDBTransaction          Transaction = db.BeginTransaction(IsolationLevel.Serializable);
            TPartnerEditUIConnector connector   = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            // create new family, location and person
            FamilyPartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);
            TCreateTestPartnerData.CreateNewLocation(FamilyPartnerRow.PartnerKey, MainDS);
            PersonRow = TCreateTestPartnerData.CreateNewPerson(MainDS,
                                                               FamilyPartnerRow.PartnerKey,
                                                               MainDS.PLocation[0].LocationKey,
                                                               "Mike",
                                                               "Mr",
                                                               0,
                                                               db);

            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create family and person record");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // check if Family partner can be deleted (still needs to be possible at this point)
            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(PersonRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(CanDeletePartner);

            // add a commitment for the person which means the person is not allowed to be deleted any longer
            UnitPartnerRow = TCreateTestPartnerData.CreateNewUnitPartner(MainDS, db);
            PmStaffDataTable CommitmentTable = new PmStaffDataTable();
            PmStaffDataRow   CommitmentRow   = CommitmentTable.NewRowTyped();

            CommitmentRow.Key               = Convert.ToInt32(TSequenceWebConnector.GetNextSequence(TSequenceNames.seq_staff_data, db));
            CommitmentRow.PartnerKey        = PersonRow.PartnerKey;
            CommitmentRow.StartOfCommitment = DateTime.Today.Date;
            CommitmentRow.EndOfCommitment   = DateTime.Today.AddDays(90).Date;
            CommitmentRow.OfficeRecruitedBy = UnitPartnerRow.PartnerKey;
            CommitmentRow.HomeOffice        = UnitPartnerRow.PartnerKey;
            CommitmentRow.ReceivingField    = UnitPartnerRow.PartnerKey;
            CommitmentTable.Rows.Add(CommitmentRow);

            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create unit to be used in commitment");
            PmStaffDataAccess.SubmitChanges(CommitmentTable, Transaction);
            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // this should now not be allowed since person record has a commitment linked to it
            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(PersonRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(!CanDeletePartner);

            // now test actual deletion of Person partner
            FamilyPartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);
            TCreateTestPartnerData.CreateNewLocation(FamilyPartnerRow.PartnerKey, MainDS);
            PersonRow = TCreateTestPartnerData.CreateNewPerson(MainDS,
                                                               FamilyPartnerRow.PartnerKey,
                                                               MainDS.PLocation[0].LocationKey,
                                                               "Mary",
                                                               "Mrs",
                                                               0,
                                                               db);
            PartnerKey = PersonRow.PartnerKey;

            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create family and person record to be deleted");

            Transaction.Commit();

            // check if Family record is being deleted
            Assert.IsTrue(TPartnerWebConnector.DeletePartner(PartnerKey, out VerificationResult));

            // check that Family record is really deleted
            Assert.IsTrue(!TPartnerServerLookups.VerifyPartner(PartnerKey));
        }
Ejemplo n.º 16
0
        public void TestDeleteFamily()
        {
            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;
            String               TextMessage;
            Boolean              CanDeletePartner;
            PPartnerRow          FamilyPartnerRow;
            PFamilyRow           FamilyRow;
            PPersonRow           PersonRow;
            TSubmitChangesResult result;
            Int64 PartnerKey;

            TDataBase      db          = DBAccess.Connect("TestDeleteFamily");
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            TPartnerEditUIConnector connector = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            FamilyPartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);
            result           = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "Create family record");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // check if Family partner can be deleted (still needs to be possible at this point)
            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(FamilyPartnerRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(CanDeletePartner);

            // add a person to the family which means the family is not allowed to be deleted any longer
            FamilyRow = (PFamilyRow)MainDS.PFamily.Rows[0];
            FamilyRow.FamilyMembers = true;
            TCreateTestPartnerData.CreateNewLocation(FamilyPartnerRow.PartnerKey, MainDS);
            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create new location");

            PartnerEditTDS PersonDS = new PartnerEditTDS();

            PersonRow = TCreateTestPartnerData.CreateNewPerson(PersonDS, FamilyPartnerRow.PartnerKey,
                                                               MainDS.PLocation[0].LocationKey, "Adam", "Mr", 0, db);
            PersonRow.FamilyKey = FamilyPartnerRow.PartnerKey;
            result = connector.SubmitChanges(ref PersonDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create person record");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(FamilyPartnerRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(!CanDeletePartner);


            // create new family and create subscription given as gift from this family: not allowed to be deleted
            FamilyPartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);
            PPublicationTable PublicationTable = PPublicationAccess.LoadByPrimaryKey("TESTPUBLICATION", Transaction);

            if (PublicationTable.Count == 0)
            {
                // first check if frequency "Annual" exists and if not then create it
                if (!AFrequencyAccess.Exists("Annual", Transaction))
                {
                    // set up details (e.g. bank account) for this Bank so deletion is not allowed
                    AFrequencyTable FrequencyTable = new AFrequencyTable();
                    AFrequencyRow   FrequencyRow   = FrequencyTable.NewRowTyped();
                    FrequencyRow.FrequencyCode        = "Annual";
                    FrequencyRow.FrequencyDescription = "Annual Frequency";
                    FrequencyTable.Rows.Add(FrequencyRow);

                    AFrequencyAccess.SubmitChanges(FrequencyTable, Transaction);
                }

                // now add the publication "TESTPUBLICATION"
                PPublicationRow PublicationRow = PublicationTable.NewRowTyped();
                PublicationRow.PublicationCode = "TESTPUBLICATION";
                PublicationRow.FrequencyCode   = "Annual";
                PublicationTable.Rows.Add(PublicationRow);

                PPublicationAccess.SubmitChanges(PublicationTable, Transaction);
            }

            // make sure that "reason subscription given" exists
            if (!PReasonSubscriptionGivenAccess.Exists("FREE", Transaction))
            {
                // set up details (e.g. bank account) for this Bank so deletion is not allowed
                PReasonSubscriptionGivenTable ReasonTable = new PReasonSubscriptionGivenTable();
                PReasonSubscriptionGivenRow   ReasonRow   = ReasonTable.NewRowTyped();
                ReasonRow.Code        = "FREE";
                ReasonRow.Description = "Free Subscription";
                ReasonTable.Rows.Add(ReasonRow);

                PReasonSubscriptionGivenAccess.SubmitChanges(ReasonTable, Transaction);
            }

            // now add the publication "TESTPUBLICATION" to the first family record and indicate it was a gift from newly created family record
            PSubscriptionRow SubscriptionRow = MainDS.PSubscription.NewRowTyped();

            SubscriptionRow.PublicationCode     = "TESTPUBLICATION";
            SubscriptionRow.PartnerKey          = FamilyRow.PartnerKey;        // link subscription with original family
            SubscriptionRow.GiftFromKey         = FamilyPartnerRow.PartnerKey; // indicate that subscription is a gift from newly created family
            SubscriptionRow.ReasonSubsGivenCode = "FREE";
            MainDS.PSubscription.Rows.Add(SubscriptionRow);

            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "add publication to family record");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // this should now not be allowed since partner record has a subscription linked to it
            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(FamilyPartnerRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(!CanDeletePartner);

            // now test actual deletion of Family partner
            FamilyPartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);
            PartnerKey       = FamilyPartnerRow.PartnerKey;
            result           = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create family record");

            Transaction.Commit();

            // check if Family record is being deleted
            Assert.IsTrue(TPartnerWebConnector.DeletePartner(PartnerKey, out VerificationResult, db));

            // check that Family record is really deleted
            Assert.IsTrue(!TPartnerServerLookups.VerifyPartner(PartnerKey));
        }
Ejemplo n.º 17
0
        public void TestNewPartnerWithLocation0()
        {
            TDataBase               db          = DBAccess.Connect("TestNewPartnerWithLocation0");
            TDBTransaction          Transaction = db.BeginTransaction(IsolationLevel.Serializable);
            TPartnerEditUIConnector connector   = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            PPartnerRow PartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);

            PPartnerLocationRow PartnerLocationRow = MainDS.PPartnerLocation.NewRowTyped();

            PartnerLocationRow.SiteKey     = DomainManager.GSiteKey;
            PartnerLocationRow.PartnerKey  = PartnerRow.PartnerKey;
            PartnerLocationRow.LocationKey = 0;
            MainDS.PPartnerLocation.Rows.Add(PartnerLocationRow);

            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving:");

            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "Create a partner with location 0");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            TCreateTestPartnerData.CreateNewLocation(PartnerRow.PartnerKey, MainDS);

            // remove location 0, same is done in csharp\ICT\Petra\Client\MCommon\logic\UC_PartnerAddresses.cs TUCPartnerAddressesLogic::AddRecord
            // Check if record with PartnerLocation.LocationKey = 0 is around > delete it
            DataRow PartnerLocationRecordZero =
                MainDS.PPartnerLocation.Rows.Find(new object[] { PartnerRow.PartnerKey, DomainManager.GSiteKey, 0 });

            if (PartnerLocationRecordZero != null)
            {
                DataRow LocationRecordZero = MainDS.PLocation.Rows.Find(new object[] { DomainManager.GSiteKey, 0 });

                if (LocationRecordZero != null)
                {
                    LocationRecordZero.Delete();
                }

                PartnerLocationRecordZero.Delete();
            }

            ResponseDS = new PartnerEditTDS();
            result     = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving:");

            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "Replace location 0 of partner");

            Assert.AreEqual(1, MainDS.PPartnerLocation.Rows.Count, "the partner should only have one location in the dataset");

            Transaction.Commit();

            // get all addresses of the partner
            TDBTransaction ReadTransaction = new TDBTransaction();

            db.ReadTransaction(
                ref ReadTransaction,
                delegate
            {
                PPartnerLocationTable testPartnerLocations = PPartnerLocationAccess.LoadViaPPartner(PartnerRow.PartnerKey, ReadTransaction);
                Assert.AreEqual(1, testPartnerLocations.Rows.Count, "the partner should only have one location");
                Assert.Greater(testPartnerLocations[0].LocationKey, 0, "TPartnerEditUIConnector SubmitChanges returns valid location key");
            });
        }
Ejemplo n.º 18
0
        public void Test_YearEnd()
        {
            intLedgerNumber = CommonNUnitFunctions.CreateNewLedger();
            TDataBase db = DBAccess.Connect("Test_YearEnd");

            TLedgerInfo LedgerInfo = new TLedgerInfo(intLedgerNumber, db);

            Assert.AreEqual(0, LedgerInfo.CurrentFinancialYear, "Before YearEnd, we should be in year 0");

            TAccountPeriodInfo periodInfo = new TAccountPeriodInfo(intLedgerNumber, 1);

            Assert.AreEqual(new DateTime(DateTime.Now.Year,
                                         1,
                                         1), periodInfo.PeriodStartDate, "Calendar from base database should start with January 1st of this year");

            CommonNUnitFunctions.LoadTestDataBase("csharp\\ICT\\Testing\\lib\\MFinance\\server\\GL\\test-sql\\gl-test-year-end.sql", intLedgerNumber);

            TDBTransaction TestBatchTransaction = db.BeginTransaction(IsolationLevel.Serializable, -1, "Test_YearEnd.PrepareBatches");

            TCommonAccountingTool commonAccountingTool =
                new TCommonAccountingTool(intLedgerNumber, "NUNIT", db);

            commonAccountingTool.AddBaseCurrencyJournal();
            commonAccountingTool.JournalDescription = "Test Data accounts";
            string strAccountGift    = "0200";
            string strAccountBank    = "6200";
            string strAccountExpense = "4100";

            // Accounting of some gifts ...
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, "4301", "Gift Example", "Debit", MFinanceConstants.IS_DEBIT, 100);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, "4302", "Gift Example", "Debit", MFinanceConstants.IS_DEBIT, 200);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, "4303", "Gift Example", "Debit", MFinanceConstants.IS_DEBIT, 300);

            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountGift, "4301", "Gift Example", "Credit", MFinanceConstants.IS_CREDIT, 100);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountGift, "4302", "Gift Example", "Credit", MFinanceConstants.IS_CREDIT, 200);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountGift, "4303", "Gift Example", "Credit", MFinanceConstants.IS_CREDIT, 300);


            // Accounting of some expenses ...

            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountExpense, "4301", "Expense Example", "Debit", MFinanceConstants.IS_DEBIT, 150);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountExpense, "4302", "Expense Example", "Debit", MFinanceConstants.IS_DEBIT, 150);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountExpense, "4303", "Expense Example", "Debit", MFinanceConstants.IS_DEBIT, 200);

            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, "4301", "Expense Example", "Credit", MFinanceConstants.IS_CREDIT, 150);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, "4302", "Expense Example", "Credit", MFinanceConstants.IS_CREDIT, 150);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, "4303", "Expense Example", "Credit", MFinanceConstants.IS_CREDIT, 200);

            TVerificationResultCollection verificationResult = new TVerificationResultCollection();

            commonAccountingTool.CloseSaveAndPost(verificationResult, db); // returns true if posting seemed to work

            TestBatchTransaction.Commit();

            bool blnLoop = true;

            while (blnLoop)
            {
                TDBTransaction PeriodEndTransaction = db.BeginTransaction(IsolationLevel.Serializable, -1, "Test_2YearEnds.PeriodEnd");
                TLedgerInfo    LedgerInfo2          = new TLedgerInfo(intLedgerNumber, db);

                if (LedgerInfo2.ProvisionalYearEndFlag)
                {
                    blnLoop = false;
                }
                else
                {
                    TVerificationResultCollection VerificationResult;
                    List <Int32> glBatchNumbers;
                    Boolean      stewardshipBatch;

                    TPeriodIntervalConnector.PeriodMonthEnd(
                        intLedgerNumber, false,
                        out glBatchNumbers,
                        out stewardshipBatch,
                        out VerificationResult,
                        db);
                    CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                        "Running MonthEnd gave critical error");
                }

                PeriodEndTransaction.Commit();
            }

            // check before year end that income and expense accounts are not 0
            int intYear = 0;

            CheckGLMEntry(intLedgerNumber, intYear, strAccountBank,
                          -50, 0, 50, 0, 100, 0);
            CheckGLMEntry(intLedgerNumber, intYear, strAccountExpense,
                          150, 0, 150, 0, 200, 0);
            CheckGLMEntry(intLedgerNumber, intYear, strAccountGift,
                          100, 0, 200, 0, 300, 0);

            // test that we cannot post to period 12 anymore, all periods are closed?
            LedgerInfo = new TLedgerInfo(intLedgerNumber, db);
            Assert.AreEqual(true, LedgerInfo.ProvisionalYearEndFlag, "Provisional YearEnd flag should be set");


            List <Int32>   glBatches    = new List <int>();
            TDBTransaction transaction  = new TDBTransaction();
            bool           SubmissionOK = false;

            db.WriteTransaction(
                ref transaction,
                ref SubmissionOK,
                delegate
            {
                //
                // Reallocation is never called explicitly like this - it's not really appropriate
                // because I'm about to call it again as part of YearEnd, below.
                // But a tweak in the reallocation code means that it should now cope with being called twice.
                TReallocation reallocation = new TReallocation(LedgerInfo, glBatches, transaction);
                reallocation.VerificationResultCollection = verificationResult;
                reallocation.IsInInfoMode = false;
                reallocation.RunOperation();
                SubmissionOK = true;
            });

            // check amounts after reallocation
            CheckGLMEntry(intLedgerNumber, intYear, strAccountBank,
                          -50, 0, 50, 0, 100, 0);
            CheckGLMEntry(intLedgerNumber, intYear, strAccountExpense,
                          0, -150, 0, -150, 0, -200);
            CheckGLMEntry(intLedgerNumber, intYear, strAccountGift,
                          0, -100, 0, -200, 0, -300);

            // first run in info mode
            TPeriodIntervalConnector.PeriodYearEnd(intLedgerNumber, true,
                                                   out glBatches,
                                                   out verificationResult, db);
            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(verificationResult,
                                                                                "YearEnd test should not have critical errors");

            transaction = db.BeginTransaction(IsolationLevel.Serializable);
            // now run for real
            TPeriodIntervalConnector.PeriodYearEnd(intLedgerNumber, false,
                                                   out glBatches,
                                                   out verificationResult, db);
            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(verificationResult,
                                                                                "YearEnd should not have critical errors");

            transaction.Commit();
            transaction = db.BeginTransaction(IsolationLevel.ReadCommitted);

            ++intYear;
            // check after year end that income and expense accounts are 0, bank account remains
            CheckGLMEntry(intLedgerNumber, intYear, strAccountBank,
                          -50, 0, 50, 0, 100, 0);
            CheckGLMEntry(intLedgerNumber, intYear, strAccountExpense,
                          0, 0, 0, 0, 0, 0);
            CheckGLMEntry(intLedgerNumber, intYear, strAccountGift,
                          0, 0, 0, 0, 0, 0);

            // also check the glm period records
            CheckGLMPeriodEntry(intLedgerNumber, intYear, 1, strAccountBank,
                                -50, 50, 100, db);
            CheckGLMPeriodEntry(intLedgerNumber, intYear, 1, strAccountExpense,
                                0, 0, 0, db);
            CheckGLMPeriodEntry(intLedgerNumber, intYear, 1, strAccountGift,
                                0, 0, 0, db);

            // 9700 is the account that the expenses and income from last year is moved to
            TGlmInfo glmInfo = new TGlmInfo(intLedgerNumber, intYear, "9700", db);

            glmInfo.Reset();
            Assert.IsTrue(glmInfo.MoveNext(), "9700 account not found");

            Assert.AreEqual(100, glmInfo.YtdActualBase);
            Assert.AreEqual(0, glmInfo.ClosingPeriodActualBase);

            LedgerInfo = new TLedgerInfo(intLedgerNumber, db);
            Assert.AreEqual(1, LedgerInfo.CurrentFinancialYear, "After YearEnd, we are in a new financial year");
            Assert.AreEqual(1, LedgerInfo.CurrentPeriod, "After YearEnd, we are in Period 1");
            Assert.AreEqual(false, LedgerInfo.ProvisionalYearEndFlag, "After YearEnd, ProvisionalYearEnd flag should not be set");

            periodInfo = new TAccountPeriodInfo(intLedgerNumber, 1, db);
            Assert.AreEqual(new DateTime(DateTime.Now.Year + 1,
                                         1,
                                         1), periodInfo.PeriodStartDate, "new Calendar should start with January 1st of next year");
            transaction.Rollback();
        }
Ejemplo n.º 19
0
        public void Test_2YearEnds()
        {
            intLedgerNumber = CommonNUnitFunctions.CreateNewLedger();
            CommonNUnitFunctions.LoadTestDataBase("csharp\\ICT\\Testing\\lib\\MFinance\\server\\GL\\test-sql\\gl-test-year-end.sql", intLedgerNumber);
            TDataBase db = DBAccess.Connect("Test_2YearEnds");

            for (int countYear = 0; countYear < 2; countYear++)
            {
                TLogging.Log("preparing year number " + countYear.ToString());

                TDBTransaction TestBatchTransaction = db.BeginTransaction(IsolationLevel.Serializable, -1, "Test_2YearEnds.PrepareBatches");

                // accounting one gift
                string strAccountGift = "0200";
                string strAccountBank = "6200";
                TCommonAccountingTool commonAccountingTool =
                    new TCommonAccountingTool(intLedgerNumber, "NUNIT", db);
                commonAccountingTool.AddBaseCurrencyJournal();
                commonAccountingTool.JournalDescription = "Test Data accounts";
                commonAccountingTool.AddBaseCurrencyTransaction(
                    strAccountBank, "4301", "Gift Example", "Debit", MFinanceConstants.IS_DEBIT, 100);
                commonAccountingTool.AddBaseCurrencyTransaction(
                    strAccountGift, "4301", "Gift Example", "Credit", MFinanceConstants.IS_CREDIT, 100);
                TVerificationResultCollection verificationResult = new TVerificationResultCollection();
                Boolean PostedOk = commonAccountingTool.CloseSaveAndPost(verificationResult, db); // returns true if posting seemed to work
                Assert.AreEqual(true, PostedOk, "Test batch can't be posted");

                TestBatchTransaction.Commit();

                bool blnLoop = true;

                while (blnLoop)
                {
                    TDBTransaction PeriodEndTransaction = db.BeginTransaction(IsolationLevel.Serializable, -1, "Test_2YearEnds.PeriodEnd");
                    TLedgerInfo    LedgerInfo           = new TLedgerInfo(intLedgerNumber, db);

                    if (LedgerInfo.ProvisionalYearEndFlag)
                    {
                        blnLoop = false;
                    }
                    else
                    {
                        List <Int32> glBatchNumbers;
                        Boolean      stewardshipBatch;
                        TVerificationResultCollection VerificationResult;

                        TPeriodIntervalConnector.PeriodMonthEnd(
                            intLedgerNumber,
                            false,
                            out glBatchNumbers,
                            out stewardshipBatch,
                            out VerificationResult,
                            db);
                        CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                            "MonthEnd gave critical error at Period" + LedgerInfo.CurrentPeriod + ":\r\n");
                    }

                    PeriodEndTransaction.Commit();
                }

                TDBTransaction transaction  = new TDBTransaction();
                bool           SubmissionOK = false;

                db.WriteTransaction(
                    ref transaction,
                    ref SubmissionOK,
                    delegate
                {
                    TLedgerInfo LedgerInfo = new TLedgerInfo(intLedgerNumber, db);

                    TLogging.Log("Closing year number " + countYear.ToString());
                    List <Int32> glBatches     = new List <int>();
                    TReallocation reallocation = new TReallocation(LedgerInfo, glBatches, transaction);
                    verificationResult         = new TVerificationResultCollection();
                    reallocation.VerificationResultCollection = verificationResult;
                    reallocation.IsInInfoMode = false;
                    //                Assert.AreEqual(1, reallocation.GetJobSize(), "Check 1 reallocation job is required"); // No job size is published by Reallocation
                    reallocation.RunOperation();

                    TYearEnd YearEndOperator       = new TYearEnd(LedgerInfo);
                    TGlmNewYearInit glmNewYearInit = new TGlmNewYearInit(LedgerInfo, countYear, YearEndOperator, transaction);
                    glmNewYearInit.VerificationResultCollection = verificationResult;
                    glmNewYearInit.IsInInfoMode = false;
                    //              Assert.Greater(glmNewYearInit.GetJobSize(), 0, "Check that NewYearInit has work to do"); // in this version, GetJobSize returns 0
                    glmNewYearInit.RunOperation();
                    YearEndOperator.SetNextPeriod(transaction);
                    SubmissionOK = true;
                });
            }

            TLedgerInfo LedgerInfo2 = new TLedgerInfo(intLedgerNumber, db);

            Assert.AreEqual(2, LedgerInfo2.CurrentFinancialYear, "After YearEnd, Ledger is in year 2");

            TAccountPeriodInfo periodInfo = new TAccountPeriodInfo(intLedgerNumber, 1);

            Assert.AreEqual(new DateTime(DateTime.Now.Year + 2,
                                         1,
                                         1), periodInfo.PeriodStartDate, "new Calendar should start with January 1st of next year");
        } // Test_2YearEnds
Ejemplo n.º 20
0
        public void TestBankingDetails()
        {
            TDataBase               db          = DBAccess.Connect("TestBankingDetails");
            TDBTransaction          Transaction = db.BeginTransaction(IsolationLevel.Serializable);
            TPartnerEditUIConnector connector   = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            PPartnerRow PartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);

            TCreateTestPartnerData.CreateNewLocation(PartnerRow.PartnerKey, MainDS);

            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving:");

            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "TPartnerEditUIConnector SubmitChanges return value");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            connector = new TPartnerEditUIConnector(PartnerRow.PartnerKey, db);

            // add a banking detail
            PartnerEditTDSPBankingDetailsRow bankingDetailsRow = MainDS.PBankingDetails.NewRowTyped(true);

            bankingDetailsRow.AccountName       = "account of " + PartnerRow.PartnerShortName;
            bankingDetailsRow.BankAccountNumber = new Random().Next().ToString();
            bankingDetailsRow.BankingDetailsKey = (MainDS.PBankingDetails.Count + 1) * -1;
            bankingDetailsRow.BankKey           = 43005004;
            bankingDetailsRow.MainAccount       = true;
            bankingDetailsRow.BankingType       = MPartnerConstants.BANKINGTYPE_BANKACCOUNT;
            MainDS.PBankingDetails.Rows.Add(bankingDetailsRow);

            PPartnerBankingDetailsRow partnerBankingDetails = MainDS.PPartnerBankingDetails.NewRowTyped(true);

            partnerBankingDetails.PartnerKey        = PartnerRow.PartnerKey;
            partnerBankingDetails.BankingDetailsKey = bankingDetailsRow.BankingDetailsKey;
            MainDS.PPartnerBankingDetails.Rows.Add(partnerBankingDetails);

            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving 2:");

            foreach (DataTable t in MainDS.Tables)
            {
                if ((t == MainDS.PBankingDetails) ||
                    (t == MainDS.PPartnerBankingDetails) ||
                    (t == MainDS.PDataLabelValuePartner))
                {
                    int NumRows = t.Rows.Count;

                    for (int RowIndex = NumRows - 1; RowIndex >= 0; RowIndex -= 1)
                    {
                        DataRow InspectDR = t.Rows[RowIndex];

                        // delete all added Rows.
                        if (InspectDR.RowState == DataRowState.Added)
                        {
                            InspectDR.Delete();
                        }
                    }
                }
            }

            MainDS.AcceptChanges();

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            Assert.AreEqual(1, PBankingDetailsUsageAccess.CountViaPPartner(PartnerRow.PartnerKey, Transaction), "count of main accounts for partner");

            // add another account
            bankingDetailsRow                   = MainDS.PBankingDetails.NewRowTyped(true);
            bankingDetailsRow.AccountName       = "2nd account of " + PartnerRow.PartnerShortName;
            bankingDetailsRow.BankAccountNumber = new Random().Next().ToString();
            bankingDetailsRow.BankingDetailsKey = (MainDS.PBankingDetails.Count + 1) * -1;
            bankingDetailsRow.BankKey           = 43005004;
            bankingDetailsRow.MainAccount       = false;
            bankingDetailsRow.BankingType       = MPartnerConstants.BANKINGTYPE_BANKACCOUNT;
            MainDS.PBankingDetails.Rows.Add(bankingDetailsRow);

            partnerBankingDetails                   = MainDS.PPartnerBankingDetails.NewRowTyped(true);
            partnerBankingDetails.PartnerKey        = PartnerRow.PartnerKey;
            partnerBankingDetails.BankingDetailsKey = bankingDetailsRow.BankingDetailsKey;
            MainDS.PPartnerBankingDetails.Rows.Add(partnerBankingDetails);

            PartnerEditTDS ChangedDS = MainDS.GetChangesTyped(true);

            result = connector.SubmitChanges(ref ChangedDS, ref ResponseDS, out VerificationResult);
            MainDS.Merge(ChangedDS);

            foreach (DataTable t in MainDS.Tables)
            {
                if ((t == MainDS.PBankingDetails) ||
                    (t == MainDS.PPartnerBankingDetails) ||
                    (t == MainDS.PDataLabelValuePartner))
                {
                    int NumRows = t.Rows.Count;

                    for (int RowIndex = NumRows - 1; RowIndex >= 0; RowIndex -= 1)
                    {
                        DataRow InspectDR = t.Rows[RowIndex];

                        // delete all added Rows.
                        if (InspectDR.RowState == DataRowState.Added)
                        {
                            InspectDR.Delete();
                        }
                    }
                }
            }

            MainDS.AcceptChanges();

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving 3:");

            // now delete the main bank account
            PartnerEditTDSPBankingDetailsRow toDelete = null;

            foreach (PartnerEditTDSPBankingDetailsRow row in MainDS.PBankingDetails.Rows)
            {
                if (row.MainAccount)
                {
                    toDelete = row;
                    break;
                }
            }

            Assert.IsNotNull(toDelete, "cannot find main account");
            Assert.AreEqual(true, toDelete.MainAccount, "should be the main account");
            MainDS.PPartnerBankingDetails.Rows.Find(new object[] { PartnerRow.PartnerKey, toDelete.BankingDetailsKey }).Delete();
            toDelete.Delete();

            ChangedDS = MainDS.GetChangesTyped(true);
            result    = connector.SubmitChanges(ref ChangedDS, ref ResponseDS, out VerificationResult);

            Assert.AreEqual(1, VerificationResult.Count, "should fail because we have no main account anymore");
            Assert.AreEqual(
                "One Bank Account of a Partner must be set as the 'Main Account'. Please select the record that should become the 'Main Account' and choose 'Set Main Account'.",
                VerificationResult[0].ResultText,
                "should fail because we have no main account anymore");

            PartnerEditTDSPBankingDetailsRow otherAccount = null;

            foreach (PartnerEditTDSPBankingDetailsRow row in MainDS.PBankingDetails.Rows)
            {
                if ((row.RowState != DataRowState.Deleted) && !row.MainAccount)
                {
                    otherAccount = row;
                    break;
                }
            }

            otherAccount.MainAccount = true;

            ChangedDS = MainDS.GetChangesTyped(true);
            result    = connector.SubmitChanges(ref ChangedDS, ref ResponseDS, out VerificationResult);

            MainDS.Merge(ChangedDS);
            MainDS.AcceptChanges();

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving 4:");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // now delete the last remaining bank account
            toDelete = MainDS.PBankingDetails[0];
            Assert.AreEqual(true, toDelete.MainAccount);
            MainDS.PPartnerBankingDetails.Rows.Find(new object[] { PartnerRow.PartnerKey, toDelete.BankingDetailsKey }).Delete();
            toDelete.Delete();
            ChangedDS = MainDS.GetChangesTyped(true);
            result    = connector.SubmitChanges(ref ChangedDS, ref ResponseDS, out VerificationResult);
            MainDS.Merge(ChangedDS);
            MainDS.AcceptChanges();

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving 5:");

            Transaction.Commit();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Records the logging-out (=disconnection) of a Client to the s_login DB Table. That DB Table contains a log
        /// of all the log-ins/log-in attempts to the system, and of log-outs from the system.
        /// </summary>
        /// <param name="AUserID">UserID of the User for which a logout should be recorded.</param>
        /// <param name="AProcessID">ProcessID of the User for which a logout should be recorded.
        /// This will need to be the number that got returned from an earlier call to
        /// <see cref="AddLoginLogEntry(string, string, string, out int, TDBTransaction)"/>!</param>
        /// <param name="ATransaction">Either an instantiated DB Transaction, or null. In the latter case
        /// a separate DB Connection gets opened, a DB Transaction on that separate DB Connection gets started,
        /// then committed/rolled back and the separate DB Connection gets closed. This is needed when this Method
        /// gets called from Method 'Ict.Common.Remoting.Server.TDisconnectClientThread.StartClientDisconnection()'!</param>
        public void RecordUserLogout(String AUserID, int AProcessID, TDBTransaction ATransaction)
        {
            TDataBase      DBConnectionObj  = null;
            TDBTransaction WriteTransaction = new TDBTransaction();
            SLoginTable    LoginTable       = new SLoginTable();
            SLoginRow      NewLoginRow      = LoginTable.NewRowTyped(false);
            bool           SubmissionOK     = false;
            DateTime       LogoutDateTime   = DateTime.Now;

            // Set DataRow values
            NewLoginRow.LoginProcessId    = -1;
            NewLoginRow.UserId            = AUserID.ToUpper();
            NewLoginRow.LoginType         = LOGIN_STATUS_TYPE_LOGOUT;
            NewLoginRow.LoginDetails      = Catalog.GetString("User logout.");
            NewLoginRow.LoginProcessIdRef = AProcessID;
            NewLoginRow.Date = LogoutDateTime.Date;
            NewLoginRow.Time = Conversions.DateTimeToInt32Time(LogoutDateTime);

            //TLogging.Log(String.Format("RecordUserLogout: NewLoginRow.Date: {0}; NewLoginRow.Time: {1}",
            //    NewLoginRow.Date, NewLoginRow.Time));

            LoginTable.Rows.Add(NewLoginRow);

            if (ATransaction == null)
            {
                // Open a separate DB Connection (necessary because this Method gets executed in the Server's (Main) AppDomain
                // which hasn't got an instance of DBAccess.GDBAccess!) ...
                DBConnectionObj = DBAccess.Connect("RecordUserLogout");

                // ...and start a DB Transaction on that separate DB Connection
                WriteTransaction = DBConnectionObj.BeginTransaction(IsolationLevel.RepeatableRead, 0, "RecordUserLogout");
            }
            else
            {
                DBConnectionObj  = ATransaction.DataBaseObj;
                WriteTransaction = ATransaction;
            }

            try
            {
                try
                {
                    SLoginAccess.SubmitChanges(LoginTable, WriteTransaction);

                    SubmissionOK = true;
                }
                catch (Exception Exc)
                {
                    TLogging.Log("RecordUserLogout: An Exception occured during the saving of a Login Log entry:" +
                                 Environment.NewLine + Exc.ToString());

                    throw;
                }
            }
            finally
            {
                if (SubmissionOK)
                {
                    ATransaction.Commit();
                }
                else
                {
                    ATransaction.Rollback();
                }

                if (DBConnectionObj != null)
                {
                    DBConnectionObj.CloseDBConnection();
                }
            }
        }