Ejemplo n.º 1
0
        public static void UnRegisterFinances(TimeTrackingBlock block)
        {
            if (!Configuration.TimeTrackingModule)
            {
                throw new Mediachase.Ibn.LicenseRestrictionException();
            }

            if (!(bool)block.Properties["AreFinancesRegistered"].Value)
            {
                throw new NotSupportedException("Finances are not registered.");
            }

            if (!TimeTrackingBlock.CheckUserRight(block, TimeTrackingManager.Right_UnRegFinances))
            {
                throw new Mediachase.Ibn.AccessDeniedException();
            }


            using (DbTransaction tran = DbTransaction.Begin())
            {
                ActualFinances.DeleteByBlockId(block.PrimaryKeyId.Value);

                // O.R. [2008-07-29]: We don't need to check the "Write" right for Block
                using (SkipSecurityCheckScope scope = Mediachase.Ibn.Data.Services.Security.SkipSecurityCheck())
                {
                    block.Properties["AreFinancesRegistered"].Value = false;
                    block.Save();
                }

                // Recalculate TotalMinutes and TotalApproved
                RecalculateProjectAndObjects(block);

                tran.Commit();
            }
        }
Ejemplo n.º 2
0
        private void btnSave_ServerClick(object sender, EventArgs e)
        {
            //int ProjectId, DateTime Date, string RowId, double Value, string Comment
            string value = tbValue.Text.Replace(',', '.');

            if (ActualFinancesId == -1)
            {
                Mediachase.IBN.Business.SpreadSheet.ActualFinances.Create(ObjectId, (ObjectTypes)ObjectTypeId, dtcDate.SelectedDate, ddAccounts.SelectedValue, Convert.ToDouble(value, CultureInfo.InvariantCulture), txtDescription.Text);
            }
            else
            {
                ActualFinances item = ActualFinances.Load(ActualFinancesId);
                item.Date    = dtcDate.SelectedDate;
                item.Value   = Convert.ToDouble(value, CultureInfo.InvariantCulture);
                item.Comment = txtDescription.Text;
                item.RowId   = ddAccounts.SelectedValue;
                ActualFinances.Update(item);
            }

            if (!String.IsNullOrEmpty(Request["btn"]))
            {
                CHelper.CloseItAndRefresh(Response, Request["btn"]);
            }
            else
            {
                CHelper.CloseItAndRefresh(Response);
            }
        }
Ejemplo n.º 3
0
        private void dgAccounts_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            int ActualId = int.Parse(e.CommandArgument.ToString());

            //Finance.DeleteActualFinances(ActualId);
            ActualFinances.Delete(ActualId);
            BindDG(dgAccounts);
        }
Ejemplo n.º 4
0
        void BindValues()
        {
            ActualFinances item = ActualFinances.Load(ActualFinancesId);

            dtcDate.SelectedDate = item.Date;
            tbValue.Text         = item.Value.ToString();
            txtDescription.Text  = item.Comment;
            if (ddAccounts.Items.FindByValue(item.RowId) != null)
            {
                ddAccounts.SelectedValue = item.RowId;
            }
        }
Ejemplo n.º 5
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            btnOk.ServerClick     += new EventHandler(btnOk_ServerClick);
            btnCancel.ServerClick += new EventHandler(btnCancel_ServerClick);
            btnOk.Text             = LocRM.GetString("tbsave_save");
            btnCancel.Text         = LocRM.GetString("tbsave_cancel");
            btnOk.CustomImage      = this.Page.ResolveUrl("~/layouts/images/accept.gif");
            btnCancel.CustomImage  = this.Page.ResolveUrl("~/layouts/images/cancel.gif");

            bool allowAdd = true;

            ActualFinances[] aFinances = ActualFinances.List(int.Parse(Request["ProjectId"], CultureInfo.InvariantCulture), Mediachase.IBN.Business.ObjectTypes.Project);

            foreach (ActualFinances af in aFinances)
            {
                if (af.RowId == this.RowId.Substring(0, RowId.IndexOf("-")))
                {
                    allowAdd = false;
                    break;
                }
            }

            if (!allowAdd)
            {
                btnOk.Style.Add("display", "none");
                rowUsual.Style.Add("display", "none");
                rowUsual2.Style.Add("display", "none");
                rowError.Style.Add("display", "block");
            }
            else
            {
                btnOk.Style.Add("display", "inline");
                rowUsual.Style.Add("display", "block");
                rowUsual2.Style.Add("display", "block");
                rowError.Style.Add("display", "none");
            }

            if (Value != string.Empty)
            {
                if (Value == "!EMPTY!")
                {
                    tbName.Text = LocRM2.GetString("tNewItem");
                    this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(), string.Format("<script language=JavaScript>window.opener.mygrid.setItemText('{0}','{1}');</script>", RowId, tbName.Text));
                }
                else
                {
                    tbName.Text = Value;
                }
            }
        }
