示例#1
0
        public async Task <IActionResult> Index([FromRoute(Name = "week-id")] int weekid,
                                                [FromRoute(Name = "employee-id")] int employeeId,
                                                [FromRoute(Name = "job-id")] int jobId,
                                                [FromRoute(Name = "task-id")] int taskId)
        {
            var currentUserId = await _sessionAdapter.EmployeeIdAsync();

            if (!User.IsInRole(UserRoleName.Admin) && employeeId != currentUserId)
            {
                var msg = "You are not allowed to edit another users effort selection.";
                return(CreateErrorResponse(msg));
            }

            var removeResult = await _removeRowCommand.RemoveRow(employeeId, weekid, taskId, jobId);

            if (removeResult.Successful)
            {
                NotificationsController.AddNotification(User.SafeUserName(), "The selected effort was removed.");
                return(new ObjectResult(new ApiResult <string>()
                {
                    Data = "The selected effort was removed."
                })
                {
                    StatusCode = StatusCodes.Status200OK
                });
            }
            else
            {
                return(CreateErrorResponse(string.Join(", ", removeResult.Errors)));
            }
        }
示例#2
0
        public async Task <ActionResult> NewEmployee(CreateEmployeeViewModel employee)
        {
            if (ModelState.IsValid)
            {
                var res = await createEmployeeCommand.Create(employee);

                if (res.Successful)
                {
                    NotificationsController.AddNotification(this.User.SafeUserName(), $"{employee.Email} has been created.");
                    return(RedirectToAction(nameof(NewEmployee)));
                }
                else
                {
                    foreach (var err in res.Errors)
                    {
                        ModelState.AddModelError(string.Empty, err);
                    }
                }
            }

            employee.AvailableJobs = await jobService.GetAsync();

            employee.AvailableRoles = await employeeService.GetAllRoles();

            return(View("NewEmployee", employee));
        }
        public async void AddNotification_ReturnsCreatedAtRouteResult_WithNotificationData()
        {
            //Arrange
            _mockUserService.Setup(Service => Service.CheckIfUserExists(It.IsAny <Guid>()))
            .ReturnsAsync(true)
            .Verifiable();

            _mockNotificationService.Setup(Service => Service.AddNotificationAsync(It.IsAny <Guid>(), It.IsAny <NotificationToAddDto>()))
            .ReturnsAsync(_mapper.Map <NotificationDto>(_notificationToAdd))
            .Verifiable();

            var controller = new NotificationsController(_loggerMock.Object, _mockNotificationService.Object, _mockUserService.Object);

            //Act
            var result = await controller.AddNotification(ConstIds.ExampleUserId, _notificationToAdd);

            //Assert
            var redirectToActionResult = Assert.IsType <CreatedAtRouteResult>(result.Result);

            Assert.Equal(ConstIds.ExampleUserId, redirectToActionResult.RouteValues["userId"].ToString());
            Assert.NotNull(redirectToActionResult.RouteValues["notificationId"].ToString());
            Assert.Equal("GetNotification", redirectToActionResult.RouteName);
            _mockUserService.Verify();
            _mockNotificationService.Verify();
        }
示例#4
0
        public async Task <ActionResult> EditClient(ClientModel client)
        {
            await _clientRepository.Save(_mapper.Map <ClientDTO>(client));

            NotificationsController.AddNotification(this.User.SafeUserName(), $"{client.ClientName} was updated");
            return(RedirectToAction(nameof(ListClients)));
        }
示例#5
0
        public async Task <ActionResult> CloseJob(int id)
        {
            var job = await _jobsRepository.GetForJobId(id);

            job.CoreInfo.JobStatusId = JobStatus.Archived;
            await _jobsRepository.Update(job.CoreInfo);

            NotificationsController.AddNotification(User.Identity.Name, $"Job {job.CoreInfo.FullJobCodeWithName} has been closed");
            return(RedirectToAction(nameof(List)));
        }
示例#6
0
        public async System.Threading.Tasks.Task <ActionResult> AddJobForCurrentUser(int id)
        {
            var me = await _employeeRepository.GetSingleEmployeeAsync(User.Identity.Name);

            me.AssignJobs.Add(id);
            _employeeRepository.Save(me);
            var employeeName = User.Identity.Name;

            NotificationsController.AddNotification(User.Identity.Name, "Job Added");
            return(RedirectToAction(nameof(List)));
        }
