Example #1
0
        public void AddNewEventShouldAddEventInDatabase()
        {
            var options = new DbContextOptionsBuilder <TaskPlannerDbContext>()
                          .UseInMemoryDatabase(databaseName: "TimeSheet_AddEvent_Database")
                          .Options;

            var dbContext = new TaskPlannerDbContext(options);

            var newEvent = new DailyAgenda
            {
                Description = "Nice short description",
                Project     = "New Project",
                StartDate   = DateTime.UtcNow,
                EndDate     = DateTime.UtcNow.AddHours(1.1),
                ThemeColor  = "red"
            };

            dbContext.DailyAgendas.Add(newEvent);
            dbContext.SaveChanges();

            var service = new TimeSheetService(dbContext);

            var actual = dbContext.DailyAgendas.FirstOrDefault(e => e.Id == newEvent.Id);

            Assert.Equal(newEvent.Project, actual.Project);
            Assert.Equal(newEvent.Description, actual.Description);
            Assert.Equal(newEvent.StartDate, actual.StartDate);
            Assert.Equal(newEvent.EndDate, actual.EndDate);
            Assert.Equal(newEvent.ThemeColor, actual.ThemeColor);
        }
        private async void btnDeleteTimesheet_Clicked()
        {
            var resp = await DisplayActionSheet("Do you want to unsubmit the timesheet?", "No", "Yes");

            if (resp != null && resp.ToString().Length > 0 && resp.Equals("Yes"))
            {
                ApiDeleteResponse result = await TimeSheetService.Delete(viewModel.CurrentPeriod.TimeSheetId.Value);

                if (result != null)
                {
                    if (result.HasErrors)
                    {
                        foreach (var error in result.Errors)
                        {
                            Common.Instance.ShowToastMessage(error.ErrorMessage, DoubleResources.DangerSnackBar);
                        }
                    }
                    else
                    {
                        Common.Instance.ShowToastMessage("Timesheet deleted!", DoubleResources.SuccessSnackBar);
                        MessagingCenter.Send(this, "TimeSheetApproved", true);
                        await Navigation.PopToRootAsync();
                    }
                    //await Navigation.PopAsync();
                }
                else
                {
                    Common.Instance.ShowToastMessage("Error contacting server!", DoubleResources.DangerSnackBar);
                }
            }
        }
Example #3
0
        public void GetEventFromIdShouldReturnCorrectEvent()
        {
            var options = new DbContextOptionsBuilder <TaskPlannerDbContext>()
                          .UseInMemoryDatabase(databaseName: "TimeSheet_GetEventById_Database")
                          .Options;

            var dbContext = new TaskPlannerDbContext(options);

            var newEvent = new DailyAgenda
            {
                Description = "Nice short description",
                Project     = "New Project",
                StartDate   = DateTime.UtcNow,
                EndDate     = DateTime.UtcNow.AddHours(1.1),
                ThemeColor  = "red"
            };

            dbContext.DailyAgendas.Add(newEvent);
            dbContext.SaveChanges();

            var service = new TimeSheetService(dbContext);

            var actual = service.GetEventFromId(newEvent);

            Assert.Equal(newEvent, actual);
        }
        private async void ApproveAll_Clicked(object sender, EventArgs e)
        {
            if (viewModel.TimeSheets == null || viewModel.TimeSheets.Count == 0)
            {
                Common.Instance.ShowToastMessage("No pending timesheets waiting for approval", DoubleResources.DangerSnackBar);
                return;
            }
            var resp = await DisplayActionSheet("Do you want to approve all time sheets?", "No", "Yes");

            if (resp != null && resp.ToString().Length > 0 && resp.Equals("Yes"))
            {
                bool isSussessfull = true;
                foreach (TimeSheetPeriod ts in viewModel.TimeSheets)
                {
                    ApiSaveResponse result = await TimeSheetService.ApproveAsync(ts.TimeSheetId.Value);

                    if (result.HasErrors)
                    {
                        isSussessfull = false;
                        foreach (var error in result.Errors)
                        {
                            Common.Instance.ShowToastMessage(error.ErrorMessage, DoubleResources.DangerSnackBar);
                        }
                    }
                }
                if (isSussessfull)
                {
                    Common.Instance.ShowToastMessage("All timesheets approved!", DoubleResources.SuccessSnackBar);
                }

                GetData();
            }
        }
