public async Task <int> CreateJobStatusUpdate(JobStatusUpdate update)
        {
            update.AuthorName  = _currentUserService.GetUser().Name();
            update.AuthorEmail = _currentUserService.GetUser().Email();
            await _repairsContext.JobStatusUpdates.AddAsync(update);

            await _repairsContext.SaveChangesAsync();

            return(update.Id);
        }
        private async Task SetStatus(WorkOrder workOrder)
        {
            var user       = _currentUserService.GetUser();
            var authorised = await _authorizationService.AuthorizeAsync(user, workOrder, "RaiseSpendLimit");

            if (await _featureManager.IsEnabledAsync(FeatureFlags.SpendLimits) && !authorised.Succeeded)
            {
                workOrder.StatusCode = WorkStatusCode.PendingApproval;
            }
            else
            {
                workOrder.StatusCode = WorkStatusCode.Open;
            }
        }
示例#3
0
        public async Task Execute(JobStatusUpdate jobStatusUpdate)
        {
            if (!_currentUserService.HasGroup(UserGroups.ContractManager))
            {
                throw new UnauthorizedAccessException(Resources.InvalidPermissions);
            }

            WorkOrder workOrder = jobStatusUpdate.RelatedWorkOrder;

            workOrder.VerifyCanApproveVariation();

            var variationJobStatus = await _jobStatusUpdateGateway.GetOutstandingVariation(workOrder.Id);

            var authorised = await _authorizationService.AuthorizeAsync(_currentUserService.GetUser(), variationJobStatus, "VarySpendLimit");

            if (!authorised.Succeeded)
            {
                throw new UnauthorizedAccessException(Resources.VariationApprovalAboveSpendLimit);
            }

            await VaryWorkOrder(workOrder, variationJobStatus);

            jobStatusUpdate.Comments = $"{jobStatusUpdate.Comments} Approved By: {_currentUserService.GetHubUser().Name}";

            await _notifier.Notify(new VariationApproved(variationJobStatus, jobStatusUpdate));

            await _repairsGateway.SaveChangesAsync();
        }
示例#4
0
        public async Task Execute(JobStatusUpdate jobStatusUpdate)
        {
            WorkOrder workOrder = jobStatusUpdate.RelatedWorkOrder;

            workOrder.VerifyCanVary();

            var workElement = jobStatusUpdate.MoreSpecificSORCode;

            await AddCodeCosts(workElement.RateScheduleItem, workOrder.AssignedToPrimary?.ContractorReference);

            // check the user has the require vary spend limit
            var authorised = await _authorizationService.AuthorizeAsync(_currentUserService.GetUser(), jobStatusUpdate, "VarySpendLimit");

            if (await _featureManager.IsEnabledAsync(FeatureFlags.SpendLimits) && !authorised.Succeeded)
            {
                workOrder.StatusCode     = WorkStatusCode.VariationPendingApproval;
                jobStatusUpdate.TypeCode = JobStatusUpdateTypeCode.ContractManagerApprovalNeeded_180;
                await _notifier.Notify(new HighCostVariationCreated(workOrder));
            }
            else
            {
                await _updateSorCodesUseCase.Execute(workOrder, workElement.DeepClone());
            }

            jobStatusUpdate.PrefixComments(Resources.VariationReason);
        }
示例#5
0
        public async Task <IEnumerable <OperativeWorkOrderListItem> > Execute(OperativeWorkOrderSearch opSearch)
        {
            var loggedInUser = _currentUserService.GetUser();

            if (!string.Equals(loggedInUser.PayrollNumber(), opSearch.PayrollNumber, StringComparison.CurrentCultureIgnoreCase))
            {
                ThrowHelper.ThrowUnauthorizedAccessException("Only the operative can retrieve their list of work orders.");
            }

            var operativeDashActiveStatusCodes = Enum.GetValues(typeof(WorkStatusCode)).Cast <int>().ToList();

            operativeDashActiveStatusCodes.RemoveAll(c => c == (int)WorkStatusCode.Canceled ||
                                                     c == (int)WorkStatusCode.PendingApproval);

            _logger.LogInformation($"Searching for operative number {opSearch.PayrollNumber} work orders with statuses {string.Join(", ", operativeDashActiveStatusCodes.Select(x => x.ToString()))}");

            var searchParams = new WorkOrderSearchParameters
            {
                StartDate     = DateTime.Today,
                EndDate       = DateTime.Today.AddDays(1),
                OperativePRNs = new List <string>
                {
                    opSearch.PayrollNumber
                },
                StatusCode = operativeDashActiveStatusCodes,
                PageSize   = opSearch.PageSize
            };
            var workOrders = await _listWorkOrdersUseCase.Execute(searchParams);

            if (!workOrders.Any())
            {
                _logger.LogWarning($"Search for work orders for operative {opSearch.PayrollNumber} did not find anything");
            }
            else
            {
                _logger.LogInformation($"{workOrders.Count()} work orders for operative {opSearch.PayrollNumber}: [${string.Join(", ", workOrders.Select(w => w.Id.ToString()))}]");
            }

            DateTime earliestAppointementDate = GetEarliestAppointmentFromWorkOrders(workOrders);

            var excludedWorkOrders = workOrders.Where(wo =>
                                                      (wo.StatusCode == WorkStatusCode.Complete && wo.ClosedDate.Value.Date < earliestAppointementDate.Date ||
                                                       wo.StatusCode == WorkStatusCode.NoAccess && wo.ClosedDate.Value.Date < earliestAppointementDate.Date
                                                      ));

            workOrders = workOrders
                         .Except(excludedWorkOrders);

            workOrders = workOrders.OrderBy(wo => wo.Appointments.Min(a => a.StartTime));

            return(workOrders.Select(wo => wo.ToOperativeListItem()));
        }
        public async Task <int> CreateWorkOrderCompletion(WorkOrderComplete completion)
        {
            var user = _currentUserService.GetUser();

            completion.JobStatusUpdates.ForEach(jsu =>
            {
                jsu.AuthorName  = user.Name();
                jsu.AuthorEmail = user.Email();
            });

            _repairsContext.WorkOrderCompletes.Add(completion);
            await _repairsContext.SaveChangesAsync();

            return(completion.Id);
        }
