Пример #1
0
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="AGridDataView"></param>
        /// <param name="APreselectedSiteKey"></param>
        /// <param name="ARowNumber"></param>
        /// <param name="ASiteKey"></param>
        public void DetermineInitiallySelectedSite(DataView AGridDataView, Int64 APreselectedSiteKey, out Int32 ARowNumber, out Int64 ASiteKey)
        {
            System.Int16 CurrentRow;

            if ((APreselectedSiteKey == 0) || (APreselectedSiteKey == -1))
            {
                ASiteKey = Convert.ToInt64(TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_SITEKEY));
            }
            else
            {
                ASiteKey = APreselectedSiteKey;
            }

            FSiteKey   = ASiteKey;
            ARowNumber = 0;

            for (CurrentRow = 0; CurrentRow <= AGridDataView.Count - 1; CurrentRow += 1)
            {
                ARowNumber = ARowNumber + 1;

                if (Convert.ToInt64(AGridDataView[CurrentRow].Row[PPartnerLedgerTable.GetPartnerKeyDBName()]) == ASiteKey)
                {
                    break;
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Gets called in regular intervals from a Timer in Class TTimedProcessing.
        /// </summary>
        /// <param name="ADBAccessObj">Instantiated DB Access object with opened DB connection.</param>
        /// <param name="ARunManually">this is true if the process was called manually from the server admin console</param>
        public static void Process(TDataBase ADBAccessObj, bool ARunManually)
        {
            // only check once a day (or as specified in config file), if not manually called
            if (!ARunManually)
            {
                DateTime LastRun =
                    TVariant.DecodeFromString(


                        TSystemDefaults.GetSystemDefault(
                            PROCESSDATACHECK_LAST_RUN,
                            new TVariant(DateTime.MinValue).EncodeToString())).ToDate();

                if (LastRun.AddDays(TAppSettingsManager.GetInt16("DataChecks.RunEveryXDays", 1)) > DateTime.Now)
                {
                    // do not run the data check more than once a day or a week (depending on configuration setting), too many emails
                    TLogging.LogAtLevel(1, "TProcessDataChecks.Process: not running, since last run was at " + LastRun.ToString());
                    return;
                }
            }

            Errors_SinceDate = DateTime.Today.AddDays(-1 * SENDREPORTFORDAYS_TOUSERS);

            TLogging.LogAtLevel(1, "TProcessDataChecks.Process: Checking Modules");
            CheckModule(ADBAccessObj, "DataCheck.MPartner.");

            TSystemDefaults.SetSystemDefault(PROCESSDATACHECK_LAST_RUN, new TVariant(DateTime.Now).EncodeToString());
        }
Пример #3
0
        private void LoadReportParams(TRptCalculator ACalc)
        {
            // Add standard parameters for the report header
            ACalc.GetParameters().Add("param_requested_by", UserInfo.GUserInfo.UserID);
            Version ClientVersion = Assembly.GetAssembly(typeof(FastReportsWrapper)).GetName().Version;

            ACalc.GetParameters().Add("param_version", ClientVersion.Major.ToString() + "." +
                                      ClientVersion.Minor.ToString() + "." +
                                      ClientVersion.Build.ToString() + "." +
                                      ClientVersion.Revision.ToString());
            //
            // Some params are always provided for reports:
            bool TaxDeductiblePercentageEnabled = Convert.ToBoolean(
                TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE"));

            ACalc.AddParameter("param_tax_deductible_pct", TaxDeductiblePercentageEnabled);


            ArrayList  reportParam = ACalc.GetParameters().Elems;
            MethodInfo FastReport_SetParameterValue = FFastReportType.GetMethod("SetParameterValue");

            foreach (Shared.MReporting.TParameter p in reportParam)
            {
                if (p.name.StartsWith("param") && (p.name != "param_calculation"))
                {
                    FastReport_SetParameterValue.Invoke(FfastReportInstance, new object[] { p.name, p.value.ToObject() });
                }
            }
        }
Пример #4
0
        /// <summary>
        /// If the wrapper didn't initialise, the caller can call this.
        /// </summary>
        public void ShowErrorPopup()
        {
            // Note from AlanP: This method will show an appropriate Fast Reports error message box depending on the InitState
            // We want to show this error if FastReports is supposed to be used but is not installed.
            // We do not want to show it if FastReports is NOT supposed to be used....
            // If FastReports is not supposed to be used the database will have an entry: USEXMLREPORTS (in system defaults table)
            // However the only quirk to this simple arrangement is that in OM we do want to use FastReports - but it does not HAVE to be installed
            //   in many circumstances.  It may well not be installed on our continuous integration server for example.
            // When the CI server runs the test suite, one of the tests is to open all the main screens from the main menu.
            // It does this on a 'new', 'blank' database which will not have 'USEXMLREPORTS' in the defaults table.
            // As a result the test fails because an unexpected modal dialog appears that is not dealt with
            // So we would like to know if the method is being run in the context of a test or not.
            // We achieve this by the first line of code in the method.
            // If FPetraUtilsObject is null, this wrapper has been created using the constructor that specifies the ReportName.
            //   This is never used (at present anyway) in the context of a test.
            // If FPetraUtilsObject is non-null, we can always (at present) detect the difference between a screen opened from the main menu and a screen opened for a test
            //   because, in the latter case, the CallerForm will be null.
            // If, in the future, this 'workaround' can no longer be used (because we start to use a FastReports test?), we will have to do things differently.

            Boolean IsTestContext = (FPetraUtilsObject != null) && (FPetraUtilsObject.GetCallerForm() == null);

            if ((TSystemDefaults.GetSystemDefault("USEXMLREPORTS", "Not Specified") == "Not Specified") && !IsTestContext)
            {
                String Msg = "";

                switch (FInitState)
                {
                case TInitState.LoadDll:
                {
                    Msg = "failed to load FastReport Dll.";
                    break;
                }

                case TInitState.LoadTemplate:
                {
                    Msg = String.Format("no reporting template found for {0}.", FReportName);
                    break;
                }

                case TInitState.InitSystem:
                {
                    Msg = "the DLL failed to initialise.";
                    break;
                }

                default:
                {
                    return;         // Anything else is not an error...
                }
                }

                MessageBox.Show("The FastReports plugin did not initialise:\r\n" +
                                Msg +
                                "\r\n(To suppress this message, set USEXMLREPORTS in SystemDefaults.)",
                                "Reporting engine");
            }
        }
        private void InitializeManualCode()
        {
            // set the number of days to default according to settings used in System Manager
            String NumberOfDays = TSystemDefaults.GetSystemDefault
                                      (SharedConstants.SYSDEFAULT_PURGEEXTRACTS, "no,365").Split(',')[1];

            txtNumberOfDays.NumberValueInt = Convert.ToInt32(NumberOfDays);

            FPurgingSuccessful = false;
        }
 private void NewRowManual(ref PmStaffDataRow ARow)
 {
     ARow.Key            = Convert.ToInt32(TRemote.MCommon.WebConnectors.GetNextSequence(TSequenceNames.seq_staff_data));
     ARow.PartnerKey     = FMainDS.PPerson[0].PartnerKey;
     ARow.ReceivingField = 0;
     ARow.SetReceivingFieldOfficeNull();
     ARow.OfficeRecruitedBy = Convert.ToInt64(TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_SITEKEY, ""));
     ARow.HomeOffice        = Convert.ToInt64(TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_SITEKEY, ""));
     ARow.StartOfCommitment = DateTime.Now.Date;
 }
        private void UpdateDefaultCombobox(Boolean ADuringScreenActivation)
        {
            // update default combobox
            String SelectedSites       = clbSites.GetCheckedStringList();
            Int64  SelectedDefaultSite = 0;
            String SiteName;

            // remember original selection for default site
            if (ADuringScreenActivation)
            {
                SelectedDefaultSite = Convert.ToInt64(TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_SITEKEY));
            }
            else
            {
                if (cmbDefaultSite.SelectedValue != null)
                {
                    SelectedDefaultSite = Convert.ToInt64(cmbDefaultSite.SelectedValue);
                }
            }

            String[] SiteKeyArray = SelectedSites.Split(',');
            Int32    Counter      = 0;

            // initialize data table for combobox
            CmbDataTable.Clear();

            for (Counter = 0; Counter < SiteKeyArray.Length; Counter++)
            {
                if (SiteKeyArray[Counter] != "")
                {
                    // find site name for given key ("Find" does not work on DataTable as it does not have primary key)
                    SiteName = "";

                    foreach (DataRow SiteRow in AvailableSitesTable.Rows)
                    {
                        if (Convert.ToInt64(SiteRow[PUnitTable.GetPartnerKeyDBName()]) == Convert.ToInt64(SiteKeyArray[Counter]))
                        {
                            SiteName = SiteRow[PUnitTable.GetUnitNameDBName()].ToString();
                            break;
                        }
                    }

                    CmbDataTable.Rows.Add(string.Format("{0:0000000000}",
                                                        Convert.ToInt64(SiteKeyArray[Counter])) + " - " + SiteName, Convert.ToInt64(SiteKeyArray[Counter]));
                }
            }

            // now reselected the original selected default site
            if (SelectedDefaultSite > 0)
            {
                cmbDefaultSite.SelectedValue = SelectedDefaultSite;
            }
        }
Пример #8
0
        private void InitializeManualCode()
        {
            string MySettings = TSystemDefaults.GetSystemDefault("IntranetExportSettings", "pswd,45,");

            string[] Setting = MySettings.Split(',');

            if (Setting.Length > 2)
            {
                FPswd     = Setting[0];
                FGiftDays = Convert.ToInt32(Setting[1]);
                FExtra    = Setting[2];
            }

            FReplyToEmail  = TUserDefaults.GetStringDefault("ReplyToEmail");
            FServerAddress = TUserDefaults.GetStringDefault("IntranetServerAddress");
        }
        private void RunOnceOnActivationManual()
        {
            // AlanP March 2013:  Use a try/catch block because nUnit testing on this screen does not support Drag/Drop in multi-threaded model
            // It is easier to do this than to configure all the different test execution methods to use STA
            try
            {
                trvUnits.AllowDrop = true;
                trvUnits.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(treeView_ItemDrag);
                trvUnits.DragOver += new System.Windows.Forms.DragEventHandler(treeView_DragOver);
                trvUnits.DragDrop += new System.Windows.Forms.DragEventHandler(treeView_DragDrop);
            }
            catch (InvalidOperationException)
            {
                // ex.Message is: DragDrop registration did not succeed.
                // Inner exception is: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made.
            }

            trvUnits.Click           += new EventHandler(UnitsClick);
            trvUnits.ShowNodeToolTips = true;
            trvUnits.MouseWheel      += new MouseEventHandler(treeView_MouseWheel);
            trvUnits.Focus();

            txtChild.TextChanged  += new EventHandler(EvaluateParentChange);
            txtParent.TextChanged += new EventHandler(EvaluateParentChange);

            FPetraUtilsObject.UnhookControl(pnlDetails, true); // I don't want changes in these values to cause SetChangedFlag.
            FPetraUtilsObject.UnhookControl(txtStatus, false);

            ArrayList UnitNodes = TRemote.MPersonnel.WebConnectors.GetUnitHeirarchy();
            //
            // The list of nodes returned by the above call are ordered to the extent that:
            //  * The root node appears first,
            //  * a parent appears before its child.
            UnitHierarchyNode RootData = (UnitHierarchyNode)UnitNodes[0];
            TreeNode          RootNode = new TreeNode(RootData.Description);

            RootNode.Tag         = RootData;
            RootNode.ToolTipText = RootData.TypeCode;
            UnitNodes.RemoveAt(0);
            trvUnits.Nodes.Add(RootNode);
            AddChildren(RootNode, UnitNodes);
            Int64 MySiteKey = Convert.ToInt64(TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_SITEKEY, ""));

            ShowThisUnit(MySiteKey);
        }
