/// <summary>
 /// I need to find out whether the specified AccountCode can be allowed.
 /// </summary>
 private void GetDetailsFromControlsManual(ACostCentreRow ARow)
 {
     //
     // If changing the PrimaryKey to that specified causes a contraints error,
     // I'll catch it here, issue a warning, and return the control to the "safe" value.
     ProtectedChangeOfPrimaryKey(FCurrentCostCentre);
 }
Пример #2
0
        /// <summary>
        /// Export the cost centres
        /// </summary>
        public static void ExportCostCentres(string AOutputPath,
                                             char ACSVSeparator,
                                             string ANewLine,
                                             Int32 ALedgerNumber,
                                             List <string> ACostCentres)
        {
            string filename = Path.GetFullPath(Path.Combine(AOutputPath, "costcentre.csv"));

            Console.WriteLine("Writing file: " + filename);

            StringBuilder sb = new StringBuilder();

            ACostCentreTable costcentres = ACostCentreAccess.LoadViaALedger(ALedgerNumber, null);

            costcentres.DefaultView.Sort = ACostCentreTable.GetCostCentreCodeDBName();

            foreach (ACostCentreRow row in costcentres.Rows)
            {
                if (ACostCentres.Contains(row.CostCentreCode))
                {
                    ACostCentreRow departmentRow = GetDepartmentCostCentre(costcentres,
                                                                           row,
                                                                           StringHelper.StrSplit(TAppSettingsManager.GetValue("SummaryCostCentres", "4300S"), ","));

                    sb.Append(StringHelper.StrMerge(new string[] { row.CostCentreCode, row.CostCentreName,
                                                                   departmentRow.CostCentreName }, ACSVSeparator));
                    sb.Append(ANewLine);
                }
            }

            StreamWriter sw = new StreamWriter(filename, false, Encoding.GetEncoding(1252));

            sw.Write(sb.ToString());
            sw.Close();
        }
        /// <summary>
        /// Delete the row in the editor
        /// NOTE: A cost centre with children cannot be deleted.
        /// </summary>
        private void DeleteCostCentre(Object sender, EventArgs e)
        {
            if (FCurrentCostCentre == null)
            {
                return;
            }

            FCurrentCostCentre.GetAttrributes();

            if (FCurrentCostCentre.CanDelete.Value)
            {
                ACostCentreRow SelectedRow = FCurrentCostCentre.CostCentreRow;
                TreeNode DeletedNode = FCurrentCostCentre.linkedTreeNode;
                TreeNode ParentNode = DeletedNode.Parent;
                SelectedRow.Delete();
                ucoCostCentreTree.DeleteSelectedCostCentre();

                // FCurrentCostCentre is now the parent of the CostCentre that was just deleted.
                // If just I added a sub-tree and I decide I don't want it, I might be about to remove the parent too.
                if (FCurrentCostCentre != null)
                {
                    FCurrentCostCentre.GetAttrributes();
                }

                FPetraUtilsObject.SetChangedFlag();
            }
            else
            {
                MessageBox.Show(
                    Catalog.GetString("This Cost Centre Code is in use and cannot be deleted.") + "\n" + FCurrentCostCentre.Msg,
                    Catalog.GetString("Delete Cost Centre"));
            }
        }
Пример #4
0
        private void InsertNodeIntoTreeView(TreeNode AParent, DataView view, ACostCentreRow ADetailRow)
        {
            TreeNode newNode = new TreeNode("");

            CostCentreNodeDetails NewNodeDetails = CostCentreNodeDetails.AddNewCostCentre(newNode, ADetailRow);

            NewNodeDetails.IsNew = false;

            SetNodeLabel(ADetailRow, newNode);

            if (AParent == null)
            {
                trvCostCentres.Nodes.Add(newNode);
            }
            else
            {
                InsertInOrder(AParent, newNode);
            }

            view.RowFilter =
                ACostCentreTable.GetCostCentreToReportToDBName() + " = '" + ADetailRow.CostCentreCode + "'";

            if (view.Count > 0)
            {
                // A cost centre cannot be deleted if it has children.
                NewNodeDetails.CanDelete       = false;
                NewNodeDetails.Msg             = Catalog.GetString("Child Cost Centres must be deleted first.");
                NewNodeDetails.CanHaveChildren = true;

                foreach (DataRowView rowView in view)
                {
                    InsertNodeIntoTreeView(newNode, view, (ACostCentreRow)rowView.Row);
                }
            }
        }
        private void UpdateOnControlChanged(Object sender, EventArgs e)
        {
            if (FIAmUpdating == 0)
            {
                ACostCentreRow Row = GetSelectedDetailRowManual();

                if ((Row != null)
                    && (cmbDetailCostCentreType.GetSelectedString() != Row.CostCentreType))
                {
                    if (Row.SystemCostCentreFlag)
                    {
                        MessageBox.Show(
                            Catalog.GetString(
                                "This is a System Cost Centre and cannot be changed."),
                            Catalog.GetString("Cost Centre Type"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);
                        FIAmUpdating++;
                        cmbDetailCostCentreType.SetSelectedString(Row.CostCentreType);
                        FIAmUpdating--;
                    }
                    else // It's not a system Cost Centre, but probably I still shouldn't be changing it...
                    {
                        if (MessageBox.Show(
                                Catalog.GetString(
                                    "Are you sure you want to change this?\n" +
                                    "Changing from Local to foreign, or vice versa,\n" +
                                    "will affect the reporting of foreign ledgers.\n" +
                                    "In OM, Foreign Cost Centres are children of ILT.\n" +
                                    "All other Cost Centres are Local."),
                                Catalog.GetString("Cost Centre Type"),
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Stop) == System.Windows.Forms.DialogResult.No)
                        {
                            FIAmUpdating++;
                            cmbDetailCostCentreType.SetSelectedString(Row.CostCentreType);
                            FIAmUpdating--;
                        }
                    }
                }

                if (CheckCostCentreValueChanged())
                {
                    return;
                }  // If not changed, or the rename didn't happen, I can carry on...

                if (
                    (Row.CostCentreActiveFlag != chkDetailCostCentreActiveFlag.Checked)
                    || (Row.CostCentreType != cmbDetailCostCentreType.GetSelectedString())
                    || (Row.CostCentreCode != txtDetailCostCentreCode.Text)
                    || (Row.CostCentreName != txtDetailCostCentreName.Text)
                    )
                {
                    FPetraUtilsObject.SetChangedFlag();
                }

                GetDataFromControlsManual();
                ucoCostCentreTree.SetNodeLabel(Row);
            }
        } // UpdateOnControlChanged
Пример #6
0
        private bool CostCentreIsActive(string ACostCentreCode = "")
        {
            bool retVal = true;

            ACostCentreRow currentCostCentreRow = null;

            //If empty, read value from combo
            if (ACostCentreCode == string.Empty)
            {
                if ((FCostCentreTable != null) && (cmbDetailBankCostCentre.SelectedIndex != -1) && (cmbDetailBankCostCentre.Count > 0) &&
                    (cmbDetailBankCostCentre.GetSelectedString() != null))
                {
                    ACostCentreCode = cmbDetailBankCostCentre.GetSelectedString();
                }
            }

            if (FCostCentreTable != null)
            {
                currentCostCentreRow = (ACostCentreRow)FCostCentreTable.Rows.Find(new object[] { FLedgerNumber, ACostCentreCode });
            }

            if (currentCostCentreRow != null)
            {
                retVal = currentCostCentreRow.CostCentreActiveFlag;
            }

            return(retVal);
        }
Пример #7
0
        public static Boolean GetPartnerKeyForForeignCostCentreCode(Int32 ALedgerNumber, String ACostCentreCode, out Int64 APartnerKey)
        {
            Boolean ReturnValue = false;

            APartnerKey = 0;

            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);

            ACostCentreTable CostCentreTable;

            CostCentreTable = ACostCentreAccess.LoadByPrimaryKey(ALedgerNumber, ACostCentreCode, Transaction);

            if (CostCentreTable.Count > 0)
            {
                ACostCentreRow CostCentreRow = (ACostCentreRow)CostCentreTable.Rows[0];

                if (CostCentreRow.CostCentreType == MFinanceConstants.FOREIGN_CC_TYPE)
                {
                    AValidLedgerNumberTable ValidLedgerNumberTable;
                    AValidLedgerNumberRow   ValidLedgerNumberRow;
                    ValidLedgerNumberTable = AValidLedgerNumberAccess.LoadViaACostCentre(ALedgerNumber, ACostCentreCode, Transaction);

                    if (ValidLedgerNumberTable.Count > 0)
                    {
                        ValidLedgerNumberRow = (AValidLedgerNumberRow)ValidLedgerNumberTable.Rows[0];
                        APartnerKey          = ValidLedgerNumberRow.PartnerKey;
                        ReturnValue          = true;
                    }
                }
            }

            DBAccess.GDBAccessObj.RollbackTransaction();

            return(ReturnValue);
        }
 private void GetDataFromControlsManual()
 {
     if (FCurrentCostCentre != null)
     {
         ACostCentreRow SelectedRow = GetSelectedDetailRowManual();
         GetDetailsFromControls(SelectedRow);
         FCurrentCostCentre.CostCentreRow.PostingCostCentreFlag = !chkDetailSummaryFlag.Checked;
     }
 }