Example #5
0
        //private async Task<bool> GetData()
        //{
        //}
        private async void OnSubmit(object sender, EventArgs e)
        {
            viewModel.VisibleLoad = true;
            try
            {
                ApiSaveResponse result = await TimeSheetService.CreateTimeSheetAndSubmitForPeriod(viewModel.TimeSheet.StartDate, viewModel.TimeSheet.EndDate, viewModel.SelectedUser != null?viewModel.SelectedUser.Id : null);

                if (result.HasErrors)
                {
                    foreach (var error in result.Errors)
                    {
                        Common.Instance.ShowToastMessage(error.ErrorMessage, DoubleResources.DangerSnackBar);
                    }
                }
                else
                {
                    Common.Instance.ShowToastMessage("Timesheet submited!", DoubleResources.SuccessSnackBar);

                    MessagingCenter.Send(this, "TimeSheetSubmited", true);
                    await Navigation.PopToRootAsync();
                }
            }
            catch (Exception ex)
            {
            }

            viewModel.VisibleLoad = false;
        }
        private async void OnUpdateStatus(object sender, EventArgs e)
        {
            viewModel.VisibleLoad    = true;
            viewModel.LoadingMessage = "";
            try
            {
                ApiSaveResponse result = await TimeSheetService.RejectAsync(Timesheet, txtCommentBody.Text ?? string.Empty);

                if (result.HasErrors)
                {
                    viewModel.VisibleLoad = false;
                    foreach (var error in result.Errors)
                    {
                        Common.Instance.ShowToastMessage(error.ErrorMessage, DoubleResources.DangerSnackBar);
                    }
                }
                else
                {
                    Common.Instance.ShowToastMessage("Timesheet rejected!", DoubleResources.SuccessSnackBar);
                    viewModel.VisibleLoad = false;
                    MessagingCenter.Send(this, "TimeSheetRejected", true);
                    await Navigation.PopToRootAsync();
                }
            }
            catch (Exception ex)
            {
                Common.Instance.ShowToastMessage("Error communication with server!", DoubleResources.DangerSnackBar);
                viewModel.VisibleLoad = false;
            }
        }
Example #7
0
 public TimeSheet()
 {
     DummyCommand = new RelayCommand(() =>
     {
         var action = ClockedIn ? TimeSheetService.ClockAction.ClockOut : TimeSheetService.ClockAction.ClockIn;
         TimeSheetService.AddData(action, Category).ConfigureAwait(false);
         OnClockEvent(Category);
     });
 }
Example #8
0
        public TimeSheetViewModel(
            IRegionManager regionManager,
            TimeSheetService timeSheetService)
        {
            _regionManager    = regionManager;
            _timeSheetService = timeSheetService;

            this.AddEntryCommand = new DelegateCommand(AddEntry);
        }
Example #9
0
        public async Task <IActionResult> GetAsync(string id, string status, string year, string month)
        {
            string url    = _iconfiguration.GetSection("Request").GetSection("Uri").Value;
            string Accept = _iconfiguration.GetSection("Request").GetSection("Accept").Value;
            string APIKey = _iconfiguration.GetSection("Request").GetSection("APIKey").Value;


            if (id == null)
            {
                _logger.LogError("should insert id");

                return(BadRequest(new { message = "should insert id" }));
            }
            if ((Convert.ToInt32(id)) <= 0)
            {
                _logger.LogDebug("should insert correct id ");
                _logger.LogError("should insert correct id ");
                return(BadRequest(new { message = "should insert correct id " }));
            }
            TimeSheetService timeService = new TimeSheetService();
            var response = await timeService.GetData(id, status, year, month, url, Accept, APIKey);

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();

                var Content = JsonConvert.DeserializeObject <RootObject>(result);
                var data    = new List <RData>();
                data = Content.d.results
                       .Select(x => new RData
                {
                    approvalStatus = x.approvalStatus,
                    endDate        = x.endDate,
                    timeType       = x.timeType,
                    startDate      = x.startDate,
                })
                       .ToList();

                if (data == null)
                {
                    _logger.LogInformation("no data with this information ");
                    return(Ok(new { message = "no data with this information ", result_data = data }));
                }

                return(Ok(data));
            }

            else
            {
                _logger.LogDebug("error in connection ");

                return(BadRequest(new { message = "error in connection" }));
            }
        }
Example #10
0
        public void AddTasksheets()
        {
            //s obzirom da ne postoji perzistencija podataka, nema potrebe kreirati mock servis
            TimeSheetService servis = new TimeSheetService();

            DayTasksheet neki = new DayTasksheet();

            for (int i = 0; i < 10; i++)
            {
                servis.addTimesheet(neki);
            }

            Assert.Equal(10, servis.GetDayTasksheets().Count);
        }
Example #11
0
        public static void ResetUserTimeSheet(TimeSheetService timeSheetService, UserTimeSheetStatusService userTimeSheetStatusService, List <UserTimeSheetStatus> userTimeSheetStatuses = null)
        {
            var timeSheets = timeSheetService.Get();

            if (userTimeSheetStatuses.IsEmpty())
            {
                userTimeSheetStatuses = userTimeSheetStatusService.Get();
            }

            foreach (var userTimeSheet in userTimeSheetStatuses)
            {
                var timeSheet = timeSheets.Where(o => o.UserId == userTimeSheet.Id).ToList();

                var startDate     = TimeSheetHelper.MIN_DATE;
                var currentMonday = DateTime.Today.GetMonday();

                while (startDate <= currentMonday)
                {
                    var monday = startDate.GetTimeSheetId();
                    var hour   = timeSheet.Where(o => o.WeekTimeSheets.ContainsKey(monday)).Select(o => o.WeekTimeSheets[monday].Sum(p => p.Value.Sum())).Sum();

                    var status = Status.Pending;

                    if (hour >= 40)
                    {
                        status = Status.Done;
                    }
                    else if (hour > 0)
                    {
                        status = Status.Ongoing;
                    }

                    KeyValuePair <Status, double> value = new KeyValuePair <Status, double>(status, hour);

                    if (userTimeSheet.Weeks.ContainsKey(monday))
                    {
                        userTimeSheet.Weeks[monday] = value;
                    }
                    else
                    {
                        userTimeSheet.Weeks.Add(monday, value);
                    }

                    startDate = startDate.AddDays(7);
                }

                userTimeSheetStatusService.Update(userTimeSheet);
            }
        }
        public TimeSheetView()
        {
            InitializeComponent();
            sheetService         = new TimeSheetService();
            lblUserLogin.Content = Menu.usermanager.UserName;
            FillListViewODP();
            FillListViewTM();
            FillListViewOPDDetails();
            CollectionView cView = CollectionViewSource.GetDefaultView(lsODP.ItemsSource) as CollectionView;

            cView.Filter = CustomFilter;
            CollectionView cView2 = CollectionViewSource.GetDefaultView(lsODPdETAILS.ItemsSource) as CollectionView;

            cView2.Filter       = CustomFilterDetails;
            dpEndDate.IsEnabled = false;
        }
