public async Task <IActionResult> Create(TicketForCreationDto ticket)
        {
            ticket.CreatorId = HttpContext.GetUserId();
            if (!await _users.UserExist(ticket.CreatorId) ||
                !await _users.UserExist(ticket.AssigneeId) ||
                !await _teams.ExistById(ticket.TeamId))
            {
                return(BadRequest("Bad request data, data don't exist."));
            }
            var team = await _teams.GetById(ticket.TeamId);

            if (!await _organizations.OrganizationExistById(team.Organization.Id) ||
                !await _organizations.UserInOrganization(ticket.CreatorId, team.Organization.Id))
            {
                return(BadRequest($"User has no access to Organization with ID {team.Organization.Id}."));
            }
            var taskToCreate = new Ticket
            {
                Title          = ticket.Title,
                Description    = ticket.Description,
                CreatorId      = ticket.CreatorId,
                AssigneeId     = ticket.AssigneeId,
                OrganizationId = team.Organization.Id,
                TeamId         = team.Id,
                Created        = DateTime.Now,
                LastUpdated    = DateTime.Now,
            };
            var taskCreated = await _repo.Create(taskToCreate);

            var taskToReturn = _mapper.Map <TicketForListDto>(taskCreated);

            return(Ok(taskToReturn));
        }
Esempio n. 2
0
        public async Task <IActionResult> AddTicket([FromBody] TicketForCreationDto ticketForCreationDto)
        {
            string userIdFromClaim = User.FindFirst(ClaimTypes.NameIdentifier).Value;

            if (!int.TryParse(userIdFromClaim, out int userId))
            {
                return(BadRequest("Can not parse user id"));
            }

            User userFromRepo = await repo.GetUser(userId);

            // Only HelpDesk user can add tasks
            if (IsTeamMemeber(userFromRepo.Type))
            {
                return(Unauthorized());
            }

            Ticket ticket = mapper.Map <Ticket>(ticketForCreationDto);

            if (await repo.AddTicket(userFromRepo, ticket))
            {
                var ticketoReturn = mapper.Map <TicketForReturnDto>(ticket);
                return(CreatedAtRoute("GetTicket", new { userId, id = ticket.Id }, ticketoReturn));
            }

            return(BadRequest("Could not add the ticket"));
        }
        public async Task <IActionResult> CreateTicket(TicketForCreationDto ticket)
        {
            if (ticket == null)
            {
                _logger.LogError("Ticket object sent from client is null.");
                return(BadRequest("Empty Ticket Cannot Be Created"));
            }
            if (!ModelState.IsValid)
            {
                _logger.LogError("Invalid model state for the Ticket");
                return(UnprocessableEntity(ModelState));
            }

            ticket.TStatusId = new Guid("4bb96000-7e4c-4e69-ae20-08d934dbcd3a");

            var ticketToCreate = _mapper.Map <Ticket>(ticket);

            var userList = User.Claims.ToList();
            //Getting the username and email from jwt token to set it to CreatedBy name and email
            var userName  = User.Claims.ToList()[1].Value;
            var userEmail = User.Claims.ToList()[3].Value;

            ticketToCreate.SubmittedByName  = userName;
            ticketToCreate.SubmittedByEmail = userEmail;
            ticketToCreate.CreatedAt        = DateTime.Now;
            _repo.Ticket.CreateTicket(ticketToCreate);
            await _repo.Save();

            return(Ok("Ticket Created Sucessfully"));
        }