示例#7
0
        private async Task <List <EntityEventSns> > CreateMessages(WorkOrder workOrder, IEnumerable <WorkOrderTask> tasks)
        {
            var user               = _currentUserService.GetUser();
            var totalSMV           = tasks is null ? 0 : tasks.Sum(t => t.StandardMinuteValue * t.Quantity);
            var totalOperativeCost = tasks is null ? 0 : tasks.Sum(t => t.OperativeCost * t.Quantity);
            var isOutOfHours       = tasks is null ? false : tasks.All(t => t.IsOutofhours);

            var msgs = new List <EntityEventSns>();

            foreach (var operative in workOrder.WorkOrderOperatives)
            {
                var op = await _operativesGateway.GetByIdAsync(operative.OperativeId);

                msgs.Add(new EntityEventSns
                {
                    Id           = Guid.NewGuid(),
                    EventType    = RepairsEventTypes.WorkOrderUpdatedEvent,
                    SourceDomain = "Repairs",
                    SourceSystem = "RepairsApi",
                    Version      = RepairsEventVersions.V2,
                    DateTime     = DateTime.UtcNow,
                    User         = new User
                    {
                        Name  = user.Claims.First(c => c.Type == ClaimTypes.Name).Value,
                        Email = user.Claims.First(c => c.Type == ClaimTypes.Email).Value
                    },
                    EventData = new WorkOrderOperativeSmvData
                    {
                        WorkOrderId         = workOrder.Id.ToString(),
                        WorkOrderStatusCode = (int)workOrder.StatusCode,
                        Address             = workOrder.Site.PropertyClass.FirstOrDefault().Address.AddressLine,
                        Description         = workOrder.DescriptionOfWork,
                        StandardMinuteValue = totalSMV,
                        OperativePrn        = op.PayrollNumber,
                        JobPercentage       = operative.JobPercentage,
                        ClosedTime          = workOrder.ClosedDate,
                        IsOutOfHours        = isOutOfHours,
                        OperativeCost       = totalOperativeCost,
                        IsOvertime          = workOrder.IsOvertime
                    }
                });
            }

            return(msgs);
        }
示例#8
0
        public static IQueryable <WorkOrder> RestrictContractor(this IQueryable <WorkOrder> source, ICurrentUserService userService)
        {
            if (userService.HasAnyGroup(UserGroups.AuthorisationManager, UserGroups.ContractManager, UserGroups.Agent, UserGroups.Service))
            {
                return(source);
            }

            var contractors = userService.GetContractors();

            if (contractors.Count > 0)
            {
                return(source.Where(wo => contractors.Contains(wo.AssignedToPrimary.ContractorReference) && wo.StatusCode != WorkStatusCode.PendingApproval));
            }

            if (userService.HasAnyGroup(UserGroups.Operative))
            {
                var userEmail = userService.GetUser().Email();
                return(source.Where(wo => wo.AssignedOperatives.Any(ao => ao.Email == userEmail)));
            }

            throw new UnauthorizedAccessException("Cannot access work orders");
        }
示例#9
0
        public async Task Execute(JobStatusUpdate jobStatusUpdate)
        {
            var workOrder = jobStatusUpdate.RelatedWorkOrder;

            workOrder.VerifyCanApproveWorkOrder();

            if (!_currentUserService.HasGroup(UserGroups.AuthorisationManager))
            {
                throw new UnauthorizedAccessException(Resources.InvalidPermissions);
            }

            var authorised = await _authorizationService.AuthorizeAsync(_currentUserService.GetUser(), workOrder, "RaiseSpendLimit");

            if (!authorised.Succeeded)
            {
                throw new UnauthorizedAccessException(Resources.WorkOrderApprovalAboveSpendLimit);
            }

            workOrder.StatusCode     = WorkStatusCode.Open;
            jobStatusUpdate.Comments = $"{jobStatusUpdate.Comments} Approved By: {_currentUserService.GetHubUser().Name}";

            await NotifyHandlers(workOrder);
        }
        public static HubUserModel GetHubUser(this ICurrentUserService currentUserService)
        {
            var hubUser = new HubUserModel();
            var user    = currentUserService.GetUser();

            hubUser.Sub                    = user.Sub();
            hubUser.Email                  = user.Email();
            hubUser.Name                   = user.Name();
            hubUser.Contractors            = user.Contractors();
            hubUser.OperativePayrollNumber = user.PayrollNumber();

            if (double.TryParse(user.FindFirst(CustomClaimTypes.RaiseLimit)?.Value, out var number))
            {
                hubUser.RaiseLimit = number.ToString(CultureInfo.InvariantCulture);
            }

            if (double.TryParse(user.FindFirst(CustomClaimTypes.VaryLimit)?.Value, out number))
            {
                hubUser.VaryLimit = number.ToString(CultureInfo.InvariantCulture);
            }

            return(hubUser);
        }