Пример #10
0
        /// <summary>
        /// add a new short term application
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewRowShortTermApp(System.Object sender, EventArgs e)
        {
            // Clear any validation errors so that the following call to ValidateAllData starts with a 'clean slate'.
            FPetraUtilsObject.VerificationResultCollection.Clear();

            if (ValidateAllData(true, TErrorProcessingMode.Epm_IgnoreNonCritical))
            {
                // we create the table locally, no dataset
                IndividualDataTDSPmGeneralApplicationRow NewRowGeneralApp = FMainDS.PmGeneralApplication.NewRowTyped(true);
                PmShortTermApplicationRow NewRowShortTermApp = FMainDS.PmShortTermApplication.NewRowTyped(true);

                NewRowGeneralApp.PartnerKey                 = FMainDS.PPerson[0].PartnerKey;
                NewRowGeneralApp.ApplicationKey             = GetNextApplicationKey();
                NewRowGeneralApp.RegistrationOffice         = Convert.ToInt64(TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_SITEKEY, ""));
                NewRowGeneralApp.GenAppDate                 = DateTime.Today;
                NewRowGeneralApp.ApplicationForEventOrField = Catalog.GetString("Event");

                //TODO temp, needs to be changed
                NewRowGeneralApp.AppTypeName = "CONFERENCE";
                NewRowGeneralApp.OldLink     =
                    TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_SITEKEY, "") + ";" + NewRowGeneralApp.ApplicationKey.ToString();
                NewRowGeneralApp.GenApplicantType = "Participant";

                NewRowShortTermApp.PartnerKey         = NewRowGeneralApp.PartnerKey;
                NewRowShortTermApp.ApplicationKey     = NewRowGeneralApp.ApplicationKey;
                NewRowShortTermApp.RegistrationOffice = NewRowGeneralApp.RegistrationOffice;
                NewRowShortTermApp.StAppDate          = NewRowGeneralApp.GenAppDate;

                //TODO temp, needs to be changed
                NewRowShortTermApp.StApplicationType = "A";
                NewRowShortTermApp.StBasicOutreachId = NewRowGeneralApp.OldLink;

                FMainDS.PmGeneralApplication.Rows.Add(NewRowGeneralApp);
                FMainDS.PmShortTermApplication.Rows.Add(NewRowShortTermApp);

                FPetraUtilsObject.SetChangedFlag();

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

                SelectDetailRowByDataTableIndex(FMainDS.PmGeneralApplication.Rows.Count - 1);
            }
        }
        private void InitializeManualCode()
        {
            const string APPLICATION_TITLE = "OpenPetra.org ";

            // Currently, only the Main Menu gets an 'OpenPetra styled' StatusBar (an 'OpenPetra styled' StatusBar
            // doesn't go with normal Forms at the moment as pnlContent's BackColor [and UserControls] is white
            // in colour and that doesn't look that good with an 'OpenPetra styled' StatusBar at the bottom).
            stbMain.UseOpenPetraToolStripRenderer = true;

            // this is needed for one screen which should only be displayed if tax deductibility is enabled
            FTaxDeductiblePercentageEnabled = Convert.ToBoolean(
                TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE"));

            InitialiseTopPanel();

            LoadNavigationUI();

            this.Text = APPLICATION_TITLE + TApplicationVersion.GetApplicationVersion();

            this.KeyDown += CustomKeyDownHandler;
        }
Пример #12
0
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="ALabelText"></param>
        /// <param name="AName"></param>
        public static void GetLocStrCounty(out String ALabelText, out String AName)
        {
            String LocalisedCountyLabel;

            LocalisedCountyLabel = TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_LOCALISEDCOUNTYLABEL, String.Empty);

            if (LocalisedCountyLabel.Trim() != String.Empty)
            {
                if (!LocalisedCountyLabel.EndsWith(":"))
                {
                    LocalisedCountyLabel = LocalisedCountyLabel + ':';
                }

                ALabelText = LocalisedCountyLabel;
            }
            else
            {
                ALabelText = StrCountyDefaultLabel;
            }

            // Remove & and : from the LabelText to get the 'Name' of the field
            AName = ALabelText.Replace("&", "");
            AName = AName.Replace(":", "");
        }
Пример #13
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);
            }
        }
Пример #14
0
        /// <summary>
        /// Find all the gifts for a year, returning "worker", "field" and "total" results.
        /// </summary>
        public static DataTable TotalGiftsThroughFieldYear(TParameterList AParameters, TResultList AResults)
        {
            bool TaxDeductiblePercentageEnabled = Convert.ToBoolean(
                TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE"));

            Int32  LedgerNum     = AParameters.Get("param_ledger_number_i").ToInt32();
            Int32  NumberOfYears = AParameters.Get("param_NumberOfYears").ToInt32();
            string SqlQuery      = "SELECT batch.a_gl_effective_date_d as Date, motive.a_report_column_c AS ReportColumn, ";

            if (AParameters.Get("param_currency").ToString() == "Base")
            {
                SqlQuery += "detail.a_gift_amount_n AS Amount";

                if (TaxDeductiblePercentageEnabled)
                {
                    SqlQuery += ", detail.a_tax_deductible_amount_base_n AS TaxDeductAmount";
                }
            }
            else
            {
                SqlQuery += "detail.a_gift_amount_intl_n AS Amount";

                if (TaxDeductiblePercentageEnabled)
                {
                    SqlQuery += ", detail.a_tax_deductible_amount_intl_n AS TaxDeductAmount";
                }
            }

            SqlQuery += (" FROM PUB_a_gift as gift, PUB_a_gift_detail as detail, PUB_a_gift_batch as batch, PUB_a_motivation_detail AS motive"

                         + " WHERE detail.a_ledger_number_i = " + LedgerNum +
                         " AND batch.a_batch_status_c = 'Posted'" +
                         " AND batch.a_batch_number_i = gift.a_batch_number_i" +
                         " AND batch.a_ledger_number_i = " + LedgerNum

                         + " AND gift.a_ledger_number_i = " + LedgerNum +
                         " AND detail.a_batch_number_i = gift.a_batch_number_i" +
                         " AND detail.a_gift_transaction_number_i = gift.a_gift_transaction_number_i"

                         + " AND motive.a_ledger_number_i = " + LedgerNum +
                         " AND motive.a_motivation_group_code_c = detail.a_motivation_group_code_c" +
                         " AND motive.a_motivation_detail_code_c = detail.a_motivation_detail_code_c" +
                         " AND motive.a_receipt_l=true");

            Boolean        newTransaction;
            TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted, out newTransaction);
            DataTable      tempTbl     = DBAccess.GDBAccessObj.SelectDT(SqlQuery, "result", Transaction);

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

            DataTable resultTable = new DataTable();

            resultTable.Columns.Add("SummaryYear", typeof(Int32));              //
            resultTable.Columns.Add("YearWorker", typeof(Decimal));             // These are the names of the variables
            resultTable.Columns.Add("YearWorkerCount", typeof(Int32));          // returned by this calculation.
            resultTable.Columns.Add("YearField", typeof(Decimal));              //
            resultTable.Columns.Add("YearFieldCount", typeof(Int32));           //
            resultTable.Columns.Add("YearTotal", typeof(Decimal));              //
            resultTable.Columns.Add("YearTotalCount", typeof(Int32));           //

            resultTable.Columns.Add("YearWorkerTaxDeduct", typeof(Decimal));
            resultTable.Columns.Add("YearFieldTaxDeduct", typeof(Decimal));
            resultTable.Columns.Add("YearTotalTaxDeduct", typeof(Decimal));

            Int32 Year = DateTime.Now.Year;

            for (Int32 YearIdx = 0; YearIdx < NumberOfYears; YearIdx++)
            {
                string yearStart = String.Format("#{0:0000}-01-01#", Year - YearIdx);
                string yearEnd   = String.Format("#{0:0000}-12-31#", Year - YearIdx);

                tempTbl.DefaultView.RowFilter = "Date >= " + yearStart + " AND Date < " + yearEnd;

                Decimal WorkerTotal = 0;
                Decimal FieldTotal  = 0;
                Int32   WorkerCount = 0;
                Int32   FieldCount  = 0;
                Int32   TotalCount  = tempTbl.DefaultView.Count;

                Decimal WorkerTotalTaxDeduct = 0;
                Decimal FieldTotalTaxDeduct  = 0;

                for (int i = 0; i < TotalCount; i++)
                {
                    DataRow Row = tempTbl.DefaultView[i].Row;

                    if (Row["ReportColumn"].ToString() == "Worker")
                    {
                        WorkerCount++;
                        WorkerTotal += Convert.ToDecimal(Row["Amount"]);

                        if (TaxDeductiblePercentageEnabled)
                        {
                            WorkerTotalTaxDeduct += Convert.ToDecimal(Row["TaxDeductAmount"]);
                        }
                    }
                    else
                    {
                        FieldCount++;
                        FieldTotal += Convert.ToDecimal(Row["Amount"]);

                        if (TaxDeductiblePercentageEnabled)
                        {
                            FieldTotalTaxDeduct += Convert.ToDecimal(Row["TaxDeductAmount"]);
                        }
                    }
                }

                DataRow resultRow = resultTable.NewRow();

                resultRow["SummaryYear"]     = Year - YearIdx;
                resultRow["YearWorker"]      = WorkerTotal;
                resultRow["YearWorkerCount"] = WorkerCount;
                resultRow["YearField"]       = FieldTotal;
                resultRow["YearFieldCount"]  = FieldCount;
                resultRow["YearTotal"]       = WorkerTotal + FieldTotal;
                resultRow["YearTotalCount"]  = TotalCount;

                resultRow["YearWorkerTaxDeduct"] = WorkerTotalTaxDeduct;
                resultRow["YearFieldTaxDeduct"]  = FieldTotalTaxDeduct;
                resultRow["YearTotalTaxDeduct"]  = WorkerTotalTaxDeduct + FieldTotalTaxDeduct;

                resultTable.Rows.Add(resultRow);
            }

            return(resultTable);
        }