Esempio n. 4
0
        public async Task <IActionResult> CreateTicket(TicketForCreationDto ticketForCreationDto)
        {
            var ticket = _mapper.Map <Ticket>(ticketForCreationDto);

            ticket.UserId = Int32.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));

            //ticket.Description = Regex.Replace(ticket.Description, "[^0-9A-Za-z]+", " ");
            var regexItem = new Regex("^[a-zA-Z0-9 ]*$");

            if (!regexItem.IsMatch(ticket.Description))
            {
                throw new Exception("Description invalid");
            }

            _repo.Add(ticket);


            if (await _repo.SaveAll())
            {
                var ticketToReturn = _mapper.Map <TicketForListDto>(ticket);
                ticketToReturn.UserName     = User.Identity.Name;
                ticketToReturn.TicketNumber = ticket.Id;
                return(CreatedAtRoute("GetTicket",
                                      new { id = ticket.Id }, ticketToReturn));
            }


            throw new Exception("Creating the message failed on save");
        }
        public IActionResult Post([FromBody] TicketForCreationDto ticket)
        {
            if (ticket == null)
            {
                return(BadRequest());
            }
            var finalTicket = Mapper.Map <Entities.Ticket>(ticket);

            // set ticket as 'new' status
            finalTicket.Status = "new";

            // Default values until Clients & Agent API is mocked
            finalTicket.ClientId = 0;
            finalTicket.AgentId  = 0;
            finalTicket.Opened   = DateTime.Now;

            _ticketRepository.Add(finalTicket);
            if (!_ticketRepository.Save())
            {
                return(BadRequest());
            }
            var createdTicket = Mapper.Map <Models.TicketDto>(finalTicket);

            return(CreatedAtRoute("GetTicket", new { id = createdTicket.Id }, createdTicket));
        }
        public async Task <TicketForListDto> CreateTicket(TicketForCreationDto ticket)
        {
            var dataJson      = JsonSerializer.Serialize(ticket);
            var stringContent = new StringContent(dataJson, Encoding.UTF8, "application/json");
            var response      = await _httpClient.PostAsync($"{_rootUrl}/create", stringContent);

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

                return(JsonSerializer.Deserialize <TicketForListDto>(responseString, defaultJsonSerializerOptions));
            }
            else
            {
                throw new Exception($"Failed to Create Ticket. {await response.Content.ReadAsStringAsync()}");
            }
        }
Esempio n. 7
0
        public async void Create_Ticket()
        {
            var controller        = new TicketsController(new TicketRepositoryMock(), new ClientRepositoryMock(), new InventoryServiceMock(), new HRServiceMock());
            var ticketForCreation = new TicketForCreationDto()
            {
                Title               = "Example 1",
                Description         = "yo this dont work",
                ProductSerialNumber = InventoryServiceMock.TestProduct.SerialNumber,
            };

            var result = await controller.Post(ticketForCreation, ClientRepositoryMock.TestClient.Id);

            var okResult = result.Should().BeOfType <CreatedAtRouteResult>().Subject;
            var ticket   = okResult.Value.Should().BeAssignableTo <TicketWithClientAndAgentDto>().Subject;

            ticket.Title.Should().Be(ticketForCreation.Title);
        }
        public async Task <IActionResult> Post([FromBody] TicketForCreationDto ticketForCreation, [FromQuery(Name = "clientId")] int clientId)
        {
            var ticket = AutoMapper.Mapper.Map <Ticket>(ticketForCreation);
            // Look up the client by id
            var client = _clientRepository.Get(clientId);

            // Ensure client exists
            if (client == null)
            {
                return(NotFound("Client not found"));
            }
            // Look up the product by serial number
            var productDetails = await _inventoryService.GetProductAsync(ticketForCreation.ProductSerialNumber);

            // Ensure the product exists
            if (productDetails == null)
            {
                return(NotFound("Serial number not found"));
            }
            // Ensure the product has been sold
            if (!(productDetails.Status == "sold"))
            {
                return(BadRequest("This device has not been sold"));
            }
            // Create the ticket
            // Tickets are set to Status=new by default
            ticket.Status = "new";
            // Tickets are associated with the product they were created for
            ticket.ProductSerialNumber = productDetails.SerialNumber;

            // Assign ticket to the agent with the lowest number of assigned tickets
            ticket.AgentId = (await _hrService.GetAgentsAsync()).OrderBy(a => _ticketRepository.GetAllByAgent(a.Id).Count()).First().Id;

            client.Tickets.Add(ticket);
            _clientRepository.Update(client);
            if (!_clientRepository.Save())
            {
                return(BadRequest("Could not create ticket"));
            }
            var result = AutoMapper.Mapper.Map <TicketWithClientAndAgentDto>(ticket);

            return(CreatedAtRoute("GetTicket", new { id = ticket.Id }, result));
        }