Пример #9
0
        /// <summary>
        /// Add this new CostCentre as child of the currently selected node
        /// </summary>
        public void AddNewCostCentre(ACostCentreRow CostCentreRow)
        {
            trvCostCentres.BeginUpdate();
            TreeNode newNode = trvCostCentres.SelectedNode.Nodes.Add(CostCentreRow.CostCentreCode);
            CostCentreNodeDetails NewCostCentre = CostCentreNodeDetails.AddNewCostCentre(newNode, CostCentreRow);

            trvCostCentres.EndUpdate();
            FParentForm.SetSelectedCostCentre(NewCostCentre); // This will set my FSelectedCostCentre and my trvCostCentres.SelectedNode
        }
Пример #10
0
        /// <summary>
        /// TReallocation.RunOperation
        /// </summary>
        public override Int32 RunOperation()
        {
            Int32 CountJobs = 0;

            if (FAccountList == null)
            {
                CalculateAccountInfo();
            }

            TCommonAccountingTool YearEndBatch = null;

            if (DoExecuteableCode)
            {
                YearEndBatch = new TCommonAccountingTool(FledgerInfo,
                    Catalog.GetString("Financial year end processing"));
                YearEndBatch.AddBaseCurrencyJournal();
                YearEndBatch.JournalDescription = Catalog.GetString("YearEnd revaluations");
                YearEndBatch.SubSystemCode = CommonAccountingSubSystemsEnum.GL;
            }

            // tCommonAccountingTool.DateEffective =""; Default is "End of actual period ..."
            // Loop with all account codes
            foreach (string strAccountCode in FAccountList)
            {
                FglmInfo = new TGlmInfo(FledgerInfo.LedgerNumber,
                    FledgerInfo.CurrentFinancialYear,
                    strAccountCode);

                while (FglmInfo.MoveNext())
                {
                    Int32 CostCentreRowIdx = FCostCentreTbl.DefaultView.Find(FglmInfo.CostCentreCode);
                    ACostCentreRow currentCostCentre = (ACostCentreRow)FCostCentreTbl.DefaultView[CostCentreRowIdx].Row;

                    if (currentCostCentre.PostingCostCentreFlag)
                    {
                        TGlmpInfo glmpInfo = new TGlmpInfo(-1, -1, FglmInfo.GlmSequence, FledgerInfo.NumberOfAccountingPeriods);

                        if (glmpInfo.ActualBase + FglmInfo.ClosingPeriodActualBase != 0)
                        {
                            if (DoExecuteableCode)
                            {
                                ReallocationLoop(glmpInfo, YearEndBatch, strAccountCode, FglmInfo.CostCentreCode);
                            }

                            CountJobs++;
                        }
                    }
                }
            }

            if (DoExecuteableCode)
            {
                YearEndBatch.CloseSaveAndPost(FverificationResults);
            }

            return CountJobs;
        }
Пример #11
0
        /// <summary>
        /// Update the name of the currently selected node
        /// </summary>
        public void SetNodeLabel(ACostCentreRow ARow, TreeNode ThisNode = null)
        {
            if ((ARow == null) || (ARow.RowState == DataRowState.Deleted) || (ARow.RowState == DataRowState.Detached))
            {
                return;
            }

            SetNodeLabel(ARow.CostCentreCode, ARow.CostCentreName, ThisNode);
        }
 private void ShowDetailsManual(ACostCentreRow ARow)
 {
     if (ARow != null)
     {
         // I allow the user to attempt to change the primary key,
         // but if the selected record is not new, AND they have made any other changes,
         // the txtDetailCostCentreCode_TextChanged method will disallow any change.
         SetPrimaryKeyReadOnly(false);
         btnRename.Visible = false;
         chkDetailSummaryFlag.Checked = !ARow.PostingCostCentreFlag;
         chkDetailSummaryFlag.Enabled = !ARow.SystemCostCentreFlag;
     }
 }
Пример #13
0
        private static ACostCentreRow GetDepartmentCostCentre(ACostCentreTable ACostCentres,
            ACostCentreRow ACostCentreToInvestigate,
            StringCollection ADepartmentCodes)
        {
            if (ADepartmentCodes.Contains(ACostCentreToInvestigate.CostCentreCode))
            {
                return ACostCentreToInvestigate;
            }

            ACostCentreRow row = (ACostCentreRow)ACostCentres.DefaultView.FindRows(ACostCentreToInvestigate.CostCentreToReportTo)[0].Row;

            return GetDepartmentCostCentre(ACostCentres, row, ADepartmentCodes);
        }
Пример #14
0
        private static ACostCentreRow GetDepartmentCostCentre(ACostCentreTable ACostCentres,
                                                              ACostCentreRow ACostCentreToInvestigate,
                                                              StringCollection ADepartmentCodes)
        {
            if (ADepartmentCodes.Contains(ACostCentreToInvestigate.CostCentreCode))
            {
                return(ACostCentreToInvestigate);
            }

            ACostCentreRow row = (ACostCentreRow)ACostCentres.DefaultView.FindRows(ACostCentreToInvestigate.CostCentreToReportTo)[0].Row;

            return(GetDepartmentCostCentre(ACostCentres, row, ADepartmentCodes));
        }
Пример #15
0
        /// <summary>
        /// link the fields in the current ledger
        /// </summary>
        /// <param name="AFieldCSVFile"></param>
        public static void GenerateFieldsFinanceOnly(string AFieldCSVFile)
        {
            XmlDocument doc = TCsv2Xml.ParseCSV2Xml(AFieldCSVFile, ",");

            XmlNode RecordNode = doc.FirstChild.NextSibling.FirstChild;

            GLSetupTDS GLSetupDS = new GLSetupTDS();

            PCountryTable CountryTable = null;

            TDBTransaction Transaction = null;

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

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

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

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

                RecordNode = RecordNode.NextSibling;
            }

            GLSetupTDSAccess.SubmitChanges(GLSetupDS);
        }
