private int GetDataTableRowIndexByPrimaryKeys(int ALedgerNumber, int ABatchNumber)
        {
            int  rowPos     = 0;
            bool batchFound = false;

            foreach (DataRowView rowView in FMainDS.AGiftBatch.DefaultView)
            {
                AGiftBatchRow row = (AGiftBatchRow)rowView.Row;

                if ((row.LedgerNumber == ALedgerNumber) && (row.BatchNumber == ABatchNumber))
                {
                    batchFound = true;
                    break;
                }

                rowPos++;
            }

            if (!batchFound)
            {
                rowPos = 0;
            }

            //remember grid is out of sync with DataView by 1 because of grid header rows
            return(rowPos + 1);
        }
Exemplo n.º 2
0
        void WriteGiftBatchLine(AGiftBatchRow giftBatch)
        {
            WriteStringQuoted("B");
            WriteStringQuoted(giftBatch.BatchDescription);
            WriteStringQuoted(giftBatch.BankAccountCode);

            if (FUseBaseCurrency)
            {
                WriteCurrency(giftBatch.HashTotal * giftBatch.ExchangeRateToBase);
            }
            else
            {
                WriteCurrency(giftBatch.HashTotal);
            }

            WriteDate(giftBatch.GlEffectiveDate);

            if (FUseBaseCurrency)
            {
                WriteStringQuoted(FMainDS.ALedger[0].BaseCurrency);
            }
            else
            {
                WriteStringQuoted(giftBatch.CurrencyCode);
            }

            WriteGeneralNumber(giftBatch.ExchangeRateToBase);
            WriteStringQuoted(giftBatch.BankCostCentre);
            WriteStringQuoted(giftBatch.GiftType, true);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Switch to the given tab
        /// </summary>
        /// <param name="ATab"></param>
        /// <param name="AAllowRepeatEvent"></param>
        public void SelectTab(eGiftTabs ATab, bool AAllowRepeatEvent = false)
        {
            if (ATab == eGiftTabs.Batches)
            {
                if ((FPreviouslySelectedTab == eGiftTabs.Batches) && !AAllowRepeatEvent)
                {
                    //Repeat event
                    return;
                }

                FPreviouslySelectedTab = eGiftTabs.Batches;

                FPetraUtilsObject.RestoreAdditionalWindowPositionProperties();
                this.tabGiftBatch.SelectedTab = this.tpgBatches;
                this.tpgTransactions.Enabled  = (ucoBatches.GetSelectedDetailRow() != null);
                this.ucoBatches.SetFocusToGrid();
            }
            else if (ATab == eGiftTabs.Transactions)
            {
                if ((FPreviouslySelectedTab == eGiftTabs.Transactions) && !AAllowRepeatEvent)
                {
                    //Repeat event
                    return;
                }

                if (this.tpgTransactions.Enabled)
                {
                    FPreviouslySelectedTab = eGiftTabs.Transactions;

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

                    AGiftBatchRow SelectedRow = ucoBatches.GetSelectedDetailRow();

                    // If there's only one GiftBatch row, I'll not require that the user has selected it!
                    if (FMainDS.AGiftBatch.Rows.Count == 1)
                    {
                        SelectedRow = FMainDS.AGiftBatch[0];
                    }

                    if (SelectedRow != null)
                    {
                        try
                        {
                            this.Cursor = Cursors.WaitCursor;

                            LoadTransactions(SelectedRow.LedgerNumber,
                                             SelectedRow.BatchNumber,
                                             SelectedRow.BatchStatus);
                        }
                        finally
                        {
                            this.Cursor = Cursors.Default;
                        }
                    }

                    ucoTransactions.FocusGrid();
                }
            }
        }
Exemplo n.º 4
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();
        }
Exemplo n.º 5
0
        /// <summary>
        /// Check if batch columns have actually changed
        /// </summary>
        /// <param name="ABatchRow"></param>
        /// <returns></returns>
        public bool BatchColumnsHaveChanged(AGiftBatchRow ABatchRow)
        {
            bool RetVal = false;

            if (ABatchRow.RowState != DataRowState.Unchanged)
            {
                bool columnValueChanged = false;

                for (int i = 0; i < FMainDS.AGiftBatch.Columns.Count; i++)
                {
                    string originalValue = ABatchRow[i, DataRowVersion.Original].ToString();
                    string currentValue  = ABatchRow[i, DataRowVersion.Current].ToString();

                    if (originalValue != currentValue)
                    {
                        columnValueChanged = true;
                        break;
                    }
                }

                if (!columnValueChanged)
                {
                    ABatchRow.RejectChanges();
                }

                RetVal = columnValueChanged;
            }

            return(RetVal);
        }
Exemplo n.º 6
0
        /// try to find a new gift batch that does already have the same properties
        private static GiftBatchTDS CreateNewGiftBatch(SortedList <string, GiftBatchTDS> ANewGiftBatches,
                                                       AGiftBatchRow AOldGiftBatch,
                                                       DateTime ADateCorrection)
        {
            string key = AOldGiftBatch.CurrencyCode + ";" +
                         AOldGiftBatch.BankAccountCode + ";" +
                         AOldGiftBatch.BankCostCentre + ";" +
                         AOldGiftBatch.GiftType;

            if (!ANewGiftBatches.ContainsKey(key))
            {
                GiftBatchTDS GiftDS = TGiftTransactionWebConnector.CreateAGiftBatch(AOldGiftBatch.LedgerNumber, ADateCorrection,
                                                                                    Catalog.GetString("Gift Adjustment (Field Change)"));
                AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];
                giftbatchRow.BankCostCentre  = AOldGiftBatch.BankCostCentre;
                giftbatchRow.BankAccountCode = AOldGiftBatch.BankAccountCode;
                giftbatchRow.GiftType        = AOldGiftBatch.GiftType;
                ANewGiftBatches.Add(key, GiftDS);

                return(GiftDS);
            }
            else
            {
                return(ANewGiftBatches[key]);
            }
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Call this to change the accounts being shown in the accounts combobox (used when changing the gift type)
        /// </summary>
        /// <param name="AActiveOnly"></param>
        /// <param name="ABankAccountOnly"></param>
        /// <param name="ALblBankAccountCode"></param>
        /// <param name="ARow"></param>
        public void SetupAccountCombo(bool AActiveOnly,
                                      bool ABankAccountOnly,
                                      ref System.Windows.Forms.Label ALblBankAccountCode,
                                      AGiftBatchRow ARow)
        {
            FCmbBankAccountCode.Clear();
            TFinanceControls.InitialiseAccountList(ref FCmbBankAccountCode,
                                                   FLedgerNumber,
                                                   true,
                                                   false,
                                                   AActiveOnly,
                                                   ABankAccountOnly,
                                                   true,
                                                   FAccountTable);

            if (ABankAccountOnly)
            {
                ALblBankAccountCode.Text = Catalog.GetString("Bank Account:");
            }
            else
            {
                ALblBankAccountCode.Text = Catalog.GetString("Account Code:");
            }

            if (ARow != null)
            {
                FCmbBankAccountCode.SetSelectedString(ARow.BankAccountCode, -1);
            }
        }
        private void SetupAccountAndCostCentreCombos(bool AActiveOnly = true, AGiftBatchRow ARow = null)
        {
            if (!FBatchLoaded || (FActiveOnly != AActiveOnly))
            {
                FActiveOnly = AActiveOnly;

                FAccountAndCostCentreLogicObject.SetupAccountAndCostCentreCombos(AActiveOnly, ARow);
            }
        }
Exemplo n.º 10
0
        private void RefreshBankAccountAndCostCentreFilters(bool AActiveOnly, AGiftBatchRow ARow = null)
        {
            if (FActiveOnly != AActiveOnly)
            {
                FActiveOnly = AActiveOnly;

                FAccountAndCostCentreLogicObject.RefreshBankAccountAndCostCentreFilters(AActiveOnly, ARow);
            }
        }