Example #13
0
        public void GetAllEventsOfUserFromDBShouldReturnCorrectEvents()
        {
            var options = new DbContextOptionsBuilder <TaskPlannerDbContext>()
                          .UseInMemoryDatabase(databaseName: "TimeSheet_GetAllEventByUserId_Database")
                          .Options;

            var dbContext = new TaskPlannerDbContext(options);

            var newEvent = new DailyAgenda
            {
                Description = "Nice short description",
                Project     = "New Project",
                StartDate   = DateTime.UtcNow,
                EndDate     = DateTime.UtcNow.AddHours(1.1),
                ThemeColor  = "red"
            };

            var newEvent2 = new DailyAgenda
            {
                Description = "Nice short description",
                Project     = "New Project 2",
                StartDate   = DateTime.UtcNow,
                EndDate     = DateTime.UtcNow.AddHours(1.1),
                ThemeColor  = "red"
            };

            var user = new ApplicationUser
            {
                Email    = "*****@*****.**",
                FullName = "Pesho"
            };

            user.DailyAgendas.Add(newEvent);
            user.DailyAgendas.Add(newEvent2);

            dbContext.DailyAgendas.Add(newEvent);
            dbContext.Users.Add(user);
            dbContext.SaveChanges();

            var service = new TimeSheetService(dbContext);

            var actual = service.GetAllEventsOfUserFromDB(user.Id);

            Assert.Equal(2, actual.Count());
        }
        public void TrackTime_ShouldReturnFalse()
        {
            //arrange
            var timeLog = new TimeLog()
            {
                Date         = new DateTime(),
                WorkingHours = 1,
                LastName     = "",
            };

            var service = new TimeSheetService();

            //act
            var result = service.TrackTime(timeLog);

            //assert
            Assert.IsTrue(result);
        }
Example #15
0
 public void Initialize()
 {
     DbContext               = new TMSDbContext();
     dbFactory               = new DbFactory();
     timeSheetRepository     = new TimeSheetRepository(dbFactory);
     statusRequestRepository = new StatusRequestRepository(dbFactory);
     AbnormalCaseRepository  = new AbnormalCaseRepository(dbFactory);
     ExplanationRepository   = new ExplanationRequestRepository(dbFactory);
     unitOfWork              = new UnitOfWork(dbFactory);
     timeSheetService        = new TimeSheetService(timeSheetRepository, AbnormalCaseRepository, ExplanationRepository, unitOfWork);
     userManager             = new UserManager <AppUser>(new UserStore <AppUser>(DbContext));
     memberID     = userManager.FindByName("tqhuy").Id;
     adminID      = userManager.FindByName("dmtuong").Id;
     approveID    = statusRequestRepository.GetSingleByCondition(x => x.Name == "Approved").ID.ToString();
     rejectID     = statusRequestRepository.GetSingleByCondition(x => x.Name == "Approved").ID.ToString();
     cancelID     = statusRequestRepository.GetSingleByCondition(x => x.Name == "Approved").ID.ToString();
     delegationID = statusRequestRepository.GetSingleByCondition(x => x.Name == "Approved").ID.ToString();
     pendingID    = statusRequestRepository.GetSingleByCondition(x => x.Name == "Approved").ID.ToString();
 }
Example #16
0
        public static DtoTimeSheet DtoTimeSheet(KadrDataContext db, int idTimeSheet, bool isEmpty = false)
        {
            var service   = new TimeSheetService();
            var timeSheet = db.TimeSheet.Where(w => w.id == idTimeSheet).Select(s => new DtoTimeSheet
            {
                IdTimeSheet     = s.id,
                DateBegin       = s.DateBeginPeriod,
                DateEnd         = s.DateEndPeriod,
                DateComposition = s.DateComposition,
                Department      = DtoDepartment(db, s.idDepartment),
                ApproveStep     = service.GetTimeSheetApproveStep(idTimeSheet),
                IsFake          = s.IsFake,
                Holidays        = db.Exception.Where(e => (e.DateException >= s.DateBeginPeriod) && (e.DateException <= s.DateEndPeriod) &&
                                                     (e.WorkShedule.AllowNight) &&
                                                     (e.idDayStatus == IdHoliday)).Select(t => DtoExceptionDay(t)).ToArray(),
                EmployeesCount = db.TimeSheetRecords.Where(we => we.idTimeSheet == idTimeSheet)
                                 .Select(ec => ec.idFactStaffHistory)
                                 .Distinct()
                                 .Count()
            }).FirstOrDefault();

            if (timeSheet == null)
            {
                return(null);
            }
            if (isEmpty)
            {
                return(timeSheet);
            }
            timeSheet.Approvers =
                Enumerable.Range(1, 3)
                .Select(s => DtoTimeSheetApprover(db, idTimeSheet, s, timeSheet.ApproveStep))
                .ToArray();
            timeSheet.Employees = db.TimeSheetRecords.Where(we => we.idTimeSheet == idTimeSheet)
                                  .Select(se => se.idFactStaffHistory)
                                  .Distinct()
                                  .Select(se => DtoTimeSheetEmployee(db, idTimeSheet, se))
                                  .ToArray().OrderByDescending(o => o.FactStaffEmployee.Post.IsMenager).
                                  ThenBy(t => t.FactStaffEmployee.Post.Category.OrderBy).
                                  ThenBy(o => o.FactStaffEmployee.Surname).
                                  ToArray();
            return(timeSheet);
        }