Ejemplo n.º 6
0
        public static void RegisterFinances(TimeTrackingBlock block, string rowId, DateTime regDate)
        {
            if (!Configuration.TimeTrackingModule)
            {
                throw new Mediachase.Ibn.LicenseRestrictionException();
            }

            if ((bool)block.Properties["AreFinancesRegistered"].Value)
            {
                throw new NotSupportedException("Finances are already registered.");
            }

            if (!TimeTrackingBlock.CheckUserRight(block, TimeTrackingManager.Right_RegFinances))
            {
                throw new Mediachase.Ibn.AccessDeniedException();
            }

            ///  TimeTrackingEntryId, UserId, ObjectTypeId, ObjectId, Title,
            ///  Day1, Day2, Day3, Day4, Day5, Day6, Day7, Total, TotalApproved, Rate, Cost
            DataTable dt = GetListTimeTrackingItemsForFinances_DataTable(block.BlockTypeInstanceId, block.StartDate, block.OwnerId);

            using (DbTransaction tran = DbTransaction.Begin())
            {
                // O.R. [2008-07-29]: We don't need to check the "Write" right for Entry and Block
                using (SkipSecurityCheckScope scope = Mediachase.Ibn.Data.Services.Security.SkipSecurityCheck())
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        // O.R. [2008-07-28]: Rate and TotalApproved may contain null values, so we need do assign them
                        TimeTrackingEntry entry = MetaObjectActivator.CreateInstance <TimeTrackingEntry>(TimeTrackingEntry.GetAssignedMetaClass(), (int)row["TimeTrackingEntryId"]);
                        entry.Properties["Rate"].Value          = row["Rate"];
                        entry.Properties["TotalApproved"].Value = row["TotalApproved"];
                        entry.Save();

                        double cost = (double)row["Cost"];
                        if (cost == 0d)
                        {
                            continue;
                        }

                        // O.R. [2008-07-24] Now we use ProjectId

                        /*					ObjectTypes objectType = ObjectTypes.Timesheet;
                         *                                      int objectId = (int)row["TimeTrackingEntryId"];
                         */
                        ObjectTypes objectType = ObjectTypes.Project;
                        int         objectId   = block.ProjectId.Value;

                        if (row["ObjectTypeId"] != DBNull.Value && row["ObjectId"] != DBNull.Value)
                        {
                            objectType = (ObjectTypes)row["ObjectTypeId"];
                            objectId   = (int)row["ObjectId"];
                        }

                        // row["TotalApproved"] alwas has not null value
                        ActualFinances.Create(objectId, objectType, regDate, rowId, cost, row["Title"].ToString(), block.PrimaryKeyId.Value, (double)row["TotalApproved"], (int)block.OwnerId);
                    }

                    block.Properties["AreFinancesRegistered"].Value = true;
                    block.Save();
                }

                // Recalculate TotalMinutes and TotalApproved
                RecalculateProjectAndObjects(block);

                tran.Commit();
            }
        }