Пример #16
0
        /// <summary>
        /// Return the list of parent cost centre codes
        /// </summary>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ACurrentCostCentreList"></param>
        private static void CostCentreParentsList(int ALedgerNumber, ref string ACurrentCostCentreList)
        {
            string ParentCostCentre;
            string CostCentreList = ACurrentCostCentreList;

            ACostCentreRow CostCentreRow = (ACostCentreRow)GLPostingDS.ACostCentre.Rows.Find(new object[] { ALedgerNumber, ACurrentCostCentreList });

            ParentCostCentre = CostCentreRow.CostCentreToReportTo;

            while (ParentCostCentre != string.Empty)
            {
                ACostCentreRow CCRow = (ACostCentreRow)GLPostingDS.ACostCentre.Rows.Find(new object[] { ALedgerNumber, ParentCostCentre });

                CostCentreList  += ":" + CCRow.CostCentreCode;
                ParentCostCentre = CCRow.CostCentreToReportTo;
            }
        }
        /// <summary>
        /// Make this CostCentre a child of the selected one in the hierarchy (from drag-drop).
        /// </summary>
        /// <param name="AChild"></param>
        /// <param name="ANewParent"></param>
        private void DoReassignment(TreeNode AChild, TreeNode ANewParent)
        {
            if ((AChild != null) && (ANewParent != null))
            {
                CostCentreNodeDetails DraggedCostCentre = (CostCentreNodeDetails)AChild.Tag;

                if (DraggedCostCentre.CostCentreRow.SystemCostCentreFlag)
                {
                    MessageBox.Show(String.Format(Catalog.GetString("{0} is a System Cost Centre and cannot be moved."),
                                                  ((CostCentreNodeDetails)AChild.Tag).CostCentreRow.CostCentreCode),
                                    Catalog.GetString("Re-assign Cost Centre"), MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    ShowNodeSelected(null);
                    return;
                }

                String         PrevParent = AChild.Parent.Text;
                ACostCentreRow ParentRow  = ((CostCentreNodeDetails)ANewParent.Tag).CostCentreRow;

                if (ParentRow.PostingCostCentreFlag)
                {
                    if (MessageBox.Show(String.Format(Catalog.GetString("Do you want to promote {0} to a summary Cost Centre?"),
                                                      ParentRow.CostCentreCode), Catalog.GetString("Move CostCentre"), MessageBoxButtons.YesNo)
                        == System.Windows.Forms.DialogResult.No)
                    {
                        ShowNodeSelected(null);
                        return;
                    }
                }

                TreeNode NewNode = (TreeNode)AChild.Clone();
                DraggedCostCentre.CostCentreRow.CostCentreToReportTo = ParentRow.CostCentreCode;
                DraggedCostCentre.linkedTreeNode = NewNode;
                InsertInOrder(ANewParent, NewNode);
                NewNode.Expand();
                ANewParent.Expand();
                ParentRow.PostingCostCentreFlag = false; // The parent is now a summary CostCentre!
                ((CostCentreNodeDetails)ANewParent.Tag).CanDelete = false;
                ANewParent.BackColor = Color.White;
                FParentForm.ShowStatus(String.Format(Catalog.GetString("{0} was moved from {1} to {2}."),
                                                     AChild.Text, PrevParent, ANewParent.Text));
                //Remove Original Node
                AChild.Remove();
                FPetraUtilsObject.SetChangedFlag();
            }
        }
        private bool CostCentreIsActive(string ACostCentreCode)
        {
            bool retVal = true;

            ACostCentreRow currentCostCentreRow = null;

            if (FCostCentreTable != null)
            {
                currentCostCentreRow = (ACostCentreRow)FCostCentreTable.Rows.Find(new object[] { FLedgerNumber, ACostCentreCode });
            }

            if (currentCostCentreRow != null)
            {
                retVal = currentCostCentreRow.CostCentreActiveFlag;
            }

            return(retVal);
        }
        /// <summary>
        /// The implementation of the logic for testing for a matching row
        /// </summary>
        /// <param name="ARow">The Row to test</param>
        /// <returns>True for a match</returns>
        public bool IsMatchingRowManual(DataRow ARow)
        {
            string strCostCentreCode = FFindTxtCostCentreCode.Text.ToLower();
            string strCostCentreType = FFindCmbCostCentreType.Text.ToLower();
            string strCostCentreName = FFindTxtCostCentreName.Text.ToLower();
            bool   isActive          = FFindChkActive.Checked;

            ACostCentreRow costCentreRow = (ACostCentreRow)ARow;

            if (strCostCentreCode != String.Empty)
            {
                if (!costCentreRow.CostCentreCode.ToLower().Contains(strCostCentreCode))
                {
                    return(false);
                }
            }

            if (strCostCentreType != String.Empty)
            {
                if (!costCentreRow.CostCentreType.ToLower().Contains(strCostCentreType))
                {
                    return(false);
                }
            }

            if (strCostCentreName != String.Empty)
            {
                if (!costCentreRow.CostCentreName.ToLower().Contains(strCostCentreName))
                {
                    return(false);
                }
            }

            if (FFindChkActive.CheckState != CheckState.Indeterminate)
            {
                if (costCentreRow.CostCentreActiveFlag != isActive)
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #20
0
        /// <summary>
        /// This method is called when the system wants to draw a comboBox item in the list.
        /// We choose the colour and weight for the font, showing inactive codes in bold red text
        /// </summary>
        private void DrawComboBoxItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();

            TCmbAutoComplete cmb     = (TCmbAutoComplete)sender;
            DataRowView      drv     = (DataRowView)cmb.Items[e.Index];
            string           content = drv[1].ToString();
            Brush            brush   = Brushes.Black;

            if (cmb.Name.StartsWith("cmbDetailBankCostCentre"))
            {
                if (FCostCentreTable != null)
                {
                    ACostCentreRow row = (ACostCentreRow)FCostCentreTable.Rows.Find(new object[] { FLedgerNumber, content });

                    if ((row != null) && !row.CostCentreActiveFlag)
                    {
                        brush = Brushes.Red;
                    }
                }
            }
            else if (cmb.Name.StartsWith("cmbDetailBankAccount"))
            {
                if (FAccountTable != null)
                {
                    AAccountRow row = (AAccountRow)FAccountTable.Rows.Find(new object[] { FLedgerNumber, content });

                    if ((row != null) && !row.AccountActiveFlag)
                    {
                        brush = Brushes.Red;
                    }
                }
            }
            else
            {
                throw new ArgumentException("Unexpected caller of DrawComboBoxItem event");
            }

            Font font = new Font(((Control)sender).Font, (brush == Brushes.Red) ? FontStyle.Bold : FontStyle.Regular);

            e.Graphics.DrawString(content, font, brush, new PointF(e.Bounds.X, e.Bounds.Y));
        }
        /// <summary>
        /// Create an CostCentreNodeDetails object for this CostCentre
        /// </summary>
        public static CostCentreNodeDetails AddNewCostCentre(TreeNode NewTreeNode, ACostCentreRow CostCentreRow)
        {
            CostCentreNodeDetails NodeDetails = new CostCentreNodeDetails();

            NodeDetails.CanHaveChildren = true;

            if (CostCentreRow.PostingCostCentreFlag) // A "Posting CostCentre" that's not been used may yet be promoted to a "Summary CostCentre".
            {
                NodeDetails.CanHaveChildren = null;
            }
            else      // A "Summary CostCentre" can have children.
            {
                NodeDetails.CanHaveChildren = true;
            }

            NodeDetails.IsNew = true;
            NodeDetails.CostCentreRow = CostCentreRow;
            NewTreeNode.Tag = NodeDetails;
            NodeDetails.linkedTreeNode = NewTreeNode;
            return NodeDetails;
        }
Пример #22
0
        public static Boolean GetPartnerKeyForForeignCostCentreCode(Int32 ALedgerNumber, String ACostCentreCode, out Int64 APartnerKey)
        {
            Boolean ReturnValue = false;

            Int64 PartnerKey = 0;

            TDBTransaction transaction = new TDBTransaction();
            TDataBase      db          = DBAccess.Connect("GetPartnerKeyForForeignCostCentreCode");

            db.ReadTransaction(ref transaction,
                               delegate
            {
                ACostCentreTable CostCentreTable;
                CostCentreTable = ACostCentreAccess.LoadByPrimaryKey(ALedgerNumber, ACostCentreCode, transaction);

                if (CostCentreTable.Count > 0)
                {
                    ACostCentreRow CostCentreRow = (ACostCentreRow)CostCentreTable.Rows[0];

                    if (CostCentreRow.CostCentreType == MFinanceConstants.FOREIGN_CC_TYPE)
                    {
                        AValidLedgerNumberTable ValidLedgerNumberTable;
                        AValidLedgerNumberRow ValidLedgerNumberRow;
                        ValidLedgerNumberTable = AValidLedgerNumberAccess.LoadViaACostCentre(ALedgerNumber, ACostCentreCode, transaction);

                        if (ValidLedgerNumberTable.Count > 0)
                        {
                            ValidLedgerNumberRow = (AValidLedgerNumberRow)ValidLedgerNumberTable.Rows[0];
                            PartnerKey           = ValidLedgerNumberRow.PartnerKey;
                            ReturnValue          = true;
                        }
                    }
                }
            });

            db.CloseDBConnection();

            APartnerKey = PartnerKey;
            return(ReturnValue);
        }
Пример #23
0
        public static Boolean GetPartnerKeyForForeignCostCentreCode(Int32 ALedgerNumber, String ACostCentreCode, out Int64 APartnerKey)
        {
            Boolean ReturnValue = false;

            Int64 PartnerKey = 0;

            TDBTransaction transaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                      TEnforceIsolationLevel.eilMinimum,
                                                                      ref transaction,
                                                                      delegate
            {
                ACostCentreTable CostCentreTable;
                CostCentreTable = ACostCentreAccess.LoadByPrimaryKey(ALedgerNumber, ACostCentreCode, transaction);

                if (CostCentreTable.Count > 0)
                {
                    ACostCentreRow CostCentreRow = (ACostCentreRow)CostCentreTable.Rows[0];

                    if (CostCentreRow.CostCentreType == MFinanceConstants.FOREIGN_CC_TYPE)
                    {
                        AValidLedgerNumberTable ValidLedgerNumberTable;
                        AValidLedgerNumberRow ValidLedgerNumberRow;
                        ValidLedgerNumberTable = AValidLedgerNumberAccess.LoadViaACostCentre(ALedgerNumber, ACostCentreCode, transaction);

                        if (ValidLedgerNumberTable.Count > 0)
                        {
                            ValidLedgerNumberRow = (AValidLedgerNumberRow)ValidLedgerNumberTable.Rows[0];
                            PartnerKey           = ValidLedgerNumberRow.PartnerKey;
                            ReturnValue          = true;
                        }
                    }
                }
            });

            APartnerKey = PartnerKey;
            return(ReturnValue);
        }
Пример #24
0
        public void Init()
        {
            TPetraServerConnector.Connect();
            FLedgerNumber = CommonNUnitFunctions.CreateNewLedger();

            // add costcentre 7300 for gift batch
            ACostCentreTable CostCentres = new ACostCentreTable();
            ACostCentreRow   CCRow       = CostCentres.NewRowTyped();

            CCRow.LedgerNumber          = FLedgerNumber;
            CCRow.CostCentreCode        = "7300";
            CCRow.CostCentreName        = "7300";
            CCRow.CostCentreType        = MFinanceConstants.FOREIGN_CC_TYPE;
            CCRow.CostCentreToReportTo  = MFinanceConstants.INTER_LEDGER_HEADING;
            CCRow.PostingCostCentreFlag = true;
            CCRow.CostCentreActiveFlag  = true;
            CostCentres.Rows.Add(CCRow);

            ACostCentreAccess.SubmitChanges(CostCentres, null);

            System.Diagnostics.Debug.WriteLine("Init: " + this.ToString());
        }
Пример #25
0
        /// <summary>
        /// return a list of costcentres that does not contail any costcentre linked to a person
        /// </summary>
        public static string WithoutPersonCostCentres(int ALedgerNumber, String ACostCentreList)
        {
            // remove all costcentres that report to a costcentre which name ends with Personalkosten
            ACostCentreTable costcentres = ACostCentreAccess.LoadViaALedger(ALedgerNumber, null);

            costcentres.DefaultView.Sort = ACostCentreTable.GetCostCentreCodeDBName();

            string[] costcentresList = ACostCentreList.Split(new char[] { ',' });

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

            foreach (string cc in costcentresList)
            {
                ACostCentreRow costcentre = (ACostCentreRow)costcentres.DefaultView.FindRows(cc)[0].Row;
                ACostCentreRow parentCC   = (ACostCentreRow)costcentres.DefaultView.FindRows(costcentre.CostCentreToReportTo)[0].Row;

                if (!parentCC.CostCentreName.EndsWith("Personalkosten"))
                {
                    newList.Add(cc);
                }
            }

            return(String.Join(",", newList.ToArray()));
        }
Пример #26
0
        /// <summary>
        /// helper function for ExportCostCentreHierarchy
        /// </summary>
        private static void InsertNodeIntoXmlDocument(GLSetupTDS AMainDS,
            XmlDocument ADoc,
            XmlNode AParentNode,
            ACostCentreRow ADetailRow)
        {
            XmlElement costCentreNode = ADoc.CreateElement(TYml2Xml.XMLELEMENT);

            // CostCentreToReportTo is encoded implicitly
            costCentreNode.SetAttribute("name", ADetailRow.CostCentreCode);
            costCentreNode.SetAttribute("descr", ADetailRow.CostCentreName);
            costCentreNode.SetAttribute("active", ADetailRow.CostCentreActiveFlag ? "True" : "False");
            costCentreNode.SetAttribute("type", ADetailRow.CostCentreType.ToString());
            AParentNode.AppendChild(costCentreNode);

            AMainDS.ACostCentre.DefaultView.Sort = ACostCentreTable.GetCostCentreCodeDBName();
            AMainDS.ACostCentre.DefaultView.RowFilter =
                ACostCentreTable.GetCostCentreToReportToDBName() + " = '" + ADetailRow.CostCentreCode + "'";

            foreach (DataRowView rowView in AMainDS.ACostCentre.DefaultView)
            {
                InsertNodeIntoXmlDocument(AMainDS, ADoc, costCentreNode, (ACostCentreRow)rowView.Row);
            }
        }
 /// <summary>
 /// Add this new CostCentre as child of the currently selected node
 /// </summary>
 public void AddNewCostCentre(ACostCentreRow CostCentreRow)
 {
     trvCostCentres.BeginUpdate();
     TreeNode newNode = trvCostCentres.SelectedNode.Nodes.Add(CostCentreRow.CostCentreCode);
     CostCentreNodeDetails NewCostCentre = CostCentreNodeDetails.AddNewCostCentre(newNode, CostCentreRow);
     trvCostCentres.EndUpdate();
     FParentForm.SetSelectedCostCentre(NewCostCentre); // This will set my FSelectedCostCentre and my trvCostCentres.SelectedNode
 }
        /// <summary>
        /// I need to find out whether the specified AccountCode can be allowed.
        /// </summary>
        private void GetDetailsFromControlsManual(ACostCentreRow ARow)
        {
            //
            // If changing the PrimaryKey to that specified causes a contraints error,
            // I'll catch it here, issue a warning, and return the control to the "safe" value.
            ProtectedChangeOfPrimaryKey(FCurrentCostCentre);

            //
            // The value of ARow.RollupStyle may contain "LOCK_" in addition to the enum value.
            // This means that all children are constrained to have this value.
            String RollupStyle = cmbRollupStyleManual.GetSelectedString();

            if (chkChildrenLocked.Checked)
            {
                RollupStyle = "LOCK_" + RollupStyle;
            }

            ARow.RollupStyle = RollupStyle;
        }
Пример #29
0
        /// <summary>
        /// helper function for ExportCostCentreHierarchy
        /// </summary>
        private static void InsertNodeIntoXmlDocument(GLSetupTDS AMainDS,
            XmlDocument ADoc,
            XmlNode AParentNode,
            ACostCentreRow ADetailRow)
        {
            #region Validate Arguments

            if (AMainDS == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString("Function:{0} - The GL Setup dataset is null!"),
                        Utilities.GetMethodName(true)));
            }
            else if (AMainDS.ACostCentre == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Cost Centre table does not exist in the dataset!"),
                        Utilities.GetMethodName(true)));
            }
            else if (ADoc == null)
            {
                throw new ArgumentException(String.Format(Catalog.GetString("Function:{0} - The XML document is null!"),
                        Utilities.GetMethodName(true)));
            }
            else if (AParentNode == null)
            {
                throw new ArgumentException(String.Format(Catalog.GetString("Function:{0} - The XML parent node is null!"),
                        Utilities.GetMethodName(true)));
            }
            else if (ADetailRow == null)
            {
                throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString(
                            "Function:{0} - The Cost Centre detail row does not exist!"),
                        Utilities.GetMethodName(true)));
            }

            #endregion Validate Arguments

            XmlElement CostCentreNode = ADoc.CreateElement(TYml2Xml.XMLELEMENT);

            // CostCentreToReportTo is encoded implicitly
            CostCentreNode.SetAttribute("name", ADetailRow.CostCentreCode);
            CostCentreNode.SetAttribute("descr", ADetailRow.CostCentreName);
            CostCentreNode.SetAttribute("active", ADetailRow.CostCentreActiveFlag ? "True" : "False");
            CostCentreNode.SetAttribute("type", ADetailRow.CostCentreType.ToString());
            AParentNode.AppendChild(CostCentreNode);

            AMainDS.ACostCentre.DefaultView.Sort = ACostCentreTable.GetCostCentreCodeDBName();
            AMainDS.ACostCentre.DefaultView.RowFilter =
                ACostCentreTable.GetCostCentreToReportToDBName() + " = '" + ADetailRow.CostCentreCode + "'";

            foreach (DataRowView rowView in AMainDS.ACostCentre.DefaultView)
            {
                InsertNodeIntoXmlDocument(AMainDS, ADoc, CostCentreNode, (ACostCentreRow)rowView.Row);
            }
        }
        public static Int32 CreateGiftBatch(
            Int32 ALedgerNumber,
            Int32 AStatementKey,
            Int32 AGiftBatchNumber,
            out TVerificationResultCollection AVerificationResult)
        {
            BankImportTDS MainDS = GetBankStatementTransactionsAndMatches(AStatementKey, ALedgerNumber);

            string MyClientID = DomainManager.GClientID.ToString();

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

            AVerificationResult = new TVerificationResultCollection();

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

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

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

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

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

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

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

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

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

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

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

            string MatchedGiftReference = stmt.Filename;

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

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

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

            DBAccess.GDBAccessObj.RollbackTransaction();

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

            AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];

            giftbatchRow.BankAccountCode = stmt.BankAccountCode;

            decimal HashTotal = 0.0M;

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

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

            int counter = 5;

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

                AEpTransactionRow transactionRow = (AEpTransactionRow)dv.Row;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            TProgressTracker.FinishJob(MyClientID);

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

            return(-1);
        }
        private void ShowDetailsManual(ACostCentreRow ARow)
        {
            if (ARow != null)
            {
                // I allow the user to attempt to change the primary key,
                // but if the selected record is not new, AND they have made any other changes,
                // the txtDetailCostCentreCode_TextChanged method will disallow any change.
                SetPrimaryKeyReadOnly(false);
                btnRename.Visible = false;
                chkDetailSummaryFlag.Checked = !ARow.PostingCostCentreFlag;
                chkDetailSummaryFlag.Enabled = !ARow.SystemCostCentreFlag;

                String ParentLock = IsLockedByParent(FCurrentCostCentre);

                if (ParentLock != "") // Equity / Roll-up Controls cannot be changed:
                {
                    grpEquitySettings.Enabled = false;
                    lblLockedMessage.Text = "These settings are derived from " + ParentLock;
                }
                else
                {
                    grpEquitySettings.Enabled = true;
                    lblLockedMessage.Text = "";
                }

                //
                // The value of ARow.RollupStyle may contain "LOCK_" in addition to the enum value.
                // This means that all children are constrained to have this value.
                String RollupStyle = ARow.RollupStyle;

                if (RollupStyle.IndexOf("LOCK_") == 0)
                {
                    RollupStyle = RollupStyle.Substring(5);
                    FCurrentCostCentre.IsLocked = true;

                    if (ParentLock == "")
                    {
                        lblLockedMessage.Text = "These settings apply to child Cost Centres.";
                    }
                }
                else
                {
                    FCurrentCostCentre.IsLocked = false;

                    if ((ParentLock == "") && (!ARow.PostingCostCentreFlag))
                    {
                        lblLockedMessage.Text = "THESE SETTINGS ARE NOT USED:\n  child Cost Centres have individual settings.";
                    }
                }

                chkChildrenLocked.Visible = (!ARow.PostingCostCentreFlag);
                lblChildrenLocked.Visible = (!ARow.PostingCostCentreFlag);

                chkChildrenLocked.Checked = FCurrentCostCentre.IsLocked;
                CCRollupStyleEnum cmbVal;

                if (!Enum.TryParse <CCRollupStyleEnum>(RollupStyle, out cmbVal))
                {
                    RollupStyle = Enum.GetName(typeof(CCRollupStyleEnum), CCRollupStyleEnum.Always);
                }

                cmbRollupStyleManual.SetSelectedString(RollupStyle);
                chkDetailProjectStatus_CheckedChanged(null, null);
            }
        }