Пример #15
0
        private static void CreateShortTermApplication(XmlNode ANode,
                                                       Int64 APartnerKey,
                                                       ref PartnerImportExportTDS AMainDS,
                                                       TDBTransaction ATransaction)
        {
            String strEventKey = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_EVENTKEY);
            long   EventKey    = -1;

            if (strEventKey.Length > 0)
            {
                try
                {
                    EventKey = long.Parse(strEventKey);
                }
                catch (System.FormatException)
                {
                    AddVerificationResult("Bad number format in EventKey: " + strEventKey);
                }

                if (!PUnitAccess.Exists(EventKey, ATransaction))
                {
                    AddVerificationResult("EventKey not known - application cannot be imported: " + EventKey);
                    return;
                }

                PmGeneralApplicationRow GenAppRow = AMainDS.PmGeneralApplication.NewRowTyped();

                GenAppRow.PartnerKey     = APartnerKey;
                GenAppRow.ApplicationKey = (int)DBAccess.GDBAccessObj.GetNextSequenceValue("seq_application", ATransaction);

                GenAppRow.OldLink =
                    TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_SITEKEY, "") + ";" + GenAppRow.ApplicationKey.ToString();
                GenAppRow.RegistrationOffice = DomainManager.GSiteKey; // When this is imported, RegistrationOffice can't be null.

                GenAppRow.GenAppDate           = DateTime.Now;
                GenAppRow.AppTypeName          = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_APPTYPE);
                GenAppRow.GenApplicationStatus = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_APPSTATUS);
                GenAppRow.Comment = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_APPCOMMENTS);

                PmShortTermApplicationRow ShortTermRow = AMainDS.PmShortTermApplication.NewRowTyped();
                ShortTermRow.PartnerKey         = APartnerKey;
                ShortTermRow.ApplicationKey     = GenAppRow.ApplicationKey;
                ShortTermRow.RegistrationOffice = GenAppRow.RegistrationOffice; // When this is imported, RegistrationOffice can't be null.
                ShortTermRow.StBasicOutreachId  = "Unused field";               // This field is scheduled for deletion, but NOT NULL now.
                ShortTermRow.StAppDate          = DateTime.Now;
                ShortTermRow.StApplicationType  = GenAppRow.AppTypeName;
                ShortTermRow.StConfirmedOption  = EventKey;
                String TimeString = "";

                try
                {
                    TimeString = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_ARRIVALDATE);

                    if (TimeString.Length > 0)
                    {
                        ShortTermRow.Arrival = DateTime.Parse(TimeString);
                    }

                    TimeString = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_DEPARTUREDATE);

                    if (TimeString.Length > 0)
                    {
                        ShortTermRow.Departure = DateTime.Parse(TimeString);
                    }
                }
                catch (System.FormatException)
                {
                    AddVerificationResult("Bad date format in Application: " + TimeString);
                }

                DateTime TempTime;

                TimeString = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_ARRIVALTIME);

                if (TimeString.Length > 0)
                {
                    try
                    {
                        TempTime = DateTime.Parse(TimeString);
                        ShortTermRow.ArrivalHour   = TempTime.Hour;
                        ShortTermRow.ArrivalMinute = TempTime.Minute;
                    }
                    catch (System.FormatException)
                    {
                        AddVerificationResult("Bad time format in Application: " + TimeString);
                    }
                }

                TimeString = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_DEPARTURETIME);

                if (TimeString.Length > 0)
                {
                    try
                    {
                        TempTime = DateTime.Parse(TimeString);
                        ShortTermRow.DepartureHour   = TempTime.Hour;
                        ShortTermRow.DepartureMinute = TempTime.Minute;
                    }
                    catch (System.FormatException)
                    {
                        AddVerificationResult("Bad time format in Application: " + TimeString);
                    }
                }

                ShortTermRow.OutreachRole = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_EVENTROLE);
                String ChargedField = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_CHARGEDFIELD);

                if (ChargedField.Length > 0)
                {
                    try
                    {
                        ShortTermRow.StFieldCharged = long.Parse(ChargedField);
                    }
                    catch
                    {
                        AddVerificationResult("Bad number format in ChargedField: " + ChargedField);
                    }
                }

                AMainDS.PmGeneralApplication.Rows.Add(GenAppRow);
                AMainDS.PmShortTermApplication.Rows.Add(ShortTermRow);
                AddVerificationResult("Application Record Created.", TResultSeverity.Resv_Status);
            }
        }
        public static DataTable GiftBatchDetailTable(Dictionary <String, TVariant> AParameters, TReportingDbAdapter DbAdapter)
        {
            TDBTransaction Transaction = null;

            int LedgerNumber = AParameters["param_ledger_number_i"].ToInt32();
            int BatchNumber  = AParameters["param_batch_number_i"].ToInt32();

            // create new datatable
            DataTable Results = new DataTable();

            DBAccess.GDBAccessObj.BeginAutoReadTransaction(
                ref Transaction,
                delegate
            {
                String CurrentDate = DateTime.Today.ToString(
                    "yyyy-MM-dd");

                string Query =
                    "SELECT DISTINCT a_gift_batch.a_batch_description_c, a_gift_batch.a_batch_status_c, a_gift_batch.a_gift_type_c, a_gift_batch.a_gl_effective_date_d, "
                    +
                    "a_gift_batch.a_bank_cost_centre_c, a_gift_batch.a_bank_account_code_c, a_gift_batch.a_currency_code_c, a_gift_batch.a_hash_total_n, a_gift_batch.a_batch_total_n, "
                    +
                    "a_gift_detail.a_gift_transaction_number_i, a_gift_detail.a_detail_number_i, a_gift_detail.a_confidential_gift_flag_l, " +
                    "a_gift_detail.p_recipient_key_n, a_gift_detail.a_gift_amount_n, a_gift_detail.a_gift_amount_intl_n, a_gift_detail.a_gift_transaction_amount_n, "
                    +
                    "a_gift_detail.a_motivation_group_code_c, a_gift_detail.a_motivation_detail_code_c, a_gift_detail.a_recipient_ledger_number_n, "
                    +
                    "a_gift_detail.a_gift_comment_one_c, a_gift_detail.a_gift_comment_two_c, a_gift_detail.a_gift_comment_three_c, a_gift_detail.a_tax_deductible_pct_n, "
                    +
                    "a_gift.p_donor_key_n AS DonorKey, a_gift.a_reference_c AS GiftReference, a_gift.a_method_of_giving_code_c, a_gift.a_method_of_payment_code_c, "
                    +
                    "a_gift.a_receipt_letter_code_c, a_gift.a_date_entered_d, a_gift.a_first_time_gift_l, a_gift.a_receipt_number_i, " +
                    "Donor.p_partner_class_c AS DonorClass, Donor.p_partner_short_name_c AS DonorShortName, Donor.p_receipt_letter_frequency_c, Donor.p_receipt_each_gift_l, "
                    +
                    "Recipient.p_partner_class_c AS RecipientClass, Recipient.p_partner_short_name_c AS RecipientShortName, " +
                    "a_gift_detail.p_mailing_code_c AS MailingCode, " +
                    "a_gift_detail.a_charge_flag_l AS ChargeFlag, "
                    +
                    // true if donor has a valid Ex-Worker special type
                    "CASE WHEN EXISTS (SELECT p_partner_type.* FROM p_partner_type WHERE " +
                    "p_partner_type.p_partner_key_n = a_gift.p_donor_key_n" +
                    " AND (p_partner_type.p_valid_from_d IS null OR p_partner_type.p_valid_from_d <= '" + CurrentDate + "')" +
                    " AND (p_partner_type.p_valid_until_d IS null OR p_partner_type.p_valid_until_d >= '" + CurrentDate + "')" +
                    " AND p_partner_type.p_type_code_c LIKE '" +
                    TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_EXWORKERSPECIALTYPE, "EX-WORKER") + "%'" +
                    ") THEN True ELSE False END AS EXWORKER, " +

                    // true if the gift is restricted for the user
                    "CASE WHEN EXISTS (SELECT s_user_group.* FROM s_user_group " +
                    "WHERE a_gift.a_restricted_l IS true" +
                    " AND NOT EXISTS (SELECT s_group_gift.s_read_access_l FROM s_group_gift, s_user_group " +
                    "WHERE s_group_gift.s_read_access_l" +
                    " AND s_group_gift.a_ledger_number_i = " + LedgerNumber +
                    " AND s_group_gift.a_batch_number_i = " + BatchNumber +
                    " AND s_group_gift.a_gift_transaction_number_i = a_gift_detail.a_gift_transaction_number_i" +
                    " AND s_user_group.s_user_id_c = '" + UserInfo.GUserInfo.UserID + "'" +
                    " AND s_user_group.s_group_id_c = s_group_gift.s_group_id_c" +
                    " AND s_user_group.s_unit_key_n = s_group_gift.s_group_unit_key_n)" +
                    ") THEN False ELSE True END AS ReadAccess " +

                    "FROM a_gift_batch, a_gift_detail, a_gift, p_partner AS Donor, p_partner AS Recipient " +

                    "WHERE a_gift_batch.a_ledger_number_i = " + LedgerNumber + " AND a_gift_batch.a_batch_number_i = " + BatchNumber +
                    " AND a_gift.a_ledger_number_i = " + LedgerNumber + " AND a_gift.a_batch_number_i = " + BatchNumber +
                    " AND a_gift_detail.a_ledger_number_i = " + LedgerNumber + " AND a_gift_detail.a_batch_number_i = " +
                    BatchNumber +
                    " AND a_gift.a_gift_transaction_number_i = a_gift_detail.a_gift_transaction_number_i " +
                    " AND Donor.p_partner_key_n = a_gift.p_donor_key_n" +
                    " AND Recipient.p_partner_key_n = a_gift_detail.p_recipient_key_n";

                Results = DbAdapter.RunQuery(Query, "Results", Transaction);
            });

            return(Results);
        }