Esempio n. 9
0
        public IActionResult CreateTicket(TicketForCreationDto ticket)
        {
            if (ticket == null)
            {
                return(BadRequest());
            }

            if (!_ticketService.ValidateTicketInput(ticket))
            {
                return(BadRequest());
            }

            var createdTicket = _ticketService.CreateTicket(ticket);

            if (createdTicket == null)
            {
                return(BadRequest());
            }

            return(Created($"create/{createdTicket.Id}",
                           _mapper.Map <TicketDto>(createdTicket)));
        }
Esempio n. 10
0
        public bool ValidateTicketInput(TicketForCreationDto ticketInput)
        {
            if (ticketInput.SelectedMatches.Any(m => m.IsTopOffer))
            {
                if (!ValidateTopOffer(ticketInput.SelectedMatches))
                {
                    return(false);
                }
            }

            //only one offer can be selected per match
            var matchIds = new HashSet <int>();

            foreach (var match in ticketInput.SelectedMatches)
            {
                if (!matchIds.Add(match.Id))
                {
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 11
0
        public Ticket CreateTicket(TicketForCreationDto ticketInput)
        {
            double totalOdd = 1;

            foreach (var match in ticketInput.SelectedMatches)
            {
                totalOdd *= match.SelectedOddValue;
            }

            var payoutTransaction =
                _transactionRepository.AddTransaction(Transaction.TransactionType.Payout, ticketInput.Stake);

            var stakeWithHandlingCost = ticketInput.Stake - ticketInput.Stake * 0.05;

            var possiblePayout = totalOdd * stakeWithHandlingCost;

            var ticket = new Ticket
            {
                TotalOdd       = Math.Round(totalOdd, 2),
                Stake          = Math.Round(ticketInput.Stake, 2),
                PossiblePayout = Math.Round(possiblePayout, 2),
                TransactionId  = payoutTransaction.Id
            };

            var createdTicket = _ticketRepository.AddTicket(ticket);

            _transactionRepository.UpdateTicketId(payoutTransaction, ticket.Id);

            if (IsWinningTicket(ticket))
            {
                var paymentTransaction =
                    _transactionRepository.AddTransaction(Transaction.TransactionType.Payment, ticket.PossiblePayout);
                _transactionRepository.UpdateTicketId(paymentTransaction, ticket.Id);
            }

            return(createdTicket);
        }
        public async Task <IActionResult> AddTicketForClient(int userId, /*string title, string description, [FromForm]*/ TicketForCreationDto ticketForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var clientFromRepo = await _repo.GetClient(userId);

            /* Tickets newTicket = new Tickets()
             * {
             *  ticketForCreationDto.Title = title
             *  ticketForCreationDto.Description = description
             *
             * };*/

            var ticketToCreate = new Tickets
            {
                Title       = ticketForCreationDto.Title,
                Description = ticketForCreationDto.Description,
                Notes       = ticketForCreationDto.Notes,
                DateIssued  = DateTime.Now,
                //DateClossed =

                // Username = clientForRegisterDto.Username,
                //PhoneNumber = clientForRegisterDto.PhoneNumber,
                //Email = clientForRegisterDto.Email,
                //DateAdded = DateTime.Now,
                //Address = clientForRegisterDto.Address
            };



            var ticket = _mapper.Map <Tickets>(ticketToCreate);

            clientFromRepo.Tickets.Add(ticket);



            if (await _repo.SaveAll())
            {
                var ticketToReturn = _mapper.Map <TicketsForDetailedDto>(ticket);
                return(CreatedAtRoute("GetTicket", new { id = ticket.Id }, ticketToReturn));
            }

            return(BadRequest("Could not book ticket"));
        }