示例#7
0
        public async Task <IActionResult> DeleteExpense([FromRoute(Name = "expense-id")] Guid expenseId)
        {
            var temp = await deleteExpenditure.Process(new DeleteExpenditureRequest(expenseId));

            if (temp.Success != null)
            {
                NotificationsController.AddNotification(this.User.SafeUserName(), "Expenditure deleted");
            }

            return(temp.AsApiResult());
        }
        public async void AddNotification_ReturnsBadRequestObjectResult_WhenTheUserIdIsInvalid()
        {
            //Arrange
            var controller = new NotificationsController(_loggerMock.Object, _mockNotificationService.Object, _mockUserService.Object);

            //Act
            var result = await controller.AddNotification(ConstIds.InvalidGuid, _notificationToAdd);

            //Assert
            var badRequestObjectResult = Assert.IsType <BadRequestObjectResult>(result.Result);

            Assert.Equal($"{ConstIds.InvalidGuid} is not valid guid.", badRequestObjectResult.Value);
        }
示例#9
0
 public ActionResult Create(ClientModel client)
 {
     try
     {
         _clientRepository.Save(_mapper.Map <ClientDTO>(client));
         NotificationsController.AddNotification(this.User.SafeUserName(), $"{client.ClientName} has been created.");
         return(RedirectToAction(nameof(Create)));
     }
     catch
     {
         return(View("CreateClient"));
     }
 }
示例#10
0
 public ActionResult Create(SiteDTO client)
 {
     try
     {
         siteService.Create(client);
         NotificationsController.AddNotification(this.User.SafeUserName(), $"{client.SiteName} has been created.");
         return(RedirectToAction(nameof(Create)));
     }
     catch
     {
         return(View());
     }
 }
示例#11
0
        public async System.Threading.Tasks.Task <ActionResult> RemoveJobForCurrentUser(int id)
        {
            var me = await _employeeRepository.GetSingleEmployeeAsync(User.Identity.Name);

            if (me.AssignJobs.Contains(id))
            {
                me.AssignJobs.Remove(id);
            }
            _employeeRepository.Save(me);

            NotificationsController.AddNotification(User.SafeUserName(), $"Removed from my jobs");
            return(RedirectToAction(nameof(List)));
        }
示例#12
0
        public async System.Threading.Tasks.Task <ActionResult> Edit(EditJobViewModel model)
        {
            var jobSaved = (await _jobsRepository.GetAsync()).Single(x => x.JobId == model.Job.JobId);

            jobSaved.JobName     = model.Job.JobName;
            jobSaved.TargetHours = model.Job.TargetHours;
            jobSaved.JobStatusId = (JobStatus)model.SelectedJobStatusId;
            jobSaved.ProjectManagerEmployeeId = model.SelectedProjectManagerEmployeeId;
            jobSaved.ClientId = model.SelectedClientId;
            jobSaved.SiteId   = model.SelectedSiteId;
            jobSaved.JobCode  = model.Job.JobCode;
            await _jobsRepository.Update(jobSaved);

            NotificationsController.AddNotification(User.SafeUserName(), $"Updated {jobSaved.FullJobCodeWithName}");
            return(RedirectToAction(nameof(Index)));
        }