Example #17
0
        public TimesheetApprovalBand()
        {
            InitializeComponent();

            if (CrossConnectivity.Current.IsConnected && Common.UserGlobalCapability != null && Common.UserGlobalCapability.IsTimeSheetApprover)
            {
                List <TimeSheet> resForApproval = TimeSheetService.GetTimesheetsForApproval();
                if (resForApproval != null && resForApproval.Count > 0)
                {
                    var count = resForApproval.Count();
                    el1.Padding = new Thickness(0, 5);
                    lblTimesheetToApprove.Text = String.Format("You have {0} time sheet{1} to approve", count.ToString(), (count > 1 ? "s" : ""));
                    el1.IsVisible = true;
                    el2.IsVisible = true;
                    el3.IsVisible = true;
                    lblTimesheetToApprove.IsVisible = true;
                }
            }
        }
        private void GetData()
        {
            viewModel.VisibleLoad = true;

            List <TimeSheet> result = TimeSheetService.GetTimesheetsForApproval();

            lstAllPeriod.Children.Clear();
            if (result != null && result.Count > 0)
            {
                int i = 0;
                foreach (var timeSheet in result)
                {
                    i++;
                    TimeSheetPeriod item = new TimeSheetPeriod();
                    item.StartDate           = timeSheet.StartDate.Value;
                    item.EndDate             = timeSheet.EndDate.Value;
                    item.ActualHours         = (timeSheet.ActualHours ?? 0);
                    item.ActualHoursFormated = timeSheet.ActualHoursFormattedString;
                    item.Status = timeSheet.ApprovalStatus ?? 0;
                    item.Name   = timeSheet.User.FirstName + " " + timeSheet.User.LastName;
                    //item.TimeEntries = timeSheet.TimeEntries;
                    item.TimeSheetId = timeSheet.Id;
                    item.User_Id     = timeSheet.User_Id;
                    viewModel.TimeSheets.Add(item);

                    //AddChildTimeSheets(timeSheet);
                    if (i == result.Count)
                    {
                        PreviousPeriods_GeneratedRows(item, true);
                    }
                    else
                    {
                        PreviousPeriods_GeneratedRows(item);
                    }
                }
            }
            else
            {
                lblNoNotif.IsVisible = true;
            }
            viewModel.VisibleLoad = false;
        }
        private async void OnApprove(object sender, EventArgs e)
        {
            viewModel.VisibleLoad = true;
            ApiSaveResponse result = await TimeSheetService.ApproveAsync(viewModel.CurrentPeriod.TimeSheetId.Value);

            if (result.HasErrors)
            {
                foreach (var error in result.Errors)
                {
                    Common.Instance.ShowToastMessage(error.ErrorMessage, DoubleResources.DangerSnackBar);
                }
            }
            else
            {
                Common.Instance.ShowToastMessage("Timesheet approved!", DoubleResources.SuccessSnackBar);
            }
            viewModel.VisibleLoad = false;
            MessagingCenter.Send(this, "TimeSheetApproved", true);
            await Navigation.PopToRootAsync();
        }
Example #20
0
        public ReportByUserHelper(BaseController controller, string departmentId, string groupId, DateTime startDate, DateTime endDate)
        {
            if (string.IsNullOrEmpty(_userId))
            {
                _userId = controller.GetUserId();
            }

            userService       = controller.GetService <UserService>();
            departmentService = controller.GetService <DepartmentService>();
            timeSheetService  = controller.GetService <TimeSheetService>();
            projectService    = controller.GetService <ProjectService>();

            _userId = controller.GetUserId();
            _user   = userService.Get(_userId);

            this.departmentId = departmentId;
            this.groupId      = groupId;

            //如果没有指定日期,就查本周的数据
            if (startDate.IsEmpty())
            {
                this._startDate = DateTimeUtil.GetCurrentMonday();
            }
            else
            {
                this._startDate = startDate;
            }

            if (endDate.IsEmpty())
            {
                this._endDate = DateTimeUtil.GetCurrentMonday().AddDays(6);
            }
            else
            {
                this._endDate = endDate;
            }

            this.controller = controller;
        }
