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

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

            TDBTransaction Transaction = new TDBTransaction();

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

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

                ForexGainsLossesAccount = LedgerTable[0].ForexGainsLossesAccount;

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

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

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

            // if DateEffective is outside the range of open periods, use the most fitting date
            TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber,
                                                      ref ADateEffective,
                                                      out BatchYear,
                                                      out BatchPeriod,
                                                      Transaction,
                                                      AForceEffectiveDateToFit);
            NewRow.BatchYear          = BatchYear;
            NewRow.BatchPeriod        = BatchPeriod;
            NewRow.GlEffectiveDate    = ADateEffective;
            NewRow.ExchangeRateToBase = 1.0M;
            NewRow.BatchDescription   = "PLEASE ENTER A DESCRIPTION";
            NewRow.BankAccountCode    = TLedgerInfo.GetDefaultBankAccount(ALedgerNumber);
            NewRow.BankCostCentre     = TLedgerInfo.GetStandardCostCentre(ALedgerNumber);
            NewRow.CurrencyCode       = LedgerTable[0].BaseCurrency;
            MainDS.AGiftBatch.Rows.Add(NewRow);
            return(NewRow);
        }
        /// <summary>
        /// post and pay all invoices in the given period, but leave some (or none) unposted
        /// </summary>
        public static bool PostAndPayInvoices(int AYear, int APeriod, int ALeaveInvoicesUnposted = 0)
        {
            TLogging.LogAtLevel(1, "PostAndPayInvoices for year " + AYear.ToString() + " / period " + APeriod.ToString());

            AccountsPayableTDS MainDS = new AccountsPayableTDS();

            string sqlLoadDocuments =
                "SELECT * FROM PUB_a_ap_document WHERE a_ledger_number_i = ? AND a_date_issued_d >= ? AND a_date_issued_d <= ? AND a_document_status_c='APPROVED'";

            DateTime PeriodStartDate, PeriodEndDate;

            TFinancialYear.GetStartAndEndDateOfPeriod(FLedgerNumber, APeriod, out PeriodStartDate, out PeriodEndDate, null);

            List <OdbcParameter> parameters = new List <OdbcParameter>();

            OdbcParameter parameter;

            parameter       = new OdbcParameter("ledgernumber", OdbcType.Int);
            parameter.Value = FLedgerNumber;
            parameters.Add(parameter);
            parameter       = new OdbcParameter("startDate", OdbcType.DateTime);
            parameter.Value = PeriodStartDate;
            parameters.Add(parameter);
            parameter       = new OdbcParameter("endDate", OdbcType.DateTime);
            parameter.Value = PeriodEndDate;
            parameters.Add(parameter);

            DBAccess.GDBAccessObj.SelectDT(MainDS.AApDocument, sqlLoadDocuments, null, parameters.ToArray(), -1, -1);

            int countUnPosted = MainDS.AApDocument.Count;

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

            foreach (AApDocumentRow invoice in MainDS.AApDocument.Rows)
            {
                if (countUnPosted <= ALeaveInvoicesUnposted)
                {
                    break;
                }

                DocumentIdsToPost.Add(invoice.ApDocumentId);

                countUnPosted--;
            }

            TVerificationResultCollection VerificationResult;

            if ((DocumentIdsToPost.Count > 0) &&
                !TAPTransactionWebConnector.PostAPDocuments(FLedgerNumber, DocumentIdsToPost, PeriodEndDate, false, out VerificationResult))
            {
                TLogging.Log(VerificationResult.BuildVerificationResultString());
                return(false);
            }

            // TODO pay the invoices as well

            return(true);
        }