示例#13
0
        public async Task <IActionResult> SaveExpense([FromForm] ExpenseViewModel model)
        {
            var saved = false;

            switch (model.ExpenseType)
            {
            case ExpenditureTypeEnum.ArcFlashLabelExpenditure:
                var afl = await updateArcFlashLabelExpenditure.Process(new UpdateArcFlashLabelExpenditureMessage(model.ArcFlashLabelExpenditure.Detail, model.ArcFlashLabelExpenditure.Detail.Id));

                saved = afl.Success != null;
                break;

            case ExpenditureTypeEnum.MiscExpenditure:
                var misc = await updateMiscExpenditure.Process(new UpdateMiscExpenditureMessage(model.MiscExpenditure.Detail, model.MiscExpenditure.Detail.Id));

                saved = misc.Success != null;
                break;

            case ExpenditureTypeEnum.ContractorExpenditure:
                var ce = await updateContractorExpenditure.Process(new UpdateContractorMessage(model.ContractorExpenditure.Detail, model.ContractorExpenditure.Detail.ExternalId));

                saved = ce.Success != null;
                break;

            case ExpenditureTypeEnum.TimeAndExpenceExpenditure:
                var te = await updateTimeAndExpenseExpenditure.Process(new UpdateTimeAndExpenseExpenditureMessage(model.TimeAndExpenceExpenditure.Detail, model.TimeAndExpenceExpenditure.Detail.Id));

                saved = te.Success != null;
                break;

            case ExpenditureTypeEnum.CompanyVehicleExpenditure:
                var cv = await updateCompanyVehicleExpenditure.Process(new UpdateCompanyVehicleExpenditureMessage(model.CompanyVehicleExpenditure.Detail, model.CompanyVehicleExpenditure.Detail.ExternalId));

                saved = cv.Success != null;
                break;

            default:
                throw new NotImplementedException();
            }

            if (saved)
            {
                NotificationsController.AddNotification(this.User.SafeUserName(), $"Expenditure Saved");
            }

            return(RedirectToAction(nameof(ExpenseList)));
        }
        public async void AddNotification_ReturnsInternalServerErrorResult_WhenExceptionThrownInService()
        {
            //Arrange
            _mockUserService.Setup(Service => Service.CheckIfUserExists(It.IsAny <Guid>()))
            .Throws(new ArgumentNullException(nameof(Guid)))
            .Verifiable();

            var controller = new NotificationsController(_loggerMock.Object, _mockNotificationService.Object, _mockUserService.Object);

            //Act
            var result = await controller.AddNotification(ConstIds.ExampleUserId, _notificationToAdd);

            //Assert
            var internalServerErrorResult = Assert.IsType <StatusCodeResult>(result.Result);

            Assert.Equal(StatusCodes.Status500InternalServerError, internalServerErrorResult.StatusCode);
            _mockUserService.Verify();
        }
        public async void AddNotification_ReturnsNotFoundObjectResult_WhenTheUserDoesntExist()
        {
            //Arrange
            _mockUserService.Setup(Service => Service.CheckIfUserExists(It.IsAny <Guid>()))
            .ReturnsAsync(false)
            .Verifiable();

            var controller = new NotificationsController(_loggerMock.Object, _mockNotificationService.Object, _mockUserService.Object);

            //Act
            var result = await controller.AddNotification(ConstIds.ExampleUserId, _notificationToAdd);

            //Assert
            var notFoundObjectResult = Assert.IsType <NotFoundObjectResult>(result.Result);

            Assert.Equal($"User: {ConstIds.ExampleUserId} not found.", notFoundObjectResult.Value);
            _mockUserService.Verify();
        }
示例#16
0
        public async Task <ActionResult> Save(TaskViewModel submittedTask)
        {
            var vm = await GetViewModel();

            var category      = vm.AllTaskCategories.Single(x => x.Id == submittedTask.SelectedCategory);
            var usageStatus   = vm.AllUsageStatusOptions.Single(x => x.Id == submittedTask.SelectedUsageStatus);
            var reportingType = vm.AllTaskReportingTypes.Single(x => x.Id == submittedTask.SelectedTaskReportingType);

            var allTasks = (await taskService.GetTasks()).ToList();
            var isBadCreateLegacyCode = submittedTask.IsInCreateModel &&
                                        allTasks.Any(x => x.LegacyCode == submittedTask.Task.LegacyCode);
            var isBadUpdateLegacyCode = !submittedTask.IsInCreateModel &&
                                        allTasks.Any(x => x.LegacyCode == submittedTask.Task.LegacyCode && x.TaskId != submittedTask.Task.TaskId);

            if (isBadCreateLegacyCode || isBadUpdateLegacyCode)
            {
                vm.SelectedCategory          = submittedTask.SelectedCategory;
                vm.SelectedUsageStatus       = submittedTask.SelectedUsageStatus;
                vm.SelectedTaskReportingType = submittedTask.SelectedTaskReportingType;
                vm.Task.LegacyCode           = submittedTask.Task.LegacyCode;
                vm.Task.Name = submittedTask.Task.Name;
                ModelState.Clear();
                ModelState.AddModelError("", $"The supplied task code ({submittedTask.Task.LegacyCode}) is already in use");
                return(View("TaskDetail", vm));
            }
            else
            {
                await taskService.Upsert(new TaskDTO()
                {
                    Description   = submittedTask.Task.Description,
                    Name          = submittedTask.Task.Name,
                    Category      = category,
                    LegacyCode    = submittedTask.Task.LegacyCode,
                    UsageStatus   = usageStatus,
                    TaskId        = submittedTask.Task.TaskId,
                    ReportingType = reportingType
                });

                NotificationsController.AddNotification(User.SafeUserName(), $"{submittedTask.Task.Name} has been saved");
                return(RedirectToAction("List", "Task"));
            }
        }