Пример #32
0
        /// <summary>
        /// Validates the GL Detail data.
        /// </summary>
        /// <param name="AContext">Context that describes where the data validation failed.</param>
        /// <param name="ABatchRow">Manually added to bring over some GL Batch fields</param>
        /// <param name="ARow">The <see cref="DataRow" /> which holds the the data against which the validation is run.</param>
        /// <param name="AVerificationResultCollection">Will be filled with any <see cref="TVerificationResult" /> items if
        /// data validation errors occur.</param>
        /// <param name="AValidationCostCentreTable">REQUIRED for importing.  A reference to a cost centre table so that inputs can be validated.</param>
        /// <param name="AvalidationAccountTable">REQUIRED for importing.  A reference to an account table so that inputs can be validated.</param>
        /// <returns>True if the validation found no data validation errors, otherwise false.</returns>
        public static bool ValidateGLDetailManual(object AContext, ABatchRow ABatchRow, ATransactionRow ARow,
                                                  ref TVerificationResultCollection AVerificationResultCollection,
                                                  ACostCentreTable AValidationCostCentreTable = null, AAccountTable AvalidationAccountTable = null)
        {
            DataColumn          ValidationColumn;
            TVerificationResult VerificationResult = null;
            object ValidationContext;
            int    VerifResultCollAddedCount = 0;

            // Don't validate deleted DataRows or non-unposted batches
            if ((ABatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED) || (ARow.RowState == DataRowState.Deleted))
            {
                return(true);
            }

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

            // When used by the GUI TransactionAmount is not in the dictionary so had to pass the control directly
            // But when importing we do have a dictionary entry
            if (isImporting)
            {
                // 'GL amount must be non-zero and positive
                ValidationColumn = ARow.Table.Columns[ATransactionTable.ColumnTransactionAmountId];

                if (true)
                {
                    VerificationResult = TNumericalChecks.IsPositiveDecimal(ARow.TransactionAmount,
                                                                            String.Empty,
                                                                            AContext, ValidationColumn);

                    // Handle addition/removal to/from TVerificationResultCollection
                    if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult))
                    {
                        VerifResultCollAddedCount++;
                    }
                }
            }
            else
            {
                if (true)
                {
                    // 'GL amount must be non-zero and positive
                    ValidationColumn  = ARow.Table.Columns[ATransactionTable.ColumnTransactionAmountId];
                    ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})",
                                                      ARow.TransactionNumber,
                                                      ARow.BatchNumber,
                                                      ARow.JournalNumber);

                    VerificationResult = TNumericalChecks.IsPositiveOrZeroDecimal(ARow.TransactionAmount,
                                                                                  "Amount of " + ValidationContext,
                                                                                  AContext, ValidationColumn);

                    if (VerificationResult != null)
                    {
                        VerificationResult.SuppressValidationToolTip = true;
                    }

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

                    return(VerifResultCollAddedCount == 0);
                }
            }

            // 'Narrative must not be empty
            ValidationColumn  = ARow.Table.Columns[ATransactionTable.ColumnNarrativeId];
            ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})",
                                              ARow.TransactionNumber,
                                              ARow.BatchNumber,
                                              ARow.JournalNumber);

            if (true)
            {
                VerificationResult = TStringChecks.StringMustNotBeEmpty(ARow.Narrative,
                                                                        (isImporting) ? String.Empty : "Narrative of " + ValidationContext,
                                                                        AContext, ValidationColumn);

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

            // 'Entered From Date' must be valid
            ValidationColumn  = ARow.Table.Columns[ATransactionTable.ColumnTransactionDateId];
            ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})",
                                              ARow.TransactionNumber,
                                              ARow.BatchNumber,
                                              ARow.JournalNumber);

            if (true)
            {
                DateTime StartDatePeriod;
                DateTime EndDatePeriod;
                TSharedFinanceValidationHelper.GetValidPeriodDates(ARow.LedgerNumber, ABatchRow.BatchYear, 0, ABatchRow.BatchPeriod,
                                                                   out StartDatePeriod,
                                                                   out EndDatePeriod);

                VerificationResult = (TScreenVerificationResult)TDateChecks.IsDateBetweenDates(ARow.TransactionDate,
                                                                                               StartDatePeriod,
                                                                                               EndDatePeriod,
                                                                                               (isImporting) ? String.Empty : "Transaction Date for " + ValidationContext.ToString(),
                                                                                               TDateBetweenDatesCheckType.dbdctUnspecific,
                                                                                               TDateBetweenDatesCheckType.dbdctUnspecific,
                                                                                               AContext,
                                                                                               ValidationColumn);

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

            if (true)
            {
                // "Reference" is mandatory
                ValidationColumn  = ARow.Table.Columns[ATransactionTable.ColumnReferenceId];
                ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})",
                                                  ARow.TransactionNumber,
                                                  ARow.BatchNumber,
                                                  ARow.JournalNumber);

                if (true)
                {
                    VerificationResult = TStringChecks.StringMustNotBeEmpty(ARow.Reference,
                                                                            (isImporting) ? String.Empty : "Reference of " + ValidationContext,
                                                                            AContext, ValidationColumn);

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

            // 'CostCentre' must be valid
            ValidationColumn  = ARow.Table.Columns[ATransactionTable.ColumnCostCentreCodeId];
            ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})",
                                              ARow.TransactionNumber,
                                              ARow.BatchNumber,
                                              ARow.JournalNumber);

            if (true)
            {
                if ((AValidationCostCentreTable != null) && !ARow.IsCostCentreCodeNull())
                {
                    // Code must exist in the cost centre table
                    ACostCentreRow foundRow = (ACostCentreRow)AValidationCostCentreTable.Rows.Find(
                        new object[] { ARow.LedgerNumber, ARow.CostCentreCode });

                    if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                            ValidationContext,
                            new TVerificationResult(ValidationContext,
                                                    String.Format(Catalog.GetString("Cost centre code '{0}' does not exist."), ARow.CostCentreCode),
                                                    TResultSeverity.Resv_Critical)))
                    {
                        VerifResultCollAddedCount++;
                    }

                    // cost centre must be a posting cost centre
                    if ((foundRow != null) && !foundRow.PostingCostCentreFlag)
                    {
                        if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(ValidationContext,
                                                                                  new TVerificationResult(ValidationContext,
                                                                                                          String.Format(Catalog.GetString("Cost centre code '{0}' is not a posting cost centre."), ARow.CostCentreCode),
                                                                                                          TResultSeverity.Resv_Critical)))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }

                    //TODO: Maybe add a user preference to determine what to do with inactive values on importing
                    // cost centre must not be inactive
                    //if ((foundRow != null) && !foundRow.CostCentreActiveFlag)
                    //{
                    //    if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(ValidationContext,
                    //            new TVerificationResult(ValidationContext,
                    //                String.Format(Catalog.GetString("Cost centre code '{0}' is an inactive cost centre."), ARow.CostCentreCode),
                    //                TResultSeverity.Resv_Critical),
                    //            ValidationColumn))
                    //    {
                    //        VerifResultCollAddedCount++;
                    //    }
                    //}
                }
            }

            // 'Account code' must be valid
            ValidationColumn  = ARow.Table.Columns[ATransactionTable.ColumnAccountCodeId];
            ValidationContext = String.Format("Transaction number {0} (batch:{1} journal:{2})",
                                              ARow.TransactionNumber,
                                              ARow.BatchNumber,
                                              ARow.JournalNumber);

            if (true)
            {
                if ((AvalidationAccountTable != null) && !ARow.IsAccountCodeNull())
                {
                    // Code must exist in the account table
                    AAccountRow foundRow = (AAccountRow)AvalidationAccountTable.Rows.Find(
                        new object[] { ARow.LedgerNumber, ARow.AccountCode });

                    if ((foundRow == null) && AVerificationResultCollection.Auto_Add_Or_AddOrRemove(
                            ValidationContext,
                            new TVerificationResult(ValidationContext,
                                                    String.Format(Catalog.GetString("Account code '{0}' does not exist."), ARow.AccountCode),
                                                    TResultSeverity.Resv_Critical)))
                    {
                        VerifResultCollAddedCount++;
                    }

                    // Account code must be a posting Account code
                    if ((foundRow != null) && !foundRow.PostingStatus)
                    {
                        if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(ValidationContext,
                                                                                  new TVerificationResult(ValidationContext,
                                                                                                          String.Format(Catalog.GetString("Account code '{0}' is not a posting account."), ARow.AccountCode),
                                                                                                          TResultSeverity.Resv_Critical)))
                        {
                            VerifResultCollAddedCount++;
                        }
                    }

                    //TODO: Maybe add a user preference to determine what to do with inactive values on importing
                    // Account code must not be inactive
                    //if ((foundRow != null) && !foundRow.AccountActiveFlag)
                    //{
                    //    if (AVerificationResultCollection.Auto_Add_Or_AddOrRemove(ValidationContext,
                    //            new TVerificationResult(ValidationContext,
                    //                String.Format(Catalog.GetString("Account code '{0}' is an inactive account."), ARow.AccountCode),
                    //                TResultSeverity.Resv_Critical),
                    //            ValidationColumn))
                    //    {
                    //        VerifResultCollAddedCount++;
                    //    }
                    //}
                }
            }

            return(VerifResultCollAddedCount == 0);
        }
        public static BankImportTDS GetBankStatementTransactionsAndMatches(Int32 AStatementKey, Int32 ALedgerNumber)
        {
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

            BankImportTDS ResultDataset = new BankImportTDS();
            string        MyClientID    = DomainManager.GClientID.ToString();

            TProgressTracker.InitProgressTracker(MyClientID,
                                                 Catalog.GetString("Load Bank Statement"),
                                                 100.0m);

            TProgressTracker.SetCurrentState(MyClientID,
                                             Catalog.GetString("loading statement"),
                                             0);

            try
            {
                AEpStatementAccess.LoadByPrimaryKey(ResultDataset, AStatementKey, Transaction);

                if (ResultDataset.AEpStatement[0].BankAccountCode.Length == 0)
                {
                    throw new Exception("Loading Bank Statement: Bank Account must not be empty");
                }

                ACostCentreAccess.LoadViaALedger(ResultDataset, ALedgerNumber, Transaction);

                AMotivationDetailAccess.LoadViaALedger(ResultDataset, ALedgerNumber, Transaction);

                AEpTransactionAccess.LoadViaAEpStatement(ResultDataset, AStatementKey, Transaction);

                BankImportTDS TempDataset = new BankImportTDS();
                AEpTransactionAccess.LoadViaAEpStatement(TempDataset, AStatementKey, Transaction);
                AEpMatchAccess.LoadViaALedger(TempDataset, ResultDataset.AEpStatement[0].LedgerNumber, Transaction);

                // load all bankingdetails and partner shortnames related to this statement
                string sqlLoadPartnerByBankAccount =
                    "SELECT DISTINCT p.p_partner_key_n AS PartnerKey, " +
                    "p.p_partner_short_name_c AS ShortName, " +
                    "t.p_branch_code_c AS BranchCode, " +
                    "t.a_bank_account_number_c AS BankAccountNumber " +
                    "FROM PUB_a_ep_transaction t, PUB_p_banking_details bd, PUB_p_bank b, PUB_p_partner_banking_details pbd, PUB_p_partner p " +
                    "WHERE t.a_statement_key_i = " + AStatementKey.ToString() + " " +
                    "AND bd.p_bank_account_number_c = t.a_bank_account_number_c " +
                    "AND b.p_partner_key_n = bd.p_bank_key_n " +
                    "AND b.p_branch_code_c = t.p_branch_code_c " +
                    "AND pbd.p_banking_details_key_i = bd.p_banking_details_key_i " +
                    "AND p.p_partner_key_n = pbd.p_partner_key_n";

                DataTable PartnerByBankAccount = DBAccess.GDBAccessObj.SelectDT(sqlLoadPartnerByBankAccount, "partnerByBankAccount", Transaction);
                PartnerByBankAccount.DefaultView.Sort = "BranchCode, BankAccountNumber";

                // get all recipients that have been merged
                string sqlGetMergedRecipients =
                    string.Format(
                        "SELECT DISTINCT p.p_partner_key_n AS PartnerKey, p.p_status_code_c AS StatusCode FROM PUB_a_ep_match m, PUB_p_partner p " +
                        "WHERE (m.p_recipient_key_n = p.p_partner_key_n OR m.p_donor_key_n = p.p_partner_key_n) AND p.p_status_code_c = '{0}'",
                        MPartnerConstants.PARTNERSTATUS_MERGED);
                DataTable MergedPartners = DBAccess.GDBAccessObj.SelectDT(sqlGetMergedRecipients, "mergedPartners", Transaction);
                MergedPartners.DefaultView.Sort = "PartnerKey";

                DBAccess.GDBAccessObj.RollbackTransaction();

                string BankAccountCode = ResultDataset.AEpStatement[0].BankAccountCode;

                TempDataset.AEpMatch.DefaultView.Sort = AEpMatchTable.GetMatchTextDBName();

                SortedList <string, AEpMatchRow> MatchesToAddLater = new SortedList <string, AEpMatchRow>();

                int count = 0;

                // load the matches or create new matches
                foreach (BankImportTDSAEpTransactionRow row in ResultDataset.AEpTransaction.Rows)
                {
                    TProgressTracker.SetCurrentState(MyClientID,
                                                     Catalog.GetString("finding matches") +
                                                     " " + count + "/" + ResultDataset.AEpTransaction.Rows.Count.ToString(),
                                                     10.0m + (count * 80.0m / ResultDataset.AEpTransaction.Rows.Count));
                    count++;

                    BankImportTDSAEpTransactionRow tempTransactionRow =
                        (BankImportTDSAEpTransactionRow)TempDataset.AEpTransaction.Rows.Find(
                            new object[] {
                        row.StatementKey,
                        row.Order,
                        row.DetailKey
                    });

                    // find a match with the same match text, or create a new one
                    if (row.IsMatchTextNull() || (row.MatchText.Length == 0) || !row.MatchText.StartsWith(BankAccountCode))
                    {
                        row.MatchText = TBankImportMatching.CalculateMatchText(BankAccountCode, row);

                        tempTransactionRow.MatchText = row.MatchText;
                    }

                    DataRowView[] matches = TempDataset.AEpMatch.DefaultView.FindRows(row.MatchText);

                    if (matches.Length > 0)
                    {
                        Decimal sum = 0.0m;

                        // update the recent date
                        foreach (DataRowView rv in matches)
                        {
                            AEpMatchRow r = (AEpMatchRow)rv.Row;

                            sum += r.GiftTransactionAmount;

                            // check if the recipient key is still valid. could be that they have married, and merged into another family record
                            if ((r.RecipientKey != 0) &&
                                (MergedPartners.DefaultView.FindRows(r.RecipientKey).Length > 0))
                            {
                                TLogging.LogAtLevel(1, "partner has been merged: " + r.RecipientKey.ToString());
                                r.RecipientKey = 0;
                                r.Action       = MFinanceConstants.BANK_STMT_STATUS_UNMATCHED;
                            }

                            // check if the donor key is still valid. could be that they have married, and merged into another family record
                            if ((r.DonorKey != 0) &&
                                (MergedPartners.DefaultView.FindRows(r.DonorKey).Length > 0))
                            {
                                TLogging.LogAtLevel(1, "partner has been merged: " + r.DonorKey.ToString());
                                r.DonorKey = 0;
                                r.Action   = MFinanceConstants.BANK_STMT_STATUS_UNMATCHED;
                            }

                            if (r.RecentMatch < row.DateEffective)
                            {
                                r.RecentMatch = row.DateEffective;
                            }

                            // do not modify tempRow.MatchAction, because that will not be stored in the database anyway, just costs time
                            row.MatchAction = r.Action;

                            if (r.IsDonorKeyNull() || (r.DonorKey <= 0))
                            {
                                FindDonorByAccountNumber(r, PartnerByBankAccount.DefaultView, row.BranchCode, row.BankAccountNumber);
                            }
                        }

                        if (sum != row.TransactionAmount)
                        {
                            TLogging.Log("we should drop this match since the total is wrong: " + row.Description);
                            row.MatchAction = MFinanceConstants.BANK_STMT_STATUS_UNMATCHED;

                            foreach (DataRowView rv in matches)
                            {
                                AEpMatchRow r = (AEpMatchRow)rv.Row;
                                r.Action = MFinanceConstants.BANK_STMT_STATUS_UNMATCHED;
                            }
                        }
                    }
                    else if (!MatchesToAddLater.ContainsKey(row.MatchText))
                    {
                        // create new match
                        AEpMatchRow tempRow = TempDataset.AEpMatch.NewRowTyped(true);
                        tempRow.EpMatchKey            = (TempDataset.AEpMatch.Count + MatchesToAddLater.Count + 1) * -1;
                        tempRow.Detail                = 0;
                        tempRow.MatchText             = row.MatchText;
                        tempRow.LedgerNumber          = ALedgerNumber;
                        tempRow.GiftTransactionAmount = row.TransactionAmount;
                        tempRow.Action                = MFinanceConstants.BANK_STMT_STATUS_UNMATCHED;

                        FindDonorByAccountNumber(tempRow, PartnerByBankAccount.DefaultView, row.BranchCode, row.BankAccountNumber);

#if disabled
                        // fuzzy search for the partner. only return if unique result
                        string sql =
                            "SELECT p_partner_key_n, p_partner_short_name_c FROM p_partner WHERE p_partner_short_name_c LIKE '{0}%' OR p_partner_short_name_c LIKE '{1}%'";
                        string[] names = row.AccountName.Split(new char[] { ' ' });

                        if (names.Length > 1)
                        {
                            string optionShortName1 = names[0] + ", " + names[1];
                            string optionShortName2 = names[1] + ", " + names[0];

                            DataTable partner = DBAccess.GDBAccessObj.SelectDT(String.Format(sql,
                                                                                             optionShortName1,
                                                                                             optionShortName2), "partner", Transaction);

                            if (partner.Rows.Count == 1)
                            {
                                tempRow.DonorKey = Convert.ToInt64(partner.Rows[0][0]);
                            }
                        }
#endif

                        MatchesToAddLater.Add(tempRow.MatchText, tempRow);

                        // do not modify tempRow.MatchAction, because that will not be stored in the database anyway, just costs time
                        row.MatchAction = tempRow.Action;
                    }
                }

                // for speed reasons, add the new rows after clearing the sort on the view
                TempDataset.AEpMatch.DefaultView.Sort = string.Empty;

                foreach (AEpMatchRow m in MatchesToAddLater.Values)
                {
                    TempDataset.AEpMatch.Rows.Add(m);
                }

                TProgressTracker.SetCurrentState(MyClientID,
                                                 Catalog.GetString("save matches"),
                                                 90.0m);

                TempDataset.ThrowAwayAfterSubmitChanges = true;
                // only store a_ep_transactions and a_ep_matches, but without additional typed fields (ie MatchAction)
                BankImportTDSAccess.SubmitChanges(TempDataset.GetChangesTyped(true));
            }
            catch (Exception e)
            {
                TLogging.Log(e.GetType().ToString() + " in BankImport, GetBankStatementTransactionsAndMatches; " + e.Message);
                TLogging.Log(e.StackTrace);
                DBAccess.GDBAccessObj.RollbackTransaction();
                throw;
            }

            // drop all matches that do not occur on this statement
            ResultDataset.AEpMatch.Clear();

            // reloading is faster than deleting all matches that are not needed
            string sqlLoadMatchesOfStatement =
                "SELECT DISTINCT m.* FROM PUB_a_ep_match m, PUB_a_ep_transaction t WHERE t.a_statement_key_i = ? AND m.a_ledger_number_i = ? AND m.a_match_text_c = t.a_match_text_c";

            OdbcParameter param = new OdbcParameter("statementkey", OdbcType.Int);
            param.Value = AStatementKey;
            OdbcParameter paramLedgerNumber = new OdbcParameter("ledgerNumber", OdbcType.Int);
            paramLedgerNumber.Value = ALedgerNumber;

            DBAccess.GDBAccessObj.SelectDT(ResultDataset.AEpMatch,
                                           sqlLoadMatchesOfStatement,
                                           null,
                                           new OdbcParameter[] { param, paramLedgerNumber }, -1, -1);

            // update the custom field for cost centre name for each match
            foreach (BankImportTDSAEpMatchRow row in ResultDataset.AEpMatch.Rows)
            {
                ACostCentreRow ccRow = (ACostCentreRow)ResultDataset.ACostCentre.Rows.Find(new object[] { row.LedgerNumber, row.CostCentreCode });

                if (ccRow != null)
                {
                    row.CostCentreName = ccRow.CostCentreName;
                }
            }

            // remove all rows that we do not need on the client side
            ResultDataset.AGiftDetail.Clear();
            ResultDataset.AMotivationDetail.Clear();
            ResultDataset.ACostCentre.Clear();

            ResultDataset.AcceptChanges();

            if (TLogging.DebugLevel > 0)
            {
                int CountMatched = 0;

                foreach (BankImportTDSAEpTransactionRow transaction in ResultDataset.AEpTransaction.Rows)
                {
                    if (!transaction.IsMatchActionNull() && (transaction.MatchAction != MFinanceConstants.BANK_STMT_STATUS_UNMATCHED))
                    {
                        CountMatched++;
                    }
                }

                TLogging.Log(
                    "Loading bank statement: matched: " + CountMatched.ToString() + " of " + ResultDataset.AEpTransaction.Rows.Count.ToString());
            }

            TProgressTracker.FinishJob(MyClientID);

            return(ResultDataset);
        }