Exemplo n.º 11
0
        /// create a new gift batch using some of the details of an existing gift batch
        private static AGiftBatchRow CreateNewGiftBatch(
            Int32 ALedgerNumber,
            Int32 ABatchNumber,
            DateTime ADateEffective,
            GiftAdjustmentFunctionEnum AFunction,
            ref GiftBatchTDS AMainDS,
            ref ALedgerTable ALedgerTable,
            TDBTransaction ATransaction)
        {
            AGiftBatchRow ReturnValue;

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

            AGiftBatchRow oldGiftBatch = AMainDS.AGiftBatch[0];

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

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

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

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

            return(ReturnValue);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Refreshes the filters on the combo boxes
        /// </summary>
        /// <param name="AActiveOnly"></param>
        /// <param name="ARow"></param>
        public void RefreshBankAccountAndCostCentreFilters(bool AActiveOnly, AGiftBatchRow ARow)
        {
            FCmbBankAccountCode.Filter = TFinanceControls.PrepareAccountFilter(true, false, AActiveOnly, true, "");
            FCmbCostCentreCode.Filter  = TFinanceControls.PrepareCostCentreFilter(true, false, AActiveOnly, true);

            if (ARow != null)
            {
                FCmbCostCentreCode.SetSelectedString(ARow.BankCostCentre, -1);
                FCmbBankAccountCode.SetSelectedString(ARow.BankAccountCode, -1);
            }
        }
Exemplo n.º 13
0
        private void ShowDetailsManual(AGiftBatchRow ARow)
        {
            ((TFrmGiftBatch)ParentForm).EnableTransactions(ARow != null &&
                                                           ARow.BatchStatus != MFinanceConstants.BATCH_CANCELLED);

            if (ARow == null)
            {
                FSelectedBatchNumber          = -1;
                dtpDetailGlEffectiveDate.Date = FDefaultDate;
                UpdateChangeableStatus();
                txtDetailHashTotal.CurrencyCode = String.Empty;
                return;
            }

            bool Unposted = (ARow.BatchStatus == MFinanceConstants.BATCH_UNPOSTED);

            if (!FPostingLogicObject.PostingInProgress)
            {
                bool ActiveOnly = Unposted;
                RefreshBankAccountAndCostCentreFilters(ActiveOnly, ARow);
            }

            FLedgerNumber        = ARow.LedgerNumber;
            FSelectedBatchNumber = ARow.BatchNumber;

            FPetraUtilsObject.DetailProtectedMode = (!Unposted || ViewMode);
            UpdateChangeableStatus();

            //Update the batch period if necessary
            UpdateBatchPeriod();

            RefreshCurrencyAndExchangeRateControls();

            if (Unposted)
            {
                //Check for inactive cost centre and/or account codes
                if (!cmbDetailBankCostCentre.SetSelectedString(ARow.BankCostCentre, -1))
                {
                    MessageBox.Show(String.Format(Catalog.GetString("Batch {0} - the Cost Centre: '{1}' is no longer active and so cannot be used."),
                                                  ARow.BatchNumber,
                                                  ARow.BankCostCentre),
                                    Catalog.GetString("Gift Batch"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                if (!cmbDetailBankAccountCode.SetSelectedString(ARow.BankAccountCode, -1))
                {
                    MessageBox.Show(String.Format(Catalog.GetString("Batch {0} - the Bank Account: '{1}' is no longer active and so cannot be used."),
                                                  ARow.BatchNumber,
                                                  ARow.BankAccountCode),
                                    Catalog.GetString("Gift Batch"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
Exemplo n.º 14
0
        /// create new gift info
        public static AGiftBatchRow CreateNewGiftInfo(Int64 APartnerKey, ref GiftBatchTDS AGiftDS, TDataBase ADataBase = null)
        {
            TDataBase      db = DBAccess.Connect("CreateNewGiftInfo", ADataBase);
            bool           NewTransaction;
            TDBTransaction Transaction = db.GetNewOrExistingTransaction(IsolationLevel.Serializable, out NewTransaction);

            ALedgerAccess.LoadAll(AGiftDS, Transaction);

            AGiftDS = TGiftTransactionWebConnector.CreateAGiftBatch(AGiftDS.ALedger[0].LedgerNumber, DateTime.Today, "Test batch", db);

            // Create a new GiftBatch
            AGiftBatchRow Batch = AGiftDS.AGiftBatch[0];

            Batch.BankAccountCode    = "6000";
            Batch.BatchYear          = 1;
            Batch.BatchPeriod        = 1;
            Batch.CurrencyCode       = "EUR";
            Batch.BankCostCentre     = Batch.LedgerNumber.ToString() + "00";
            Batch.LastGiftNumber     = 1;
            Batch.ExchangeRateToBase = 0.5M;

            // Create a new Gift record
            AGiftRow Gift = AGiftDS.AGift.NewRowTyped();

            Gift.LedgerNumber          = Batch.LedgerNumber;
            Gift.BatchNumber           = Batch.BatchNumber;
            Gift.GiftTransactionNumber = 1;
            Gift.DonorKey = APartnerKey;
            AGiftDS.AGift.Rows.Add(Gift);

            // Create a new GiftDetail record
            AGiftDetailRow GiftDetail = AGiftDS.AGiftDetail.NewRowTyped();

            GiftDetail.LedgerNumber          = Gift.LedgerNumber;
            GiftDetail.BatchNumber           = Gift.BatchNumber;
            GiftDetail.GiftTransactionNumber = Gift.GiftTransactionNumber;
            GiftDetail.DetailNumber          = 1;
            GiftDetail.MotivationGroupCode   = "GIFT";
            GiftDetail.MotivationDetailCode  = "SUPPORT";
            // this won't work with RecipientKey 0 anymore. see https://github.com/openpetra/openpetra/issues/183
            GiftDetail.RecipientKey          = 43000000;
            GiftDetail.RecipientLedgerNumber = APartnerKey;
            GiftDetail.GiftTransactionAmount = 10;
            AGiftDS.AGiftDetail.Rows.Add(GiftDetail);

            if (NewTransaction)
            {
                Transaction.Rollback();
            }

            return(Batch);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Call this to do initial set up the Bank account and cost centre combo boxes
        /// </summary>
        /// <param name="AActiveOnly"></param>
        /// <param name="ARow"></param>
        public void SetupAccountAndCostCentreCombos(bool AActiveOnly, AGiftBatchRow ARow)
        {
            FCmbCostCentreCode.Clear();
            FCmbBankAccountCode.Clear();
            TFinanceControls.InitialiseAccountList(ref FCmbBankAccountCode, FLedgerNumber, true, false, AActiveOnly, true, true, FAccountTable);
            TFinanceControls.InitialiseCostCentreList(ref FCmbCostCentreCode, FLedgerNumber, true, false, AActiveOnly, true, true, FCostCentreTable);

            if (ARow != null)
            {
                FCmbCostCentreCode.SetSelectedString(ARow.BankCostCentre, -1);
                FCmbBankAccountCode.SetSelectedString(ARow.BankAccountCode, -1);
            }
        }
Exemplo n.º 16
0
        public void UpdateRecord()
        {
            TDBTransaction ReadTransaction = new TDBTransaction();
            GiftBatchTDS   MainDS          = new GiftBatchTDS();
            TDataBase      db = DBAccess.Connect("test");

            db.ReadTransaction(ref ReadTransaction,
                               delegate
            {
                ALedgerAccess.LoadAll(MainDS, ReadTransaction);
            });
            ReadTransaction.Rollback();

            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        = 0;
            batch.BatchPeriod      = 1;
            batch.CurrencyCode     = "EUR";
            batch.BatchDescription = "test";
            batch.BankCostCentre   = (MainDS.ALedger[0].LedgerNumber * 100).ToString("0000");
            batch.LastGiftNumber   = 0;
            batch.HashTotal        = 83;
            MainDS.AGiftBatch.Rows.Add(batch);

            GiftBatchTDSAccess.SubmitChanges(MainDS);
            MainDS.AcceptChanges();

            MainDS.AGiftBatch[0].BatchDescription = "test2";
            GiftBatchTDSAccess.SubmitChanges(MainDS);


            TDBTransaction  transaction = new TDBTransaction();
            AGiftBatchTable batches     = null;

            db.ReadTransaction(
                ref transaction,
                delegate
            {
                batches = AGiftBatchAccess.LoadByPrimaryKey(batch.LedgerNumber, batch.BatchNumber, transaction);
            });

            // some problems with sqlite and datagrid
            Assert.AreEqual(typeof(decimal), batches[0][AGiftBatchTable.ColumnHashTotalId].GetType(), "type decimal");
            Assert.AreEqual(83.0m, batches[0].HashTotal, "gift batch hashtotal does not equal");
        }
Exemplo n.º 17
0
        /// <summary>
        /// Re-show the specified row
        /// </summary>
        /// <param name="AModifiedBatchRow"></param>
        /// <param name="ARedisplay"></param>
        public void UndoModifiedBatchRow(AGiftBatchRow AModifiedBatchRow, bool ARedisplay)
        {
            //Check if new row or not
            if (AModifiedBatchRow.RowState == DataRowState.Added)
            {
                return;
            }

            AModifiedBatchRow.RejectChanges();

            if (ARedisplay)
            {
                ShowDetails(AModifiedBatchRow);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// post all gift batches in the given period, but leave some (or none) unposted
        /// </summary>
        public static bool PostBatches(int AYear, int APeriod, int ALeaveBatchesUnposted, TDataBase ADataBase)
        {
            GiftBatchTDS MainDS = new GiftBatchTDS();

            AGiftBatchRow GiftBatchTemplateRow = MainDS.AGiftBatch.NewRowTyped(false);

            GiftBatchTemplateRow.LedgerNumber = FLedgerNumber;
            GiftBatchTemplateRow.BatchYear    = AYear;
            GiftBatchTemplateRow.BatchPeriod  = APeriod;
            GiftBatchTemplateRow.BatchStatus  = MFinanceConstants.BATCH_UNPOSTED;

            TDBTransaction Transaction = new TDBTransaction();

            ADataBase.ReadTransaction(ref Transaction,
                                      delegate
            {
                AGiftBatchAccess.LoadUsingTemplate(MainDS, GiftBatchTemplateRow, Transaction);
            });

            int countUnPosted = MainDS.AGiftBatch.Count;

            List <Int32> GiftBatchesToPost  = new List <int>();
            List <Int32> generatedGlBatches = new List <int>();

            foreach (AGiftBatchRow batch in MainDS.AGiftBatch.Rows)
            {
                if (countUnPosted <= ALeaveBatchesUnposted)
                {
                    break;
                }

                countUnPosted--;

                GiftBatchesToPost.Add(batch.BatchNumber);
            }

            TVerificationResultCollection VerificationResult;

            if (!TGiftTransactionWebConnector.PostGiftBatches(FLedgerNumber, GiftBatchesToPost, generatedGlBatches, out VerificationResult, ADataBase))
            {
                TLogging.Log(VerificationResult.BuildVerificationResultString());
                return(false);
            }

            return(true);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Returns the corporate exchange rate for a given batch row
        ///  and specifies whether or not the transaction is in International
        ///  currency
        /// </summary>
        /// <param name="ABatchRow"></param>
        /// <param name="AIsTransactionInIntlCurrency"></param>
        /// <param name="AAlwaysReportError"></param>
        /// <returns></returns>
        public decimal InternationalCurrencyExchangeRate(AGiftBatchRow ABatchRow,
                                                         out bool AIsTransactionInIntlCurrency, bool AAlwaysReportError = false)
        {
            decimal IntlToBaseCurrencyExchRate = 1;

            AIsTransactionInIntlCurrency = false;

            string   BatchCurrencyCode       = ABatchRow.CurrencyCode;
            decimal  BatchExchangeRateToBase = ABatchRow.ExchangeRateToBase;
            DateTime BatchEffectiveDate      = ABatchRow.GlEffectiveDate;
            DateTime StartOfMonth            = new DateTime(BatchEffectiveDate.Year, BatchEffectiveDate.Month, 1);
            string   LedgerBaseCurrency      = FMainDS.ALedger[0].BaseCurrency;
            string   LedgerIntlCurrency      = FMainDS.ALedger[0].IntlCurrency;

            if (LedgerBaseCurrency == LedgerIntlCurrency)
            {
                IntlToBaseCurrencyExchRate = 1;
            }
            else if (BatchCurrencyCode == LedgerIntlCurrency)
            {
                AIsTransactionInIntlCurrency = true;
            }
            else
            {
                IntlToBaseCurrencyExchRate = TRemote.MFinance.GL.WebConnectors.GetCorporateExchangeRate(LedgerBaseCurrency,
                                                                                                        LedgerIntlCurrency,
                                                                                                        StartOfMonth,
                                                                                                        BatchEffectiveDate);

                if ((IntlToBaseCurrencyExchRate == 0) && (FWarnAboutMissingIntlExchangeRate || AAlwaysReportError))
                {
                    FWarnAboutMissingIntlExchangeRate = false;

                    string IntlRateErrorMessage =
                        String.Format(Catalog.GetString("No Corporate Exchange rate exists for {0} to {1} for the month: {2:MMMM yyyy}!"),
                                      LedgerBaseCurrency,
                                      LedgerIntlCurrency,
                                      BatchEffectiveDate);

                    MessageBox.Show(IntlRateErrorMessage, Catalog.GetString(
                                        "Lookup Corporate Exchange Rate"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }

            return(IntlToBaseCurrencyExchRate);
        }
Exemplo n.º 20
0
        private void ValidateDataDetailsManual(AGiftBatchRow ARow)
        {
            if ((ARow == null) || (ARow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return;
            }

            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;

            //Hash total special case in view of the textbox handling
            ParseHashTotal(ARow);

            //Check if the user has made a Bank Cost Centre or Account Code inactive
            //this was removed because of speed issues!
            //TODO: Revisit this
            //RefreshBankCostCentreAndAccountCodes();

            TSharedFinanceValidation_Gift.ValidateGiftBatchManual(this, ARow, ref VerificationResultCollection,
                                                                  FValidationControlsDict, FAccountTable, FCostCentreTable);
        }
Exemplo n.º 21
0
        /// create new gift info
        public static AGiftBatchRow CreateNewGiftInfo(Int64 APartnerKey, ref GiftBatchTDS AGiftDS)
        {
            ALedgerAccess.LoadAll(AGiftDS, DBAccess.GDBAccessObj.Transaction);

            AGiftDS = TGiftTransactionWebConnector.CreateAGiftBatch(AGiftDS.ALedger[0].LedgerNumber, DateTime.Today, "Test batch");

            // Create a new GiftBatch
            AGiftBatchRow Batch = AGiftDS.AGiftBatch[0];

            Batch.BankAccountCode    = "6000";
            Batch.BatchYear          = 1;
            Batch.BatchPeriod        = 1;
            Batch.CurrencyCode       = "EUR";
            Batch.BankCostCentre     = Batch.LedgerNumber.ToString() + "00";
            Batch.LastGiftNumber     = 1;
            Batch.ExchangeRateToBase = 0.5M;

            // Create a new Gift record
            AGiftRow Gift = AGiftDS.AGift.NewRowTyped();

            Gift.LedgerNumber          = Batch.LedgerNumber;
            Gift.BatchNumber           = Batch.BatchNumber;
            Gift.GiftTransactionNumber = 1;
            Gift.DonorKey = APartnerKey;
            AGiftDS.AGift.Rows.Add(Gift);

            // Create a new GiftDetail record
            AGiftDetailRow GiftDetail = AGiftDS.AGiftDetail.NewRowTyped();

            GiftDetail.LedgerNumber          = Gift.LedgerNumber;
            GiftDetail.BatchNumber           = Gift.BatchNumber;
            GiftDetail.GiftTransactionNumber = Gift.GiftTransactionNumber;
            GiftDetail.DetailNumber          = 1;
            GiftDetail.MotivationGroupCode   = "GIFT";
            GiftDetail.MotivationDetailCode  = "SUPPORT";
            GiftDetail.RecipientKey          = 0;
            GiftDetail.RecipientLedgerNumber = APartnerKey;
            AGiftDS.AGiftDetail.Rows.Add(GiftDetail);

            return(Batch);
        }
Exemplo n.º 22
0
        private void ParseHashTotal(AGiftBatchRow ARow)
        {
            decimal CorrectHashValue = 0m;

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

            if ((txtDetailHashTotal.NumberValueDecimal != null) && txtDetailHashTotal.NumberValueDecimal.HasValue)
            {
                CorrectHashValue = txtDetailHashTotal.NumberValueDecimal.Value;
            }

            if (ARow.HashTotal != CorrectHashValue)
            {
                ARow.HashTotal = CorrectHashValue;
                txtDetailHashTotal.NumberValueDecimal = CorrectHashValue;
                FPetraUtilsObject.SetChangedFlag();
            }
        }
Exemplo n.º 23
0
        private void ParseHashTotal(AGiftBatchRow ARow)
        {
            decimal correctHashValue;

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

            if ((txtDetailHashTotal.NumberValueDecimal == null) || !txtDetailHashTotal.NumberValueDecimal.HasValue)
            {
                correctHashValue = 0m;
            }
            else
            {
                correctHashValue = txtDetailHashTotal.NumberValueDecimal.Value;
            }

            txtDetailHashTotal.NumberValueDecimal = correctHashValue;
            ARow.HashTotal = correctHashValue;
        }
Exemplo n.º 24
0
        private void ValidateDataDetailsManual(AGiftBatchRow ARow)
        {
            if ((ARow == null) || (ARow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return;
            }

            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;

            //Hash total special case in view of the textbox handling
            ParseHashTotal(ARow);

            //Check if the user has made a Bank Cost Centre or Account Code inactive
            //this was removed because of speed issues!
            //TODO: Revisit this
            //RefreshBankCostCentreAndAccountCodes();

            TSharedFinanceValidation_Gift.ValidateGiftBatchManual(this, ARow, ref VerificationResultCollection,
                                                                  FValidationControlsDict, FAccountTable, FCostCentreTable);

            //TODO: remove this once database definition is set for Batch Description to be NOT NULL
            // Description is mandatory then make sure it is set
            if (txtDetailBatchDescription.Text.Length == 0)
            {
                DataColumn          ValidationColumn;
                TVerificationResult VerificationResult = null;
                object ValidationContext;

                ValidationColumn  = ARow.Table.Columns[AGiftBatchTable.ColumnBatchDescriptionId];
                ValidationContext = String.Format("Batch number {0}",
                                                  ARow.BatchNumber);

                VerificationResult = TStringChecks.StringMustNotBeEmpty(ARow.BatchDescription,
                                                                        "Description of " + ValidationContext,
                                                                        this, ValidationColumn, null);

                // Handle addition/removal to/from TVerificationResultCollection
                VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn, true);
            }
        }
        private void UpdateTransactionsCurrencyAmounts(AGiftBatchRow ABatchRow,
                                                       Decimal AIntlToBaseCurrencyExchRate,
                                                       Boolean ATransactionInIntlCurrency)
        {
            int     LedgerNumber            = ABatchRow.LedgerNumber;
            int     BatchNumber             = ABatchRow.BatchNumber;
            decimal BatchExchangeRateToBase = ABatchRow.ExchangeRateToBase;

            if (!LoadGiftDataForBatch(LedgerNumber, BatchNumber))
            {
                return;
            }

            DataView transDV = new DataView(FMainDS.AGiftDetail);

            transDV.RowFilter = String.Format("{0}={1}",
                                              AGiftDetailTable.GetBatchNumberDBName(),
                                              BatchNumber);

            foreach (DataRowView drvTrans in transDV)
            {
                AGiftDetailRow gdr = (AGiftDetailRow)drvTrans.Row;

                gdr.GiftAmount = GLRoutines.Divide(gdr.GiftTransactionAmount, BatchExchangeRateToBase);

                if (!ATransactionInIntlCurrency)
                {
                    gdr.GiftAmountIntl = (AIntlToBaseCurrencyExchRate == 0) ? 0 : GLRoutines.Divide(gdr.GiftAmount, AIntlToBaseCurrencyExchRate);
                }
                else
                {
                    gdr.GiftAmountIntl = gdr.GiftTransactionAmount;
                }

                if (FSETUseTaxDeductiblePercentageFlag)
                {
                    TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref gdr);
                }
            }
        }
Exemplo n.º 26
0
        public static bool GiftRevertAdjust(Hashtable requestParams, out TVerificationResultCollection AMessages)
        {
            AMessages = new TVerificationResultCollection();

            Int32   ALedgerNumber   = (Int32)requestParams["ALedgerNumber"];
            Boolean batchSelected   = (Boolean)requestParams["NewBatchSelected"];
            Int32   ANewBatchNumber = 0;

            bool TaxDeductiblePercentageEnabled = Convert.ToBoolean(
                TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE"));

            if (batchSelected)
            {
                ANewBatchNumber = (Int32)requestParams["NewBatchNumber"];
            }

            String Function          = (String)requestParams["Function"];
            Int32  AGiftDetailNumber = (Int32)requestParams["GiftDetailNumber"];
            Int32  AGiftNumber       = (Int32)requestParams["GiftNumber"];
            Int32  ABatchNumber      = (Int32)requestParams["BatchNumber"];

            //decimal batchHashTotal = 0;
            decimal batchGiftTotal = 0;

            GiftBatchTDS   MainDS      = new GiftBatchTDS();
            TDBTransaction Transaction = null;
            DateTime       ADateEffective;

            Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

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

                AGiftBatchRow giftBatch;

                if (!batchSelected)
                {
                    ADateEffective = (DateTime)requestParams["GlEffectiveDate"];

                    AGiftBatchAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, Transaction);

                    AGiftBatchRow oldGiftBatch = MainDS.AGiftBatch[0];
                    TGiftBatchFunctions.CreateANewGiftBatchRow(ref MainDS, ref Transaction, ref LedgerTable, ALedgerNumber, ADateEffective);
                    giftBatch = MainDS.AGiftBatch[1];
                    giftBatch.BankAccountCode     = oldGiftBatch.BankAccountCode;
                    giftBatch.BankCostCentre      = oldGiftBatch.BankCostCentre;
                    giftBatch.CurrencyCode        = oldGiftBatch.CurrencyCode;
                    giftBatch.ExchangeRateToBase  = oldGiftBatch.ExchangeRateToBase;
                    giftBatch.MethodOfPaymentCode = oldGiftBatch.MethodOfPaymentCode;
                    giftBatch.HashTotal           = 0;

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

                    giftBatch.BankCostCentre = oldGiftBatch.BankCostCentre;
                    giftBatch.GiftType       = oldGiftBatch.GiftType;

                    if (Function.Equals("AdjustGift"))
                    {
                        giftBatch.BatchDescription = Catalog.GetString("Gift Adjustment");
                    }
                    else
                    {
                        giftBatch.BatchDescription = Catalog.GetString("Reverse Gift");
                    }
                }
                else
                {
                    AGiftBatchAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ANewBatchNumber, Transaction);

                    giftBatch      = MainDS.AGiftBatch[0];
                    ADateEffective = giftBatch.GlEffectiveDate;
                    //If into an existing batch, then retrive the existing batch total
                    batchGiftTotal = giftBatch.BatchTotal;
                }

                if (Function.Equals("ReverseGiftBatch"))
                {
                    AGiftAccess.LoadViaAGiftBatch(MainDS, ALedgerNumber, ABatchNumber, Transaction);

                    foreach (AGiftRow gift in MainDS.AGift.Rows)
                    {
                        AGiftDetailAccess.LoadViaAGift(MainDS, ALedgerNumber, ABatchNumber, gift.GiftTransactionNumber, Transaction);
                    }
                }
                else
                {
                    AGiftAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, AGiftNumber, Transaction);

                    if (Function.Equals("ReverseGiftDetail"))
                    {
                        AGiftDetailAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, AGiftNumber, AGiftDetailNumber, Transaction);
                    }
                    else
                    {
                        AGiftDetailAccess.LoadViaAGift(MainDS, ALedgerNumber, ABatchNumber, AGiftNumber, Transaction);
                    }
                }

                //assuming new elements are added after these static borders

                int cycle = 0;

                MainDS.AGift.DefaultView.Sort = string.Format("{0}, {1}",
                                                              AGiftTable.GetBatchNumberDBName(),
                                                              AGiftTable.GetGiftTransactionNumberDBName());

                MainDS.AGiftDetail.DefaultView.Sort = string.Format("{0}, {1}, {2}",
                                                                    AGiftDetailTable.GetBatchNumberDBName(),
                                                                    AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                    AGiftDetailTable.GetDetailNumberDBName());

                do
                {
                    foreach (DataRowView giftRow in MainDS.AGift.DefaultView)
                    {
                        AGiftRow oldGift = (AGiftRow)giftRow.Row;

                        if ((oldGift.BatchNumber == ABatchNumber) && (oldGift.LedgerNumber == ALedgerNumber) &&
                            (Function.Equals("ReverseGiftBatch") || (oldGift.GiftTransactionNumber == AGiftNumber)))
                        {
                            AGiftRow gift = MainDS.AGift.NewRowTyped(true);
                            DataUtilities.CopyAllColumnValuesWithoutPK(oldGift, gift);
                            gift.LedgerNumber          = giftBatch.LedgerNumber;
                            gift.BatchNumber           = giftBatch.BatchNumber;
                            gift.DateEntered           = ADateEffective;
                            gift.GiftTransactionNumber = giftBatch.LastGiftNumber + 1;
                            giftBatch.LastGiftNumber++;
                            gift.LastDetailNumber = 0;

                            MainDS.AGift.Rows.Add(gift);

                            foreach (DataRowView giftDetailRow in MainDS.AGiftDetail.DefaultView)
                            {
                                AGiftDetailRow oldGiftDetail = (AGiftDetailRow)giftDetailRow.Row;

                                if ((oldGiftDetail.GiftTransactionNumber == oldGift.GiftTransactionNumber) &&
                                    (oldGiftDetail.BatchNumber == ABatchNumber) &&
                                    (oldGiftDetail.LedgerNumber == ALedgerNumber) &&
                                    (!Function.Equals("ReverseGiftDetail") || (oldGiftDetail.DetailNumber == AGiftDetailNumber)))
                                {
                                    if ((cycle == 0) && oldGiftDetail.ModifiedDetail)
                                    {
                                        AMessages.Add(new TVerificationResult(
                                                          String.Format(Catalog.GetString("Cannot reverse or adjust Gift {0} with Detail {1} in Batch {2}"),
                                                                        oldGiftDetail.GiftTransactionNumber, oldGiftDetail.DetailNumber, oldGiftDetail.BatchNumber),
                                                          String.Format(Catalog.GetString("It was already adjusted or reversed.")),
                                                          TResultSeverity.Resv_Critical));

                                        DBAccess.GDBAccessObj.RollbackTransaction();

                                        return(false);
                                    }

                                    AGiftDetailRow giftDetail = MainDS.AGiftDetail.NewRowTyped(true);
                                    DataUtilities.CopyAllColumnValuesWithoutPK(oldGiftDetail, giftDetail);

                                    giftDetail.DetailNumber = ++gift.LastDetailNumber;

                                    giftDetail.LedgerNumber          = gift.LedgerNumber;
                                    giftDetail.BatchNumber           = giftBatch.BatchNumber;
                                    giftDetail.GiftTransactionNumber = gift.GiftTransactionNumber;
                                    //Identify the reversal source
                                    giftDetail.ModifiedDetailKey = "|" + oldGiftDetail.BatchNumber.ToString() + "|" +
                                                                   oldGiftDetail.GiftTransactionNumber.ToString() + "|" +
                                                                   oldGiftDetail.DetailNumber.ToString();

                                    decimal signum = (cycle == 0) ? -1 : 1;
                                    giftDetail.GiftTransactionAmount = signum * oldGiftDetail.GiftTransactionAmount;
                                    batchGiftTotal           += giftDetail.GiftTransactionAmount;
                                    giftDetail.GiftAmount     = signum * oldGiftDetail.GiftAmount;
                                    giftDetail.GiftAmountIntl = signum * oldGiftDetail.GiftAmountIntl;

                                    if (TaxDeductiblePercentageEnabled)
                                    {
                                        giftDetail.TaxDeductibleAmount     = signum * oldGiftDetail.TaxDeductibleAmount;
                                        giftDetail.TaxDeductibleAmountBase = signum * oldGiftDetail.TaxDeductibleAmountBase;
                                        giftDetail.TaxDeductibleAmountIntl = signum * oldGiftDetail.TaxDeductibleAmountIntl;
                                        giftDetail.NonDeductibleAmount     = signum * oldGiftDetail.NonDeductibleAmount;
                                        giftDetail.NonDeductibleAmountBase = signum * oldGiftDetail.NonDeductibleAmountBase;
                                        giftDetail.NonDeductibleAmountIntl = signum * oldGiftDetail.NonDeductibleAmountIntl;
                                    }

                                    giftDetail.GiftCommentOne   = (String)requestParams["ReversalCommentOne"];
                                    giftDetail.GiftCommentTwo   = (String)requestParams["ReversalCommentTwo"];
                                    giftDetail.GiftCommentThree = (String)requestParams["ReversalCommentThree"];
                                    giftDetail.CommentOneType   = (String)requestParams["ReversalCommentOneType"];
                                    giftDetail.CommentTwoType   = (String)requestParams["ReversalCommentTwoType"];
                                    giftDetail.CommentThreeType = (String)requestParams["ReversalCommentThreeType"];

                                    // This is used to mark both as a Reverted giftDetails, except the adjusted (new) gift

                                    giftDetail.ModifiedDetail    = (cycle == 0);
                                    oldGiftDetail.ModifiedDetail = (cycle == 0);
                                    MainDS.AGiftDetail.Rows.Add(giftDetail);
                                }
                            }
                        }
                    }

                    cycle++;
                } while ((cycle < 2) && Function.Equals("AdjustGift"));

                //When reversing into a new or existing batch, set batch total
                if (!Function.Equals("AdjustGift"))
                {
                    giftBatch.BatchTotal = batchGiftTotal;
                }

                // save everything at the end
                AGiftBatchAccess.SubmitChanges(MainDS.AGiftBatch, Transaction);

                ALedgerAccess.SubmitChanges(LedgerTable, Transaction);

                AGiftAccess.SubmitChanges(MainDS.AGift, Transaction);

                AGiftDetailAccess.SubmitChanges(MainDS.AGiftDetail, Transaction);

                MainDS.AGiftBatch.AcceptChanges();

                DBAccess.GDBAccessObj.CommitTransaction();

                return(true);
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured while performing Gift Reverse/Adjust:" + Environment.NewLine + Exc.ToString());

                DBAccess.GDBAccessObj.RollbackTransaction();

                throw new EOPAppException(Catalog.GetString("Gift Reverse/Adjust failed."), Exc);
            }
        }
        private void SetupAccountAndCostCentreCombos(bool AActiveOnly, AGiftBatchRow ARow = null)
        {
            if (!FBatchLoaded || (FActiveOnly != AActiveOnly))
            {
                FActiveOnly = AActiveOnly;

                FAccountAndCostCentreLogicObject.SetupAccountAndCostCentreCombos(AActiveOnly, ARow);
            }
        }
Exemplo n.º 28
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);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Import a transactions file or a clipboard equivalent
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch to import to</param>
        /// <param name="AImportSource">The import source - eg File or Clipboard</param>
        /// <returns>True if the import was successful</returns>
        public bool ImportTransactions(AGiftBatchRow ACurrentBatchRow, TGiftImportDataSourceEnum AImportSource)
        {
            bool           ok = false;
            String         importString;
            String         impOptions;
            OpenFileDialog dialog      = null;
            Boolean        IsPlainText = false;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to import
                MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString(
                                    "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                MessageBox.Show(Catalog.GetString("Please select an unposted batch to import transactions."), Catalog.GetString(
                                    "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            if (ACurrentBatchRow.LastGiftNumber > 0)
            {
                if (MessageBox.Show(Catalog.GetString(
                                        "The current batch already contains some gift transactions.  Do you really want to add more transactions to this batch?"),
                                    Catalog.GetString("Gift Transaction Import"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return(false);
                }
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportSource == TGiftImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                                    Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData           = importString;
                FdlgSeparator.DateFormat        = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportSource == TGiftImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                string exportPath = TClientSettings.GetExportPath();
                string fullPath   = TUserDefaults.GetStringDefault("Imp Filename",
                                                                   exportPath + Path.DirectorySeparatorChar + "import.csv");
                TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath);

                dialog.Title  = Catalog.GetString("Import Transactions from CSV File");
                dialog.Filter = Catalog.GetString("Gift Transactions files (*.csv)|*.csv|Text Files (*.txt)|*.txt");
                impOptions    = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                // This call fixes Windows7 Open File Dialogs.  It must be the line before ShowDialog()
                TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath));

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                                        Catalog.GetString("Gift Import"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Stop);
                        return(false);
                    }

                    importString = File.ReadAllText(dialog.FileName, Encoding.Default);
                    IsPlainText  = (Path.GetExtension(dialog.FileName).ToLower() == ".txt");

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions   = String.Empty;
                importString = String.Empty;
            }

            if (IsPlainText || (FdlgSeparator.ShowDialog() == DialogResult.OK))
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);

                bool Repeat = true;

                while (Repeat)
                {
                    Repeat = false;

                    TVerificationResultCollection AMessages = new TVerificationResultCollection();
                    GiftBatchTDSAGiftDetailTable  NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable();

                    Thread ImportThread = new Thread(() => ImportGiftTransactions(
                                                         requestParams,
                                                         importString,
                                                         ACurrentBatchRow.BatchNumber,
                                                         out AMessages,
                                                         out ok,
                                                         out NeedRecipientLedgerNumber));

                    using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                    {
                        ImportDialog.ShowDialog();
                    }

                    ShowMessages(AMessages);

                    // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination
                    // then the import will have failed and we need to alert the user
                    if (NeedRecipientLedgerNumber.Rows.Count > 0)
                    {
                        bool OfferToRunImportAgain = true;

                        // for each gift in which the recipient needs a Git Destination
                        foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows)
                        {
                            if (MessageBox.Show(string.Format(
                                                    Catalog.GetString(
                                                        "Gift Import has been cancelled as the recipient '{0}' ({1}) has no Gift Destination assigned."),
                                                    Row.RecipientDescription, Row.RecipientKey) +
                                                "\n\n" +
                                                Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"),
                                                Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                                == DialogResult.Yes)
                            {
                                // allow the user to assign a Gift Destingation
                                TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey);
                                GiftDestinationForm.ShowDialog();
                            }
                            else
                            {
                                OfferToRunImportAgain = false;
                            }
                        }

                        // if the user has clicked yes to assigning Gift Destinations then offer to restart the import
                        if (OfferToRunImportAgain &&
                            (MessageBox.Show(Catalog.GetString("Would you like to import these Gift Transactions again?"),
                                             Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                             MessageBoxDefaultButton.Button1)
                             == DialogResult.Yes))
                        {
                            Repeat = true;
                        }
                    }
                }

                // We save the defaults even if ok is false - because the client will probably want to try and import
                //   the same file again after correcting any errors
                SaveUserDefaults(dialog, impOptions);
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                                Catalog.GetString("Gift Import"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);

                //FMyUserControl.LoadBatchesForCurrentYear();
                FPetraUtilsObject.DisableSaveButton();
            }

            return(ok);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Returns the corporate exchange rate for a given batch row
        ///  and specifies whether or not the transaction is in International
        ///  currency
        /// </summary>
        /// <param name="ABatchRow"></param>
        /// <param name="AIsTransactionInIntlCurrency"></param>
        /// <param name="AAlwaysReportError"></param>
        /// <returns></returns>
        public decimal InternationalCurrencyExchangeRate(AGiftBatchRow ABatchRow,
            out bool AIsTransactionInIntlCurrency, bool AAlwaysReportError = false)
        {
            decimal IntlToBaseCurrencyExchRate = 1;

            AIsTransactionInIntlCurrency = false;

            string BatchCurrencyCode = ABatchRow.CurrencyCode;
            decimal BatchExchangeRateToBase = ABatchRow.ExchangeRateToBase;
            DateTime BatchEffectiveDate = ABatchRow.GlEffectiveDate;
            DateTime StartOfMonth = new DateTime(BatchEffectiveDate.Year, BatchEffectiveDate.Month, 1);
            string LedgerBaseCurrency = FMainDS.ALedger[0].BaseCurrency;
            string LedgerIntlCurrency = FMainDS.ALedger[0].IntlCurrency;

            if (LedgerBaseCurrency == LedgerIntlCurrency)
            {
                IntlToBaseCurrencyExchRate = 1;
            }
            else if (BatchCurrencyCode == LedgerIntlCurrency)
            {
                AIsTransactionInIntlCurrency = true;
            }
            else
            {
                IntlToBaseCurrencyExchRate = TRemote.MFinance.GL.WebConnectors.GetCorporateExchangeRate(LedgerBaseCurrency,
                    LedgerIntlCurrency,
                    StartOfMonth,
                    BatchEffectiveDate);

                if ((IntlToBaseCurrencyExchRate == 0) && (FWarnAboutMissingIntlExchangeRate || AAlwaysReportError))
                {
                    FWarnAboutMissingIntlExchangeRate = false;

                    string IntlRateErrorMessage =
                        String.Format(Catalog.GetString("No Corporate Exchange rate exists for {0} to {1} for the month: {2:MMMM yyyy}!"),
                            LedgerBaseCurrency,
                            LedgerIntlCurrency,
                            BatchEffectiveDate);

                    MessageBox.Show(IntlRateErrorMessage, Catalog.GetString(
                            "Lookup Corporate Exchange Rate"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }

            return IntlToBaseCurrencyExchRate;
        }
Exemplo n.º 31
0
        private void ParseTransactionLine(AGiftRow AGift,
            AGiftBatchRow AGiftBatch,
            ref AGiftRow APreviousGift,
            int ANumberOfColumns,
            ref decimal ATotalBatchAmount,
            ref string AImportMessage,
            int ARowNumber,
            decimal AIntlRateFromBase,
            TVerificationResultCollection AMessages,
            AMotivationDetailTable AMotivationDetailTable,
//            TValidationControlsDict AValidationControlsDictGift,
//            TValidationControlsDict AValidationControlsDictGiftDetail,
//            ACostCentreTable AValidationCostCentreTable,
//            AAccountTable AValidationAccountTable,
//            AMotivationGroupTable AValidationMotivationGroupTable,
//            AMethodOfGivingTable AValidationMethodOfGivingTable,
//            AMethodOfPaymentTable AValidationMethodOfPaymentTable,
//            PMailingTable AValidationMailingTable,
            GiftBatchTDSAGiftDetailTable ANeedRecipientLedgerNumber,
            AGiftDetailRow AGiftDetails)
        {
            // Start parsing
            int preParseMessageCount = AMessages.Count;

            // Is this the format with extra columns?
            // Actually if it has the extra columns but does not have the optional final 8 columns we cannot distiguish using this test...
            //   A file without extra columns will have between 13 and 21 columns - depending on whether some of the optional ones at the end are included.
            //   A file with extra columns will be between 19 and 27.
            //  So any count between 19 and 21 is ambiguous.  We will assume that if the file has extra columns it also has
            //   at least enough of the optional ones to exceed 21.
            bool HasExtraColumns = (ANumberOfColumns > 21);

            AImportMessage = Catalog.GetString("Importing the gift data");

            AGift.DonorKey = TCommonImport.ImportInt64(ref FImportLine, FDelimiter, Catalog.GetString("Donor key"),
                FMainDS.AGift.ColumnDonorKey, ARowNumber, AMessages, null);

            TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString(
                    "short name of donor (unused)"), null, ARowNumber, AMessages, null);                                                                   // unused

            // This group is optional and database NULL's are allowed
            AGift.MethodOfGivingCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Method of giving Code"),
                FMainDS.AGift.ColumnMethodOfGivingCode, ARowNumber, AMessages, null, false);
            AGift.MethodOfPaymentCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Method Of Payment Code"),
                FMainDS.AGift.ColumnMethodOfPaymentCode, ARowNumber, AMessages, null, false);
            AGift.Reference = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Reference"),
                FMainDS.AGift.ColumnReference, ARowNumber, AMessages, null, false);
            AGift.ReceiptLetterCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Receipt letter code"),
                FMainDS.AGift.ColumnReceiptLetterCode, ARowNumber, AMessages, null, false);

            if (AGift.MethodOfGivingCode != null)
            {
                AGift.MethodOfGivingCode = AGift.MethodOfGivingCode.ToUpper();
            }

            if (AGift.MethodOfPaymentCode != null)
            {
                AGift.MethodOfPaymentCode = AGift.MethodOfPaymentCode.ToUpper();
            }

            if (AGift.ReceiptLetterCode != null)
            {
                AGift.ReceiptLetterCode = AGift.ReceiptLetterCode.ToUpper();
            }

            if (HasExtraColumns)
            {
                TCommonImport.ImportInt32(ref FImportLine, FDelimiter, Catalog.GetString("Receipt number"),
                    FMainDS.AGift.ColumnReceiptNumber, ARowNumber, AMessages, null);
                TCommonImport.ImportBoolean(ref FImportLine, FDelimiter, Catalog.GetString("First time gift"),
                    FMainDS.AGift.ColumnFirstTimeGift, ARowNumber, AMessages, null);
                TCommonImport.ImportBoolean(ref FImportLine, FDelimiter, Catalog.GetString("Receipt printed"),
                    FMainDS.AGift.ColumnReceiptPrinted, ARowNumber, AMessages, null);
            }

            AImportMessage = Catalog.GetString("Importing the gift details");

            if ((APreviousGift != null) && (AGift.DonorKey == APreviousGift.DonorKey)
                && (AGift.MethodOfGivingCode == APreviousGift.MethodOfGivingCode)
                && (AGift.MethodOfPaymentCode == APreviousGift.MethodOfPaymentCode)
                && (AGift.Reference == APreviousGift.Reference)
                && (AGift.ReceiptLetterCode == APreviousGift.ReceiptLetterCode)
                && (AGift.ReceiptNumber == APreviousGift.ReceiptNumber)
                && (AGift.FirstTimeGift == APreviousGift.FirstTimeGift)
                && (AGift.ReceiptPrinted == APreviousGift.ReceiptPrinted))
            {
                // this row is a new detail for the previousGift
                AGift = APreviousGift;
                AGift.LastDetailNumber++;
                AGiftDetails.DetailNumber = AGift.LastDetailNumber;
            }
            else
            {
                APreviousGift = AGift;
                AGift.LedgerNumber = AGiftBatch.LedgerNumber;
                AGift.BatchNumber = AGiftBatch.BatchNumber;
                AGift.GiftTransactionNumber = AGiftBatch.LastGiftNumber + 1;
                AGiftBatch.LastGiftNumber++;
                AGift.LastDetailNumber = 1;
                FMainDS.AGift.Rows.Add(AGift);
                AGiftDetails.DetailNumber = 1;
            }

            AGiftDetails.LedgerNumber = AGift.LedgerNumber;
            AGiftDetails.BatchNumber = AGiftBatch.BatchNumber;
            AGiftDetails.GiftTransactionNumber = AGift.GiftTransactionNumber;
            FMainDS.AGiftDetail.Rows.Add(AGiftDetails);

            AGiftDetails.RecipientKey = TCommonImport.ImportInt64(ref FImportLine, FDelimiter, Catalog.GetString("Recipient key"),
                FMainDS.AGiftDetail.ColumnRecipientKey, ARowNumber, AMessages, null);

            TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString(
                    "short name of recipient (unused)"), null, ARowNumber, AMessages, null);                           // unused

            if (HasExtraColumns)
            {
                TCommonImport.ImportInt32(ref FImportLine, FDelimiter, Catalog.GetString("Recipient ledger number"),
                    FMainDS.AGiftDetail.ColumnRecipientLedgerNumber, ARowNumber, AMessages, null);
            }

            // we always calculate RecipientLedgerNumber
            AGiftDetails.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(
                AGiftDetails.RecipientKey, AGiftBatch.GlEffectiveDate);

            decimal currentGiftAmount =
                TCommonImport.ImportDecimal(ref FImportLine, FDelimiter, FCultureInfoNumberFormat, Catalog.GetString("Gift amount"),
                    FMainDS.AGiftDetail.ColumnGiftTransactionAmount, ARowNumber, AMessages, null);
            AGiftDetails.GiftTransactionAmount = currentGiftAmount;     // amount in batch currency
            ATotalBatchAmount += currentGiftAmount;

            AGiftDetails.GiftAmount = GLRoutines.Divide(currentGiftAmount, AGiftBatch.ExchangeRateToBase);      // amount in ledger currency

            if (HasExtraColumns)
            {
                // amount in international currency
                TCommonImport.ImportDecimal(ref FImportLine, FDelimiter, FCultureInfoNumberFormat, Catalog.GetString("Gift amount intl"),
                    FMainDS.AGiftDetail.ColumnGiftAmountIntl, ARowNumber, AMessages, null);
            }
            else if (AIntlRateFromBase > 0.0m)
            {
                AGiftDetails.GiftAmountIntl = GLRoutines.Divide(AGiftDetails.GiftAmount, AIntlRateFromBase, 2);
            }

            AGiftDetails.ConfidentialGiftFlag = TCommonImport.ImportBoolean(ref FImportLine, FDelimiter, Catalog.GetString("Confidential gift"),
                FMainDS.AGiftDetail.ColumnConfidentialGiftFlag, ARowNumber, AMessages, null);
            AGiftDetails.MotivationGroupCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Motivation group code"),
                FMainDS.AGiftDetail.ColumnMotivationGroupCode, ARowNumber, AMessages, null).ToUpper();
            AGiftDetails.MotivationDetailCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Motivation detail"),
                FMainDS.AGiftDetail.ColumnMotivationDetailCode, ARowNumber, AMessages, null).ToUpper();

            if (HasExtraColumns)
            {
                TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Cost centre code"),
                    FMainDS.AGiftDetail.ColumnCostCentreCode, ARowNumber, AMessages, null);
            }

            // "In Petra Cost Centre is always inferred from recipient field and motivation detail so is not needed in the import."
            AGiftDetails.CostCentreCode = TGiftTransactionWebConnector.RetrieveCostCentreCodeForRecipient(
                AGiftDetails.LedgerNumber, AGiftDetails.RecipientKey, AGiftDetails.RecipientLedgerNumber,
                AGift.DateEntered, AGiftDetails.MotivationGroupCode, AGiftDetails.MotivationDetailCode);

            // All the remaining columns are optional and can contain database NULL
            AGiftDetails.GiftCommentOne = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Gift comment one"),
                FMainDS.AGiftDetail.ColumnGiftCommentOne, ARowNumber, AMessages, null, false);
            string commentOneType = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Comment one type"),
                FMainDS.AGiftDetail.ColumnCommentOneType, ARowNumber, AMessages, null, false);

            AGiftDetails.MailingCode = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Mailing code"),
                FMainDS.AGiftDetail.ColumnMailingCode, ARowNumber, AMessages, null, false);

            AGiftDetails.GiftCommentTwo = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Gift comment two"),
                FMainDS.AGiftDetail.ColumnGiftCommentTwo, ARowNumber, AMessages, null, false);
            string commentTwoType = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Comment two type"),
                FMainDS.AGiftDetail.ColumnCommentTwoType, ARowNumber, AMessages, null, false);
            AGiftDetails.GiftCommentThree = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Gift comment three"),
                FMainDS.AGiftDetail.ColumnGiftCommentThree, ARowNumber, AMessages, null, false);
            string commentThreeType = TCommonImport.ImportString(ref FImportLine, FDelimiter, Catalog.GetString("Comment three type"),
                FMainDS.AGiftDetail.ColumnCommentThreeType, ARowNumber, AMessages, null, false);

            SetCommentTypeCase(ref commentOneType);
            AGiftDetails.CommentOneType = commentOneType;

            SetCommentTypeCase(ref commentTwoType);
            AGiftDetails.CommentTwoType = commentTwoType;

            SetCommentTypeCase(ref commentThreeType);
            AGiftDetails.CommentThreeType = commentThreeType;

            if (AGiftDetails.MailingCode != null)
            {
                AGiftDetails.MailingCode = AGiftDetails.MailingCode.ToUpper();
            }

            // Find the default Tax deductabilty from the motivation detail. This ensures that the column can be missing.
            AMotivationDetailRow motivationDetailRow = (AMotivationDetailRow)AMotivationDetailTable.Rows.Find(
                new object[] { FLedgerNumber, AGiftDetails.MotivationGroupCode, AGiftDetails.MotivationDetailCode });
            string defaultTaxDeductible =
                ((motivationDetailRow != null) && !motivationDetailRow.IsTaxDeductibleAccountCodeNull()
                 && motivationDetailRow.TaxDeductible) ? "yes" : "no";

            AGiftDetails.TaxDeductible = TCommonImport.ImportBoolean(ref FImportLine, FDelimiter, Catalog.GetString("Tax deductible"),
                FMainDS.AGiftDetail.ColumnTaxDeductible, ARowNumber, AMessages, null, defaultTaxDeductible);

            // Account Codes are always inferred from the motivation detail and so is not needed in the import.
            string NewAccountCode = null;
            string NewTaxDeductibleAccountCode = null;

            // get up-to-date account codes
            if (motivationDetailRow != null)
            {
                NewAccountCode = motivationDetailRow.AccountCode;
                NewTaxDeductibleAccountCode = motivationDetailRow.TaxDeductibleAccountCode;
            }

            AGiftDetails.AccountCode = NewAccountCode;
            AGiftDetails.TaxDeductibleAccountCode = NewTaxDeductibleAccountCode;

            // Date entered cannot be imported although it can be modified in the GUI.
            // This is because it would have to be the last column in the import for compatibility
            // but it belongs with the gift and not the detail so it would need to go in an earlier column.
            // For now the import date entered is the effective date.
            AGift.DateEntered = AGiftBatch.GlEffectiveDate;

            // Enforce the correct case for our GIFT constant
            if (String.Compare(AGiftDetails.MotivationGroupCode, MFinanceConstants.MOTIVATION_GROUP_GIFT, true) == 0)
            {
                AGiftDetails.MotivationGroupCode = MFinanceConstants.MOTIVATION_GROUP_GIFT;
            }
        } // Parse TransactionLine