示例#17
0
        public async Task <IActionResult> SetTimeForEffort([FromBody] Dictionary <DayOfWeek, Day> saveRequest,
                                                           [FromRoute(Name = "week-id")] int weekid,
                                                           [FromRoute(Name = "employee-id")] int employeeId,
                                                           [FromRoute(Name = "job-id")] int jobId,
                                                           [FromRoute(Name = "task-id")] int taskId)
        {
            var currentUserId = await _sessionAdapter.EmployeeIdAsync();

            if (!User.IsInRole(UserRoleName.Admin) && employeeId != currentUserId)
            {
                var msg = "You are not allowed to edit another users effort selection.";
                return(CreateErrorResponse(msg));
            }

            var currentTime = await _weekOfTimeEntriesQuery.GetFullTimeEntryViewModelAsync(new WeekOfTimeEntriesRequest()
            {
                EmployeeId            = employeeId,
                RequestingUserIsAdmin = User.IsInRole(UserRoleName.Admin),
                RequestingUserName    = User.SafeUserName(),
                WeekId = weekid
            });

            var rowToChange = currentTime.TimeEntryRow.FirstOrDefault(x => x.SelectedJobId == jobId & x.SelectedTaskId == taskId);

            foreach (var day in rowToChange.AllDays())
            {
                day.Hours         = saveRequest[day.DayOfWeek].Hours;
                day.OvertimeHours = saveRequest[day.DayOfWeek].OvertimeHours;
            }

            var addResult = await _saveTimeEntriesCommand.SaveTimeEntriesAsync(employeeId, weekid, currentTime);

            if (addResult.Successful)
            {
                NotificationsController.AddNotification(User.SafeUserName(), "Time saved");
                return(new StatusCodeResult(StatusCodes.Status200OK));
            }
            else
            {
                return(CreateErrorResponse(string.Join(", ", addResult.Errors)));
            }
        }
示例#18
0
        public async Task <IActionResult> Index([FromBody] NewEffort effort, [FromRoute(Name = "week-id")] int weekid, [FromRoute(Name = "employee-id")] int employeeId)
        {
            var currentUserId = await _sessionAdapter.EmployeeIdAsync();

            if (!User.IsInRole(UserRoleName.Admin) && employeeId != currentUserId)
            {
                var msg = "You are not allowed to edit another users effort selection.";
                return(CreateErrorResponse(msg));
            }

            var addResult = await _addNewJobTaskComboCommand.AddNewJobTaskCombo(employeeId, weekid, effort.SelectedTaskId, effort.SelectedJobId);

            if (addResult.Successful)
            {
                NotificationsController.AddNotification(User.SafeUserName(), "The selected task has been added.");
                return(new StatusCodeResult(StatusCodes.Status201Created));
            }
            else
            {
                return(CreateErrorResponse(string.Join(", ", addResult.Errors)));
            }
        }