Пример #17
0
        public static Boolean GetMotivationGroupAndDetail(Int64 APartnerKey,
                                                          ref String AMotivationGroup,
                                                          ref String AMotivationDetail)
        {
            Boolean PartnerKeyIsValid = false;

            if (APartnerKey != 0)
            {
                AMotivationGroup = MFinanceConstants.MOTIVATION_GROUP_GIFT;

                string MotivationDetail = AMotivationDetail;

                TDBTransaction readTransaction = null;
                DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                          TEnforceIsolationLevel.eilMinimum,
                                                                          ref readTransaction,
                                                                          delegate
                {
                    PPartnerTable myPPartnerTable =
                        PPartnerAccess.LoadByPrimaryKey(APartnerKey, readTransaction);

                    if (myPPartnerTable.Rows.Count == 1)
                    {
                        // Entry for partnerKey is valid
                        PartnerKeyIsValid      = true;
                        PPartnerRow partnerRow = (PPartnerRow)myPPartnerTable.Rows[0];

                        // Change motivationDetail if ColumnPartnerClass is UNIT
                        if (partnerRow.PartnerClass.Equals(MPartnerConstants.PARTNERCLASS_UNIT))
                        {
                            // AND KEY-MIN
                            PUnitTable pUnitTable =
                                PUnitAccess.LoadByPrimaryKey(APartnerKey, readTransaction);

                            if (pUnitTable.Rows.Count == 1)
                            {
                                PUnitRow unitRow = (PUnitRow)pUnitTable.Rows[0];

                                if (unitRow.UnitTypeCode.Equals(MPartnerConstants.UNIT_TYPE_KEYMIN))
                                {
                                    MotivationDetail = MFinanceConstants.GROUP_DETAIL_KEY_MIN;
                                }
                                else
                                {
                                    MotivationDetail =
                                        TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_DEFAULTFIELDMOTIVATION,
                                                                         MFinanceConstants.GROUP_DETAIL_FIELD);

                                    // if system default is empty then set to FIELD
                                    if (string.IsNullOrEmpty(MotivationDetail))
                                    {
                                        MotivationDetail = MFinanceConstants.GROUP_DETAIL_FIELD;
                                    }
                                }
                            }
                        }
                        else
                        {
                            MotivationDetail = MFinanceConstants.GROUP_DETAIL_SUPPORT;
                        }
                    }
                });

                AMotivationDetail = MotivationDetail;
            }

            return(PartnerKeyIsValid);
        }
Пример #18
0
        /// <summary>
        /// Create new partner, family, location and PartnerLocation records in MainDS
        /// </summary>
        private static Int64 CreateNewFamily(XmlNode ANode, out int ALocationKey, ref PartnerImportExportTDS AMainDS)
        {
            PPartnerRow newPartner = AMainDS.PPartner.NewRowTyped();

            AMainDS.PPartner.Rows.Add(newPartner);

            newPartner.PartnerKey   = (AMainDS.PPartner.Rows.Count + 1) * -1;
            newPartner.PartnerClass = MPartnerConstants.PARTNERCLASS_FAMILY;
            newPartner.StatusCode   = MPartnerConstants.PARTNERSTATUS_ACTIVE;
            newPartner.Comment      = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_NOTESFAMILY);

            String AcquisitionCode = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_AQUISITION);

            newPartner.AcquisitionCode = (AcquisitionCode.Length > 0) ? AcquisitionCode : MPartnerConstants.PARTNERIMPORT_AQUISITION_DEFAULT;

            newPartner.AddresseeTypeCode = MPartnerConstants.ADDRESSEETYPE_DEFAULT;

            if (TXMLParser.HasAttribute(ANode, MPartnerConstants.PARTNERIMPORT_ADDRESSEE_TYPE))
            {
                newPartner.AddresseeTypeCode = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_ADDRESSEE_TYPE);
            }
            else
            {
                string gender = GetGenderCode(ANode);

                if (gender == MPartnerConstants.GENDER_MALE)
                {
                    newPartner.AddresseeTypeCode = MPartnerConstants.ADDRESSEETYPE_MALE;
                }
                else if (gender == MPartnerConstants.GENDER_FEMALE)
                {
                    newPartner.AddresseeTypeCode = MPartnerConstants.ADDRESSEETYPE_FEMALE;
                }
            }

            if (TXMLParser.HasAttribute(ANode, MPartnerConstants.PARTNERIMPORT_LANGUAGE))
            {
                newPartner.LanguageCode = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_LANGUAGE);
            }
            else if (TUserDefaults.HasDefault(MSysManConstants.PARTNER_LANGUAGECODE))
            {
                newPartner.LanguageCode = TUserDefaults.GetStringDefault(MSysManConstants.PARTNER_LANGUAGECODE);
            }

            string[] giftReceiptingDefaults = TSystemDefaults.GetSystemDefault("GiftReceiptingDefaults", ",no").Split(new char[] { ',' });
            newPartner.ReceiptLetterFrequency = giftReceiptingDefaults[0];
            newPartner.ReceiptEachGift        = giftReceiptingDefaults[1] == "YES" || giftReceiptingDefaults[1] == "TRUE";


            PFamilyRow newFamily = AMainDS.PFamily.NewRowTyped();

            AMainDS.PFamily.Rows.Add(newFamily);

            newFamily.PartnerKey    = newPartner.PartnerKey;
            newFamily.FirstName     = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_FIRSTNAME);
            newFamily.FamilyName    = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_FAMILYNAME);
            newFamily.MaritalStatus = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_MARITALSTATUS);
            newFamily.Title         = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_TITLE);
            newFamily.MaritalStatus = GetMaritalStatusCode(ANode);

            newPartner.PartnerShortName = Calculations.DeterminePartnerShortName(newFamily.FamilyName, newFamily.Title, newFamily.FirstName);
            PLocationRow newLocation = AMainDS.PLocation.NewRowTyped(true);

            AMainDS.PLocation.Rows.Add(newLocation);
            newLocation.LocationKey = TPartnerImportCSV.FLocationKey;
            newLocation.Locality    = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_LOCALITY);
            newLocation.StreetName  = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_STREETNAME);
            newLocation.Address3    = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_ADDRESS);
            newLocation.PostalCode  = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_POSTALCODE);
            newLocation.City        = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_CITY);
            newLocation.County      = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_COUNTY);
            newLocation.CountryCode = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_COUNTRYCODE);

            PPartnerLocationRow partnerlocation = AMainDS.PPartnerLocation.NewRowTyped(true);

            partnerlocation.LocationKey     = TPartnerImportCSV.FLocationKey;
            partnerlocation.SiteKey         = 0;
            partnerlocation.PartnerKey      = newPartner.PartnerKey;
            partnerlocation.DateEffective   = DateTime.Now;
            partnerlocation.LocationType    = MPartnerConstants.LOCATIONTYPE_HOME;
            partnerlocation.SendMail        = true;
            partnerlocation.EmailAddress    = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_EMAIL);
            partnerlocation.TelephoneNumber = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_PHONE);
            partnerlocation.MobileNumber    = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_MOBILEPHONE);
            AMainDS.PPartnerLocation.Rows.Add(partnerlocation);

            ALocationKey = TPartnerImportCSV.FLocationKey;
            TPartnerImportCSV.FLocationKey--;
            return(newPartner.PartnerKey);
        }