Beispiel #4
0
        private void GetLedgerInfo(out DateTime APeriodStartDate, out DateTime APeriodEndDate,
                                   out string AForexGainsLossesAccount)
        {
            ALedgerTable LedgerTable = null;

            TDBTransaction Transaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                      TEnforceIsolationLevel.eilMinimum,
                                                                      ref Transaction,
                                                                      delegate
            {
                LedgerTable = ALedgerAccess.LoadByPrimaryKey(FLedgerNumber, Transaction);
            });

            AForexGainsLossesAccount = LedgerTable[0].ForexGainsLossesAccount;

            TFinancialYear.GetStartAndEndDateOfPeriod(FLedgerNumber, LedgerTable[0].CurrentPeriod, out APeriodStartDate, out APeriodEndDate, null);
        }
        public void TestPerformStewardshipCalculation()
        {
            TVerificationResultCollection VerificationResults = new TVerificationResultCollection();

            Int32        PeriodNumber             = 5;
            const string CostCentreGIF            = "9500";
            const string CostCentreReceivingField = "7300";

            // run possibly empty stewardship calculation, to process all gifts that do not belong to this test
            TStewardshipCalculationWebConnector.PerformStewardshipCalculation(FLedgerNumber,
                                                                              PeriodNumber, out VerificationResults);
            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResults,
                                                                                "Performing initial Stewardship Calculation Failed!");

            // make sure we have some admin fees
            ImportAdminFees();

            decimal AdminGrantIncomeBefore = new TGet_GLM_Info(FLedgerNumber,
                                                               MFinanceConstants.ADMIN_FEE_INCOME_ACCT,
                                                               (FLedgerNumber * 100).ToString("0000")).YtdActual;
            decimal GIFBefore = new TGet_GLM_Info(FLedgerNumber,
                                                  MFinanceConstants.ICH_ACCT_SETTLEMENT,
                                                  CostCentreGIF).YtdActual;
            decimal RecipientBefore = new TGet_GLM_Info(FLedgerNumber,
                                                        MFinanceConstants.ICH_ACCT_SETTLEMENT,
                                                        CostCentreReceivingField).YtdActual;
            decimal ClearingHouseBefore = new TGet_GLM_Info(FLedgerNumber,
                                                            MFinanceConstants.ICH_ACCT_ICH,
                                                            (FLedgerNumber * 100).ToString("0000")).YtdActual;

            // import new gift batch. use proper period and date effective
            DateTime PeriodStartDate, PeriodEndDate;

            TFinancialYear.GetStartAndEndDateOfPeriod(FLedgerNumber, PeriodNumber, out PeriodStartDate, out PeriodEndDate, null);
            ImportAndPostGiftBatch(PeriodStartDate);

            TStewardshipCalculationWebConnector.PerformStewardshipCalculation(FLedgerNumber,
                                                                              PeriodNumber, out VerificationResults);
            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResults,
                                                                                "Performing Stewardship Calculation Failed!");

            // Home office keeps 1.40 => 4300/3400 Admin Grant income
            decimal AdminGrantIncomeAfter = new TGet_GLM_Info(FLedgerNumber,
                                                              MFinanceConstants.ADMIN_FEE_INCOME_ACCT,
                                                              (FLedgerNumber * 100).ToString("0000")).YtdActual;

            Assert.AreEqual(20.0m * 7.0m / 100.0m, AdminGrantIncomeAfter - AdminGrantIncomeBefore,
                            "Home office keeps 7% of 20 Euro gift");

            // GIF should get 0.20 => 9500/5601
            decimal GIFAfter = new TGet_GLM_Info(FLedgerNumber,
                                                 MFinanceConstants.ICH_ACCT_SETTLEMENT,
                                                 CostCentreGIF).YtdActual;

            Assert.AreEqual(20.0m / 100.0m, GIFAfter - GIFBefore,
                            "GIF should get 1% of 20 Euro gift. Before: " + GIFBefore + ", After: " + GIFAfter);

            // Receiving field should get 20-1.60 = 18.40 => 7300/5601
            decimal RecipientAfter = new TGet_GLM_Info(FLedgerNumber,
                                                       MFinanceConstants.ICH_ACCT_SETTLEMENT,
                                                       CostCentreReceivingField).YtdActual;

            Assert.AreEqual(20.0m * (100.0m - 1.0m - 7.0m) / 100.0m, RecipientAfter - RecipientBefore,
                            "Receiving field should get 92% of 20 Euro gift");

            // Clearing House (4300/8500) should receive the money for GIF and receiving field
            decimal ClearingHouseAfter = new TGet_GLM_Info(FLedgerNumber,
                                                           MFinanceConstants.ICH_ACCT_ICH,
                                                           (FLedgerNumber * 100).ToString("0000")).YtdActual;

            Assert.AreEqual(20.0m * (100.0m - 7.0m) / 100.0m, ClearingHouseAfter - ClearingHouseBefore,
                            "We have to give everything apart from our 7% to ICH");
        }
        public static Int32 CreateGLBatch(BankImportTDS AMainDS,
                                          Int32 ALedgerNumber,
                                          Int32 AStatementKey,
                                          Int32 AGLBatchNumber,
                                          out TVerificationResultCollection AVerificationResult)
        {
            AMainDS.AEpTransaction.DefaultView.RowFilter =
                String.Format("{0}={1}",
                              AEpTransactionTable.GetStatementKeyDBName(),
                              AStatementKey);
            AMainDS.AEpStatement.DefaultView.RowFilter =
                String.Format("{0}={1}",
                              AEpStatementTable.GetStatementKeyDBName(),
                              AStatementKey);
            AEpStatementRow stmt = (AEpStatementRow)AMainDS.AEpStatement.DefaultView[0].Row;

            AVerificationResult = null;

            Int32          DateEffectivePeriodNumber, DateEffectiveYearNumber;
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);

            if (!TFinancialYear.IsValidPostingPeriod(ALedgerNumber, stmt.Date, out DateEffectivePeriodNumber, out DateEffectiveYearNumber,
                                                     Transaction))
            {
                string msg = String.Format(Catalog.GetString("Cannot create a GL batch for date {0} since it is not in an open period of the ledger."),
                                           stmt.Date.ToShortDateString());
                TLogging.Log(msg);
                AVerificationResult = new TVerificationResultCollection();
                AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating GL Batch"), msg, TResultSeverity.Resv_Critical));

                DBAccess.GDBAccessObj.RollbackTransaction();
                return(-1);
            }

            Int32 BatchYear, BatchPeriod;

            // if DateEffective is outside the range of open periods, use the most fitting date
            DateTime DateEffective = stmt.Date;

            TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber, ref DateEffective, out BatchYear, out BatchPeriod, Transaction, true);

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

            DBAccess.GDBAccessObj.RollbackTransaction();

            GLBatchTDS GLDS = TGLTransactionWebConnector.CreateABatch(ALedgerNumber);

            ABatchRow glbatchRow = GLDS.ABatch[0];

            glbatchRow.BatchPeriod      = BatchPeriod;
            glbatchRow.DateEffective    = DateEffective;
            glbatchRow.BatchDescription = String.Format(Catalog.GetString("bank import for date {0}"), stmt.Date.ToShortDateString());

            decimal HashTotal   = 0.0M;
            decimal DebitTotal  = 0.0M;
            decimal CreditTotal = 0.0M;

            // TODO: support several journals
            // TODO: support several currencies, support other currencies than the base currency
            AJournalRow gljournalRow = GLDS.AJournal.NewRowTyped();

            gljournalRow.LedgerNumber        = glbatchRow.LedgerNumber;
            gljournalRow.BatchNumber         = glbatchRow.BatchNumber;
            gljournalRow.JournalNumber       = glbatchRow.LastJournal + 1;
            gljournalRow.TransactionCurrency = LedgerTable[0].BaseCurrency;
            glbatchRow.LastJournal++;
            gljournalRow.JournalPeriod       = glbatchRow.BatchPeriod;
            gljournalRow.DateEffective       = glbatchRow.DateEffective;
            gljournalRow.JournalDescription  = glbatchRow.BatchDescription;
            gljournalRow.SubSystemCode       = CommonAccountingSubSystemsEnum.GL.ToString();
            gljournalRow.TransactionTypeCode = CommonAccountingTransactionTypesEnum.STD.ToString();
            gljournalRow.ExchangeRateToBase  = 1.0m;
            GLDS.AJournal.Rows.Add(gljournalRow);

            foreach (DataRowView dv in AMainDS.AEpTransaction.DefaultView)
            {
                AEpTransactionRow transactionRow = (AEpTransactionRow)dv.Row;

                DataView v = AMainDS.AEpMatch.DefaultView;
                v.RowFilter = AEpMatchTable.GetActionDBName() + " = '" + MFinanceConstants.BANK_STMT_STATUS_MATCHED_GL + "' and " +
                              AEpMatchTable.GetMatchTextDBName() + " = '" + transactionRow.MatchText + "'";

                if (v.Count > 0)
                {
                    AEpMatchRow     match = (AEpMatchRow)v[0].Row;
                    ATransactionRow trans = GLDS.ATransaction.NewRowTyped();
                    trans.LedgerNumber      = glbatchRow.LedgerNumber;
                    trans.BatchNumber       = glbatchRow.BatchNumber;
                    trans.JournalNumber     = gljournalRow.JournalNumber;
                    trans.TransactionNumber = gljournalRow.LastTransactionNumber + 1;
                    trans.AccountCode       = match.AccountCode;
                    trans.CostCentreCode    = match.CostCentreCode;
                    trans.Reference         = match.Reference;
                    trans.Narrative         = match.Narrative;
                    trans.TransactionDate   = transactionRow.DateEffective;

                    if (transactionRow.TransactionAmount < 0)
                    {
                        trans.AmountInBaseCurrency = -1 * transactionRow.TransactionAmount;
                        trans.TransactionAmount    = -1 * transactionRow.TransactionAmount;
                        trans.DebitCreditIndicator = true;
                        DebitTotal += trans.AmountInBaseCurrency;
                    }
                    else
                    {
                        trans.AmountInBaseCurrency = transactionRow.TransactionAmount;
                        trans.TransactionAmount    = transactionRow.TransactionAmount;
                        trans.DebitCreditIndicator = false;
                        CreditTotal += trans.AmountInBaseCurrency;
                    }

                    GLDS.ATransaction.Rows.Add(trans);
                    gljournalRow.LastTransactionNumber++;

                    // add one transaction for the bank as well
                    trans = GLDS.ATransaction.NewRowTyped();
                    trans.LedgerNumber      = glbatchRow.LedgerNumber;
                    trans.BatchNumber       = glbatchRow.BatchNumber;
                    trans.JournalNumber     = gljournalRow.JournalNumber;
                    trans.TransactionNumber = gljournalRow.LastTransactionNumber + 1;
                    trans.AccountCode       = stmt.BankAccountCode;
                    trans.CostCentreCode    = TLedgerInfo.GetStandardCostCentre(ALedgerNumber);
                    trans.Reference         = match.Reference;
                    trans.Narrative         = match.Narrative;
                    trans.TransactionDate   = transactionRow.DateEffective;

                    if (transactionRow.TransactionAmount < 0)
                    {
                        trans.AmountInBaseCurrency = -1 * transactionRow.TransactionAmount;
                        trans.TransactionAmount    = -1 * transactionRow.TransactionAmount;
                        trans.DebitCreditIndicator = false;
                        CreditTotal += trans.AmountInBaseCurrency;
                    }
                    else
                    {
                        trans.AmountInBaseCurrency = transactionRow.TransactionAmount;
                        trans.TransactionAmount    = transactionRow.TransactionAmount;
                        trans.DebitCreditIndicator = true;
                        DebitTotal += trans.AmountInBaseCurrency;
                    }

                    GLDS.ATransaction.Rows.Add(trans);
                    gljournalRow.LastTransactionNumber++;
                }
            }

            gljournalRow.JournalDebitTotal  = DebitTotal;
            gljournalRow.JournalCreditTotal = CreditTotal;
            glbatchRow.BatchDebitTotal      = DebitTotal;
            glbatchRow.BatchCreditTotal     = CreditTotal;
            glbatchRow.BatchControlTotal    = HashTotal;

            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = TGLTransactionWebConnector.SaveGLBatchTDS(ref GLDS,
                                                                                    out VerificationResult);

            if (result == TSubmitChangesResult.scrOK)
            {
                return(glbatchRow.BatchNumber);
            }

            TLogging.Log("Problems storing GL Batch");
            return(-1);
        }
        public static Int32 CreateGiftBatch(
            Int32 ALedgerNumber,
            Int32 AStatementKey,
            Int32 AGiftBatchNumber,
            out TVerificationResultCollection AVerificationResult)
        {
            BankImportTDS MainDS = GetBankStatementTransactionsAndMatches(AStatementKey, ALedgerNumber);

            string MyClientID = DomainManager.GClientID.ToString();

            TProgressTracker.InitProgressTracker(MyClientID,
                                                 Catalog.GetString("Creating gift batch"),
                                                 MainDS.AEpTransaction.DefaultView.Count + 10);

            AVerificationResult = new TVerificationResultCollection();

            MainDS.AEpTransaction.DefaultView.RowFilter =
                String.Format("{0}={1}",
                              AEpTransactionTable.GetStatementKeyDBName(),
                              AStatementKey);
            MainDS.AEpStatement.DefaultView.RowFilter =
                String.Format("{0}={1}",
                              AEpStatementTable.GetStatementKeyDBName(),
                              AStatementKey);
            AEpStatementRow stmt = (AEpStatementRow)MainDS.AEpStatement.DefaultView[0].Row;

            // TODO: optional: use the preselected gift batch, AGiftBatchNumber

            Int32          DateEffectivePeriodNumber, DateEffectiveYearNumber;
            DateTime       BatchDateEffective = stmt.Date;
            TDBTransaction Transaction        = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);

            if (!TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber, ref BatchDateEffective, out DateEffectiveYearNumber,
                                                           out DateEffectivePeriodNumber,
                                                           Transaction, true))
            {
                // just use the latest possible date
                string msg =
                    String.Format(Catalog.GetString("Date {0} is not in an open period of the ledger, using date {1} instead for the gift batch."),
                                  stmt.Date.ToShortDateString(),
                                  BatchDateEffective.ToShortDateString());
                AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating Gift Batch"), msg, TResultSeverity.Resv_Info));
            }

            ACostCentreAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
            AMotivationDetailAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);

            MainDS.AEpMatch.DefaultView.Sort =
                AEpMatchTable.GetActionDBName() + ", " +
                AEpMatchTable.GetMatchTextDBName();

            if (MainDS.AEpTransaction.DefaultView.Count == 0)
            {
                AVerificationResult.Add(new TVerificationResult(
                                            Catalog.GetString("Creating Gift Batch"),
                                            String.Format(Catalog.GetString("There are no transactions for statement #{0}."), AStatementKey),
                                            TResultSeverity.Resv_Info));
                return(-1);
            }

            foreach (DataRowView dv in MainDS.AEpTransaction.DefaultView)
            {
                AEpTransactionRow transactionRow = (AEpTransactionRow)dv.Row;

                DataRowView[] matches = MainDS.AEpMatch.DefaultView.FindRows(new object[] {
                    MFinanceConstants.BANK_STMT_STATUS_MATCHED_GIFT,
                    transactionRow.MatchText
                });

                if (matches.Length > 0)
                {
                    AEpMatchRow match = (AEpMatchRow)matches[0].Row;

                    if (match.IsDonorKeyNull() || (match.DonorKey == 0))
                    {
                        string msg =
                            String.Format(Catalog.GetString("Cannot create a gift for transaction {0} since there is no valid donor."),
                                          transactionRow.Description);
                        AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating Gift Batch"), msg, TResultSeverity.Resv_Critical));
                        DBAccess.GDBAccessObj.RollbackTransaction();
                        return(-1);
                    }
                }
            }

            string MatchedGiftReference = stmt.Filename;

            if (!stmt.IsBankAccountKeyNull())
            {
                string sqlGetBankSortCode =
                    "SELECT bank.p_branch_code_c " +
                    "FROM PUB_p_banking_details details, PUB_p_bank bank " +
                    "WHERE details.p_banking_details_key_i = ?" +
                    "AND details.p_bank_key_n = bank.p_partner_key_n";
                OdbcParameter param = new OdbcParameter("detailkey", OdbcType.Int);
                param.Value = stmt.BankAccountKey;

                PBankTable bankTable = new PBankTable();
                DBAccess.GDBAccessObj.SelectDT(bankTable, sqlGetBankSortCode, Transaction, new OdbcParameter[] { param }, 0, 0);

                MatchedGiftReference = bankTable[0].BranchCode + " " + stmt.Date.Day.ToString();
            }

            DBAccess.GDBAccessObj.RollbackTransaction();

            GiftBatchTDS GiftDS = TGiftTransactionWebConnector.CreateAGiftBatch(
                ALedgerNumber,
                BatchDateEffective,
                String.Format(Catalog.GetString("bank import for date {0}"), stmt.Date.ToShortDateString()));

            AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];

            giftbatchRow.BankAccountCode = stmt.BankAccountCode;

            decimal HashTotal = 0.0M;

            MainDS.AEpTransaction.DefaultView.Sort =
                AEpTransactionTable.GetNumberOnPaperStatementDBName();

            MainDS.AEpMatch.DefaultView.RowFilter = String.Empty;
            MainDS.AEpMatch.DefaultView.Sort      =
                AEpMatchTable.GetActionDBName() + ", " +
                AEpMatchTable.GetMatchTextDBName();

            int counter = 5;

            foreach (DataRowView dv in MainDS.AEpTransaction.DefaultView)
            {
                TProgressTracker.SetCurrentState(MyClientID,
                                                 Catalog.GetString("Preparing the gifts"),
                                                 counter++);

                AEpTransactionRow transactionRow = (AEpTransactionRow)dv.Row;

                DataRowView[] matches = MainDS.AEpMatch.DefaultView.FindRows(new object[] {
                    MFinanceConstants.BANK_STMT_STATUS_MATCHED_GIFT,
                    transactionRow.MatchText
                });

                if (matches.Length > 0)
                {
                    AEpMatchRow match = (AEpMatchRow)matches[0].Row;

                    AGiftRow gift = GiftDS.AGift.NewRowTyped();
                    gift.LedgerNumber          = giftbatchRow.LedgerNumber;
                    gift.BatchNumber           = giftbatchRow.BatchNumber;
                    gift.GiftTransactionNumber = giftbatchRow.LastGiftNumber + 1;
                    gift.DonorKey    = match.DonorKey;
                    gift.DateEntered = transactionRow.DateEffective;
                    gift.Reference   = MatchedGiftReference;
                    GiftDS.AGift.Rows.Add(gift);
                    giftbatchRow.LastGiftNumber++;

                    foreach (DataRowView r in matches)
                    {
                        match = (AEpMatchRow)r.Row;

                        AGiftDetailRow detail = GiftDS.AGiftDetail.NewRowTyped();
                        detail.LedgerNumber          = gift.LedgerNumber;
                        detail.BatchNumber           = gift.BatchNumber;
                        detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                        detail.DetailNumber          = gift.LastDetailNumber + 1;
                        gift.LastDetailNumber++;

                        detail.GiftTransactionAmount = match.GiftTransactionAmount;
                        detail.GiftAmount            = match.GiftTransactionAmount;
                        HashTotal += match.GiftTransactionAmount;
                        detail.MotivationGroupCode  = match.MotivationGroupCode;
                        detail.MotivationDetailCode = match.MotivationDetailCode;

                        // do not use the description in comment one, because that could show up on the gift receipt???
                        // detail.GiftCommentOne = transactionRow.Description;

                        detail.CommentOneType        = MFinanceConstants.GIFT_COMMENT_TYPE_BOTH;
                        detail.CostCentreCode        = match.CostCentreCode;
                        detail.RecipientKey          = match.RecipientKey;
                        detail.RecipientLedgerNumber = match.RecipientLedgerNumber;

                        AMotivationDetailRow motivation = (AMotivationDetailRow)MainDS.AMotivationDetail.Rows.Find(
                            new object[] { ALedgerNumber, detail.MotivationGroupCode, detail.MotivationDetailCode });

                        if (motivation == null)
                        {
                            AVerificationResult.Add(new TVerificationResult(
                                                        String.Format(Catalog.GetString("creating gift for match {0}"), transactionRow.Description),
                                                        String.Format(Catalog.GetString("Cannot find motivation group '{0}' and motivation detail '{1}'"),
                                                                      detail.MotivationGroupCode, detail.MotivationDetailCode),
                                                        TResultSeverity.Resv_Critical));
                        }

                        if (detail.CostCentreCode.Length == 0)
                        {
                            // try to retrieve the current costcentre for this recipient
                            if (detail.RecipientKey != 0)
                            {
                                detail.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(detail.RecipientKey);

                                detail.CostCentreCode = TGiftTransactionWebConnector.IdentifyPartnerCostCentre(detail.LedgerNumber,
                                                                                                               detail.RecipientLedgerNumber);
                            }
                            else
                            {
                                if (motivation != null)
                                {
                                    detail.CostCentreCode = motivation.CostCentreCode;
                                }
                            }
                        }

                        // check for active cost centre
                        ACostCentreRow costcentre = (ACostCentreRow)MainDS.ACostCentre.Rows.Find(new object[] { ALedgerNumber, detail.CostCentreCode });

                        if ((costcentre == null) || !costcentre.CostCentreActiveFlag)
                        {
                            AVerificationResult.Add(new TVerificationResult(
                                                        String.Format(Catalog.GetString("creating gift for match {0}"), transactionRow.Description),
                                                        Catalog.GetString("Invalid or inactive cost centre"),
                                                        TResultSeverity.Resv_Critical));
                        }

                        GiftDS.AGiftDetail.Rows.Add(detail);
                    }
                }
            }

            TProgressTracker.SetCurrentState(MyClientID,
                                             Catalog.GetString("Submit to database"),
                                             counter++);

            if (AVerificationResult.HasCriticalErrors)
            {
                return(-1);
            }

            giftbatchRow.HashTotal  = HashTotal;
            giftbatchRow.BatchTotal = HashTotal;

            // do not overwrite the parameter, because there might be the hint for a different gift batch date
            TVerificationResultCollection VerificationResultSubmitChanges;

            TSubmitChangesResult result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref GiftDS,
                                                                                        out VerificationResultSubmitChanges);

            TProgressTracker.FinishJob(MyClientID);

            if (result == TSubmitChangesResult.scrOK)
            {
                return(giftbatchRow.BatchNumber);
            }

            return(-1);
        }