示例#19
0
        private async Task <ActionResult> ReloadPageForErrorCorrection(int weekId, int employeeId, FullTimeEntryViewModel vm, Result res)
        {
            var req = new WeekOfTimeEntriesRequest()
            {
                EmployeeId            = employeeId,
                RequestingUserIsAdmin = User.IsInRole(UserRoleName.Admin),
                RequestingUserName    = User.Identity.Name,
                WeekId = weekId
            };
            var vmDefault = await weekOfTimeEntriesQuery.GetFullTimeEntryViewModelAsync(req);

            foreach (var day in vmDefault.TimeEntryRow)
            {
                var match = vm.TimeEntryRow.Single(x => x.RowId == day.RowId);

                day.Monday.Hours    = match.Monday.Hours;
                day.Tuesday.Hours   = match.Tuesday.Hours;
                day.Wednesday.Hours = match.Wednesday.Hours;
                day.Thursday.Hours  = match.Thursday.Hours;
                day.Friday.Hours    = match.Friday.Hours;
                day.Saturday.Hours  = match.Saturday.Hours;
                day.Sunday.Hours    = match.Sunday.Hours;

                day.Monday.OvertimeHours    = match.Monday.OvertimeHours;
                day.Tuesday.OvertimeHours   = match.Tuesday.OvertimeHours;
                day.Wednesday.OvertimeHours = match.Wednesday.OvertimeHours;
                day.Thursday.OvertimeHours  = match.Thursday.OvertimeHours;
                day.Friday.OvertimeHours    = match.Friday.OvertimeHours;
                day.Saturday.OvertimeHours  = match.Saturday.OvertimeHours;
                day.Sunday.OvertimeHours    = match.Sunday.OvertimeHours;
            }
            NotificationsController.AddNotification(User.SafeUserName(), $"Timesheet was not saved {string.Join("<br />", res.Errors)}");
            ModelState.Clear();
            foreach (var err in res.Errors)
            {
                ModelState.AddModelError("", err);
            }
            return(View("Week", vmDefault));
        }
示例#20
0
        public async Task <ActionResult> ApplyApproval(TimeApprovalModel request)
        {
            var req = new TimeApprovalRequest(
                approvingUserId: await sessionAdapter.EmployeeIdAsync(),
                approvingUserIsAdmin: User.IsInRole(UserRoleName.Admin),
                employeeId: request.EmployeeId,
                weekId: request.WeekId,
                newApprovalState: request.NewApprovalState
                );
            var res = await approveTimeCommand.ApplyApproval(req);

            if (res.Successful)
            {
                NotificationsController.AddNotification(this.User.SafeUserName(), $"Timesheet is {request.NewApprovalState}");
                return(Ok());
            }
            else
            {
                NotificationsController.AddNotification(this.User.SafeUserName(), $"{string.Join(",",res.Errors)}");
                return(Unauthorized());
            }
        }
示例#21
0
        public async Task <ActionResult> Create(CreateJobViewModel jobToCreate)
        {
            var clients = await clientRepository.GetAllClients();

            var sites = await siteRepository.GetAll();

            var mappedJob = jobToCreate.Job;
            var createDto = new CreateJobDto()
            {
                ClientId    = jobToCreate.SelectedClientId,
                JobCode     = jobToCreate.Job.JobCode,
                JobName     = jobToCreate.Job.JobName,
                JobStatusId = (JobStatus)jobToCreate.SelectedJobStatusId,
                ProjectManagerEmployeeId = jobToCreate.SelectedProjectManagerEmployeeId,
                SiteId      = jobToCreate.SelectedSiteId,
                TargetHours = jobToCreate.Job.TargetHours,
            };

            await _jobsRepository.Create(createDto);

            NotificationsController.AddNotification(User.SafeUserName(), $"Sucessfully created {jobToCreate.Job.FullJobCodeWithName}");
            return(RedirectToAction(nameof(Index)));
        }
示例#22
0
        public async Task <ActionResult> EditEmployee(EditEmployeeViewModel employee)
        {
            if (ModelState.IsValid)
            {
                var res = await updateEmployeeCommand.UpdateAsync(employee);

                if (res.Successful)
                {
                    NotificationsController.AddNotification(this.User.SafeUserName(), $"{employee.Email} has been updated.");
                    return(RedirectToAction(nameof(Edit), new { employee = employee.Email }));
                }
                else
                {
                    foreach (var err in res.Errors)
                    {
                        ModelState.AddModelError(string.Empty, err);
                    }
                }
            }

            employee.AvailableRoles = await employeeService.GetAllRoles();

            return(View("Edit", employee));
        }