Пример #19
0
        public static Boolean GetMotivationGroupAndDetail(Int64 APartnerKey,
                                                          ref String AMotivationGroup,
                                                          ref String AMotivationDetail)
        {
            Boolean PartnerKeyIsValid = false;

            if (APartnerKey != 0)
            {
                string MotivationGroup  = MFinanceConstants.MOTIVATION_GROUP_GIFT;
                string MotivationDetail = AMotivationDetail;

                TDBTransaction readTransaction = null;
                DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                          TEnforceIsolationLevel.eilMinimum,
                                                                          ref readTransaction,
                                                                          delegate
                {
                    PPartnerTable myPPartnerTable =
                        PPartnerAccess.LoadByPrimaryKey(APartnerKey, readTransaction);

                    if (myPPartnerTable.Rows.Count == 1)
                    {
                        // Entry for partnerKey is valid
                        PartnerKeyIsValid      = true;
                        PPartnerRow partnerRow = (PPartnerRow)myPPartnerTable.Rows[0];

                        // Change motivationDetail if ColumnPartnerClass is UNIT
                        if (partnerRow.PartnerClass.Equals(MPartnerConstants.PARTNERCLASS_UNIT))
                        {
                            // AND KEY-MIN

                            bool KeyMinFound = false;

                            // first check if a motivation detail is linked to this potential key min
                            AMotivationDetailTable MotivationDetailTable = AMotivationDetailAccess.LoadViaPPartner(APartnerKey, readTransaction);

                            if ((MotivationDetailTable != null) && (MotivationDetailTable.Rows.Count > 0))
                            {
                                foreach (AMotivationDetailRow Row in MotivationDetailTable.Rows)
                                {
                                    if (Row.MotivationStatus)
                                    {
                                        MotivationGroup  = MotivationDetailTable[0].MotivationGroupCode;
                                        MotivationDetail = MotivationDetailTable[0].MotivationDetailCode;

                                        KeyMinFound = true;
                                        break;
                                    }
                                }
                            }

                            // second check to see if this is a key min
                            if (!KeyMinFound)
                            {
                                PUnitTable pUnitTable =
                                    PUnitAccess.LoadByPrimaryKey(APartnerKey, readTransaction);

                                if (pUnitTable.Rows.Count == 1)
                                {
                                    PUnitRow unitRow = (PUnitRow)pUnitTable.Rows[0];

                                    if (unitRow.UnitTypeCode.Equals(MPartnerConstants.UNIT_TYPE_KEYMIN))
                                    {
                                        MotivationDetail = MFinanceConstants.GROUP_DETAIL_KEY_MIN;
                                    }
                                    else
                                    {
                                        MotivationDetail =
                                            TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_DEFAULTFIELDMOTIVATION,
                                                                             MFinanceConstants.GROUP_DETAIL_FIELD);

                                        // if system default is empty then set to FIELD
                                        if (string.IsNullOrEmpty(MotivationDetail))
                                        {
                                            MotivationDetail = MFinanceConstants.GROUP_DETAIL_FIELD;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            MotivationDetail = MFinanceConstants.GROUP_DETAIL_SUPPORT;
                        }
                    }
                });

                AMotivationGroup  = MotivationGroup;
                AMotivationDetail = MotivationDetail;
            }

            return(PartnerKeyIsValid);
        }
Пример #20
0
        //
        // This will be called if the Fast Reports Wrapper loaded OK.
        // Returns True if the data apparently loaded OK and the report should be printed.
        private bool LoadReportData(TRptCalculator ACalc)
        {
            ArrayList reportParam = ACalc.GetParameters().Elems;

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

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

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

            if (this.IsDisposed) // There's no cancel function as such - if the user has pressed Esc the form is closed!
            {
                return(false);
            }

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

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

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

            DataTable LedgerNameTable = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.LedgerNameList);
            DataView  LedgerView      = new DataView(LedgerNameTable);

            LedgerView.RowFilter = "LedgerNumber=" + FLedgerNumber;
            String LedgerName = "";

            if (LedgerView.Count > 0)
            {
                LedgerName = LedgerView[0].Row["LedgerName"].ToString();
            }

            ACalc.AddStringParameter("param_ledger_name", LedgerName);
            ACalc.AddStringParameter("param_linked_partner_cc", ""); // I may want to use this for auto_email, but usually it's unused.

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

            ACalc.AddParameter("param_tax_deductible_pct", TaxDeductiblePercentageEnabled);

            if (ACalc.GetParameters().Exists("param_currency") &&
                (ACalc.GetParameters().Get("param_currency").ToString() == Catalog.GetString("Transaction")))
            {
                ACalc.RemoveParameter("param_currency_name");
                ACalc.AddParameter("param_currency_name",
                                   TRemote.MFinance.Reporting.WebConnectors.GetTransactionCurrency(FLedgerNumber, Convert.ToInt32(txtBatchNumber.Text)));
            }

            return(true);
        }
Пример #21
0
        public static TPetraPrincipal PerformUserAuthentication(String AUserID, String APassword, out Boolean ASystemEnabled)
        {
            DateTime        LoginDateTime;
            TPetraPrincipal PetraPrincipal = null;

            Int32 AProcessID = -1;

            ASystemEnabled = true;

            string EmailAddress = AUserID;

            if (AUserID.Contains("@"))
            {
                AUserID = AUserID.Substring(0, AUserID.IndexOf("@")).
                          Replace(".", string.Empty).
                          Replace("_", string.Empty).ToUpper();
            }

            try
            {
                SUserRow UserDR = LoadUser(AUserID, out PetraPrincipal);

                // Already assign the global variable here, because it is needed for SUserAccess.SubmitChanges later in this function
                UserInfo.GUserInfo = PetraPrincipal;

                // Check if user is retired
                if (PetraPrincipal.PetraIdentity.Retired)
                {
                    throw new EUserRetiredException(StrInvalidUserIDPassword);
                }

                int FailedLoginsUntilRetire = Convert.ToInt32(
                    TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_FAILEDLOGINS_UNTIL_RETIRE, "10"));

                // Console.WriteLine('PetraPrincipal.PetraIdentity.FailedLogins: ' + PetraPrincipal.PetraIdentity.FailedLogins.ToString +
                // '; PetraPrincipal.PetraIdentity.Retired: ' + PetraPrincipal.PetraIdentity.Retired.ToString);
                // Check if user should be autoretired
                if ((PetraPrincipal.PetraIdentity.FailedLogins >= FailedLoginsUntilRetire) && ((!PetraPrincipal.PetraIdentity.Retired)))
                {
                    UserDR.Retired      = true;
                    UserDR.FailedLogins = 0;

                    SaveUser(AUserID, (SUserTable)UserDR.Table);

                    throw new EAccessDeniedException(StrInvalidUserIDPassword);
                }

                // Check SystemLoginStatus (Petra enabled/disabled) in the SystemStatus table (always holds only one record)
                Boolean            NewTransaction = false;
                SSystemStatusTable SystemStatusDT;

                TDBTransaction ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                                                                                                   TEnforceIsolationLevel.eilMinimum,
                                                                                                   out NewTransaction);

                try
                {
                    SystemStatusDT = SSystemStatusAccess.LoadAll(ReadTransaction);
                }
                finally
                {
                    if (NewTransaction)
                    {
                        DBAccess.GDBAccessObj.CommitTransaction();
                        TLogging.LogAtLevel(7, "TUserManager.PerformUserAuthentication: committed own transaction.");
                    }
                }

                if (SystemStatusDT[0].SystemLoginStatus)
                {
                    ASystemEnabled = true;
                }
                else
                {
                    ASystemEnabled = false;

                    if (PetraPrincipal.IsInGroup("SYSADMIN"))
                    {
                        PetraPrincipal.LoginMessage =
                            String.Format(StrSystemDisabled1,
                                          SystemStatusDT[0].SystemDisabledReason) + Environment.NewLine + Environment.NewLine + StrSystemDisabled2Admin;
                    }
                    else
                    {
                        TLoginLog.AddLoginLogEntry(AUserID, "System disabled", true, out AProcessID);

                        throw new ESystemDisabledException(String.Format(StrSystemDisabled1,
                                                                         SystemStatusDT[0].SystemDisabledReason) + Environment.NewLine + Environment.NewLine +
                                                           String.Format(StrSystemDisabled2, StringHelper.DateToLocalizedString(SystemStatusDT[0].SystemAvailableDate.Value),
                                                                         SystemStatusDT[0].SystemAvailableDate.Value.AddSeconds(SystemStatusDT[0].SystemAvailableTime).ToShortTimeString()));
                    }
                }

                if ((AUserID == "SYSADMIN") && TSession.HasVariable("ServerAdminToken"))
                {
                    // Login via server admin console authenticated by file token
                }
                else
                {
                    string UserAuthenticationMethod = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false);

                    if (UserAuthenticationMethod == "OpenPetraDBSUser")
                    {
                        // TODO 1 oChristianK cSecurity : Perform user authentication by verifying password hash in the DB
                        // see also ICTPetraWiki: Todo_Petra.NET#Implement_Security_.7B2.7D_.5BChristian.5D
                        if (CreateHashOfPassword(String.Concat(APassword,
                                                               UserDR.PasswordSalt)) != UserDR.PasswordHash)
                        {
                            // increase failed logins
                            UserDR.FailedLogins++;
                            LoginDateTime          = DateTime.Now;
                            UserDR.FailedLoginDate = LoginDateTime;
                            UserDR.FailedLoginTime = Conversions.DateTimeToInt32Time(LoginDateTime);
                            SaveUser(AUserID, (SUserTable)UserDR.Table);

                            throw new EPasswordWrongException(StrInvalidUserIDPassword);
                        }
                    }
                    else
                    {
                        IUserAuthentication auth = LoadAuthAssembly(UserAuthenticationMethod);

                        string ErrorMessage;

                        if (!auth.AuthenticateUser(EmailAddress, APassword, out ErrorMessage))
                        {
                            UserDR.FailedLogins++;
                            LoginDateTime          = DateTime.Now;
                            UserDR.FailedLoginDate = LoginDateTime;
                            UserDR.FailedLoginTime = Conversions.DateTimeToInt32Time(LoginDateTime);
                            SaveUser(AUserID, (SUserTable)UserDR.Table);

                            throw new EPasswordWrongException(ErrorMessage);
                        }
                    }
                }

                // Save successful login
                LoginDateTime        = DateTime.Now;
                UserDR.LastLoginDate = LoginDateTime;
                UserDR.LastLoginTime = Conversions.DateTimeToInt32Time(LoginDateTime);
                UserDR.FailedLogins  = 0;

                SaveUser(AUserID, (SUserTable)UserDR.Table);

                PetraPrincipal.PetraIdentity.CurrentLogin = LoginDateTime;

                // PetraPrincipal.PetraIdentity.FailedLogins := 0;

                if (PetraPrincipal.IsInGroup("SYSADMIN"))
                {
                    TLoginLog.AddLoginLogEntry(AUserID, "Successful  SYSADMIN", out AProcessID);
                }
                else
                {
                    TLoginLog.AddLoginLogEntry(AUserID, "Successful", out AProcessID);
                }

                PetraPrincipal.ProcessID = AProcessID;
                AProcessID = 0;

                if (UserDR.PasswordNeedsChange)
                {
                    // The user needs to change their password before they can use OpenPetra
                    PetraPrincipal.LoginMessage = Catalog.GetString("You need to change your password immediately.");
                }
            }
            finally
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
            }

            return(PetraPrincipal);
        }