Beispiel #8
0
        /// <summary>
        /// create a new batch with a consecutive batch number in the ledger
        /// for call inside a server function
        /// for performance reasons submitting (save the data in the database) is done later (not here)
        /// </summary>
        /// <param name="AMainDS"></param>
        /// <param name="ATransaction"></param>
        /// <param name="ALedgerTbl"></param>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ADateEffective"></param>
        /// <param name="AForceEffectiveDateToFit"></param>
        /// <returns>the new gift batch row</returns>
        public static AGiftBatchRow CreateANewGiftBatchRow(ref GiftBatchTDS AMainDS,
                                                           ref TDBTransaction ATransaction,
                                                           ref ALedgerTable ALedgerTbl,
                                                           Int32 ALedgerNumber,
                                                           DateTime ADateEffective,
                                                           bool AForceEffectiveDateToFit = true)
        {
            #region Validate Arguments

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

            #endregion Validate Arguments

            AGiftBatchRow NewRow = null;

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

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

                NewRow.BatchYear          = BatchYear;
                NewRow.BatchPeriod        = BatchPeriod;
                NewRow.GlEffectiveDate    = ADateEffective;
                NewRow.ExchangeRateToBase = 1.0M;
                NewRow.BatchDescription   = "PLEASE ENTER A DESCRIPTION";
                NewRow.BankAccountCode    = TLedgerInfo.GetDefaultBankAccount(ALedgerNumber);
                NewRow.BankCostCentre     = TLedgerInfo.GetStandardCostCentre(ALedgerNumber);
                NewRow.CurrencyCode       = ALedgerTbl[0].BaseCurrency;
                AMainDS.AGiftBatch.Rows.Add(NewRow);
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }

            return(NewRow);
        }