Exemplo n.º 32
0
        /// <summary>
        /// Validates the Gift Batch data.
        /// </summary>
        /// <param name="AContext">Context that describes where the data validation failed.</param>
        /// <param name="ARow">The <see cref="DataRow" /> which holds the the data against which the validation is run.</param>
        /// <param name="AVerificationResultCollection">Will be filled with any <see cref="TVerificationResult" /> items if
        /// data validation errors occur.</param>
        /// <param name="AValidationControlsDict">A <see cref="TValidationControlsDict" /> containing the Controls that
        /// display data that is about to be validated.</param>
        /// <param name="AAccountTableRef">Account Table.  A reference to this table is REQUIRED when importing - optional otherwise</param>
        /// <param name="ACostCentreTableRef">Cost centre table.  A reference to this table is REQUIRED when importing - optional otherwise</param>
        /// <param name="AAccountPropertyTableRef">Account Property Table.  A reference to this table is REQUIRED when importing - optional otherwise</param>
        /// <param name="AAccountingPeriodTableRef">Accounting Period Table.  A reference to this table is REQUIRED when importing - optional otherwise</param>
        /// <param name="ACorporateExchangeTableRef">Corporate exchange rate table.  A reference to this table is REQUIRED when importing - optional otherwise</param>
        /// <param name="ACurrencyTableRef">Currency table.  A reference to this table is REQUIRED when importing - optional otherwise</param>
        /// <param name="ABaseCurrency">Ledger base currency.  Required when importing</param>
        /// <param name="AInternationalCurrency">Ledger international currency.  Required when importing</param>
        /// <returns>True if the validation found no data validation errors, otherwise false.</returns>
        public static bool ValidateGiftBatchManual(object AContext,
            AGiftBatchRow ARow,
            ref TVerificationResultCollection AVerificationResultCollection,
            TValidationControlsDict AValidationControlsDict,
            AAccountTable AAccountTableRef = null,
            ACostCentreTable ACostCentreTableRef = null,
            AAccountPropertyTable AAccountPropertyTableRef = null,
            AAccountingPeriodTable AAccountingPeriodTableRef = null,
            ACorporateExchangeRateTable ACorporateExchangeTableRef = null,
            ACurrencyTable ACurrencyTableRef = null,
            string ABaseCurrency = null,
            string AInternationalCurrency = null)
        {
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TScreenVerificationResult VerificationResult;
            object ValidationContext;
            int VerifResultCollAddedCount = 0;

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

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

            // Bank Account Code must be active
            ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnBankAccountCodeId];
            ValidationContext = ARow.BankAccountCode;

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                if (!ARow.IsBankAccountCodeNull() && (AAccountTableRef != null))
                {
                    // We even need to check that the code exists!
                    AAccountRow foundRow = (AAccountRow)AAccountTableRef.Rows.Find(new object[] { ARow.LedgerNumber, ARow.BankAccountCode });

                    if ((foundRow == null)
                        && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                            AContext,
                            new TVerificationResult(ValidationContext,
                                String.Format(Catalog.GetString("Unknown bank account code '{0}'."), ARow.BankAccountCode),
                                TResultSeverity.Resv_Critical),
                            ValidationColumn))
                    {
                        VerifResultCollAddedCount++;
                    }

                    // If it does exist and the account is a foreign currency account then the batch currency must match
                    if ((foundRow != null) && foundRow.ForeignCurrencyFlag)
                    {
                        if ((foundRow.ForeignCurrencyCode != ARow.CurrencyCode) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                AContext,
                                new TVerificationResult(ValidationContext,
                                    String.Format(Catalog.GetString(
                                            "The bank account code '{0}' is a foreign currency account so the currency code for the batch must be '{1}'."),
                                        ARow.BankAccountCode, foundRow.ForeignCurrencyCode),
                                    TResultSeverity.Resv_Critical),
                                ValidationColumn))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }

                    // If it does exist it must be a posting account
                    if (foundRow != null)
                    {
                        if (!foundRow.PostingStatus && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                AContext,
                                new TVerificationResult(ValidationContext,
                                    String.Format(Catalog.GetString(
                                            "The bank account code '{0}' is not a posting account."),
                                        ARow.BankAccountCode),
                                    TResultSeverity.Resv_Critical),
                                ValidationColumn))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }

                    if ((foundRow != null) && (ARow.GiftType == MFinanceConstants.GIFT_TYPE_GIFT))
                    {
                        // The account must be a bank account as defined in the AccountProperty table
                        if (AAccountPropertyTableRef != null)
                        {
                            AAccountPropertyRow foundRow2 = (AAccountPropertyRow)AAccountPropertyTableRef.Rows.Find(
                                new object[] { ARow.LedgerNumber, ARow.BankAccountCode, "BANK ACCOUNT", "true" });

                            if ((foundRow2 == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                    AContext,
                                    new TVerificationResult(ValidationContext,
                                        String.Format(Catalog.GetString(
                                                "The bank account code '{0}' must be associated with a real 'Bank Account' when the gift type is a 'Gift'."),
                                            ARow.BankAccountCode),
                                        TResultSeverity.Resv_Critical),
                                    ValidationColumn))
                            {
                                VerifResultCollAddedCount++;
                            }
                        }
                    }
                }

                VerificationResult = (TScreenVerificationResult)TStringChecks.ValidateValueIsActive(ARow.LedgerNumber,
                    AAccountTableRef,
                    ValidationContext.ToString(),
                    AAccountTable.GetAccountActiveFlagDBName(),
                    AContext,
                    ValidationColumn,
                    ValidationControlsData.ValidationControl);

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

            // Bank Cost Centre Code validation
            ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnBankCostCentreId];
            ValidationContext = ARow.BankCostCentre;

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                if (!ARow.IsBankCostCentreNull() && (ACostCentreTableRef != null))
                {
                    // We even need to check that the code exists!
                    ACostCentreRow foundRow = (ACostCentreRow)ACostCentreTableRef.Rows.Find(new object[] { ARow.LedgerNumber, ARow.BankCostCentre });

                    if ((foundRow == null)
                        && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                            AContext,
                            new TScreenVerificationResult(ValidationContext,
                                ValidationColumn,
                                String.Format(Catalog.GetString("Unknown Bank Cost Centre: '{0}'."), ARow.BankCostCentre),
                                ValidationControlsData.ValidationControl,
                                TResultSeverity.Resv_Critical),
                            ValidationColumn))
                    {
                        VerifResultCollAddedCount++;
                    }

                    // Even if the cost centre exists it must be a 'posting' cost centre
                    if (foundRow != null)
                    {
                        if (!foundRow.PostingCostCentreFlag && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                AContext,
                                new TScreenVerificationResult(ValidationContext,
                                    ValidationColumn,
                                    String.Format(Catalog.GetString("The cost centre '{0}' is not a Posting Cost Centre."), ARow.BankCostCentre),
                                    ValidationControlsData.ValidationControl,
                                    TResultSeverity.Resv_Critical),
                                ValidationColumn))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }
                }

                // Bank Cost Centre Code must be active
                VerificationResult = (TScreenVerificationResult)TStringChecks.ValidateValueIsActive(ARow.LedgerNumber,
                    ACostCentreTableRef,
                    ValidationContext.ToString(),
                    ACostCentreTable.GetCostCentreActiveFlagDBName(),
                    AContext,
                    ValidationColumn,
                    ValidationControlsData.ValidationControl);

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

            // Currency Code validation
            ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnCurrencyCodeId];
            ValidationContext = ARow.BatchNumber;

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                if (!ARow.IsCurrencyCodeNull() && (ACurrencyTableRef != null))
                {
                    // Currency code must exist in the currency table
                    ACurrencyRow foundRow = (ACurrencyRow)ACurrencyTableRef.Rows.Find(ARow.CurrencyCode);

                    if ((foundRow == null)
                        && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                            AContext,
                            new TScreenVerificationResult(ValidationContext,
                                ValidationColumn,
                                String.Format(Catalog.GetString("Unknown currency code '{0}'."), ARow.CurrencyCode),
                                ValidationControlsData.ValidationControl,
                                TResultSeverity.Resv_Critical),
                            ValidationColumn))
                    {
                        VerifResultCollAddedCount++;
                    }
                }
            }

            // 'Exchange Rate' must be greater than 0
            ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnExchangeRateToBaseId];
            ValidationContext = ARow.BatchNumber;

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

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

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

            // 'Effective From Date' must be valid
            ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnGlEffectiveDateId];
            ValidationContext = ARow.BatchNumber;

            DateTime StartDateCurrentPeriod;
            DateTime EndDateLastForwardingPeriod;
            TSharedFinanceValidationHelper.GetValidPostingDateRange(ARow.LedgerNumber,
                out StartDateCurrentPeriod,
                out EndDateLastForwardingPeriod);

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                VerificationResult = (TScreenVerificationResult)TDateChecks.IsDateBetweenDates(ARow.GlEffectiveDate,
                    StartDateCurrentPeriod,
                    EndDateLastForwardingPeriod,
                    ValidationControlsData.ValidationControlLabel + (IsImporting ? String.Empty : " of Batch Number " + ValidationContext.ToString()),
                    TDateBetweenDatesCheckType.dbdctUnspecific,
                    TDateBetweenDatesCheckType.dbdctUnspecific,
                    AContext,
                    ValidationColumn,
                    ValidationControlsData.ValidationControl);

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

                // If the GL date was good we need to have a corporate exchange rate for base currency to Intl for the first day of the period
                if ((VerificationResult == null) && (ACorporateExchangeTableRef != null) && !ARow.IsGlEffectiveDateNull()
                    && (ABaseCurrency != null) && (AInternationalCurrency != null) && (ABaseCurrency != AInternationalCurrency))
                {
                    DateTime firstOfMonth;

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

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

            // Gift Type must be one of our predefined constants
            ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnGiftTypeId];
            ValidationContext = ARow.BatchNumber;

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                if (!ARow.IsGiftTypeNull())
                {
                    // Ensure the gift type is correct and that it matches one of the allowable options (applies when importing)
                    if ((ARow.GiftType != MFinanceConstants.GIFT_TYPE_GIFT)
                        && (ARow.GiftType != MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND)
                        && (ARow.GiftType != MFinanceConstants.GIFT_TYPE_OTHER))
                    {
                        if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                                AContext,
                                new TScreenVerificationResult(ValidationContext,
                                    ValidationColumn,
                                    String.Format(Catalog.GetString("Unknown gift type '{0}'. Expected one of '{1}', '{2}' or '{3}'"),
                                        ARow.GiftType,
                                        MFinanceConstants.GIFT_TYPE_GIFT, MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND, MFinanceConstants.GIFT_TYPE_OTHER),
                                    ValidationControlsData.ValidationControl,
                                    TResultSeverity.Resv_Critical),
                                ValidationColumn))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }
                }
            }

            return VerifResultCollAddedCount == 0;
        }
        private void UpdateControlsProtection(AGiftDetailRow ARow)
        {
            bool firstIsEnabled = (ARow != null) && (ARow.DetailNumber == 1) && !ViewMode;
            bool pnlDetailsEnabledState = false;

            dtpDateEntered.Enabled = firstIsEnabled;
            txtDetailDonorKey.Enabled = firstIsEnabled;
            cmbDetailMethodOfGivingCode.Enabled = firstIsEnabled;

            cmbDetailMethodOfPaymentCode.Enabled = firstIsEnabled && !BatchHasMethodOfPayment();
            txtDetailReference.Enabled = firstIsEnabled;
            cmbDetailReceiptLetterCode.Enabled = firstIsEnabled;

            if (FBatchRow == null)
            {
                FBatchRow = GetCurrentBatchRow();
            }

            if (ARow == null)
            {
                PnlDetailsProtected = (ViewMode
                                       || !FBatchUnposted
                                       );
            }
            else
            {
                PnlDetailsProtected = (ViewMode
                                       || !FBatchUnposted
                                       || (ARow.GiftTransactionAmount < 0 && GetGiftRow(ARow.GiftTransactionNumber).ReceiptNumber != 0)
                                       );    // taken from old petra
            }

            pnlDetailsEnabledState = (!PnlDetailsProtected && grdDetails.Rows.Count > 1);
            pnlDetails.Enabled = pnlDetailsEnabledState;

            btnDelete.Enabled = pnlDetailsEnabledState;
            btnDeleteAll.Enabled = btnDelete.Enabled;
            btnNewDetail.Enabled = !PnlDetailsProtected;
            btnNewGift.Enabled = !PnlDetailsProtected;
        }
        private void UpdateControlsProtection(AGiftDetailRow ARow)
        {
            bool firstIsEnabled = (ARow != null) && (ARow.DetailNumber == 1) && !ViewMode;
            bool pnlDetailsEnabledState = false;

            dtpDateEntered.Enabled = firstIsEnabled;
            txtDetailDonorKey.Enabled = firstIsEnabled;
            cmbDetailMethodOfGivingCode.Enabled = firstIsEnabled;

            cmbDetailMethodOfPaymentCode.Enabled = firstIsEnabled && !BatchHasMethodOfPayment();
            txtDetailReference.Enabled = firstIsEnabled;
            cmbDetailReceiptLetterCode.Enabled = firstIsEnabled;

            if (FBatchRow == null)
            {
                FBatchRow = GetBatchRow();
            }

            if (ARow == null)
            {
                PnlDetailsProtected = (ViewMode
                                       || !FBatchUnposted
                                       );
            }
            else
            {
                PnlDetailsProtected = (ViewMode
                                       || !FBatchUnposted
                                       || (ARow.GiftTransactionAmount < 0 && GetGiftRow(ARow.GiftTransactionNumber).ReceiptNumber != 0)
                                       );    // taken from old petra
            }

            pnlDetailsEnabledState = (!PnlDetailsProtected && grdDetails.Rows.Count > 1);
            pnlDetails.Enabled = pnlDetailsEnabledState;

            btnDelete.Enabled = pnlDetailsEnabledState;
            btnDeleteAll.Enabled = btnDelete.Enabled;
            btnNewDetail.Enabled = !PnlDetailsProtected;
            btnNewGift.Enabled = !PnlDetailsProtected;

            mniDonorFinanceDetails.Enabled = (ARow != null);

            // Only show the NoReceipt check box under special circumstances
            chkNoReceiptOnAdjustment.Visible = IsUnpostedReversedDetailAdjustment(ARow);
            chkNoReceiptOnAdjustment.Enabled = firstIsEnabled;
        }
        /// <summary>
        /// update the transaction method payment from outside
        /// </summary>
        public void UpdateMethodOfPayment(bool ACalledLocally)
        {
            Int32 LedgerNumber;
            Int32 BatchNumber;

            if (ACalledLocally)
            {
                cmbDetailMethodOfPaymentCode.SetSelectedString(FBatchMethodOfPayment);
                return;
            }

            if (!((TFrmGiftBatch) this.ParentForm).GetBatchControl().FBatchLoaded)
            {
                return;
            }

            FBatchRow = GetBatchRow();

            if (FBatchRow == null)
            {
                FBatchRow = ((TFrmGiftBatch) this.ParentForm).GetBatchControl().GetSelectedDetailRow();
            }

            FBatchMethodOfPayment = ((TFrmGiftBatch) this.ParentForm).GetBatchControl().MethodOfPaymentCode;

            LedgerNumber = FBatchRow.LedgerNumber;
            BatchNumber = FBatchRow.BatchNumber;

            if (!LoadGiftDataForBatch(LedgerNumber, BatchNumber))
            {
                //No transactions exist to process or corporate exchange rate not found
                return;
            }

            if ((FLedgerNumber == LedgerNumber) || (FBatchNumber == BatchNumber))
            {
                //Rows already active in transaction tab. Need to set current row ac code below will not update selected row
                if (FPreviouslySelectedDetailRow != null)
                {
                    FPreviouslySelectedDetailRow.MethodOfPaymentCode = FBatchMethodOfPayment;
                    cmbDetailMethodOfPaymentCode.SetSelectedString(FBatchMethodOfPayment);
                }
            }

            //Update all transactions
            foreach (AGiftRow giftRow in FMainDS.AGift.Rows)
            {
                if ((giftRow.RowState != DataRowState.Deleted)
                    && giftRow.BatchNumber.Equals(BatchNumber) && giftRow.LedgerNumber.Equals(LedgerNumber)
                    && (giftRow.MethodOfPaymentCode != FBatchMethodOfPayment))
                {
                    giftRow.MethodOfPaymentCode = FBatchMethodOfPayment;
                }
            }
        }
        private void ValidateDataDetailsManual(GiftBatchTDSAGiftDetailRow ARow)
        {
            //Ensure FBatchRow is correct, as this gets called from the batch tab validation
            FBatchRow = GetBatchRow();

            if ((ARow == null) || (ARow.RowState == DataRowState.Deleted) || (FBatchRow == null)
                || (FBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)
                || (FBatchRow.BatchNumber != ARow.BatchNumber))
            {
                return;
            }

            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;

            if ((ARow.RecipientField != 0)
                && (ARow.RecipientKey != 0)
                && ((int)ARow.RecipientField / 1000000 != ARow.LedgerNumber))
            {
                TVerificationResultCollection TempVerificationResultCollection;

                if (!TRemote.MFinance.Gift.WebConnectors.IsRecipientLedgerNumberSetupForILT(FLedgerNumber, FPreviouslySelectedDetailRow.RecipientKey,
                        Convert.ToInt64(txtDetailRecipientLedgerNumber.Text), out TempVerificationResultCollection))
                {
                    DataColumn ValidationColumn = ARow.Table.Columns[AGiftDetailTable.ColumnRecipientLedgerNumberId];
                    object ValidationContext = String.Format("Batch Number {0} (transaction:{1} detail:{2})",
                        ARow.BatchNumber,
                        ARow.GiftTransactionNumber,
                        ARow.DetailNumber);

                    TValidationControlsData ValidationControlsData;

                    if (FValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                    {
                        TVerificationResult VerificationResult = new TVerificationResult(this,
                            ValidationContext.ToString() + ": " + TempVerificationResultCollection[0].ResultText,
                            PetraErrorCodes.ERR_RECIPIENTFIELD_NOT_ILT, TResultSeverity.Resv_Critical);

                        VerificationResultCollection.Auto_Add_Or_AddOrRemove(this,
                            new TScreenVerificationResult(VerificationResult, ValidationColumn, ValidationControlsData.ValidationControl),
                            ValidationColumn, true);
                    }
                }
            }

            TSharedFinanceValidation_Gift.ValidateGiftDetailManual(this, ARow, ref VerificationResultCollection,
                FValidationControlsDict, txtDetailRecipientKey.CurrentPartnerClass, null, null, null);

            //It is necessary to validate the unbound control for date entered. This requires us to pass the control.
            AGiftRow giftRow = GetGiftRow(ARow.GiftTransactionNumber);

            TSharedFinanceValidation_Gift.ValidateGiftManual(this,
                giftRow,
                FBatchRow.BatchYear,
                FBatchRow.BatchPeriod,
                dtpDateEntered,
                ref VerificationResultCollection,
                FValidationControlsDict);

            if (FTaxDeductiblePercentageEnabled)
            {
                ValidateTaxDeductiblePct(ARow, ref VerificationResultCollection);
            }
        }
        /// <summary>
        /// Refresh the dataset for this form
        /// </summary>
        public void RefreshAllData()
        {
            Cursor prevCursor = ParentForm.Cursor;

            ParentForm.Cursor = Cursors.WaitCursor;

            if ((FMainDS != null) && (FMainDS.AGiftDetail != null))
            {
                FMainDS.AGiftDetail.Rows.Clear();
            }

            // Get the current batch row from the batch tab
            FBatchRow = GetBatchRow();

            if (FBatchRow != null)
            {
                // Be sure to pass the true parameter because we definitely need to update FMainDS.AGiftDetail as it is now empty!
                LoadGifts(FBatchRow.LedgerNumber, FBatchRow.BatchNumber, FBatchRow.BatchStatus, true);
            }

            ParentForm.Cursor = prevCursor;
        }
        /// <summary>
        /// update the transaction DateEntered from outside
        /// </summary>
        /// <param name="ABatchRow"></param>
        public void UpdateDateEntered(AGiftBatchRow ABatchRow)
        {
            Int32 ledgerNumber;
            Int32 batchNumber;
            DateTime batchEffectiveDate;

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

            ledgerNumber = ABatchRow.LedgerNumber;
            batchNumber = ABatchRow.BatchNumber;
            batchEffectiveDate = ABatchRow.GlEffectiveDate;

            DataView giftDataView = new DataView(FMainDS.AGift);

            giftDataView.RowFilter = String.Format("{0}={1} And {2}={3}",
                AGiftTable.GetLedgerNumberDBName(),
                ledgerNumber,
                AGiftTable.GetBatchNumberDBName(),
                batchNumber);

            ((TFrmGiftBatch)ParentForm).EnsureGiftDataPresent(ledgerNumber, batchNumber);

            if ((FPreviouslySelectedDetailRow != null) && (FBatchNumber == batchNumber))
            {
                //Rows already active in transaction tab. Need to set current row as code below will not update currently selected row
                FGLEffectivePeriodChanged = true;
                GetSelectedDetailRow().DateEntered = batchEffectiveDate;
            }

            //Update all gift rows in this batch
            foreach (DataRowView dv in giftDataView)
            {
                AGiftRow giftRow = (AGiftRow)dv.Row;
                giftRow.DateEntered = batchEffectiveDate;
            }

            //If current row exists then refresh details
            if (FGLEffectivePeriodChanged)
            {
                ShowDetails();
            }
        }
        private void ShowDetailsManual(AGiftBatchRow ARow)
        {
            ((TFrmGiftBatch)ParentForm).EnableTransactions(ARow != null
                && ARow.BatchStatus != MFinanceConstants.BATCH_CANCELLED);

            if (ARow == null)
            {
                FSelectedBatchNumber = -1;
                dtpDetailGlEffectiveDate.Date = FDefaultDate;
                UpdateChangeableStatus();
                txtDetailHashTotal.CurrencyCode = String.Empty;
                return;
            }

            bool Unposted = (ARow.BatchStatus == MFinanceConstants.BATCH_UNPOSTED);

            if (!FPostingLogicObject.PostingInProgress)
            {
                bool ActiveOnly = Unposted;
                RefreshBankAccountAndCostCentreFilters(ActiveOnly, ARow);
            }

            FLedgerNumber = ARow.LedgerNumber;
            FSelectedBatchNumber = ARow.BatchNumber;

            FPetraUtilsObject.DetailProtectedMode = (!Unposted || ViewMode);
            UpdateChangeableStatus();

            //Update the batch period if necessary
            UpdateBatchPeriod();

            RefreshCurrencyAndExchangeRateControls();

            if (Unposted)
            {
                //Check for inactive cost centre and/or account codes
                if (!cmbDetailBankCostCentre.SetSelectedString(ARow.BankCostCentre, -1))
                {
                    MessageBox.Show(String.Format(Catalog.GetString("Batch {0} - the Cost Centre: '{1}' is no longer active and so cannot be used."),
                            ARow.BatchNumber,
                            ARow.BankCostCentre),
                        Catalog.GetString("Gift Batch"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                if (!cmbDetailBankAccountCode.SetSelectedString(ARow.BankAccountCode, -1))
                {
                    MessageBox.Show(String.Format(Catalog.GetString("Batch {0} - the Bank Account: '{1}' is no longer active and so cannot be used."),
                            ARow.BatchNumber,
                            ARow.BankAccountCode),
                        Catalog.GetString("Gift Batch"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        /// <summary>
        /// Import a transactions file or a clipboard equivalent
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch to import to</param>
        /// <param name="AImportSource">The import source - eg File or Clipboard</param>
        /// <returns>True if the import was successful</returns>
        public bool ImportTransactions(AGiftBatchRow ACurrentBatchRow, TGiftImportDataSourceEnum AImportSource)
        {
            bool ok = false;
            String importString;
            String impOptions;
            OpenFileDialog dialog = null;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to import
                MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString(
                        "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                MessageBox.Show(Catalog.GetString("Please select an unposted batch to import transactions."), Catalog.GetString(
                        "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (ACurrentBatchRow.LastGiftNumber > 0)
            {
                if (MessageBox.Show(Catalog.GetString(
                            "The current batch already contains some gift transactions.  Do you really want to add more transactions to this batch?"),
                        Catalog.GetString("Gift Transaction Import"),
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return false;
                }
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportSource == TGiftImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                        Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData = importString;
                FdlgSeparator.DateFormat = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportSource == TGiftImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                dialog.FileName = TUserDefaults.GetStringDefault("Imp Filename",
                    TClientSettings.GetExportPath() + Path.DirectorySeparatorChar + "import.csv");

                dialog.Title = Catalog.GetString("Import Transactions from CSV File");
                dialog.Filter = Catalog.GetString("Gift Transactions files (*.csv)|*.csv");
                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                            Catalog.GetString("Gift Import"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);
                        return false;
                    }

                    importString = File.ReadAllText(dialog.FileName);

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return false;
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions = String.Empty;
                importString = String.Empty;
            }

            if (FdlgSeparator.ShowDialog() == DialogResult.OK)
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);

                bool Repeat = true;

                while (Repeat)
                {
                    Repeat = false;

                    TVerificationResultCollection AMessages = new TVerificationResultCollection();
                    GiftBatchTDSAGiftDetailTable NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable();

                    Thread ImportThread = new Thread(() => ImportGiftTransactions(
                            requestParams,
                            importString,
                            ACurrentBatchRow.BatchNumber,
                            out AMessages,
                            out ok,
                            out NeedRecipientLedgerNumber));

                    using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                    {
                        ImportDialog.ShowDialog();
                    }

                    ShowMessages(AMessages);

                    // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination
                    // then the import will have failed and we need to alert the user
                    if (NeedRecipientLedgerNumber.Rows.Count > 0)
                    {
                        bool OfferToRunImportAgain = true;

                        // for each gift in which the recipient needs a Git Destination
                        foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows)
                        {
                            if (MessageBox.Show(string.Format(
                                        Catalog.GetString(
                                            "Gift Import has been cancelled as the recipient '{0}' ({1}) has no Gift Destination assigned."),
                                        Row.RecipientDescription, Row.RecipientKey) +
                                    "\n\n" +
                                    Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"),
                                    Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                                == DialogResult.Yes)
                            {
                                // allow the user to assign a Gift Destingation
                                TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey);
                                GiftDestinationForm.ShowDialog();
                            }
                            else
                            {
                                OfferToRunImportAgain = false;
                            }
                        }

                        // if the user has clicked yes to assigning Gift Destinations then offer to restart the import
                        if (OfferToRunImportAgain
                            && (MessageBox.Show(Catalog.GetString("Would you like to import these Gift Transactions again?"),
                                    Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button1)
                                == DialogResult.Yes))
                        {
                            Repeat = true;
                        }
                    }
                }
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                    Catalog.GetString("Gift Import"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                SaveUserDefaults(dialog, impOptions);
                //FMyUserControl.LoadBatchesForCurrentYear();
                FPetraUtilsObject.DisableSaveButton();
            }

            return ok;
        }
Exemplo n.º 41
0
        private void ParseTransactionLine(AGiftRow AGift, AGiftBatchRow AGiftBatch, ref AGiftRow APreviousGift, int ANumberOfColumns,
            ref decimal ATotalBatchAmount, ref string AImportMessage, int ARowNumber, TVerificationResultCollection AMessages,
            TValidationControlsDict AValidationControlsDictGift, TValidationControlsDict AValidationControlsDictGiftDetail,
            ACostCentreTable AValidationCostCentreTable, AMotivationGroupTable AValidationMotivationGroupTable,
            AMotivationDetailTable AValidationMotivationDetailTable, AMethodOfGivingTable AValidationMethodOfGivingTable,
            AMethodOfPaymentTable AValidationMethodOfPaymentTable,
            ref GiftBatchTDSAGiftDetailTable ANeedRecipientLedgerNumber, out AGiftDetailRow AGiftDetails)
        {
            // Is this the format with extra columns?
            // Actually if it has the extra columns but does not have the optional final 8 columns we cannot distiguish using this test...
            //   A file without extra columns will have between 13 and 21 columns - depending on whether some of the optional ones at the end are included.
            //   A file with extra columns will be between 19 and 27.
            //  So any count between 19 and 21 is ambiguous.  We will assume that if the file has extra columns it also has
            //   at least enough of the optional ones to exceed 21.
            bool HasExtraColumns = (ANumberOfColumns > 21);

            AImportMessage = Catalog.GetString("Importing the gift data");

            AGift.DonorKey = ImportInt64(Catalog.GetString("Donor key"),
                FMainDS.AGift.ColumnDonorKey, ARowNumber, AMessages, AValidationControlsDictGift);

            ImportString(Catalog.GetString("short name of donor (unused)"), null, null); // unused

            // This group is optional and database NULL's are allowed
            AGift.MethodOfGivingCode = ImportString(Catalog.GetString("Method of giving Code"),
                FMainDS.AGift.ColumnMethodOfGivingCode, AValidationControlsDictGift, false);
            AGift.MethodOfPaymentCode = ImportString(Catalog.GetString("Method Of Payment Code"),
                FMainDS.AGift.ColumnMethodOfPaymentCode, AValidationControlsDictGift, false);
            AGift.Reference = ImportString(Catalog.GetString("Reference"),
                FMainDS.AGift.ColumnReference, AValidationControlsDictGift, false);
            AGift.ReceiptLetterCode = ImportString(Catalog.GetString("Receipt letter code"),
                FMainDS.AGift.ColumnReceiptLetterCode, AValidationControlsDictGift, false);

            if (HasExtraColumns)
            {
                ImportInt32(Catalog.GetString("Receipt number"),
                    FMainDS.AGift.ColumnReceiptNumber, ARowNumber, AMessages, AValidationControlsDictGift);
                ImportBoolean(Catalog.GetString("First time gift"),
                    FMainDS.AGift.ColumnFirstTimeGift, AValidationControlsDictGift);
                ImportBoolean(Catalog.GetString("Receipt printed"),
                    FMainDS.AGift.ColumnReceiptPrinted, AValidationControlsDictGift);
            }

            AImportMessage = Catalog.GetString("Importing the gift details");

            AGiftDetails = FMainDS.AGiftDetail.NewRowTyped(true);

            if ((APreviousGift != null) && (AGift.DonorKey == APreviousGift.DonorKey)
                && (AGift.MethodOfGivingCode == APreviousGift.MethodOfGivingCode)
                && (AGift.MethodOfPaymentCode == APreviousGift.MethodOfPaymentCode)
                && (AGift.Reference == APreviousGift.Reference)
                && (AGift.ReceiptLetterCode == APreviousGift.ReceiptLetterCode)
                && (AGift.ReceiptNumber == APreviousGift.ReceiptNumber)
                && (AGift.FirstTimeGift == APreviousGift.FirstTimeGift)
                && (AGift.ReceiptPrinted == APreviousGift.ReceiptPrinted))
            {
                // this row is a new detail for the previousGift
                AGift = APreviousGift;
                AGift.LastDetailNumber++;
                AGiftDetails.DetailNumber = AGift.LastDetailNumber;
            }
            else
            {
                APreviousGift = AGift;
                AGift.LedgerNumber = AGiftBatch.LedgerNumber;
                AGift.BatchNumber = AGiftBatch.BatchNumber;
                AGift.GiftTransactionNumber = AGiftBatch.LastGiftNumber + 1;
                AGiftBatch.LastGiftNumber++;
                AGift.LastDetailNumber = 1;
                FMainDS.AGift.Rows.Add(AGift);
                AGiftDetails.DetailNumber = 1;
            }

            AGiftDetails.LedgerNumber = AGift.LedgerNumber;
            AGiftDetails.BatchNumber = AGiftBatch.BatchNumber;
            AGiftDetails.GiftTransactionNumber = AGift.GiftTransactionNumber;
            FMainDS.AGiftDetail.Rows.Add(AGiftDetails);

            AGiftDetails.RecipientKey = ImportInt64(Catalog.GetString("Recipient key"),
                FMainDS.AGiftDetail.ColumnRecipientKey, ARowNumber, AMessages, AValidationControlsDictGiftDetail);

            ImportString(Catalog.GetString("short name of recipient (unused)"), null, null); // unused

            if (HasExtraColumns)
            {
                ImportInt32(Catalog.GetString("Recipient ledger number"),
                    FMainDS.AGiftDetail.ColumnRecipientLedgerNumber, ARowNumber, AMessages, AValidationControlsDictGiftDetail);
            }

            // we always calculate RecipientLedgerNumber
            AGiftDetails.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(
                AGiftDetails.RecipientKey, AGiftBatch.GlEffectiveDate);

            decimal currentGiftAmount = ImportDecimal(Catalog.GetString("Gift amount"),
                FMainDS.AGiftDetail.ColumnGiftTransactionAmount, ARowNumber, AMessages, AValidationControlsDictGiftDetail);
            AGiftDetails.GiftTransactionAmount = currentGiftAmount;     // amount in batch currency
            ATotalBatchAmount += currentGiftAmount;

            AGiftDetails.GiftAmount = GLRoutines.Divide(currentGiftAmount, AGiftBatch.ExchangeRateToBase);      // amount in ledger currency

            if (HasExtraColumns)
            {
                // amount in international currency
                ImportDecimal(Catalog.GetString("Gift amount intl"),
                    FMainDS.AGiftDetail.ColumnGiftAmountIntl, ARowNumber, AMessages, AValidationControlsDictGiftDetail);
            }

            AGiftDetails.ConfidentialGiftFlag = ImportBoolean(Catalog.GetString("Confidential gift"),
                FMainDS.AGiftDetail.ColumnConfidentialGiftFlag, AValidationControlsDictGiftDetail, "no");
            AGiftDetails.MotivationGroupCode = ImportString(Catalog.GetString("Motivation group code"),
                FMainDS.AGiftDetail.ColumnMotivationGroupCode, AValidationControlsDictGiftDetail);
            AGiftDetails.MotivationDetailCode = ImportString(Catalog.GetString("Motivation detail"),
                FMainDS.AGiftDetail.ColumnMotivationDetailCode, AValidationControlsDictGiftDetail);

            if (HasExtraColumns)
            {
                ImportString(Catalog.GetString("Cost centre code"),
                    FMainDS.AGiftDetail.ColumnCostCentreCode, AValidationControlsDictGiftDetail);
            }

            // "In Petra Cost Centre is always inferred from recipient field and motivation detail so is not needed in the import."
            AGiftDetails.CostCentreCode = InferCostCentre(AGiftDetails);

            // All the remaining columns are optional and can contain database NULL
            AGiftDetails.GiftCommentOne = ImportString(Catalog.GetString("Gift comment one"),
                FMainDS.AGiftDetail.ColumnGiftCommentOne, AValidationControlsDictGiftDetail, false);
            string commentOneType = ImportString(Catalog.GetString("Comment one type"),
                FMainDS.AGiftDetail.ColumnCommentOneType, AValidationControlsDictGiftDetail, false);

            AGiftDetails.MailingCode = ImportString(Catalog.GetString("Mailing code"),
                FMainDS.AGiftDetail.ColumnMailingCode, AValidationControlsDictGiftDetail, false);

            AGiftDetails.GiftCommentTwo = ImportString(Catalog.GetString("Gift comment two"),
                FMainDS.AGiftDetail.ColumnGiftCommentTwo, AValidationControlsDictGiftDetail, false);
            string commentTwoType = ImportString(Catalog.GetString("Comment two type"),
                FMainDS.AGiftDetail.ColumnCommentTwoType, AValidationControlsDictGiftDetail, false);
            AGiftDetails.GiftCommentThree = ImportString(Catalog.GetString("Gift comment three"),
                FMainDS.AGiftDetail.ColumnGiftCommentThree, AValidationControlsDictGiftDetail, false);
            string commentThreeType = ImportString(Catalog.GetString("Comment three type"),
                FMainDS.AGiftDetail.ColumnCommentThreeType, AValidationControlsDictGiftDetail, false);

            SetCommentTypeCase(ref commentOneType);
            AGiftDetails.CommentOneType = commentOneType;

            SetCommentTypeCase(ref commentTwoType);
            AGiftDetails.CommentOneType = commentTwoType;

            SetCommentTypeCase(ref commentThreeType);
            AGiftDetails.CommentOneType = commentThreeType;

            // Find the default Tax deductabilty from the motivation detail. This ensures that the column can be missing.
            AMotivationDetailRow motivationDetailRow = (AMotivationDetailRow)AValidationMotivationDetailTable.Rows.Find(
                new object[] { FLedgerNumber, AGiftDetails.MotivationGroupCode, AGiftDetails.MotivationDetailCode });
            string defaultTaxDeductible =
                ((motivationDetailRow != null) && !motivationDetailRow.IsTaxDeductibleAccountNull()
                 && motivationDetailRow.TaxDeductible) ? "yes" : "no";

            AGiftDetails.TaxDeductible = ImportBoolean(Catalog.GetString("Tax deductible"),
                FMainDS.AGiftDetail.ColumnTaxDeductible, AValidationControlsDictGiftDetail, defaultTaxDeductible);

            // Date entered cannot be imported although it can be modified in the GUI.
            // This is because it would have to be the last column in the import for compatibility
            // but it belongs with the gift and not the detail so it would need to go in an earlier column.
            // For now the import date entered is the effective date.
            AGift.DateEntered = AGiftBatch.GlEffectiveDate;

            // Enforce the correct case for our GIFT constant
            if (String.Compare(AGiftDetails.MotivationGroupCode, MFinanceConstants.MOTIVATION_GROUP_GIFT, true) == 0)
            {
                AGiftDetails.MotivationGroupCode = MFinanceConstants.MOTIVATION_GROUP_GIFT;
            }

            TPartnerClass RecipientClass;
            string RecipientDescription;
            TPartnerServerLookups.GetPartnerShortName(AGiftDetails.RecipientKey, out RecipientDescription, out RecipientClass);

            // If the gift has a Family recipient with no Gift Destination then the import will fail. Gift is added to a table and returned to client.
            if ((AGiftDetails.RecipientLedgerNumber == 0) && (AGiftDetails.MotivationGroupCode == MFinanceConstants.MOTIVATION_GROUP_GIFT))
            {
                if (RecipientClass == TPartnerClass.FAMILY)
                {
                    ((GiftBatchTDSAGiftDetailRow)AGiftDetails).RecipientDescription = RecipientDescription;
                    ANeedRecipientLedgerNumber.Rows.Add((object[])AGiftDetails.ItemArray.Clone());
                }
            }

            AImportMessage = Catalog.GetString("Validating the gift data");

            int messageCountBeforeValidate = AMessages.Count;

            // Do our standard validation on this gift
            AGiftValidation.Validate(this, AGift, ref AMessages, AValidationControlsDictGift);
            TSharedFinanceValidation_Gift.ValidateGiftManual(this, AGift, AGiftBatch.BatchYear, AGiftBatch.BatchPeriod,
                null, ref AMessages, AValidationControlsDictGift, AValidationMethodOfGivingTable, AValidationMethodOfPaymentTable);

            AImportMessage = Catalog.GetString("Validating the gift details data");

            AGiftDetailValidation.Validate(this, AGiftDetails, ref AMessages, AValidationControlsDictGiftDetail);
            TSharedFinanceValidation_Gift.ValidateGiftDetailManual(this, (GiftBatchTDSAGiftDetailRow)AGiftDetails,
                ref AMessages, AValidationControlsDictGiftDetail, RecipientClass, AValidationCostCentreTable, AValidationMotivationGroupTable,
                AValidationMotivationDetailTable, AGiftDetails.RecipientKey);

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

                if (AMessages[i] is TScreenVerificationResult)
                {
                    TVerificationResult downgrade = new TVerificationResult((TScreenVerificationResult)AMessages[i]);
                    AMessages.RemoveAt(i);
                    AMessages.Insert(i, downgrade);
                }
            }
        }
        /// <summary>
        /// Refreshes the filters on the combo boxes
        /// </summary>
        /// <param name="AActiveOnly"></param>
        /// <param name="ARow"></param>
        public void RefreshBankAccountAndCostCentreFilters(bool AActiveOnly, AGiftBatchRow ARow)
        {
            FCmbBankAccountCode.Filter = TFinanceControls.PrepareAccountFilter(true, false, AActiveOnly, true, "");
            FCmbCostCentreCode.Filter = TFinanceControls.PrepareCostCentreFilter(true, false, AActiveOnly, true);

            if (ARow != null)
            {
                FCmbCostCentreCode.SetSelectedString(ARow.BankCostCentre, -1);
                FCmbBankAccountCode.SetSelectedString(ARow.BankAccountCode, -1);
            }
        }
Exemplo n.º 43
0
        void WriteGiftBatchLine(AGiftBatchRow giftBatch)
        {
            WriteStringQuoted("B");
            WriteStringQuoted(giftBatch.BatchDescription);
            WriteStringQuoted(giftBatch.BankAccountCode);

            if (FUseBaseCurrency)
            {
                WriteCurrency(giftBatch.HashTotal * giftBatch.ExchangeRateToBase);
            }
            else
            {
                WriteCurrency(giftBatch.HashTotal);
            }

            WriteDate(giftBatch.GlEffectiveDate);

            if (FUseBaseCurrency)
            {
                WriteStringQuoted(FMainDS.ALedger[0].BaseCurrency);
            }
            else
            {
                WriteStringQuoted(giftBatch.CurrencyCode);
            }

            WriteGeneralNumber(giftBatch.ExchangeRateToBase);
            WriteStringQuoted(giftBatch.BankCostCentre);
            WriteStringQuoted(giftBatch.GiftType, true);
        }
Exemplo n.º 44
0
        private static void AddGiftDetailToGLBatch(ref GLBatchTDS AGLDataset,
            string ACostCentre, string AAccountCode, decimal ATransactionAmount, decimal AAmountInBaseCurrency, decimal AAmountInIntlCurrency,
            AJournalRow AJournal, AGiftBatchRow AGiftBatch)
        {
            ATransactionRow transaction = null;

            // do we have already a transaction for this costcentre&account?
            AGLDataset.ATransaction.DefaultView.RowFilter = String.Format("{0}='{1}' and {2}='{3}'",
                ATransactionTable.GetAccountCodeDBName(),
                AAccountCode,
                ATransactionTable.GetCostCentreCodeDBName(),
                ACostCentre);

            if (AGLDataset.ATransaction.DefaultView.Count == 0)
            {
                transaction = AGLDataset.ATransaction.NewRowTyped();
                transaction.LedgerNumber = AJournal.LedgerNumber;
                transaction.BatchNumber = AJournal.BatchNumber;
                transaction.JournalNumber = AJournal.JournalNumber;
                transaction.TransactionNumber = ++AJournal.LastTransactionNumber;
                transaction.AccountCode = AAccountCode;
                transaction.CostCentreCode = ACostCentre;
                transaction.Narrative = "GB - Gift Batch " + AGiftBatch.BatchNumber.ToString();
                transaction.Reference = "GB" + AGiftBatch.BatchNumber.ToString();
                transaction.DebitCreditIndicator = ATransactionAmount < 0;
                transaction.TransactionAmount = 0;
                transaction.AmountInBaseCurrency = 0;
                transaction.AmountInIntlCurrency = 0;
                transaction.SystemGenerated = true;
                transaction.TransactionDate = AGiftBatch.GlEffectiveDate;

                AGLDataset.ATransaction.Rows.Add(transaction);
            }
            else
            {
                transaction = (ATransactionRow)AGLDataset.ATransaction.DefaultView[0].Row;
            }

            // if gift has same debit/credit indicator as transaction
            if (transaction.DebitCreditIndicator == ATransactionAmount < 0)
            {
                transaction.TransactionAmount += Math.Abs(ATransactionAmount);
                transaction.AmountInBaseCurrency += Math.Abs(AAmountInBaseCurrency);
                transaction.AmountInIntlCurrency += Math.Abs(AAmountInIntlCurrency);
            }
            // if gift has a different debit/credit indicator as transaction
            else
            {
                transaction.TransactionAmount -= Math.Abs(ATransactionAmount);
                transaction.AmountInBaseCurrency -= Math.Abs(AAmountInBaseCurrency);
                transaction.AmountInIntlCurrency -= Math.Abs(AAmountInIntlCurrency);

                // if transaction amount has went negative then the debit/credit indicator must change
                if (transaction.TransactionAmount < 0)
                {
                    transaction.TransactionAmount = Math.Abs(transaction.TransactionAmount);
                    transaction.AmountInBaseCurrency = Math.Abs(transaction.AmountInBaseCurrency);
                    transaction.AmountInIntlCurrency = Math.Abs(transaction.AmountInIntlCurrency);

                    transaction.DebitCreditIndicator = !transaction.DebitCreditIndicator;
                }
            }

            if (transaction.TransactionAmount == 0)
            {
                transaction.Delete();
            }
        }
Exemplo n.º 45
0
        /// <summary>
        /// This "Einzahlungsschein mit Referenznummer" (ESR) input format is only used in Switzerland.
        /// This method could be pulled out of here, but sits here quite nicely.
        /// </summary>
        /// <param name="AImportLine"></param>
        /// <param name="AgiftBatch"></param>
        /// <param name="Agift"></param>
        /// <param name="AgiftDetails"></param>
        /// <param name="AIntlRateToBase"></param>
        /// <param name="AMotivationDetailTable"></param>
        /// <param name="ANeedRecipientLedgerNumber"></param>
        /// <param name="AMessages"></param>
        /// <returns></returns>
        private Boolean ParseEsrTransactionLine(
            String AImportLine,
            AGiftBatchRow AgiftBatch,
            AGiftRow Agift,
            AGiftDetailRow AgiftDetails,
            Decimal AIntlRateToBase,
            AMotivationDetailTable AMotivationDetailTable,
            GiftBatchTDSAGiftDetailTable ANeedRecipientLedgerNumber,
            TVerificationResultCollection AMessages
            )
        {
            Boolean NonNumericError = false;
            String Field = AImportLine.Substring(0, 3);

            Int32 FunctionType = 0;

            NonNumericError &= !Int32.TryParse(Field, out FunctionType);

            Int64 DonorKey = 0;
            Field = AImportLine.Substring(12, 10);
            NonNumericError &= !Int64.TryParse(Field, out DonorKey);

            Int64 RecipientKey = 0;
            Field = AImportLine.Substring(22, 10);
            NonNumericError &= !Int64.TryParse(Field, out RecipientKey);

            Int64 intAmount = 0;
            Field = AImportLine.Substring(39, 10);
            NonNumericError &= !Int64.TryParse(Field, out intAmount);

            Decimal Amount = intAmount / 100;

            if (NonNumericError)
            {
                return false;
            }

            String MotivGroup = "GIFT";
            String MotivDetail = "UNDESIG";
            TGuiTools.GetMotivationGroupAndDetail(RecipientKey, ref MotivGroup, ref MotivDetail);

            Agift.LedgerNumber = AgiftBatch.LedgerNumber;
            Agift.BatchNumber = AgiftBatch.BatchNumber;
            Agift.GiftTransactionNumber = AgiftBatch.LastGiftNumber + 1;
            AgiftBatch.LastGiftNumber++;
            AgiftBatch.BatchTotal += Amount;
            Agift.LastDetailNumber = 1;

            ExchangeFieldsInEsrTransaction(ref DonorKey, ref RecipientKey, AMessages, Agift.GiftTransactionNumber);

            Agift.DonorKey = DonorKey;
            Agift.MethodOfGivingCode = "DEFAULT";
            Agift.MethodOfPaymentCode = "ESR";
            FMainDS.AGift.Rows.Add(Agift);

            AgiftDetails.RecipientKey = RecipientKey;
            AgiftDetails.LedgerNumber = AgiftBatch.LedgerNumber;
            AgiftDetails.BatchNumber = AgiftBatch.BatchNumber;
            AgiftDetails.GiftTransactionNumber = Agift.GiftTransactionNumber;
            AgiftDetails.DetailNumber = 1;
            AgiftDetails.GiftTransactionAmount = Amount;
            AgiftDetails.GiftAmount = GLRoutines.Divide(Amount, AgiftBatch.ExchangeRateToBase);      // amount in ledger currency

            if (AIntlRateToBase > 0.0m)
            {
                AgiftDetails.GiftAmountIntl = GLRoutines.Divide(AgiftDetails.GiftAmount, AIntlRateToBase, 2);
            }

            AgiftDetails.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(AgiftDetails.RecipientKey,
                AgiftBatch.GlEffectiveDate);


            AgiftDetails.MotivationGroupCode = MotivGroup;
            AgiftDetails.MotivationDetailCode = MotivDetail;
            AgiftDetails.CostCentreCode = TGiftTransactionWebConnector.RetrieveCostCentreCodeForRecipient(
                AgiftDetails.LedgerNumber, AgiftDetails.RecipientKey, AgiftDetails.RecipientLedgerNumber,
                Agift.DateEntered, AgiftDetails.MotivationGroupCode, AgiftDetails.MotivationDetailCode);

            AMotivationDetailRow motivationDetailRow = (AMotivationDetailRow)AMotivationDetailTable.Rows.Find(
                new object[] { FLedgerNumber, AgiftDetails.MotivationGroupCode, AgiftDetails.MotivationDetailCode });

            // Account Code is inferred from the motivation detail.
            Boolean IsTaxDeductible = false;
            string NewAccountCode = null;
            string NewTaxDeductibleAccountCode = null;

            if (motivationDetailRow != null)
            {
                IsTaxDeductible = motivationDetailRow.TaxDeductible;
                NewAccountCode = motivationDetailRow.AccountCode;
                NewTaxDeductibleAccountCode = motivationDetailRow.TaxDeductibleAccountCode;
            }

            AgiftDetails.TaxDeductible = IsTaxDeductible;
            AgiftDetails.AccountCode = NewAccountCode;
            AgiftDetails.TaxDeductibleAccountCode = NewTaxDeductibleAccountCode;

            // If the gift has a recipient with no Gift Destination then the import will fail. Gift is added to a table and returned to client.
            if ((AgiftDetails.RecipientLedgerNumber == 0) && (AgiftDetails.MotivationGroupCode == MFinanceConstants.MOTIVATION_GROUP_GIFT))
            {
                ((GiftBatchTDSAGiftDetailRow)AgiftDetails).RecipientDescription = "Fault: RecipientLedger Not known";
                ANeedRecipientLedgerNumber.Rows.Add((object[])AgiftDetails.ItemArray.Clone());
            }

            FMainDS.AGiftDetail.Rows.Add(AgiftDetails);
            return true;
        }
        /// <summary>
        /// Main method to post a specified batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch row to post</param>
        /// <returns>True if the batch was successfully posted</returns>
        public bool PostBatch(AGiftBatchRow ACurrentBatchRow)
        {
            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return false;
            }

            FSelectedBatchNumber = ACurrentBatchRow.BatchNumber;
            TVerificationResultCollection Verifications;

            try
            {
                FMyForm.Cursor = Cursors.WaitCursor;

                FMyForm.EnsureGiftDataPresent(FLedgerNumber, FSelectedBatchNumber);

                GiftBatchTDSAGiftDetailTable BatchGiftDetails = new GiftBatchTDSAGiftDetailTable();

                foreach (GiftBatchTDSAGiftDetailRow Row in FMainDS.AGiftDetail.Rows)
                {
                    if (Row.BatchNumber == FSelectedBatchNumber)
                    {
                        BatchGiftDetails.Rows.Add((object[])Row.ItemArray.Clone());
                    }
                }

                // there are no gifts in this batch!
                if (BatchGiftDetails.Rows.Count == 0)
                {
                    FMyForm.Cursor = Cursors.Default;
                    MessageBox.Show(Catalog.GetString("Batch is empty!"), Catalog.GetString("Posting failed"),
                        MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return false;
                }

                bool CancelledDueToExWorkerOrAnonDonor;

                // save first, then post
                if (!FMyForm.SaveChangesForPosting(BatchGiftDetails, out CancelledDueToExWorkerOrAnonDonor))
                {
                    FMyForm.Cursor = Cursors.Default;

                    if (!CancelledDueToExWorkerOrAnonDonor)
                    {
                        // saving failed, therefore do not try to post
                        MessageBox.Show(Catalog.GetString("The batch was not posted due to problems during saving; ") + Environment.NewLine +
                            Catalog.GetString("Please first save the batch, and then post it!"));
                    }

                    return false;
                }
            }
            finally
            {
                FMyForm.Cursor = Cursors.Default;
            }

            //Check for missing international exchange rate
            bool IsTransactionInIntlCurrency = false;

            if (FMyForm.InternationalCurrencyExchangeRate(ACurrentBatchRow, out IsTransactionInIntlCurrency, true) == 0)
            {
                return false;
            }

            //Check for inactive KeyMinistries
            DataTable GiftsWithInactiveKeyMinistries;

            if (TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber,
                    out GiftsWithInactiveKeyMinistries))
            {
                string listOfRow = "Gift   Detail   Recipient        KeyMinistry" + Environment.NewLine;
                listOfRow += "------------------------------------------------";

                foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows)
                {
                    listOfRow += String.Format("{0}{1:0000}    {2:00}    {3:00000000000}    {4}",
                        Environment.NewLine,
                        dr[0],
                        dr[1],
                        dr[2],
                        dr[3]);
                }

                string msg = String.Format(Catalog.GetString("Cannot post Batch {0} as inactive Key Ministries found in gifts:{1}{1}{2}"),
                    FSelectedBatchNumber,
                    Environment.NewLine,
                    listOfRow);

                MessageBox.Show(msg, Catalog.GetString("Inactive Key Ministries Found"));

                return false;
            }

            // ask if the user really wants to post the batch
            if (MessageBox.Show(String.Format(Catalog.GetString("Do you really want to post gift batch {0}?"),
                        FSelectedBatchNumber),
                    Catalog.GetString("Confirm posting of Gift Batch"),
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
            {
                return false;
            }

            Verifications = new TVerificationResultCollection();

            try
            {
                FPostingInProgress = true;

                Thread postingThread = new Thread(() => PostGiftBatch(out Verifications));

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

                if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications))
                {
                    string ErrorMessages = String.Empty;

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

                    System.Windows.Forms.MessageBox.Show(ErrorMessages, Catalog.GetString("Posting failed"));
                }
                else
                {
                    MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"));

                    return true;
                }
            }
            catch
            {
                //Do nothing
            }
            finally
            {
                FPostingInProgress = false;
            }

            return false;
        }
Exemplo n.º 47
0
        /// <summary>
        /// Check if batch columns have actually changed
        /// </summary>
        /// <param name="ABatchRow"></param>
        /// <returns></returns>
        public bool BatchColumnsHaveChanged(AGiftBatchRow ABatchRow)
        {
            bool RetVal = false;

            if (ABatchRow.RowState != DataRowState.Unchanged)
            {
                bool columnValueChanged = false;

                for (int i = 0; i < FMainDS.AGiftBatch.Columns.Count; i++)
                {
                    string originalValue = ABatchRow[i, DataRowVersion.Original].ToString();
                    string currentValue = ABatchRow[i, DataRowVersion.Current].ToString();

                    if (originalValue != currentValue)
                    {
                        columnValueChanged = true;
                        break;
                    }
                }

                if (!columnValueChanged)
                {
                    ABatchRow.RejectChanges();
                }

                RetVal = columnValueChanged;
            }

            return RetVal;
        }
        /// <summary>
        /// Method to cancel a specified batch
        /// </summary>
        /// <param name="ACurrentBatchRow"></param>
        /// <returns></returns>
        public bool CancelBatch(AGiftBatchRow ACurrentBatchRow)
        {
            //Assign default value(s)
            bool CancellationSuccessful = false;

            string CancelMessage = string.Empty;
            string CompletionMessage = string.Empty;

            List <string>ModifiedDetailKeys = new List <string>();

            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return CancellationSuccessful;
            }

            CancelMessage = String.Format(Catalog.GetString("Are you sure you want to cancel gift batch number: {0}?"),
                ACurrentBatchRow.BatchNumber);

            if ((MessageBox.Show(CancelMessage,
                     "Cancel Batch",
                     MessageBoxButtons.YesNo,
                     MessageBoxIcon.Question,
                     MessageBoxDefaultButton.Button2) != System.Windows.Forms.DialogResult.Yes))
            {
                return CancellationSuccessful;
            }

            //Backup the Dataset for reversion purposes
            GiftBatchTDS BackupMainDS = (GiftBatchTDS)FMainDS.Copy();
            BackupMainDS.Merge(FMainDS);

            try
            {
                FMyForm.Cursor = Cursors.WaitCursor;

                //Normally need to set the message parameters before the delete is performed if requiring any of the row values
                CompletionMessage = String.Format(Catalog.GetString("Batch no.: {0} cancelled successfully."),
                    ACurrentBatchRow.BatchNumber);

                FMyForm.GetBatchControl().UndoModifiedBatchRow(ACurrentBatchRow, true);

                //Load all journals for current Batch
                //clear any transactions currently being editied in the Transaction Tab
                FMyForm.GetTransactionsControl().ClearCurrentSelection();

                //Clear gifts and details etc for current and any other loaded batches
                FMainDS.AGiftDetail.Clear();
                FMainDS.AGift.Clear();

                //Load tables afresh
                FMainDS.Merge(TRemote.MFinance.Gift.WebConnectors.LoadGiftTransactionsForBatch(FLedgerNumber, ACurrentBatchRow.BatchNumber));
                FMainDS.AcceptChanges();

                //Delete gift details
                for (int i = FMainDS.AGiftDetail.Count - 1; i >= 0; i--)
                {
                    // if the gift detail being cancelled is a reversed gift
                    if (FMainDS.AGiftDetail[i].ModifiedDetail && !string.IsNullOrEmpty(FMainDS.AGiftDetail[i].ModifiedDetailKey))
                    {
                        ModifiedDetailKeys.Add(FMainDS.AGiftDetail[i].ModifiedDetailKey);
                    }

                    FMainDS.AGiftDetail[i].Delete();
                }

                //Delete gifts
                for (int i = FMainDS.AGift.Count - 1; i >= 0; i--)
                {
                    FMainDS.AGift[i].Delete();
                }

                //Batch is only cancelled and never deleted
                ACurrentBatchRow.BatchTotal = 0;
                ACurrentBatchRow.BatchStatus = MFinanceConstants.BATCH_CANCELLED;

                // save first
                if (FMyForm.SaveChanges())
                {
                    TRemote.MFinance.Gift.WebConnectors.RemoveModifiedDetailOnCancel(FLedgerNumber, ModifiedDetailKeys);

                    MessageBox.Show(CompletionMessage,
                        "Batch Cancelled",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                }
                else
                {
                    throw new Exception(Catalog.GetString("The batch failed to save after being cancelled! Reopen the form and retry."));
                }

                CancellationSuccessful = true;
            }
            catch (Exception ex)
            {
                CompletionMessage = ex.Message;
                MessageBox.Show(CompletionMessage,
                    "Cancellation Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                //Revert to previous state
                FMainDS.Merge(BackupMainDS);
            }
            finally
            {
                FMyForm.Cursor = Cursors.Default;
            }

            return CancellationSuccessful;
        }
        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);
        }
        /// <summary>
        /// Call this to change the accounts being shown in the accounts combobox (used when changing the gift type)
        /// </summary>
        /// <param name="AActiveOnly"></param>
        /// <param name="ABankAccountOnly"></param>
        /// <param name="ALblBankAccoountCode"></param>
        /// <param name="ARow"></param>
        public void SetupAccountCombo(bool AActiveOnly,
            bool ABankAccountOnly,
            ref System.Windows.Forms.Label ALblBankAccoountCode,
            AGiftBatchRow ARow)
        {
            FCmbBankAccountCode.Clear();
            TFinanceControls.InitialiseAccountList(ref FCmbBankAccountCode,
                FLedgerNumber,
                true,
                false,
                AActiveOnly,
                ABankAccountOnly,
                true,
                FAccountTable);

            if (ABankAccountOnly)
            {
                ALblBankAccoountCode.Text = Catalog.GetString("Bank Account:");
            }
            else
            {
                ALblBankAccoountCode.Text = Catalog.GetString("Account Code:");
            }

            if (ARow != null)
            {
                FCmbBankAccountCode.SetSelectedString(ARow.BankAccountCode, -1);
            }
        }
Exemplo n.º 51
0
        /// try to find a new gift batch that does already have the same properties
        private static GiftBatchTDS CreateNewGiftBatch(SortedList <string, GiftBatchTDS>ANewGiftBatches,
            AGiftBatchRow AOldGiftBatch,
            DateTime ADateCorrection)
        {
            string key = AOldGiftBatch.CurrencyCode + ";" +
                         AOldGiftBatch.BankAccountCode + ";" +
                         AOldGiftBatch.BankCostCentre + ";" +
                         AOldGiftBatch.GiftType;

            if (!ANewGiftBatches.ContainsKey(key))
            {
                GiftBatchTDS GiftDS = TGiftTransactionWebConnector.CreateAGiftBatch(AOldGiftBatch.LedgerNumber, ADateCorrection,
                    Catalog.GetString("Gift Adjustment (Field Change)"));
                AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];
                giftbatchRow.BankCostCentre = AOldGiftBatch.BankCostCentre;
                giftbatchRow.BankAccountCode = AOldGiftBatch.BankAccountCode;
                giftbatchRow.GiftType = AOldGiftBatch.GiftType;
                ANewGiftBatches.Add(key, GiftDS);

                return GiftDS;
            }
            else
            {
                return ANewGiftBatches[key];
            }
        }
        /// <summary>
        /// Call this to do initial set up the Bank account and cost centre combo boxes
        /// </summary>
        /// <param name="AActiveOnly"></param>
        /// <param name="ARow"></param>
        public void SetupAccountAndCostCentreCombos(bool AActiveOnly, AGiftBatchRow ARow)
        {
            FCmbCostCentreCode.Clear();
            FCmbBankAccountCode.Clear();
            TFinanceControls.InitialiseAccountList(ref FCmbBankAccountCode, FLedgerNumber, true, false, AActiveOnly, true, true, FAccountTable);
            TFinanceControls.InitialiseCostCentreList(ref FCmbCostCentreCode, FLedgerNumber, true, false, AActiveOnly, true, true, FCostCentreTable);

            if (ARow != null)
            {
                FCmbCostCentreCode.SetSelectedString(ARow.BankCostCentre, -1);
                FCmbBankAccountCode.SetSelectedString(ARow.BankAccountCode, -1);
            }
        }
Exemplo n.º 53
0
        public static Int32 FieldChangeAdjustment(Int32 ALedgerNumber,
                                                  Int64 ARecipientKey,
                                                  DateTime AStartDate,
                                                  DateTime AEndDate,
                                                  Int64 AOldField,
                                                  DateTime ADateCorrection,
                                                  bool AWithReceipt)
        {
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);
            GiftBatchTDS   oldGiftDS   = new GiftBatchTDS();

            try
            {
                // find all gifts that need reversing.
                // criteria:
                // posted gift batches only
                // no adjusted/reversed gifts
                // date of gift batch in specified date range
                // recipient field is the old field
                string SqlStmt = TDataBase.ReadSqlFile("Gift.GetGiftsToReverse.sql");

                List <OdbcParameter> parameters = new List <OdbcParameter>();
                OdbcParameter        param      = new OdbcParameter("LedgerNumber", OdbcType.Int);
                param.Value = ALedgerNumber;
                parameters.Add(param);
                param       = new OdbcParameter("StartDate", OdbcType.Date);
                param.Value = AStartDate;
                parameters.Add(param);
                param       = new OdbcParameter("EndDate", OdbcType.Date);
                param.Value = AEndDate;
                parameters.Add(param);
                param       = new OdbcParameter("RecipientKey", OdbcType.BigInt);
                param.Value = ARecipientKey;
                parameters.Add(param);
                param       = new OdbcParameter("OldField", OdbcType.BigInt);
                param.Value = AOldField;
                parameters.Add(param);

                DBAccess.GDBAccessObj.Select(oldGiftDS, SqlStmt, oldGiftDS.AGiftDetail.TableName, Transaction, parameters.ToArray());

                // load the gift and the gift batch records if they have not been loaded yet
                foreach (AGiftDetailRow giftdetail in oldGiftDS.AGiftDetail.Rows)
                {
                    oldGiftDS.AGift.DefaultView.RowFilter = String.Format("{0} = {1} and {2} = {3}",
                                                                          AGiftTable.GetBatchNumberDBName(),
                                                                          giftdetail.BatchNumber,
                                                                          AGiftTable.GetGiftTransactionNumberDBName(),
                                                                          giftdetail.GiftTransactionNumber);

                    if (oldGiftDS.AGift.DefaultView.Count == 0)
                    {
                        AGiftTable tempGiftTable =
                            AGiftAccess.LoadByPrimaryKey(giftdetail.LedgerNumber,
                                                         giftdetail.BatchNumber,
                                                         giftdetail.GiftTransactionNumber,
                                                         Transaction);
                        oldGiftDS.AGift.Merge(tempGiftTable);
                    }

                    oldGiftDS.AGiftBatch.DefaultView.RowFilter = String.Format("{0} = {1}",
                                                                               AGiftTable.GetBatchNumberDBName(),
                                                                               giftdetail.BatchNumber);

                    if (oldGiftDS.AGiftBatch.DefaultView.Count == 0)
                    {
                        AGiftBatchTable tempGiftBatchTable =
                            AGiftBatchAccess.LoadByPrimaryKey(giftdetail.LedgerNumber,
                                                              giftdetail.BatchNumber,
                                                              Transaction);
                        oldGiftDS.AGiftBatch.Merge(tempGiftBatchTable);
                    }
                }

                DBAccess.GDBAccessObj.RollbackTransaction();
            }
            catch (Exception)
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
                throw;
            }

            // we need to create a gift batch for each set of gifts with the same Currency, BankAccountCode, BankCostCentre, and Gift Type
            SortedList <string, GiftBatchTDS> NewGiftBatches = new SortedList <string, GiftBatchTDS>();

            foreach (GiftBatchTDSAGiftDetailRow oldGiftDetail in oldGiftDS.AGiftDetail.Rows)
            {
                // get the gift batch row for this detail
                oldGiftDS.AGiftBatch.DefaultView.RowFilter =
                    String.Format("{0} = {1}",
                                  AGiftTable.GetBatchNumberDBName(), oldGiftDetail.BatchNumber);

                AGiftBatchRow oldGiftBatch = (AGiftBatchRow)oldGiftDS.AGiftBatch.DefaultView[0].Row;

                GiftBatchTDS GiftDS = CreateNewGiftBatch(NewGiftBatches, oldGiftBatch, ADateCorrection);

                AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];

                // get the gift row for this detail
                DataView v = oldGiftDS.AGift.DefaultView;
                v.RowFilter =
                    String.Format("{0} = {1} and {2} = {3}",
                                  AGiftTable.GetBatchNumberDBName(), oldGiftDetail.BatchNumber,
                                  AGiftTable.GetGiftTransactionNumberDBName(), oldGiftDetail.GiftTransactionNumber);

                AGiftRow oldGift = (AGiftRow)v[0].Row;

                AGiftRow gift = GiftDS.AGift.NewRowTyped();
                gift.LedgerNumber          = giftbatchRow.LedgerNumber;
                gift.BatchNumber           = giftbatchRow.BatchNumber;
                gift.GiftTransactionNumber = giftbatchRow.LastGiftNumber + 1;
                gift.DonorKey    = oldGift.DonorKey;
                gift.DateEntered = ADateCorrection;
                giftbatchRow.LastGiftNumber++;
                GiftDS.AGift.Rows.Add(gift);

                if (!AWithReceipt)
                {
                    gift.ReceiptLetterCode = "NO*RECET";
                }

                // reverse the original gift
                GiftBatchTDSAGiftDetailRow detail = GiftDS.AGiftDetail.NewRowTyped();

                DataUtilities.CopyAllColumnValues(oldGiftDetail, detail);

                detail.LedgerNumber          = gift.LedgerNumber;
                detail.BatchNumber           = gift.BatchNumber;
                detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                detail.DetailNumber          = gift.LastDetailNumber + 1;
                detail.GiftAmount            = detail.GiftAmount * -1;
                detail.GiftAmountIntl        = detail.GiftAmountIntl * -1;
                detail.GiftTransactionAmount = detail.GiftTransactionAmount * -1;
                gift.LastDetailNumber++;

                GiftDS.AGiftDetail.Rows.Add(detail);

                // create the detail for the corrected gift to the new field
                detail = GiftDS.AGiftDetail.NewRowTyped();

                DataUtilities.CopyAllColumnValues(oldGiftDetail, detail);

                detail.LedgerNumber          = gift.LedgerNumber;
                detail.BatchNumber           = gift.BatchNumber;
                detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                detail.DetailNumber          = gift.LastDetailNumber + 1;
                detail.GiftCommentOne        = String.Format(Catalog.GetString("posted on {0}"), oldGiftBatch.GlEffectiveDate.ToShortDateString());
                gift.LastDetailNumber++;

                // TODO: calculate costcentre code from current commitment; this currently is done only at time of posting
                // detail.RecipientLedgerNumber = oldGiftDetail.RecipientLedgerNumber;
                // detail.CostCentreCode = oldGiftDetail.CostCentreCode;

                GiftDS.AGiftDetail.Rows.Add(detail);

                // TODO: how to make sure that the gl transaction is marked as System generated? avoid display on HOSA?

                // mark original gift detail as modified
                oldGiftDetail.ModifiedDetail = true;
            }

            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = TSubmitChangesResult.scrOK;

            for (Int32 batchCounter = 0; batchCounter < NewGiftBatches.Count; batchCounter++)
            {
                if (result == TSubmitChangesResult.scrOK)
                {
                    GiftBatchTDS GiftDS = NewGiftBatches.Values[batchCounter];
                    result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref GiftDS, out VerificationResult);
                }
            }

            if (result == TSubmitChangesResult.scrOK)
            {
                result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref oldGiftDS, out VerificationResult);

                if ((result == TSubmitChangesResult.scrOK) && (NewGiftBatches.Count > 0))
                {
                    return(NewGiftBatches.Values[0].AGiftBatch[0].BatchNumber);
                }
            }

            return(-1);
        }
        private void ValidateDataDetailsManual(AGiftBatchRow ARow)
        {
            if ((ARow == null) || (ARow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return;
            }

            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;

            //Hash total special case in view of the textbox handling
            ParseHashTotal(ARow);

            //Check if the user has made a Bank Cost Centre or Account Code inactive
            //this was removed because of speed issues!
            //TODO: Revisit this
            //RefreshBankCostCentreAndAccountCodes();

            TSharedFinanceValidation_Gift.ValidateGiftBatchManual(this, ARow, ref VerificationResultCollection,
                FValidationControlsDict, FAccountTable, FCostCentreTable);

            //TODO: remove this once database definition is set for Batch Description to be NOT NULL
            // Description is mandatory then make sure it is set
            if (txtDetailBatchDescription.Text.Length == 0)
            {
                DataColumn ValidationColumn;
                TVerificationResult VerificationResult = null;
                object ValidationContext;

                ValidationColumn = ARow.Table.Columns[AGiftBatchTable.ColumnBatchDescriptionId];
                ValidationContext = String.Format("Batch number {0}",
                    ARow.BatchNumber);

                VerificationResult = TStringChecks.StringMustNotBeEmpty(ARow.BatchDescription,
                    "Description of " + ValidationContext,
                    this, ValidationColumn, null);

                // Handle addition/removal to/from TVerificationResultCollection
                VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn, true);
            }
        }
        private void RefreshBankAccountAndCostCentreFilters(bool AActiveOnly, AGiftBatchRow ARow = null)
        {
            if (FActiveOnly != AActiveOnly)
            {
                FActiveOnly = AActiveOnly;

                FAccountAndCostCentreLogicObject.RefreshBankAccountAndCostCentreFilters(AActiveOnly, ARow);
            }
        }
        /// <summary>
        /// load the gifts into the grid
        /// </summary>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ABatchNumber"></param>
        /// <param name="ABatchStatus"></param>
        /// <param name="AForceLoadFromServer">Set to true to get data from the server even though it is apparently the current batch number and status</param>
        /// <returns>True if gift transactions were loaded from server, false if transactions had been loaded already.</returns>
        public bool LoadGifts(Int32 ALedgerNumber, Int32 ABatchNumber, string ABatchStatus, bool AForceLoadFromServer = false)
        {
            //Set key flags
            bool FirstGiftTransLoad = (FLedgerNumber == -1);
            bool SameCurrentBatch =
                ((FLedgerNumber == ALedgerNumber) && (FBatchNumber == ABatchNumber) && (FBatchStatus == ABatchStatus) && !AForceLoadFromServer);

            //Read key fields
            FBatchRow = GetBatchRow();

            if ((FBatchRow == null) && (GetAnyBatchRow(ABatchNumber) == null))
            {
                MessageBox.Show(String.Format("Cannot load transactions for Gift Batch {0} as the batch is not currently loaded!", ABatchNumber));
                return false;
            }

            FLedgerNumber = ALedgerNumber;
            FBatchNumber = ABatchNumber;
            FBatchStatus = ABatchStatus;
            FBatchUnposted = (FBatchStatus == MFinanceConstants.BATCH_UNPOSTED);
            FBatchCurrencyCode = FBatchRow.CurrencyCode;
            FBatchMethodOfPayment = FBatchRow.MethodOfPaymentCode;

            if (FirstGiftTransLoad)
            {
                InitialiseControls();
            }

            UpdateCurrencySymbols(FBatchRow.CurrencyCode);

            //Check if the same batch is selected, so no need to apply filter
            if (SameCurrentBatch)
            {
                //Same as previously selected and we have not been asked to force a full refresh
                if (FBatchUnposted && (GetSelectedRowIndex() > 0))
                {
                    if (FGLEffectivePeriodChanged)
                    {
                        //Just in case for the currently selected row, the date field has not been updated
                        FGLEffectivePeriodChanged = false;
                        GetSelectedDetailRow().DateEntered = FBatchRow.GlEffectiveDate;
                        dtpDateEntered.Date = FBatchRow.GlEffectiveDate;
                    }

                    //Same as previously selected
                    if (GetSelectedRowIndex() > 0)
                    {
                        GetDetailsFromControls(GetSelectedDetailRow());
                    }
                }

                UpdateControlsProtection();

                if (FBatchUnposted
                    && ((FBatchCurrencyCode != FBatchRow.CurrencyCode)
                        || (FBatchExchangeRateToBase != FBatchRow.ExchangeRateToBase)))
                {
                    UpdateBaseAmount(false);
                }

                return false;
            }

            //New set of transactions to be loaded
            TFrmStatusDialog dlgStatus = new TFrmStatusDialog(FPetraUtilsObject.GetForm());

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

            FGiftTransactionsLoaded = false;
            FSuppressListChanged = true;

            //Apply new filter
            FPreviouslySelectedDetailRow = null;
            grdDetails.DataSource = null;

            // if this form is readonly, then we need all codes, because old (inactive) codes might have been used
            if (FirstGiftTransLoad || (FActiveOnly == (ViewMode || !FBatchUnposted)))
            {
                FActiveOnly = !(ViewMode || !FBatchUnposted);
                dlgStatus.CurrentStatus = Catalog.GetString("Initialising controls ...");

                try
                {
                    //Without this, the Save button enables even for Posted batches!
                    FPetraUtilsObject.SuppressChangeDetection = true;

                    TFinanceControls.InitialiseMotivationGroupList(ref cmbDetailMotivationGroupCode, FLedgerNumber, FActiveOnly);
                    TFinanceControls.InitialiseMotivationDetailList(ref cmbDetailMotivationDetailCode, FLedgerNumber, FActiveOnly);
                    TFinanceControls.InitialiseMethodOfGivingCodeList(ref cmbDetailMethodOfGivingCode, FActiveOnly);
                    TFinanceControls.InitialiseMethodOfPaymentCodeList(ref cmbDetailMethodOfPaymentCode, FActiveOnly);
                    TFinanceControls.InitialisePMailingList(ref cmbDetailMailingCode, FActiveOnly);
                }
                finally
                {
                    FPetraUtilsObject.SuppressChangeDetection = false;
                }
            }

            // This sets the incomplete filter but does check the panel enabled state
            ShowData();

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

            // only load from server if there are no transactions loaded yet for this batch
            // otherwise we would overwrite transactions that have already been modified
            if (FMainDS.AGiftDetail.DefaultView.Count == 0)
            {
                dlgStatus.CurrentStatus = Catalog.GetString("Requesting transactions from server ...");
                LoadGiftDataForBatch(ALedgerNumber, ABatchNumber);
            }

            //Check if need to update batch period in each gift
            if (FBatchUnposted)
            {
                dlgStatus.CurrentStatus = Catalog.GetString("Updating batch period ...");
                ((TFrmGiftBatch)ParentForm).GetBatchControl().UpdateBatchPeriod();
            }

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

            SelectRowInGrid(1);

            UpdateControlsProtection();

            FSuppressListChanged = false;

            dlgStatus.CurrentStatus = Catalog.GetString("Updating totals for the batch ...");
            UpdateTotals();

            if ((FPreviouslySelectedDetailRow != null) && (FBatchUnposted))
            {
                bool disableSave = (FBatchRow.RowState == DataRowState.Unchanged && !FPetraUtilsObject.HasChanges);

                if (disableSave && FPetraUtilsObject.HasChanges && !DataUtilities.DataRowColumnsHaveChanged(FBatchRow))
                {
                    FPetraUtilsObject.DisableSaveButton();
                }
            }

            FGiftTransactionsLoaded = true;
            dlgStatus.Close();

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

            AModifiedBatchRow.RejectChanges();

            if (ARedisplay)
            {
                ShowDetails(AModifiedBatchRow);
            }
        }