Пример #34
0
        /// <summary>
        /// generate the units
        /// </summary>
        /// <param name="AFieldCSVFile"></param>
        public static void GenerateFields(string AFieldCSVFile)
        {
            XmlDocument doc = TCsv2Xml.ParseCSVFile2Xml(AFieldCSVFile, ",");

            XmlNode RecordNode = doc.FirstChild.NextSibling.FirstChild;

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

            PCountryTable CountryTable = null;

            TDBTransaction Transaction = new TDBTransaction();

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

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

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

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

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

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

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

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

                RecordNode = RecordNode.NextSibling;
            }

            PartnerImportExportTDSAccess.SubmitChanges(PartnerDS);

            GLSetupTDSAccess.SubmitChanges(GLSetupDS);
        }
        private void AddNewCostCentre(Object sender, EventArgs e)
        {
            if (FCurrentCostCentre == null)
            {
                MessageBox.Show(Catalog.GetString("You can only add a new cost centre after selecting a parent cost centre"));
                return;
            }

            if (ValidateAllData(true, true))
            {
                FCurrentCostCentre.GetAttrributes();
                ACostCentreRow ParentRow = FCurrentCostCentre.CostCentreRow;

                if (!FCurrentCostCentre.CanHaveChildren.Value)
                {
                    MessageBox.Show(
                        String.Format(Catalog.GetString("Cost Centre {0} is in use and cannot become a summary Cost Centre."),
                            ParentRow.CostCentreCode), Catalog.GetString("NewCostCentre"));
                    return;
                }

                Int32 countNewCostCentre = 0;
                string newCostCentreName = FnameForNewCostCentre;

                if (FMainDS.ACostCentre.Rows.Find(new object[] { FLedgerNumber, newCostCentreName }) != null)
                {
                    while (FMainDS.ACostCentre.Rows.Find(new object[] { FLedgerNumber, newCostCentreName + countNewCostCentre.ToString() }) != null)
                    {
                        countNewCostCentre++;
                    }

                    newCostCentreName += countNewCostCentre.ToString();
                }

                ParentRow.PostingCostCentreFlag = false;
                FCurrentCostCentre.CanDelete = false;

                ACostCentreRow newCostCentreRow = FMainDS.ACostCentre.NewRowTyped();
                newCostCentreRow.CostCentreCode = newCostCentreName;
                newCostCentreRow.LedgerNumber = FLedgerNumber;
                newCostCentreRow.CostCentreActiveFlag = true;

                //
                // OM - specific code ahead!
                if (ParentRow.CostCentreCode == "ILT")
                {
                    newCostCentreRow.CostCentreType = "Foreign";
                }
                else
                {
                    newCostCentreRow.CostCentreType = ParentRow.CostCentreType;
                }

                newCostCentreRow.PostingCostCentreFlag = true;
                newCostCentreRow.CostCentreToReportTo = ParentRow.CostCentreCode;
                FMainDS.ACostCentre.Rows.Add(newCostCentreRow);

                FRecentlyUpdatedDetailCostCentreCode = INTERNAL_UNASSIGNED_DETAIL_COSTCENTRE_CODE;

                FIAmUpdating++;
                ShowDetails(newCostCentreRow);
                FIAmUpdating--;

                ucoCostCentreTree.AddNewCostCentre(newCostCentreRow);
                txtDetailCostCentreCode.Focus();
                txtDetailCostCentreCode.SelectAll();
                FPetraUtilsObject.SetChangedFlag();
            }
        }
