private async Task RemoveOtherRelations(ChangeRequestAgentDto dto, CancellationToken cancellationToken) { var agentRequest = await _requestAgentService .GetAsync(i => i.AgentId == _userProvider.AgentId.Value && i.RequestId == dto.RequestId && i.IsActive == true, cancellationToken); if (agentRequest != null) { agentRequest.IsActive = false; agentRequest.ToDate = DateTime.UtcNow; await _requestAgentService.UpdateAsync(agentRequest , cancellationToken); } }
public async Task <ActionResult> ChangeRequestAgent([FromBody] ChangeRequestAgentDto dto, CancellationToken cancellationToken) { using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { try { if (!_userProvider.IsAgent || !_userProvider.IsResponsible.GetValueOrDefault(false)) { return(Forbid("Only agents can access this section")); } var req = await ModelService.Queryable.Include(i => i.RequestAgent).Include(i => i.RequestState) .FirstOrDefaultAsync(r => r.Id == dto.RequestId, cancellationToken); if (req is null) { return(NotFound()); } if (!_userProvider.IsResponsible.GetValueOrDefault(false) && req.RequestAgent.All(i => i.AgentId != _userProvider.AgentId)) { return(Forbid("You cannot change others request")); } await RemoveOtherRelations(dto, cancellationToken); req.AgentId = dto.NewAgentId; await ModelService.UpdateAsync(req, cancellationToken); var haveStates = _requestStateService.AsQueryable(r => r.RequestId == req.Id).Any(); if (!haveStates) { var firstStep = _workflowStepService.AsQueryable(r => r.WorkflowId == req.WorkflowId).OrderBy(r => r.StepNumber).FirstOrDefault().Id; await _requestStateService.CreateAsync(new RequestState { RequestId = req.Id, WorkflowStepId = firstStep, StartStepDate = DateTime.UtcNow, IsDone = false, AgentId = dto.NewAgentId, }); } //await _requestAgentService.CreateAsync(new RequestAgent //{ // AgentId = dto.NewAgentId, // FromDate = DateTime.UtcNow, // Description = dto.Description, // IsActive = true, // RequestId = dto.RequestId, //}, cancellationToken); await _signaler.Signal( _userAccountService.Get(u => u.AgentUserAccount.Any(a => a.Id == dto.NewAgentId)).Id, nameof(Request), "A new request has been assigned to you"); scope.Complete(); return(Ok()); } catch (Exception ex) { scope.Dispose(); throw; } } }