Example #21
0
        public static void ResetTimeSheet(ProjectService projectService, TimeSheetService timeSheetService, List <TimeSheet> timeSheets = null)
        {
            var projectIds = projectService.GetIds();

            if (timeSheets.IsEmpty())
            {
                timeSheets = timeSheetService.Get();
            }

            foreach (var item in timeSheets)
            {
                if (!projectIds.Contains(item.ProjectId))
                {
                    timeSheetService.Delete(item.Id);
                }
                else
                {
                    var project = projectService.Get(item.ProjectId);

                    if (!project.IsPublic)
                    {
                        foreach (var week in item.WeekTimeSheets)
                        {
                            var taskIds = new List <int>(week.Value.Keys);
                            foreach (var taskId in taskIds)
                            {
                                if (!project.Tasks.Select(o => o.Id).Contains(taskId))
                                {
                                    week.Value.Remove(taskId);
                                }
                            }
                        }

                        timeSheetService.Update(item);
                    }
                }
            }
        }
Example #22
0
        public UserOverviewHelper(BaseController controller, string userId, DateTime startDate, DateTime endDate)
        {
            if (string.IsNullOrEmpty(userId))
            {
                userId = controller.GetUserId();
            }

            userService       = controller.GetService <UserService>();
            departmentService = controller.GetService <DepartmentService>();
            timeSheetService  = controller.GetService <TimeSheetService>();
            projectService    = controller.GetService <ProjectService>();

            user = userService.Get(userId);

            //如果没有指定日期,就查本周的数据
            if (startDate.IsEmpty())
            {
                this.startDate = DateTimeUtil.GetCurrentMonday();
            }
            else
            {
                this.startDate = startDate;
            }

            if (endDate.IsEmpty())
            {
                this.endDate = DateTimeUtil.GetCurrentMonday().AddDays(6);
            }
            else
            {
                this.endDate = endDate;
            }

            this.controller = controller;
            this.userId     = userId;
        }
Example #23
0
        private async Task <bool> GetData()
        {
            List <TimeSheetInfo> result = await TimeSheetService.GetRecentTimeSheetInformation();

            viewModel.PastPeriods = new ObservableCollection <TimeSheetPeriod>();
            var settings = await TimeEntryService.Get();

            bool UseHoursMinutes = false;

            if (settings != null)
            {
                UseHoursMinutes = settings.UseHoursMinutesInput;
            }
            if (result != null && result.Count > 0)
            {
                lstAllPeriod.Children.Clear();

                for (int i = 0; i <= result.Count - 1; i++)
                {
                    var item = result[i];
                    if (i == 0)
                    {
                        viewModel.CurrentPeriod.StartDate           = item.StartDate;
                        viewModel.CurrentPeriod.EndDate             = item.EndDate;
                        viewModel.CurrentPeriod.ActualHours         = (item.ActualHoursNotOnTimeSheet ?? 0);
                        viewModel.CurrentPeriod.ActualHoursFormated = string.IsNullOrEmpty(item.ActualHoursNotOnTimeSheetFormattedString) ? (UseHoursMinutes ? "00:00" : "0") : item.ActualHoursNotOnTimeSheetFormattedString;
                        viewModel.CurrentPeriod.Status           = 0;
                        viewModel.CurrentPeriod.TimeEntries      = item.TimeSheet != null ? item.TimeSheet.TimeEntries : null;
                        viewModel.CurrentPeriod.ShowSubmitButton = true;
                        //viewModel.CurrentPeriod.Name = "";
                        if (item.AllTimeSheetsForPeriod != null && item.AllTimeSheetsForPeriod.Count > 0)
                        {
                            foreach (var ts in item.AllTimeSheetsForPeriod)
                            {
                                AddTimeSheet(ts);
                            }
                        }
                    }
                    else
                    {
                        AddPreviousTimeSheets(item);
                    }
                }


                if (viewModel.PastPeriods == null || viewModel.PastPeriods.Count() == 0)
                {
                    lblNoPreviousRecords.IsVisible = true;
                }
                else
                {
                    lblNoPreviousRecords.IsVisible = false;
                }

                int count = 0;
                foreach (var item in viewModel.PastPeriods)
                {
                    count++;

                    if (count == viewModel.PastPeriods.Count)
                    {
                        PreviousPeriods_GeneratedRows(item, true);
                    }
                    else
                    {
                        PreviousPeriods_GeneratedRows(item);
                    }
                }
            }
            return(true);
        }
Example #24
0
        //private readonly IExtendedService<TimeSheetHours> timeSheetHoursService;

        // Inject Dependent Object
        // This DI Object will play roles relevant to DB connected
        public TimeSheetController(TimeSheetService timeSheetService)
        {
            this.timeSheetService = timeSheetService;
            //this.timeSheetHoursService = timeSheetHoursService;
        }