Пример #36
0
        /// <summary>
        /// Data loader for HOSA data,
        /// Made static so it can be called from Stewardship Reports
        /// </summary>
        public static Boolean LoadReportDataStaticInner(Form ParentForm,
                                                        TFrmPetraReportingUtils UtilsObject,
                                                        FastReportsWrapper ReportingEngine,
                                                        TRptCalculator ACalc)
        {
            Shared.MReporting.TParameterList pm = ACalc.GetParameters();
            String Csv = "";

            //
            // My "a_transaction" table forms the lower half of the HOSA:
            // All transactions for all the "Expense" accounts for the selected Cost Centre within the selected dates or periods.

            String LedgerFilter     = "a_ledger_number_i=" + pm.Get("param_ledger_number_i").ToInt32();
            String TranctDateFilter = ""; // Optional Date Filter, as periods or dates
            String CostCentreCodes  = pm.Get("param_cost_centre_codes").ToString();

            if (CostCentreCodes == String.Empty)
            {
                MessageBox.Show(Catalog.GetString("Please select one or more Cost Centres."), "HOSA");
                return(false);
            }

            String CostCentreFilter = "";

            if (CostCentreCodes == "ALL")
            {
                CostCentreFilter = " AND a_cost_centre.a_cost_centre_type_c='Foreign' ";
            }
            else
            {
                CostCentreCodes = CostCentreCodes.Replace('"', '\'');
                ACalc.AddStringParameter("param_cost_centre_codes", CostCentreCodes);
                CostCentreFilter = " AND a_cost_centre.a_cost_centre_code_c IN (" + CostCentreCodes + ") ";
            }

            if (pm.Get("param_period").ToBool() == true)
            {
                Int32 PeriodStart = pm.Get("param_start_period_i").ToInt32();
                Int32 PeriodEnd   = pm.Get("param_end_period_i").ToInt32();

                DateTime DateStart = pm.Get("param_start_date").ToDate();
                DateTime DateEnd   = pm.Get("param_end_date").ToDate();

                ALedgerTable LedgerDetailsTable = (ALedgerTable)TDataCache.TMFinance.GetCacheableFinanceTable(
                    TCacheableFinanceTablesEnum.LedgerDetails);
                ALedgerRow LedgerRow = LedgerDetailsTable[0];
                Boolean    IsClosed  = (!pm.Get("param_current_financial_year").ToBool() || (PeriodEnd < LedgerRow.CurrentPeriod));
                ACalc.AddParameter("param_period_closed", IsClosed);
                Boolean IsCurrent = (pm.Get("param_current_financial_year").ToBool() && (PeriodEnd == LedgerRow.CurrentPeriod));
                ACalc.AddParameter("param_period_current", IsCurrent);

                String PeriodTitle = " (" + DateStart.ToString("dd-MMM-yyyy") + " - " + DateEnd.ToString("dd-MMM-yyyy") + ")";

                if (PeriodEnd > PeriodStart)
                {
                    PeriodTitle = String.Format("{0} - {1}", PeriodStart, PeriodEnd) + PeriodTitle;
                }
                else
                {
                    PeriodTitle = String.Format("{0}", PeriodStart) + PeriodTitle;
                }

                pm.Add("param_date_title", PeriodTitle);
            }
            else
            {
                String PeriodTitle = " " + pm.Get("param_start_date").DateToString("yyyy-MM-dd") + " - " +
                                     pm.Get("param_end_date").DateToString("yyyy-MM-dd");

                pm.Add("param_date_title", PeriodTitle);
            }

            TranctDateFilter = "a_transaction_date_d>='" + pm.Get("param_start_date").DateToString("yyyy-MM-dd") +
                               "' AND a_transaction_date_d<='" + pm.Get("param_end_date").DateToString("yyyy-MM-dd") + "'";

            Csv = StringHelper.AddCSV(Csv,
                                      "AAccount/SELECT * FROM a_account WHERE " + LedgerFilter + " AND a_posting_status_l=true AND a_account_active_flag_l=true");
            Csv = StringHelper.AddCSV(Csv,
                                      "ACostCentre/SELECT * FROM a_cost_centre WHERE " + LedgerFilter + CostCentreFilter +
                                      " AND a_posting_cost_centre_flag_l=true AND a_cost_centre_active_flag_l=true");
            Csv = StringHelper.AddCSV(
                Csv,
                "ATransaction/SELECT a_transaction.* FROM a_transaction, a_cost_centre WHERE a_transaction." + LedgerFilter +
                " AND " + TranctDateFilter +
                " AND NOT (a_system_generated_l = true AND (a_narrative_c LIKE 'Gifts received - Gift Batch%' OR a_narrative_c LIKE 'GB - Gift Batch%' OR a_narrative_c LIKE 'Year end re-allocation%'))"
                +
                " AND a_transaction.a_ledger_number_i = a_cost_centre.a_ledger_number_i " +
                " AND a_transaction.a_cost_centre_code_c = a_cost_centre.a_cost_centre_code_c " +
                CostCentreFilter +
                " ORDER BY a_account_code_c, a_transaction_date_d");

            GLReportingTDS ReportDs    = TRemote.MReporting.WebConnectors.GetReportingDataSet(Csv);
            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.Add(p.name, p.value);
                }
            }

            DataTable GiftsTable       = TRemote.MReporting.WebConnectors.GetReportDataTable("HOSA", paramsDictionary);
            DataTable KeyMinGiftsTable = TRemote.MReporting.WebConnectors.GetReportDataTable("FieldGifts", paramsDictionary);

            //
            // I'm going to get rid of any Cost Centres that saw no activity in the requested period:
            for (Int32 Idx = ReportDs.ACostCentre.Rows.Count - 1; Idx >= 0; Idx--)
            {
                ACostCentreRow Row = ReportDs.ACostCentre[Idx];
                ReportDs.ATransaction.DefaultView.RowFilter = String.Format("a_cost_centre_code_c='{0}'", Row.CostCentreCode);
                GiftsTable.DefaultView.RowFilter            = String.Format("CostCentre='{0}'", Row.CostCentreCode);

                if ((ReportDs.ATransaction.DefaultView.Count == 0) && (GiftsTable.DefaultView.Count == 0))
                {
                    ReportDs.ACostCentre.Rows.Remove(Row);
                }
            }

            if (ParentForm.IsDisposed)
            {
                return(false);
            }

            if (GiftsTable == null)
            {
                UtilsObject.WriteToStatusBar("Report Cancelled.");
                return(false);
            }

            ReportingEngine.RegisterData(GiftsTable, "Gifts");
            ReportingEngine.RegisterData(KeyMinGiftsTable, "FieldGifts");
            ReportingEngine.RegisterData(ReportDs.AAccount, "a_account");
            ReportingEngine.RegisterData(ReportDs.ACostCentre, "a_costCentre");
            ReportingEngine.RegisterData(ReportDs.ATransaction, "a_transaction");

            Boolean HasData = (ReportDs.ATransaction.Rows.Count > 0) || (GiftsTable.Rows.Count > 0);

            if (!HasData)
            {
                MessageBox.Show(Catalog.GetString("No Transactions found for selected Cost Centres."), "HOSA");
            }

            return(HasData);
        }
        /// <summary>
        /// Update the name of the currently selected node
        /// </summary>
        public void SetNodeLabel(ACostCentreRow ARow, TreeNode ThisNode = null)
        {
            if ((ARow == null) || (ARow.RowState == DataRowState.Deleted) || (ARow.RowState == DataRowState.Detached))
            {
                return;
            }

            SetNodeLabel(ARow.CostCentreCode, ARow.CostCentreName, ThisNode);
        }
        private void InsertNodeIntoTreeView(TreeNode AParent, DataView view, ACostCentreRow ADetailRow)
        {
            TreeNode newNode = new TreeNode("");

            CostCentreNodeDetails NewNodeDetails = CostCentreNodeDetails.AddNewCostCentre(newNode, ADetailRow);

            NewNodeDetails.IsNew = false;

            SetNodeLabel(ADetailRow, newNode);

            if (AParent == null)
            {
                trvCostCentres.Nodes.Add(newNode);
            }
            else
            {
                InsertInOrder(AParent, newNode);
            }

            view.RowFilter =
                ACostCentreTable.GetCostCentreToReportToDBName() + " = '" + ADetailRow.CostCentreCode + "'";

            if (view.Count > 0)
            {
                // A cost centre cannot be deleted if it has children.
                NewNodeDetails.CanDelete = false;
                NewNodeDetails.Msg = Catalog.GetString("Child Cost Centres must be deleted first.");
                NewNodeDetails.CanHaveChildren = true;

                foreach (DataRowView rowView in view)
                {
                    InsertNodeIntoTreeView(newNode, view, (ACostCentreRow)rowView.Row);
                }
            }
        }