示例#23
0
        public async Task <ActionResult> Save(int weekId, int employeeId, FullTimeEntryViewModel vm, string postType)
        {
            var currentUserId = await sessionAdapter.EmployeeIdAsync();

            if (!User.IsInRole(UserRoleName.Admin) && employeeId != currentUserId)
            {
                return(RedirectToAction("Index", new { weekId }));
            }

            if (postType == "Save" || postType == "Add Task" || postType == "Submit")
            {
                var res = await saveTimeEntriesCommand.SaveTimeEntriesAsync(employeeId, weekId, vm);

                if (res.Successful)
                {
                    NotificationsController.AddNotification(User.SafeUserName(), "Timesheet has been saved");
                }
                else
                {
                    return(await ReloadPageForErrorCorrection(weekId, employeeId, vm, res));
                }
            }

            if (postType == "Add Task")
            {
                var AddResult = await addNewJobTaskComboCommand.AddNewJobTaskCombo(employeeId, weekId, vm.NewEntry.SelectedTaskId ?? 0, vm.NewEntry.SelectedJobId ?? 0);

                if (AddResult.Successful)
                {
                    NotificationsController.AddNotification(User.SafeUserName(), "The selected task has been added.");
                }
                else
                {
                    NotificationsController.AddNotification(User.SafeUserName(), "Select task could not be added.");
                    return(await ReloadPageForErrorCorrection(weekId, employeeId, vm, AddResult));
                }
            }

            if (postType == "Copy Job/Tasks From Previous Week")
            {
                await copyPreviousWeekTimeCommand.CopyPreviousWeekTime(employeeId, weekId);
            }

            if (postType == "Submit")
            {
                var req = new TimeApprovalRequest(
                    approvingUserId: await sessionAdapter.EmployeeIdAsync(),
                    approvingUserIsAdmin: User.IsInRole(UserRoleName.Admin),
                    employeeId: employeeId,
                    newApprovalState: TimeApprovalStatus.Submitted,
                    weekId: weekId
                    );
                var res = await approveTimeCommand.ApplyApproval(req);

                NotificationsController.AddNotification(User.SafeUserName(), $"Timesheet is {TimeApprovalStatus.Submitted}");
            }

            if (postType == "Approve")
            {
                var req = new TimeApprovalRequest(
                    approvingUserId: await sessionAdapter.EmployeeIdAsync(),
                    approvingUserIsAdmin: User.IsInRole(UserRoleName.Admin),
                    employeeId: employeeId,
                    newApprovalState: TimeApprovalStatus.Approved,
                    weekId: weekId
                    );
                var res = await approveTimeCommand.ApplyApproval(req);

                NotificationsController.AddNotification(User.SafeUserName(), $"Timesheet is {TimeApprovalStatus.Submitted}");
            }

            if (postType == "Reject")
            {
                var req = new TimeApprovalRequest(
                    approvingUserId: await sessionAdapter.EmployeeIdAsync(),
                    approvingUserIsAdmin: User.IsInRole(UserRoleName.Admin),
                    employeeId: employeeId,
                    newApprovalState: TimeApprovalStatus.Rejected,
                    weekId: weekId
                    );
                var res = await approveTimeCommand.ApplyApproval(req);

                NotificationsController.AddNotification(User.SafeUserName(), $"Timesheet is {TimeApprovalStatus.Rejected}");
            }
            if (postType == "Save New Combination")
            {
                var rowId     = vm.SelectedRowId;
                var oldJobId  = int.Parse(rowId.Substring(0, rowId.IndexOf(".")));
                var oldTaskId = int.Parse(rowId.Substring(rowId.IndexOf(".") + 1));
                var res       = await modifyJobTaskComboCommand.ModifyJobTaskCombo(employeeId, weekId, vm.NewEntry.SelectedTaskId ?? 0, vm.NewEntry.SelectedJobId ?? 0, oldTaskId, oldJobId);
            }

            if (postType == "RemoveRow")
            {
                var rowId  = vm.SelectedRowId;
                var jobId  = rowId.Substring(0, rowId.IndexOf("."));
                var taskId = rowId.Substring(rowId.IndexOf(".") + 1);
                var res    = await removeRowCommand.RemoveRow(employeeId, weekId, int.Parse(taskId), int.Parse(jobId));
            }
            return(RedirectToAction(nameof(Edit), new { weekId = weekId, employeeId = employeeId }));
        }