Example #25
0
 public TimeSheetServiceTest()
 {
     mockTimeSheetRepository = new Mock <ITimeSheetRepository>();
     timeSheetService        = new TimeSheetService(mockTimeSheetRepository.Object);
 }
        private async void LoadData()
        {
            viewModel.VisibleLoad = true;

            viewModel.CurrentPeriod = tsp;
            if (IsCurrent)
            {
                List <TimeSheetInfo> result = await TimeSheetService.GetRecentTimeSheetInformation();

                var settings = await TimeEntryService.Get();

                bool UseHoursMinutes = false;
                if (settings != null)
                {
                    UseHoursMinutes = settings.UseHoursMinutesInput;
                }
                if (result != null && result.Count > 0)
                {
                    lstAllPeriod.Children.Clear();
                    viewModel.CurrentPeriod = new TimeSheetPeriod();
                    for (int i = 0; i <= result.Count - 1; i++)
                    {
                        var item = result[i];
                        if (i == 0)
                        {
                            viewModel.CurrentPeriod.StartDate           = item.StartDate;
                            viewModel.CurrentPeriod.EndDate             = item.EndDate;
                            viewModel.CurrentPeriod.ActualHours         = (item.ActualHoursNotOnTimeSheet ?? 0);
                            viewModel.CurrentPeriod.ActualHoursFormated = string.IsNullOrEmpty(item.ActualHoursNotOnTimeSheetFormattedString) ? (UseHoursMinutes ? "00:00" : "0") : item.ActualHoursNotOnTimeSheetFormattedString;
                            viewModel.CurrentPeriod.Status           = 0;
                            viewModel.CurrentPeriod.TimeEntries      = item.TimeSheet != null ? item.TimeSheet.TimeEntries : null;
                            viewModel.CurrentPeriod.ShowSubmitButton = true;

                            viewModel.CurrentPeriod.RequiresApprovalFromCurrentUser = false;
                            var timeEntries = TimeEntryService.client.GetByUserUnsubmittedForDateRange(viewModel.CurrentPeriod.StartDate, viewModel.CurrentPeriod.EndDate, modelProperties: new ProjectInsight.Models.Base.ModelProperties("default,Name,Task_Id,ToDo_Id,Issue_Id,Company_Id"));
                            viewModel.TimeEntries = timeEntries;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                if (viewModel.CurrentPeriod != null)
                {
                    if (viewModel.CurrentPeriod.TimeSheetId.HasValue)
                    {
                        try
                        {
                            var ts = await TimeSheetService.client.GetAsync(viewModel.CurrentPeriod.TimeSheetId.Value, new ProjectInsight.Models.Base.ModelProperties(
                                                                                "default,UserApprover,ApprovalStatusDescription,RequiresApprovalFromCurrentUser,User,TimeEntries;TimeEntry:default,Name,Task_Id,ToDo_Id,Issue_Id,Company_Id;User:default,Photo,PhotoUrl,PhotoMediumUrl,PhotoThumbnailUrl,AvatarHtml"));

                            viewModel.TimeEntries        = ts.TimeEntries;
                            viewModel.CurrentPeriod.Name = ts.User.FirstName + " " + ts.User.LastName;
                            viewModel.CurrentPeriod.RequiresApprovalFromCurrentUser = ts.RequiresApprovalFromCurrentUser ?? false;
                            viewModel.CurrentPeriod.ActualHoursFormated             = ts.ActualHoursFormattedString;
                            viewModel.timeSheet = ts;

                            viewModel.ShowStatus = true;
                            int status = ts.ApprovalStatus ?? 0;
                            //----------------------
                            if (status == 5)
                            {
                                statusIcon.Source = "approved"; // "timesheet_approved.png";
                            }
                            else if (status == 6)
                            {
                                statusIcon.Source = "rejected";//"timesheet_rejected.png";
                            }
                            else
                            {
                                statusIcon.Source = "pending"; //"timesheet_pending.png";
                            }
                            slAvatar.Children.Clear();
                            if (string.IsNullOrEmpty(ts.UserApprover.PhotoUrl))
                            {
                                if (!string.IsNullOrEmpty(ts.UserApprover.AvatarHtml))
                                {
                                    string userHTML = ts.UserApprover.AvatarHtml;
                                    //"<div class=\"user-avatar\" title=\"Gjoko Veljanoski\" style=\"background-color:#00bfff\">GV</div>"
                                    //<img class="user-avatar" src="/ProjectInsight.WebApp/Sites/Files/a222e57233a14e15ab67d25e6dbab95e/UserPhotos/6fcc5602c49043c3a2d8d39175040e68/tn_avatar.png" alt="Gjoko Veljanoski" title="Gjoko Veljanoski" />
                                    string       myDiv = ts.UserApprover.AvatarHtml;
                                    HtmlDocument doc   = new HtmlDocument();
                                    doc.LoadHtml(myDiv);
                                    HtmlNode node           = doc.DocumentNode.SelectSingleNode("div");
                                    string   AvatarInitials = "US";
                                    string   AvatarColor    = "#fff";
                                    string   PhotoURL       = string.Empty;

                                    if (node != null)
                                    {
                                        AvatarInitials = (node.ChildNodes[0]).OuterHtml;
                                        foreach (HtmlAttribute attr in node.Attributes)
                                        {
                                            if (attr.Name.ToLower() == "style")
                                            {
                                                string[] parts = attr.Value.Split('#');
                                                if (parts != null && parts.Length > 1)
                                                {
                                                    AvatarColor = parts[1];
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        HtmlNode node2 = doc.DocumentNode.SelectSingleNode("img");
                                        if (node2 != null)
                                        {
                                            foreach (HtmlAttribute attr in node2.Attributes)
                                            {
                                                if (attr.Name.ToLower() == "src")
                                                {
                                                    string imageUrl = attr.Value.Replace("/ProjectInsight.WebApp", "");
                                                    PhotoURL = Common.CurrentWorkspace.WorkspaceURL + imageUrl;
                                                }
                                            }
                                        }
                                    }

                                    if (string.IsNullOrEmpty(PhotoURL))
                                    {
                                        slAvatar.BackgroundColor = Color.FromHex(AvatarColor);

                                        Label lbInitials = new Label();
                                        lbInitials.HeightRequest           = 50;
                                        lbInitials.WidthRequest            = 50;
                                        lbInitials.HorizontalOptions       = LayoutOptions.CenterAndExpand;
                                        lbInitials.VerticalOptions         = LayoutOptions.CenterAndExpand;
                                        lbInitials.HorizontalTextAlignment = TextAlignment.Center;
                                        lbInitials.VerticalTextAlignment   = TextAlignment.Center;
                                        lbInitials.TextColor = Color.White;
                                        lbInitials.Text      = AvatarInitials;
                                        lbInitials.FontSize  = 26;
                                        if (Device.RuntimePlatform.ToLower() == "android")
                                        {
                                            lbInitials.FontFamily = "OpenSans-SemiBold.ttf#Open Sans";
                                        }
                                        else
                                        {
                                            lbInitials.FontFamily = "OpenSans-SemiBold";
                                        }
                                        slAvatar.Children.Add(lbInitials);
                                    }
                                    else
                                    {
                                        Image photo = new Image();
                                        photo.Source            = ImageSource.FromUri(new Uri(Common.CurrentWorkspace.WorkspaceURL + ts.UserApprover.PhotoUrl));
                                        photo.HeightRequest     = 50;
                                        photo.WidthRequest      = 50;
                                        photo.HorizontalOptions = LayoutOptions.CenterAndExpand;
                                        photo.VerticalOptions   = LayoutOptions.CenterAndExpand;
                                        slAvatar.Children.Add(photo);
                                    }
                                    slStatus.Children.Add(slAvatar);
                                }
                            }
                            else
                            {
                                Image photo = new Image();
                                photo.Source        = ImageSource.FromUri(new Uri(Common.CurrentWorkspace.WorkspaceURL + ts.UserApprover.PhotoUrl));
                                photo.HeightRequest = 50;
                                photo.WidthRequest  = 50;
                                //photo.HorizontalOptions = LayoutOptions.CenterAndExpand;
                                photo.VerticalOptions = LayoutOptions.CenterAndExpand;
                                slAvatar.Children.Add(photo);
                            }
                            //----------------------
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                    else
                    {
                        try
                        {
                            viewModel.CurrentPeriod.RequiresApprovalFromCurrentUser = false;
                            var timeEntries = TimeEntryService.client.GetByUserUnsubmittedForDateRange(viewModel.CurrentPeriod.StartDate, viewModel.CurrentPeriod.EndDate, modelProperties: new ProjectInsight.Models.Base.ModelProperties("default,Name,Task_Id,ToDo_Id,Issue_Id,Company_Id"));
                            viewModel.TimeEntries = timeEntries;
                            //viewModel.CurrentPeriod.ShowSubmitButton = true;
                            slCreateTimeEntry.IsVisible = false;
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                else
                {
                    if (tId != null)
                    {
                        viewModel.CurrentPeriod = new TimeSheetPeriod();
                        var ts = TimeSheetService.client.Get(tId, new ProjectInsight.Models.Base.ModelProperties("default,RequiresApprovalFromCurrentUser,User,TimeEntries;TimeEntry:default,Name,Task_Id,ToDo_Id,Issue_Id,Company_Id;User:FirstName,LastName;"));
                        viewModel.CurrentPeriod.Name = ts.User.FirstName + " " + ts.User.LastName;
                        viewModel.CurrentPeriod.RequiresApprovalFromCurrentUser = ts.RequiresApprovalFromCurrentUser ?? false;
                        viewModel.CurrentPeriod.TimeSheetId         = ts.Id;
                        viewModel.CurrentPeriod.StartDate           = ts.StartDate.Value;
                        viewModel.CurrentPeriod.EndDate             = ts.EndDate.Value;
                        viewModel.CurrentPeriod.ActualHours         = ts.ActualHours;
                        viewModel.CurrentPeriod.ActualHoursFormated = ts.ActualHoursFormattedString;
                        viewModel.CurrentPeriod.Status      = ts.ApprovalStatus;
                        viewModel.CurrentPeriod.TimeEntries = ts.TimeEntries;
                        viewModel.CurrentPeriod.User_Id     = ts.User_Id;
                        viewModel.timeSheet   = ts;
                        viewModel.TimeEntries = ts.TimeEntries;

                        if (viewModel.CurrentPeriod.ShowPendingApprovalIcon && viewModel.CurrentPeriod.User_Id == Common.CurrentWorkspace.UserID)
                        {
                            ToolbarItems.Add(new ToolbarItem()
                            {
                                Text = "", Icon = "unsubmit_icon.png", Command = new Command(this.btnDeleteTimesheet_Clicked)
                            });
                        }
                    }
                }
            }
            if (viewModel.TimeEntries != null && viewModel.TimeEntries.Count > 0)
            {
                GenerateTimeEntryGrid();
            }

            viewModel.VisibleLoad = false;
        }
        public ActionResult Index()

        {
            List <DashboardViewModel> dashboardItems = new List <DashboardViewModel>();
            List <DashboardViewModel> items          = new List <DashboardViewModel>();
            var viewModel = new DashboardViewModels();

            SupportService   supportService   = new SupportService();
            TimeSheetService timesheetService = new TimeSheetService();
            ExpenseService   expenseService   = new ExpenseService();
            LOAService       loaService       = new LOAService();

            var roles = ((ClaimsIdentity)User.Identity).Claims
                        .Where(c => c.Type == ClaimTypes.Role)
                        .Select(c => c.Value);

            if (roles.Contains("TimeSheetAdmin"))
            {
                viewModel.AdminPendingExpensesCount   = expenseService.GetPendingExpensesCount();
                viewModel.AdminPendingLOAsCount       = loaService.GetPendingLOAsCount();
                viewModel.AdminPendingTimesheetsCount = timesheetService.GetPendingTimesheetsCount();

                //    viewModel.DasboardList.AddRange(ExpenseModuleAdmin());
            }
            else if (roles.Contains("TimeSheetManager"))
            {
                viewModel.ManagerPendingTimesheetsCount = timesheetService.GetPendingTimesheetsCount();
                viewModel.MangerPendingExpensesCount    = expenseService.GetPendingExpensesCount();
                viewModel.MangerPendingLOAsCount        = loaService.GetPendingLOAsCount();
                //    viewModel.DasboardList.AddRange(TimeSheetModuleManager());
                //    viewModel.DasboardList.AddRange(LOAModuleManager());
                //    items.AddRange(ExpenseModuleManager());
            }

            if (roles.Contains("TimeSheetReportingManager"))
            {
                viewModel.ReportingManagerPendingExpensesCount   = expenseService.GetPendingExpensesCount(User.Identity.GetUserId());
                viewModel.ReportingManagerPendingLOAsCount       = loaService.GetPendingLOAsCount(User.Identity.GetUserId());
                viewModel.ReportingManagerPendingTimesheetsCount = timesheetService.GetPendingTimesheetsCount(User.Identity.GetUserId());
                //    viewModel.DasboardList.AddRange(TimeSheetModuleReportingManager());
                //    viewModel.DasboardList.AddRange(LOAModuleReportingManager());
                //    viewModel.DasboardList.AddRange(ExpenseModuleReportingManager());
            }

            if (roles.Contains("SupportUser"))
            {
                //viewModel.DasboardList.AddRange(SupportModuleUserPendingRequest());
                //viewModel.DasboardList.AddRange(SupportModuleUserDoneRequest());
                //viewModel.DasboardList.AddRange(SupportModuleUserClosedRequest());
                viewModel.MyPendingRequestsCount = supportService.GetMyPendingRequestsCount(User.Identity.GetUserId());
                viewModel.MyClosedRequestsCount  = supportService.GetMyClosedRequestsCount(User.Identity.GetUserId());
                viewModel.MyDoneRequestsCount    = supportService.GetMyDoneRequestsCount(User.Identity.GetUserId());
            }



            //viewModel.DasboardList.AddRange(items);

            //dashboardItems.AddRange(items);

            return(View(viewModel));
        }
Example #28
0
        public static void UpdateProject(TimeSheetService timeSheetService, ProjectService projectService, List <Project> projects = null)
        {
            if (projects.IsEmpty())
            {
                projects = projectService.Get();
            }

            foreach (var project in projects)
            {
                if (project.IsPublic)
                {
                    continue;
                }

                var timeSheets = timeSheetService.Get(o => o.ProjectId == project.Id);

                project.ActualHours = new Dictionary <string, double>();

                //更新总时间
                foreach (var item in timeSheets)
                {
                    project.ActualHours.Add(item.UserId, item.GetTotalHours());
                }

                //更新Task
                foreach (var task in project.Tasks)
                {
                    var timeSheet = timeSheets.Where(o => o.UserId == task.UserId).FirstOrDefault();

                    //为空,则任务为初始状态
                    if (timeSheet == null)
                    {
                        task.Status          = Status.Pending;
                        task.ActualHour      = 0;
                        task.ActualDateRange = new DateRange();
                    }
                    else
                    {
                        task.ActualHour = timeSheet.GetTaskHours(task.Id);

                        if (task.Status == Status.Done)
                        {
                            task.ActualDateRange.StartDate = timeSheet.GetTaskStartDate(task.Id);
                            task.ActualDateRange.EndDate   = timeSheet.GetTaskEndDate(task.Id);
                        }
                        else
                        {
                            if (task.ActualHour > 0)
                            {
                                task.Status = Status.Ongoing;
                                task.ActualDateRange.StartDate = timeSheet.GetTaskStartDate(task.Id);
                                task.ActualDateRange.EndDate   = DateTime.MinValue;
                            }
                            else
                            {
                                task.Status = Status.Pending;
                                task.ActualDateRange.StartDate = DateTime.MinValue;
                                task.ActualDateRange.EndDate   = DateTime.MinValue;
                            }
                        }
                    }
                }

                project.UpdateProjectStatus();
                project.UpdateProjectActualTime();
                projectService.Update(project);
            }
        }