Exemplo n.º 58
0
        private void ParseBatchLine(ref AGiftBatchRow AGiftBatch,
            ref TDBTransaction ATransaction,
            ref ALedgerTable ALedgerTable,
            ref string AImportMessage,
            int ARowNumber,
            TVerificationResultCollection AMessages,
            TValidationControlsDict AValidationControlsDictBatch,
            AAccountTable AValidationAccountTable,
            AAccountPropertyTable AValidationAccountPropertyTable,
            AAccountingPeriodTable AValidationAccountingPeriodTable,
            ACostCentreTable AValidationCostCentreTable,
            ACorporateExchangeRateTable AValidationCorporateExchTable,
            ACurrencyTable AValidationCurrencyTable)
        {
            // There are 8 elements to import (the last of which can be blank)
            string BatchDescription = ImportString(Catalog.GetString("Batch description"),
                FMainDS.AGiftBatch.ColumnBatchDescription, AValidationControlsDictBatch);
            string BankAccountCode = ImportString(Catalog.GetString("Bank account code"),
                FMainDS.AGiftBatch.ColumnBankAccountCode, AValidationControlsDictBatch).ToUpper();
            decimal HashTotal = ImportDecimal(Catalog.GetString("Hash total"),
                FMainDS.AGiftBatch.ColumnHashTotal, ARowNumber, AMessages, AValidationControlsDictBatch);
            DateTime GlEffectiveDate = ImportDate(Catalog.GetString("Effective Date"),
                FMainDS.AGiftBatch.ColumnGlEffectiveDate, ARowNumber, AMessages, AValidationControlsDictBatch);

            AImportMessage = "Creating new batch";

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

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

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

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

            int messageCountBeforeValidate = AMessages.Count;

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

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

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

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

            if (AGiftBatch.ExchangeRateToBase > 10000000)  // Huge numbers here indicate that the decimal comma/point is incorrect.
            {
                AMessages.Add(new TVerificationResult(String.Format(MCommonConstants.StrImportValidationErrorInLine, ARowNumber),
                        String.Format(Catalog.GetString("A huge exchange rate of {0} suggests a decimal point format problem."),
                            AGiftBatch.ExchangeRateToBase),
                        TResultSeverity.Resv_Noncritical));
            }
        }
        private void ParseHashTotal(AGiftBatchRow ARow)
        {
            decimal CorrectHashValue = 0m;

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

            if ((txtDetailHashTotal.NumberValueDecimal != null) && txtDetailHashTotal.NumberValueDecimal.HasValue)
            {
                CorrectHashValue = txtDetailHashTotal.NumberValueDecimal.Value;
            }

            if (ARow.HashTotal != CorrectHashValue)
            {
                ARow.HashTotal = CorrectHashValue;
                txtDetailHashTotal.NumberValueDecimal = CorrectHashValue;
                FPetraUtilsObject.SetChangedFlag();
            }
        }
        /// <summary>
        /// Update all single batch transactions currency amounts fields
        /// </summary>
        /// <param name="ABatchRow"></param>
        /// <param name="AIntlToBaseCurrencyExchRate"></param>
        /// <param name="ATransactionInIntlCurrency"></param>
        public void RecalcTransactionsCurrencyAmounts(AGiftBatchRow ABatchRow,
            Decimal AIntlToBaseCurrencyExchRate,
            Boolean ATransactionInIntlCurrency)
        {
            int LedgerNumber = ABatchRow.LedgerNumber;
            int BatchNumber = ABatchRow.BatchNumber;
            decimal BatchExchangeRateToBase = ABatchRow.ExchangeRateToBase;

            if (!LoadGiftDataForBatch(LedgerNumber, BatchNumber))
            {
                return;
            }

            DataView transDV = new DataView(FMainDS.AGiftDetail);
            transDV.RowFilter = String.Format("{0}={1}",
                AGiftDetailTable.GetBatchNumberDBName(),
                BatchNumber);

            foreach (DataRowView drvTrans in transDV)
            {
                AGiftDetailRow gdr = (AGiftDetailRow)drvTrans.Row;

                gdr.GiftAmount = GLRoutines.Divide(gdr.GiftTransactionAmount, BatchExchangeRateToBase);

                if (!ATransactionInIntlCurrency)
                {
                    gdr.GiftAmountIntl = (AIntlToBaseCurrencyExchRate == 0) ? 0 : GLRoutines.Divide(gdr.GiftAmount, AIntlToBaseCurrencyExchRate);
                }
                else
                {
                    gdr.GiftAmountIntl = gdr.GiftTransactionAmount;
                }

                if (FTaxDeductiblePercentageEnabled)
                {
                    TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref gdr);
                }
            }
        }