Пример #22
0
        /// <summary>
        /// Format the letter for the donor with all the gifts
        ///
        /// Can also used for a single receipt.
        /// </summary>
        /// <returns>One or more html documents, each in its own body tag, for printing with the HTML printer</returns>
        private static string FormatLetter(Int64 ADonorKey,
                                           string ADonorName,
                                           DataTable ADonations,
                                           string ABaseCurrency,
                                           string AHTMLTemplate,
                                           string ALedgerCountryCode,
                                           TDBTransaction ATransaction)
        {
            // get details of the donor, and best address

            PLocationTable        Location;
            PPartnerLocationTable PartnerLocation;
            string CountryName;
            string EmailAddress;

            if (!TAddressTools.GetBestAddress(ADonorKey, out Location, out PartnerLocation, out CountryName, out EmailAddress, ATransaction))
            {
                return("");
            }

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

            string msg = AHTMLTemplate;

            if (ADonorName.Contains(","))
            {
                msg = msg.Replace("#TITLE", Calculations.FormatShortName(ADonorName, eShortNameFormat.eOnlyTitle));
            }
            else
            {
                // organisations have no title
                msg = msg.Replace("#TITLE", "");
            }

            msg = msg.Replace("#NAME", Calculations.FormatShortName(ADonorName, eShortNameFormat.eReverseWithoutTitle));
            msg = msg.Replace("#STREETNAME", GetStringOrEmpty(Location[0].StreetName));
            msg = msg.Replace("#LOCATION", GetStringOrEmpty(Location[0].Locality));
            msg = msg.Replace("#ADDRESS3", GetStringOrEmpty(Location[0].Address3));
            msg = msg.Replace("#BUILDING1", GetStringOrEmpty(Location[0].Building1));
            msg = msg.Replace("#BUILDING2", GetStringOrEmpty(Location[0].Building2));
            msg = msg.Replace("#CITY", GetStringOrEmpty(Location[0].City));
            msg = msg.Replace("#POSTALCODE", GetStringOrEmpty(Location[0].PostalCode));
            msg = msg.Replace("#DATE", DateTime.Now.ToString("d. MMMM yyyy"));

            // according to German Post, there is no country code in front of the post code
            // if country code is same for the address of the recipient and this office, then COUNTRYNAME is cleared
            if (GetStringOrEmpty(Location[0].CountryCode) != ALedgerCountryCode)
            {
                msg = msg.Replace("#COUNTRYNAME", CountryName);
            }
            else
            {
                msg = msg.Replace("#COUNTRYNAME", "");
            }

            // recognise detail lines automatically
            string RowTemplate;

            msg = TPrinterHtml.GetTableRow(msg, "#AMOUNT", out RowTemplate);
            string  OrigRowTemplate = RowTemplate;
            string  rowTexts        = "";
            decimal sum             = 0;
            decimal sumTaxDeduct    = 0;
            decimal sumNonDeduct    = 0;

            decimal  prevAmount          = 0.0M;
            decimal  prevAmountTaxDeduct = 0.0M;
            decimal  prevAmountNonDeduct = 0.0M;
            string   prevCurrency        = String.Empty;
            string   prevCommentOne      = String.Empty;
            string   prevAccountDesc     = String.Empty;
            string   prevCostCentreDesc  = String.Empty;
            string   prevgifttype        = string.Empty;
            DateTime prevDateEntered     = DateTime.MaxValue;

            foreach (DataRow rowGifts in ADonations.Rows)
            {
                DateTime dateEntered         = Convert.ToDateTime(rowGifts["DateEntered"]);
                decimal  amount              = Convert.ToDecimal(rowGifts["TransactionAmount"]);
                decimal  taxDeductibleAmount = 0;
                decimal  nonDeductibleAmount = 0;
                string   currency            = rowGifts["Currency"].ToString();
                string   commentOne          = rowGifts["CommentOne"].ToString();
                string   accountDesc         = rowGifts["AccountDesc"].ToString();
                string   costcentreDesc      = rowGifts["CostCentreDesc"].ToString();
                string   gifttype            = rowGifts["GiftType"].ToString();
                RowTemplate = OrigRowTemplate;

                sum += Convert.ToDecimal(rowGifts["AmountInBaseCurrency"]);

                if (TaxDeductiblePercentageEnabled)
                {
                    taxDeductibleAmount = Convert.ToDecimal(rowGifts["TaxDeductibleAmount"]);
                    nonDeductibleAmount = Convert.ToDecimal(rowGifts["NonDeductibleAmount"]);
                    sumTaxDeduct       += Convert.ToDecimal(rowGifts["TaxDeductibleAmountBase"]);
                    sumNonDeduct       += Convert.ToDecimal(rowGifts["NonDeductibleAmountBase"]);
                }

                // can we sum up donations on the same date, or do we need to print each detail with the account description?
                if (RowTemplate.Contains("#COMMENTONE") || RowTemplate.Contains("#ACCOUNTDESC") || RowTemplate.Contains("#COSTCENTREDESC"))
                {
                    if (gifttype == MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND)
                    {
                        RowTemplate = TPrinterHtml.RemoveDivWithClass(RowTemplate, MFinanceConstants.GIFT_TYPE_GIFT);
                    }
                    else if (gifttype == MFinanceConstants.GIFT_TYPE_GIFT)
                    {
                        RowTemplate = TPrinterHtml.RemoveDivWithClass(RowTemplate, MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND);
                    }

                    rowTexts += RowTemplate.
                                Replace("#DONATIONDATE", dateEntered.ToString("dd.MM.yyyy")).
                                Replace("#AMOUNTCURRENCY", currency).
                                Replace("#AMOUNT", StringHelper.FormatUsingCurrencyCode(amount, currency)).
                                Replace("#TAXDEDUCTAMOUNT", StringHelper.FormatUsingCurrencyCode(taxDeductibleAmount, currency)).
                                Replace("#TAXNONDEDUCTAMOUNT", StringHelper.FormatUsingCurrencyCode(nonDeductibleAmount, currency)).
                                Replace("#COMMENTONE", commentOne).
                                Replace("#ACCOUNTDESC", accountDesc).
                                Replace("#COSTCENTREDESC", costcentreDesc);
                }
                else
                {
                    if ((dateEntered != prevDateEntered) && (prevDateEntered != DateTime.MaxValue))
                    {
                        if (prevgifttype == MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND)
                        {
                            RowTemplate = TPrinterHtml.RemoveDivWithClass(RowTemplate, MFinanceConstants.GIFT_TYPE_GIFT);
                        }
                        else if (prevgifttype == MFinanceConstants.GIFT_TYPE_GIFT)
                        {
                            RowTemplate = TPrinterHtml.RemoveDivWithClass(RowTemplate, MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND);
                        }

                        rowTexts += RowTemplate.
                                    Replace("#DONATIONDATE", prevDateEntered.ToString("dd.MM.yyyy")).
                                    Replace("#AMOUNTCURRENCY", prevCurrency).
                                    Replace("#AMOUNT", StringHelper.FormatUsingCurrencyCode(prevAmount, prevCurrency)).
                                    Replace("#TAXDEDUCTAMOUNT", StringHelper.FormatUsingCurrencyCode(prevAmountTaxDeduct, prevCurrency)).
                                    Replace("#TAXNONDEDUCTAMOUNT", StringHelper.FormatUsingCurrencyCode(prevAmountNonDeduct, prevCurrency)).
                                    Replace("#COMMENTONE", prevCommentOne).
                                    Replace("#ACCOUNTDESC", prevAccountDesc).
                                    Replace("#COSTCENTREDESC", prevCostCentreDesc);
                        prevAmount = amount;

                        if (TaxDeductiblePercentageEnabled)
                        {
                            prevAmountTaxDeduct = taxDeductibleAmount;
                            prevAmountNonDeduct = nonDeductibleAmount;
                        }
                    }
                    else
                    {
                        prevAmount += amount;

                        if (TaxDeductiblePercentageEnabled)
                        {
                            prevAmountTaxDeduct += taxDeductibleAmount;
                            prevAmountNonDeduct += nonDeductibleAmount;
                        }
                    }

                    prevCurrency       = currency;
                    prevDateEntered    = dateEntered;
                    prevCommentOne     = commentOne;
                    prevAccountDesc    = accountDesc;
                    prevCostCentreDesc = costcentreDesc;
                    prevgifttype       = gifttype;
                }
            }

            if (prevDateEntered != DateTime.MaxValue)
            {
                RowTemplate = OrigRowTemplate;

                if (prevgifttype == MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND)
                {
                    RowTemplate = TPrinterHtml.RemoveDivWithClass(RowTemplate, MFinanceConstants.GIFT_TYPE_GIFT);
                }
                else if (prevgifttype == MFinanceConstants.GIFT_TYPE_GIFT)
                {
                    RowTemplate = TPrinterHtml.RemoveDivWithClass(RowTemplate, MFinanceConstants.GIFT_TYPE_GIFT_IN_KIND);
                }

                rowTexts += RowTemplate.
                            Replace("#DONATIONDATE", prevDateEntered.ToString("dd.MM.yyyy")).
                            Replace("#AMOUNTCURRENCY", prevCurrency).
                            Replace("#AMOUNT", StringHelper.FormatUsingCurrencyCode(prevAmount, prevCurrency)).
                            Replace("#TAXDEDUCTAMOUNT", StringHelper.FormatUsingCurrencyCode(prevAmountTaxDeduct, prevCurrency)).
                            Replace("#TAXNONDEDUCTAMOUNT", StringHelper.FormatUsingCurrencyCode(prevAmountNonDeduct, prevCurrency)).
                            Replace("#COMMENTONE", prevCommentOne).
                            Replace("#ACCOUNTDESC", prevAccountDesc).
                            Replace("#COSTCENTREDESC", prevCostCentreDesc);
                prevAmount = 0.0M;

                if (TaxDeductiblePercentageEnabled)
                {
                    prevAmountTaxDeduct = 0.0M;
                    prevAmountNonDeduct = 0.0M;
                }
            }

            msg = msg.Replace("#OVERALLAMOUNTCURRENCY", ABaseCurrency).
                  Replace("#OVERALLAMOUNT", StringHelper.FormatUsingCurrencyCode(sum, ABaseCurrency)).
                  Replace("#OVERALLTAXDEDUCTAMOUNT", StringHelper.FormatUsingCurrencyCode(sumTaxDeduct, ABaseCurrency)).
                  Replace("#OVERALLTAXNONDEDUCTAMOUNT", StringHelper.FormatUsingCurrencyCode(sumNonDeduct, ABaseCurrency));

            if ((ADonations.Rows.Count == 1) && msg.Contains("#DONATIONDATE"))
            {
                // this is a receipt for just one gift
                msg = msg.Replace("#DONATIONDATE", Convert.ToDateTime(ADonations.Rows[0]["DateEntered"]).ToString("dd.MM.yyyy"));
            }

            // TODO allow other currencies. use a_currency table, and base currency
            msg = msg.Replace("#TOTALAMOUNTINWORDS", NumberToWords.AmountToWords(sum, "Euro", "Cent")).
                  Replace("#TOTALTAXDEDUCTAMOUNTINWORDS", NumberToWords.AmountToWords(sumTaxDeduct, "Euro", "Cent")).
                  Replace("#TOTALTAXNONDEDUCTAMOUNTINWORDS", NumberToWords.AmountToWords(sumNonDeduct, "Euro", "Cent"));

            return(msg.Replace("#ROWTEMPLATE", rowTexts));
        }