Ejemplo n.º 7
0
        private void BindDG(DataGrid dg)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add(new DataColumn("ActualId", typeof(int)));
            dt.Columns.Add(new DataColumn("OutlineLevel", typeof(int)));
            dt.Columns.Add(new DataColumn("Description", typeof(string)));
            dt.Columns.Add(new DataColumn("ActualDate", typeof(DateTime)));
            dt.Columns.Add(new DataColumn("AValue", typeof(double)));
            dt.Columns.Add(new DataColumn("LastEditorId", typeof(int)));
            dt.Columns.Add(new DataColumn("LastEditorName", typeof(string)));
            dt.Columns.Add(new DataColumn("ObjectTypeId", typeof(int)));
            dt.Columns.Add(new DataColumn("ObjectId", typeof(int)));
            dt.Columns.Add(new DataColumn("RowId", typeof(string)));
            dt.Columns.Add(new DataColumn("BlockId", typeof(int)));
            dt.Columns.Add(new DataColumn("TotalApproved", typeof(string)));
            dt.Columns.Add(new DataColumn("OwnerDisplayName", typeof(string)));
            dt.Columns.Add(new DataColumn("OwnerName", typeof(string)));

            if (ObjectId > 0)
            {
                int       projectId = Util.CommonHelper.GetProjectIdByObjectIdObjectType(ObjectId, ObjectTypeId);
                bool      projectSpreadSheetIsActive = ProjectSpreadSheet.IsActive(projectId);
                Hashtable rowNameHashtable           = ProjectSpreadSheet.GetRowNameByIdHash(projectId);

                #region dates
                DateTime?dt1 = null;
                DateTime?dt2 = null;
                switch (PeriodList.SelectedValue)
                {
                case "[DateTimeThisAny]":
                    break;

                case "[DateTimeThisWeek]":
                    dt1 = CHelper.GetRealWeekStartByDate(DateTime.Today);
                    dt2 = CHelper.GetRealWeekEndByDate(DateTime.Today);
                    break;

                case "[DateTimeLastWeek]":
                    dt1 = CHelper.GetRealWeekStartByDate(DateTime.Today.AddDays(-7));
                    dt2 = CHelper.GetRealWeekEndByDate(DateTime.Today.AddDays(-7));
                    break;

                case "[DateTimeThisMonth]":
                    dt1 = DateTime.Today.AddDays(1 - DateTime.Today.Day);
                    dt2 = DateTime.Today;
                    break;

                case "[DateTimeLastMonth]":
                    dt1 = DateTime.Today.AddDays(1 - DateTime.Today.Day).AddMonths(-1);
                    dt2 = DateTime.Today.AddDays(-DateTime.Today.Day);
                    break;

                case "[DateTimeThisYear]":
                    dt1 = DateTime.Today.AddDays(1 - DateTime.Today.DayOfYear);
                    dt2 = DateTime.Today;
                    break;

                case "[DateTimeLastYear]":
                    dt1 = DateTime.Today.AddDays(1 - DateTime.Now.DayOfYear).AddYears(-1);
                    dt2 = DateTime.Today.AddDays(-DateTime.Now.DayOfYear);
                    break;

                case "0":
                    dt1 = Dtc0.SelectedDate;
                    dt2 = CHelper.GetRealWeekEndByDate(Dtc0.SelectedDate);
                    break;

                case "-1":
                    dt1 = Dtc1.SelectedDate;
                    dt2 = Dtc2.SelectedDate;
                    break;

                default:
                    break;
                }
                #endregion

                foreach (ActualFinances af in ActualFinances.List(ObjectId, (ObjectTypes)ObjectTypeId, dt1, dt2))
                {
                    DataRow row = dt.NewRow();
                    row["ActualId"]       = af.ActualFinancesId;
                    row["Description"]    = af.Comment;
                    row["ActualDate"]     = af.Date;
                    row["AValue"]         = af.Value;
                    row["LastEditorId"]   = af.CreatorId;
                    row["LastEditorName"] = Util.CommonHelper.GetUserStatusPureName(af.CreatorId);
                    row["OutlineLevel"]   = 1;
                    row["ObjectTypeId"]   = af.ObjectTypeId;
                    row["ObjectId"]       = af.ObjectId;
                    if (projectSpreadSheetIsActive && rowNameHashtable.ContainsKey(af.RowId))
                    {
                        row["RowId"] = rowNameHashtable[af.RowId].ToString();
                    }
                    else
                    {
                        row["RowId"] = string.Empty;
                    }

                    if (af.BlockId.HasValue)
                    {
                        row["BlockId"] = af.BlockId.Value;
                    }

                    if (af.TotalApproved.HasValue)
                    {
                        if (dg == dgExport)
                        {
                            row["TotalApproved"] = (int)af.TotalApproved.Value;
                        }
                        else
                        {
                            row["TotalApproved"] = CommonHelper.GetHours((int)af.TotalApproved.Value);
                        }
                    }

                    if (af.OwnerId.HasValue)
                    {
                        row["OwnerDisplayName"] = Util.CommonHelper.GetUserStatus(af.OwnerId.Value);
                        if (dgExport.Visible)
                        {
                            row["OwnerName"] = Util.CommonHelper.GetUserStatusAndPositionPureName(af.OwnerId.Value);
                        }
                        else
                        {
                            row["OwnerName"] = Util.CommonHelper.GetUserStatusPureName(af.OwnerId.Value);
                        }
                    }

                    dt.Rows.Add(row);
                }
            }

            /*else if(TaskId>0)
             *      dt = Finance.GetListActualFinancesByTask(TaskId);
             * else if(IncidentId>0)
             *      dt = Finance.GetListActualFinancesByIncident(IncidentId);
             * else if(DocumentId>0)
             *      dt = Finance.GetListActualFinancesByDocument(DocumentId);
             * else if(EventId>0)
             *      dt = Finance.GetListActualFinancesByEvent(EventId);
             * else if(ToDoId>0)
             *      dt = Finance.GetListActualFinancesByToDo(ToDoId);*/

            DataView dv = dt.DefaultView;
            dv.Sort = pc["FinAct_Sort"].ToString();

            if (pc["FinAct_PageSize"] != null)
            {
                dg.PageSize = int.Parse(pc["FinAct_PageSize"]);
            }

            if (pc["FinAct_Page"] != null)
            {
                dg.CurrentPageIndex = int.Parse(pc["FinAct_Page"]);
            }

            int pageindex = dg.CurrentPageIndex;
            int ppi       = dv.Count / dg.PageSize;
            if (dv.Count % dg.PageSize == 0)
            {
                ppi = ppi - 1;
            }

            if (pageindex <= ppi)
            {
                dg.CurrentPageIndex = pageindex;
            }
            else
            {
                dg.CurrentPageIndex = 0;
                pc["FinAct_Page"]   = "0";
            }

            dg.DataSource = dv;
            dg.DataBind();

            bool haveRights = false;
            if (ProjectId > 0)
            {
                haveRights = Project.CanEditFinances(ProjectId);
            }
            if (TaskId > 0)
            {
                haveRights = Task.CanViewFinances(TaskId);
            }
            if (IncidentId > 0)
            {
                haveRights = Incident.CanViewFinances(IncidentId);
            }
            if (DocumentId > 0)
            {
                haveRights = Document.CanViewFinances(DocumentId);
            }
            if (EventId > 0)
            {
                haveRights = CalendarEntry.CanViewFinances(EventId);
            }
            if (ToDoId > 0)
            {
                haveRights = Mediachase.IBN.Business.ToDo.CanViewFinances(ToDoId);
            }

            foreach (DataGridItem dgi in dg.Items)
            {
                if (dgi.FindControl("ibDelete") != null)
                {
                    ImageButton ibDelete = (ImageButton)dgi.FindControl("ibDelete");
                    ibDelete.Attributes.Add("onclick", "return confirm('" + LocRM.GetString("Warning") + "')");
                }

                if (dgi.FindControl("ibEdit") != null)
                {
                    ImageButton ibEdit = (ImageButton)dgi.FindControl("ibEdit");

                    string link = string.Empty;
                    if (ObjectId > 0 && haveRights)
                    {
                        link = String.Format(CultureInfo.InvariantCulture,
                                             "javascript:OpenWindow(\"{0}?ObjectId={1}&ObjectTypeId={2}&ActualFinancesId={3}&btn={4}\",520,270,false);return false;",
                                             ResolveClientUrl("~/projects/AddFinanceActual.aspx"),
                                             ObjectId,
                                             ObjectTypeId, dgi.Cells[0].Text,
                                             Page.ClientScript.GetPostBackEventReference(RefreshButton, ""));
                    }
                    ibEdit.Attributes.Add("onclick", link);
                }
            }
            //			if(!Project.CanEditFinances(ProjectId))
            //				dg.Columns[10].Visible = false;
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Generates the project task business score report.
        /// </summary>
        /// <param name="projectIdList">The project id list.</param>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <param name="completion">The completion.</param>
        /// <param name="completionFrom">The completion from.</param>
        /// <param name="completionTo">The completion to.</param>
        /// <returns></returns>
        public static ReportResult GenerateProjectTaskBusinessScoreReport(List <int> projectIdList,
                                                                          DateTime from, DateTime to, int completion, DateTime completionFromDate, DateTime completionToDate)
        {
            if (projectIdList == null)
            {
                throw new ArgumentNullException("projectIdList");
            }
            // test only;
            //projectIdList = new List<int>(new int[] { 624, 544, 665, 680, 686, 687, 688, 689, 681, 691, 781, 633, 809, 803, 801, 838, 407, 852, 849, 853, 841, 856, 819, 848 });

            TimeZone tz = Security.CurrentUser.CurrentTimeZone;

            completionFromDate = tz.ToUniversalTime(completionFromDate);
            completionToDate   = tz.ToUniversalTime(completionToDate);

            ReportResult result = new ReportResult();

            foreach (int projectId in projectIdList)
            {
                // Get Project Title
                string projectTitleName = Project.GetProjectTitle(projectId);

                ReportResultItem projectItem = new ReportResultItem(ObjectTypes.Project, projectId, projectTitleName);

                #region Load Task List
                // Get Task(Id,Name) List by projectId and fill projectItem.Items
                using (IDataReader reader = DbReport.GetTasks(projectId, completion, completionFromDate, completionToDate))
                {
                    while (reader.Read())
                    {
                        int    taskId    = (int)reader["TaskId"];
                        string taskTitle = (string)reader["Title"];

                        ReportResultItem taskItem = new ReportResultItem(ObjectTypes.Task, taskId, taskTitle);

                        // Add taskItem to projectItem
                        projectItem.ChildItems.Add(taskItem);
                    }
                }
                #endregion

                #region Create SpreadSheetDocument and SpreadSheetView
                // Create a new Spread Sheet Document
                SpreadSheetDocument ssDocument = new SpreadSheetDocument(SpreadSheetDocumentType.Total);

                // Load Template
                ssDocument.Template.Load(Path.Combine(ProjectSpreadSheet.TemplateDirectory, "ProfitAndLossStatementSimple_RU.xml"));

                ProjectSpreadSheetRow[] projectSpreadSheets = ProjectSpreadSheetRow.List(projectId);
                ProjectSpreadSheetRow   projectSpreadSheet  = projectSpreadSheets[0];

                // Add user rows
                if (projectSpreadSheet.UserRows != string.Empty)
                {
                    try
                    {
                        ssDocument.Template.LoadXml(projectSpreadSheet.UserRows);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Trace.WriteLine(ex);
                    }
                }

                SpreadSheetView ssView = new SpreadSheetView(ssDocument);
                #endregion

                // Load Business Score
                //BusinessScore[] businessScoreList = BusinessScore.List();
                List <ReportResultItem> taskWithoutFinancesRemoveIt = new List <ReportResultItem>();

                #region Calcualte Business Score
                // Calcualte Business Score
                foreach (ReportResultItem taskItem in projectItem.ChildItems)
                {
                    // Cleare Spread Sheet Document
                    ssView.Document.DeleteAllCells();

                    // Get Actual Finances for current task + task/todo
                    ActualFinances[] finances = ActualFinances.List(taskItem.ObjectId, taskItem.ObjectType, from, to);

                    if (finances.Length > 0)
                    {
                        // Append Actual Finances to SpreadSheetDocument
                        foreach (ActualFinances finance in finances)
                        {
                            string columnId = SpreadSheetView.GetColumnByDate(ssView.Document.DocumentType, finance.Date);
                            string rowId    = finance.RowId;

                            Cell cell = ssView.Document.GetCell(columnId, rowId);
                            if (cell == null)
                            {
                                cell = ssView.Document.AddCell(columnId, rowId, CellType.Common, 0);
                            }

                            cell.Value += finance.Value;
                        }

                        // Add Business Scope ReportResultItem and Calculate Business Scope total.
                        // TODO: Localize ReportResultItem.Name
                        taskItem.ChildItems.Add(new ReportResultItem(ObjectTypes.UNDEFINED, -1, "Доходы" /*"Revenues"*/));
                        taskItem.ChildItems.Add(new ReportResultItem(ObjectTypes.UNDEFINED, -1, "Расходы" /*Expenses"*/));
                        taskItem.ChildItems.Add(new ReportResultItem(ObjectTypes.UNDEFINED, -1, "Чистый доход" /*"NetIncome"*/));

                        taskItem.ChildItems[0].Total = ssView["TT", "Revenues"];
                        taskItem.ChildItems[1].Total = ssView["TT", "Expenses"];
                        taskItem.ChildItems[2].Total = ssView["TT", "NetIncome"];

                        // Copy NetIncome to total
                        taskItem.Total = taskItem.ChildItems[2].Total;
                    }
                    else
                    {
                        taskWithoutFinancesRemoveIt.Add(taskItem);
                    }
                }

                // Remove Empty Tasks
                foreach (ReportResultItem item in taskWithoutFinancesRemoveIt)
                {
                    projectItem.ChildItems.Remove(item);
                }
                #endregion

                projectItem.Total = CalculateTotal(projectItem.ChildItems);

                // Add projectItem to result
                result.Items.Add(projectItem);
            }

            // Calculate Report Total
            result.Total = CalculateTotal(result.Items);

            // Final return result
            return(result);
        }