Пример #23
0
        /// <summary>
        /// Looks for gifts where the recipient is an ExWorker and asks the user if they want to continue.
        /// (Make sure GetDataFromControls is called before this method so that AMainDS is up-to-date.)
        /// </summary>
        /// <param name="AAction">Why this method is being called</param>
        /// <param name="AMainDS"></param>
        /// <param name="APetraUtilsObject"></param>
        /// <param name="APostingGiftDetails">Only used when being called in order to carry out a batch posting</param>
        /// <returns>Returns true if saving/posting can continue</returns>
        public static bool CanContinueWithAnyExWorkers(GiftBatchAction AAction,
                                                       GiftBatchTDS AMainDS,
                                                       TFrmPetraEditUtils APetraUtilsObject,
                                                       DataTable APostingGiftDetails = null)
        {
            DataTable ExWorkers     = null;
            string    Msg           = string.Empty;
            int       BatchNumber   = -1;
            int       ExWorkerGifts = 0;

            string ExWorkerSpecialType = TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_EXWORKERSPECIALTYPE, "EX-WORKER");

            // first check for Ex-Workers in the batch that is being posted/submitted (if a batch is being posted/submitted)
            if ((APostingGiftDetails != null) && (APostingGiftDetails.Rows.Count > 0))
            {
                ExWorkers      = TRemote.MFinance.Gift.WebConnectors.FindGiftRecipientExWorker(APostingGiftDetails, BatchNumber);
                ExWorkerGifts += ExWorkers.Rows.Count;

                Msg = GetExWorkersString(AAction, ExWorkerSpecialType, ExWorkers);

                if (ExWorkers.Rows.Count > 0)
                {
                    BatchNumber = (int)APostingGiftDetails.Rows[0][GiftBatchTDSAGiftDetailTable.GetBatchNumberDBName()];
                }
            }

            // check for Ex-Workers in all added and modified data
            if (APetraUtilsObject.HasChanges)
            {
                DataTable Changes = new DataTable();

                if (AMainDS.AGiftDetail.GetChangesTyped() != null)
                {
                    Changes.Merge(AMainDS.AGiftDetail.GetChangesTyped());
                }
                else if (AMainDS.ARecurringGiftDetail.GetChangesTyped() != null)
                {
                    Changes.Merge(AMainDS.ARecurringGiftDetail.GetChangesTyped());
                }

                if ((Changes != null) && (Changes.Rows.Count > 0))
                {
                    ExWorkers      = TRemote.MFinance.Gift.WebConnectors.FindGiftRecipientExWorker(Changes, BatchNumber);
                    ExWorkerGifts += ExWorkers.Rows.Count;

                    Msg += GetExWorkersString(null, ExWorkerSpecialType, ExWorkers);
                }
            }

            // alert the user to any recipients who are Ex-Workers
            if (Msg != string.Empty)
            {
                if (AAction == GiftBatchAction.SAVING)
                {
                    Msg += Catalog.GetString("Do you want to continue with saving anyway?");
                }
                else
                {
                    // singular
                    if (ExWorkerGifts == 1)
                    {
                        if (AAction == GiftBatchAction.POSTING)
                        {
                            Msg += Catalog.GetString("This gift will need to be saved before this batch can be posted.");
                        }
                        else if (AAction == GiftBatchAction.NEWBATCH)
                        {
                            Msg += Catalog.GetString("This gift will need to be saved before a new batch can be created.");
                        }
                        else if (AAction == GiftBatchAction.CANCELLING)
                        {
                            Msg += Catalog.GetString("This gift will need to be saved before this batch can be cancelled.");
                        }
                        else if (AAction == GiftBatchAction.SUBMITTING)
                        {
                            Msg += Catalog.GetString("This gift will need to be saved before this batch can be submitted.");
                        }
                        else if (AAction == GiftBatchAction.DELETING)
                        {
                            Msg += Catalog.GetString("This gift will need to be saved before this batch can be deleted.");
                        }
                    }
                    // plural
                    else
                    {
                        if (AAction == GiftBatchAction.POSTING)
                        {
                            Msg += Catalog.GetString("These gifts will need to be saved before this batch can be posted.");
                        }
                        else if (AAction == GiftBatchAction.NEWBATCH)
                        {
                            Msg += Catalog.GetString("These gifts will need to be saved before a new batch can be created.");
                        }
                        else if (AAction == GiftBatchAction.CANCELLING)
                        {
                            Msg += Catalog.GetString("These gifts will need to be saved before this batch can be cancelled.");
                        }
                        else if (AAction == GiftBatchAction.SUBMITTING)
                        {
                            Msg += Catalog.GetString("These gifts will need to be saved before this batch can be submitted.");
                        }
                        else if (AAction == GiftBatchAction.DELETING)
                        {
                            Msg += Catalog.GetString("These gifts will need to be saved before this batch can be deleted.");
                        }
                    }

                    Msg += " " + Catalog.GetString("Do you want to continue?");
                }

                if (MessageBox.Show(
                        Msg, string.Format(Catalog.GetString("{0} Warning"), ExWorkerSpecialType), MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                    == DialogResult.No)
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #24
0
        /// <summary>
        /// Adds a duplicate Gift Detail (or reversed duplicate GiftDetail) to Gift.
        /// </summary>
        /// <param name="AMainDS"></param>
        /// <param name="AGift"></param>
        /// <param name="AOldGiftDetail"></param>
        /// <param name="AReversal">True for reverse or false for straight duplicate</param>
        /// <param name="ATransaction"></param>
        /// <param name="ARequestParams"></param>
        private static void AddDuplicateGiftDetailToGift(ref GiftBatchTDS AMainDS,
                                                         ref AGiftRow AGift,
                                                         AGiftDetailRow AOldGiftDetail,
                                                         bool AReversal,
                                                         TDBTransaction ATransaction,
                                                         Hashtable ARequestParams = null)
        {
            bool TaxDeductiblePercentageEnabled = Convert.ToBoolean(
                TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE"));

            GiftAdjustmentFunctionEnum Function = (GiftAdjustmentFunctionEnum)ARequestParams["Function"];

            AGiftDetailRow giftDetail = AMainDS.AGiftDetail.NewRowTyped(true);

            DataUtilities.CopyAllColumnValuesWithoutPK(AOldGiftDetail, giftDetail);

            giftDetail.DetailNumber = AGift.LastDetailNumber + 1;
            AGift.LastDetailNumber++;

            giftDetail.LedgerNumber          = AGift.LedgerNumber;
            giftDetail.BatchNumber           = AGift.BatchNumber;
            giftDetail.GiftTransactionNumber = AGift.GiftTransactionNumber;

            decimal signum = (AReversal) ? -1 : 1;

            giftDetail.GiftTransactionAmount = signum * AOldGiftDetail.GiftTransactionAmount;
            giftDetail.GiftAmount            = signum * AOldGiftDetail.GiftAmount;
            giftDetail.GiftAmountIntl        = signum * AOldGiftDetail.GiftAmountIntl;

            if (TaxDeductiblePercentageEnabled)
            {
                if (!AReversal && Function.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust))
                {
                    giftDetail.TaxDeductiblePct = Convert.ToDecimal(ARequestParams["NewPct"]);
                    TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetail);
                }
                else if (!AReversal)
                {
                    if (ARequestParams.ContainsKey("UpdateTaxDeductiblePct"))
                    {
                        List <string[]> UpdateTaxDeductiblePctRecipeints = (List <string[]>)ARequestParams["UpdateTaxDeductiblePct"];
                        string[]        Result = UpdateTaxDeductiblePctRecipeints.Find(x => x[0] == giftDetail.RecipientKey.ToString());

                        // true if a new percentage is available and the user wants to use it
                        if (Result != null)
                        {
                            giftDetail.TaxDeductiblePct = Convert.ToDecimal(Result[1]);
                            TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetail);
                        }
                    }
                }
                else
                {
                    giftDetail.TaxDeductibleAmount     = signum * AOldGiftDetail.TaxDeductibleAmount;
                    giftDetail.TaxDeductibleAmountBase = signum * AOldGiftDetail.TaxDeductibleAmountBase;
                    giftDetail.TaxDeductibleAmountIntl = signum * AOldGiftDetail.TaxDeductibleAmountIntl;
                    giftDetail.NonDeductibleAmount     = signum * AOldGiftDetail.NonDeductibleAmount;
                    giftDetail.NonDeductibleAmountBase = signum * AOldGiftDetail.NonDeductibleAmountBase;
                    giftDetail.NonDeductibleAmountIntl = signum * AOldGiftDetail.NonDeductibleAmountIntl;
                }
            }

            if (ARequestParams != null)
            {
                if ((bool)ARequestParams["AutoCompleteComments"]) // only used for tax deductible pct gift adjustments
                {
                    AGiftRow OldGiftRow = (AGiftRow)AMainDS.AGift.Rows.Find(
                        new object[] { AOldGiftDetail.LedgerNumber, AOldGiftDetail.BatchNumber, AOldGiftDetail.GiftTransactionNumber });

                    giftDetail.GiftCommentThree = Catalog.GetString("Original gift date: " + OldGiftRow.DateEntered.ToString("dd-MMM-yyyy"));
                    giftDetail.CommentThreeType = "Both";
                }
                else // user defined
                {
                    giftDetail.GiftCommentOne   = (String)ARequestParams["ReversalCommentOne"];
                    giftDetail.GiftCommentTwo   = (String)ARequestParams["ReversalCommentTwo"];
                    giftDetail.GiftCommentThree = (String)ARequestParams["ReversalCommentThree"];
                    giftDetail.CommentOneType   = (String)ARequestParams["ReversalCommentOneType"];
                    giftDetail.CommentTwoType   = (String)ARequestParams["ReversalCommentTwoType"];
                    giftDetail.CommentThreeType = (String)ARequestParams["ReversalCommentThreeType"];
                }
            }

            // If reversal: mark the new gift as a reversal
            if (AReversal)
            {
                giftDetail.ModifiedDetail = true;

                //Identify the reversal source
                giftDetail.ModifiedDetailKey = "|" + AOldGiftDetail.BatchNumber.ToString() + "|" +
                                               AOldGiftDetail.GiftTransactionNumber.ToString() + "|" +
                                               AOldGiftDetail.DetailNumber.ToString();
            }
            else
            {
                giftDetail.ModifiedDetail = false;

                // Make sure the motivation detail is still active. If not then we need a new one.
                AMotivationDetailTable MotivationDetailTable = AMotivationDetailAccess.LoadViaAMotivationGroup(
                    giftDetail.LedgerNumber, giftDetail.MotivationGroupCode, ATransaction);
                DataRow CurrentMotivationDetail = MotivationDetailTable.Rows.Find(
                    new object[] { giftDetail.LedgerNumber, giftDetail.MotivationGroupCode, giftDetail.MotivationDetailCode });

                // Motivation detail has been made inactive (or doesn't exist) then use default
                if (!((MotivationDetailTable != null) && (MotivationDetailTable.Rows.Count > 0) && (CurrentMotivationDetail != null)) ||
                    !Convert.ToBoolean(CurrentMotivationDetail[AMotivationDetailTable.GetMotivationStatusDBName()]))
                {
                    bool ActiveRowFound = false;

                    // search for first alternative active detail that is part of the same group
                    foreach (AMotivationDetailRow Row in MotivationDetailTable.Rows)
                    {
                        if ((Row.MotivationDetailCode != giftDetail.MotivationDetailCode) && Row.MotivationStatus)
                        {
                            ActiveRowFound = true;
                            giftDetail.MotivationGroupCode  = Row.MotivationGroupCode;
                            giftDetail.MotivationDetailCode = Row.MotivationDetailCode;
                            break;
                        }
                    }

                    // if none found then use default group and detail
                    if (!ActiveRowFound)
                    {
                        giftDetail.MotivationGroupCode  = MFinanceConstants.MOTIVATION_GROUP_GIFT;
                        giftDetail.MotivationDetailCode = MFinanceConstants.GROUP_DETAIL_SUPPORT;
                    }
                }

                // if the gift destination should be fixed
                if (ARequestParams.ContainsKey("FixedGiftDestination") &&
                    (Function.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust) && (bool)ARequestParams["FixedGiftDestination"] ||
                     (((List <string>)ARequestParams["FixedGiftDestination"]).Exists(x => x == giftDetail.RecipientKey.ToString()))))
                {
                    giftDetail.FixedGiftDestination = true;
                }
                else
                {
                    giftDetail.FixedGiftDestination = false;
                }
            }

            AMainDS.AGiftDetail.Rows.Add(giftDetail);
        }
Пример #25
0
        /*
         * Not used
         * /// <summary>
         * /// get all gifts for the current costcentre and account
         * /// </summary>
         * public static DataTable HosaCalculateGifts(TParameterList AParameters, TResultList AResults)
         * {
         *  SortedList<string, string> Defines = new SortedList<string, string>();
         *  List<OdbcParameter> SqlParameterList = new List<OdbcParameter>();
         *
         *  if (AParameters.Get("param_filter_cost_centres").ToString() == "PersonalCostcentres")
         *  {
         *      Defines.Add("PERSONALHOSA", "true");
         *  }
         *
         *  SqlParameterList.Add(new OdbcParameter("ledgernumber", OdbcType.Decimal)
         *      {
         *          Value = AParameters.Get("param_ledger_number_i").ToDecimal()
         *      });
         *  SqlParameterList.Add(new OdbcParameter("costcentre", OdbcType.VarChar)
         *      {
         *          Value = AParameters.Get("line_a_cost_centre_code_c")
         *      });
         *
         *  if (AParameters.Get("param_ich_number").ToInt32() == 0)
         *  {
         *      Defines.Add("NOT_LIMITED_TO_ICHNUMBER", "true");
         *  }
         *  else
         *  {
         *      SqlParameterList.Add(new OdbcParameter("ichnumber", OdbcType.Int)
         *          {
         *              Value = AParameters.Get("param_ich_number").ToInt32()
         *          });
         *  }
         *
         *  SqlParameterList.Add(new OdbcParameter("batchstatus", OdbcType.VarChar)
         *      {
         *          Value = MFinanceConstants.BATCH_POSTED
         *      });
         *
         *  if (AParameters.Get("param_period").ToBool() == true)
         *  {
         *      Defines.Add("BYPERIOD", "true");
         *      SqlParameterList.Add(new OdbcParameter("batchyear", OdbcType.Int)
         *          {
         *              Value = AParameters.Get("param_year_i").ToInt32()
         *          });
         *      SqlParameterList.Add(new OdbcParameter("batchperiod_start", OdbcType.Int)
         *          {
         *              Value = AParameters.Get("param_start_period_i").ToInt32()
         *          });
         *      SqlParameterList.Add(new OdbcParameter("batchperiod_end", OdbcType.Int)
         *          {
         *              Value = AParameters.Get("param_end_period_i").ToInt32()
         *          });
         *  }
         *  else
         *  {
         *      SqlParameterList.Add(new OdbcParameter("param_start_date", OdbcType.Int)
         *          {
         *              Value = AParameters.Get("param_start_date").ToInt32()
         *          });
         *      SqlParameterList.Add(new OdbcParameter("param_end_date", OdbcType.Int)
         *          {
         *              Value = AParameters.Get("param_end_date").ToInt32()
         *          });
         *  }
         *
         *  SqlParameterList.Add(new OdbcParameter("accountcode", OdbcType.VarChar)
         *      {
         *          Value = AParameters.Get("line_a_account_code_c")
         *      });
         *
         *  string SqlStmt = TDataBase.ReadSqlFile("ICH.HOSAReportGiftSummary.sql", Defines);
         *  DataTable resultTable = null;
         *
         *  TDBTransaction Transaction = null;
         *  DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction,
         *      delegate
         *      {
         *
         *          // now run the database query
         *          resultTable = DBAccess.GDBAccessObj.SelectDT(SqlStmt, "result", Transaction,
         *              SqlParameterList.ToArray());
         *      });
         *  // if this is taking a long time, every now and again update the TLogging statusbar, and check for the cancel button
         *  if (AParameters.Get("CancelReportCalculation").ToBool() == true)
         *  {
         *      return null;
         *  }
         *
         *  resultTable.Columns.Add("a_transaction_amount_n", typeof(Decimal));
         *  resultTable.Columns.Add("a_amount_in_base_currency_n", typeof(Decimal));
         *  resultTable.Columns.Add("a_amount_in_intl_currency_n", typeof(Decimal));
         *  resultTable.Columns.Add("a_reference_c", typeof(string));
         *  resultTable.Columns.Add("a_narrative_c", typeof(string));
         *
         *  Boolean InternationalCurrency = AParameters.Get("param_currency").ToString() == "International";
         *  Double ExchangeRate = 1.00;  // TODO Get exchange rate!
         *
         *  foreach (DataRow Row in resultTable.Rows)
         *  {
         *      Row["a_transaction_amount_n"] = Convert.ToDecimal(Row["GiftTransactionAmount"]);
         *      Row["a_amount_in_base_currency_n"] = Convert.ToDecimal(Row["GiftBaseAmount"]);
         *
         *      if (InternationalCurrency)
         *      {
         *          Row["a_amount_in_intl_currency_n"] = (Decimal)(Convert.ToDouble(Row["GiftBaseAmount"]) * ExchangeRate);
         *      }
         *
         *      Row["a_reference_c"] = StringHelper.PartnerKeyToStr(Convert.ToInt64(Row["RecipientKey"]));
         *      Row["a_narrative_c"] = Row["RecipientShortname"].ToString();
         *  }
         *
         *  return resultTable;
         * }
         */

        /// <summary>
        /// Find all the gifts for a specific month, returning "worker", "field" and "total" results.
        /// </summary>
        public static DataTable TotalGiftsThroughFieldMonth(TParameterList AParameters, TResultList AResults)
        {
            Int32 LedgerNum = AParameters.Get("param_ledger_number_i").ToInt32();
            Int32 Year      = AParameters.Get("param_YearBlock").ToInt32();
            //TODO: Calendar vs Financial Date Handling - Check if financial year start/end should be used not calendar
            string YearStart = String.Format("#{0:0000}-01-01#", Year);
            string YearEnd   = String.Format("#{0:0000}-12-31#", Year);

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

            string SqlQuery = "SELECT batch.a_gl_effective_date_d as Date, motive.a_report_column_c AS ReportColumn, ";

            if (AParameters.Get("param_currency").ToString() == "Base")
            {
                SqlQuery += "detail.a_gift_amount_n AS Amount";

                if (TaxDeductiblePercentageEnabled)
                {
                    SqlQuery += ", detail.a_tax_deductible_amount_base_n AS TaxDeductAmount";
                }
            }
            else
            {
                SqlQuery += "detail.a_gift_amount_intl_n AS Amount";

                if (TaxDeductiblePercentageEnabled)
                {
                    SqlQuery += ", detail.a_tax_deductible_amount_intl_n AS TaxDeductAmount";
                }
            }

            SqlQuery += (" FROM PUB_a_gift as gift, PUB_a_gift_detail as detail, PUB_a_gift_batch as batch, PUB_a_motivation_detail AS motive"

                         + " WHERE detail.a_ledger_number_i = " + LedgerNum +
                         " AND batch.a_batch_status_c = 'Posted'" +
                         " AND batch.a_batch_number_i = gift.a_batch_number_i" +
                         " AND batch.a_ledger_number_i = " + LedgerNum +
                         " AND batch.a_gl_effective_date_d >= " + YearStart +
                         " AND batch.a_gl_effective_date_d <= " + YearEnd

                         + " AND gift.a_ledger_number_i = " + LedgerNum +
                         " AND detail.a_batch_number_i = gift.a_batch_number_i" +
                         " AND detail.a_gift_transaction_number_i = gift.a_gift_transaction_number_i"

                         + " AND motive.a_ledger_number_i = " + LedgerNum +
                         " AND motive.a_motivation_group_code_c = detail.a_motivation_group_code_c" +
                         " AND motive.a_motivation_detail_code_c = detail.a_motivation_detail_code_c" +
                         " AND motive.a_receipt_l=true");
            DataTable      tempTbl     = null;
            TDBTransaction Transaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                      TEnforceIsolationLevel.eilMinimum,
                                                                      ref Transaction,
                                                                      delegate
            {
                tempTbl = DBAccess.GDBAccessObj.SelectDT(SqlQuery, "result", Transaction);
            });

            DataTable resultTable = new DataTable();

            resultTable.Columns.Add("MonthName", typeof(String));               //
            resultTable.Columns.Add("MonthWorker", typeof(Decimal));            // These are the names of the variables
            resultTable.Columns.Add("MonthWorkerCount", typeof(Int32));         // returned by this calculation.
            resultTable.Columns.Add("MonthField", typeof(Decimal));             //
            resultTable.Columns.Add("MonthFieldCount", typeof(Int32));          //
            resultTable.Columns.Add("MonthTotal", typeof(Decimal));             //
            resultTable.Columns.Add("MonthTotalCount", typeof(Int32));          //

            resultTable.Columns.Add("MonthWorkerTaxDeduct", typeof(Decimal));
            resultTable.Columns.Add("MonthFieldTaxDeduct", typeof(Decimal));
            resultTable.Columns.Add("MonthTotalTaxDeduct", typeof(Decimal));

            //TODO: Calendar vs Financial Date Handling - Check if financial year should be used not calendar, e.g. periods could equal 13
            for (int mnth = 1; mnth <= 12; mnth++)
            {
                string monthStart     = String.Format("#{0:0000}-{1:00}-01#", Year, mnth);
                string nextMonthStart = String.Format("#{0:0000}-{1:00}-01#", Year, mnth + 1);

                if (mnth == 12)
                {
                    nextMonthStart = String.Format("#{0:0000}-01-01#", Year + 1);
                }

                tempTbl.DefaultView.RowFilter = "Date >= " + monthStart + " AND Date < " + nextMonthStart;

                Decimal WorkerTotal = 0;
                Decimal FieldTotal  = 0;
                Int32   WorkerCount = 0;
                Int32   FieldCount  = 0;
                Int32   TotalCount  = tempTbl.DefaultView.Count;

                Decimal WorkerTotalTaxDeduct = 0;
                Decimal FieldTotalTaxDeduct  = 0;

                for (int i = 0; i < TotalCount; i++)
                {
                    DataRow Row = tempTbl.DefaultView[i].Row;

                    if (Row["ReportColumn"].ToString() == "Worker")
                    {
                        WorkerCount++;
                        WorkerTotal += Convert.ToDecimal(Row["Amount"]);

                        if (TaxDeductiblePercentageEnabled)
                        {
                            WorkerTotalTaxDeduct += Convert.ToDecimal(Row["TaxDeductAmount"]);
                        }
                    }
                    else
                    {
                        FieldCount++;
                        FieldTotal += Convert.ToDecimal(Row["Amount"]);

                        if (TaxDeductiblePercentageEnabled)
                        {
                            FieldTotalTaxDeduct += Convert.ToDecimal(Row["TaxDeductAmount"]);
                        }
                    }
                }

                DataRow resultRow = resultTable.NewRow();

                resultRow["MonthName"]        = StringHelper.GetLongMonthName(mnth);
                resultRow["MonthWorker"]      = WorkerTotal;
                resultRow["MonthWorkerCount"] = WorkerCount;
                resultRow["MonthField"]       = FieldTotal;
                resultRow["MonthFieldCount"]  = FieldCount;
                resultRow["MonthTotal"]       = WorkerTotal + FieldTotal;
                resultRow["MonthTotalCount"]  = TotalCount;

                resultRow["MonthWorkerTaxDeduct"] = WorkerTotalTaxDeduct;
                resultRow["MonthFieldTaxDeduct"]  = FieldTotalTaxDeduct;
                resultRow["MonthTotalTaxDeduct"]  = WorkerTotalTaxDeduct + FieldTotalTaxDeduct;

                resultTable.Rows.Add(resultRow);
            }

            return(resultTable);
        } // Total Gifts Through Field Month