using Microsoft.AspNetCore.Mvc; using vendorApproverBackend.Requests; using vendorApproverBackend.Enums; using vendorApproverBackend.Services; using Microsoft.AspNetCore.Authorization; using vendorApproverBackend.Responses; using vendorApproverBackend.Entities; using System.Security.Claims; namespace vendorApproverBackend.Controllers { [ApiController] [Route("api/requests")] public class RequestController : ControllerBase { private readonly PrequalificationRequestService _requestService; private readonly VendorService _vendorService; private readonly UserService _userService; private readonly ILogger _logger; public RequestController( PrequalificationRequestService requestService, VendorService vendorService, UserService userService, ILogger logger) { _requestService = requestService; _vendorService = vendorService; _userService = userService; _logger = logger; } [HttpPost("add-request/{userId}")] [Authorize(Roles = "VENDOR")] public async Task AddRequest(long userId, [FromBody] AddPrequalificationRequestRequest requestDto) { var vendor = await _vendorService.GetVendorByUserIdAsync(userId); if (vendor == null) { return StatusCode(406, $"No vendor found for User ID {userId}."); } try { var newRequest = await _requestService.CreateRequestAsync(vendor.Id, requestDto); return CreatedAtAction(nameof(GetRequestById), new { requestId = newRequest.Id }, newRequest); } catch (Exception ex) { _logger.LogError(ex, "Error creating request for vendor {VendorId}", vendor.Id); return BadRequest(ex.Message); } } [HttpPut("update-request/{requestId}")] [Authorize(Roles = "ADMIN,EMPLOYEE,VENDOR,FINANCIAL,RENWE_APPROVER,MANAGER,PERFERMANCE_MANAGER")] public async Task UpdateRequest(long requestId, [FromBody] AddPrequalificationRequestRequest requestDto) { var updatedRequest = await _requestService.UpdateRequestAsync(requestId, requestDto); if (updatedRequest == null) { return NotFound($"Request with ID {requestId} not found."); } return Ok(updatedRequest); } [HttpPut("update-Request-Comments/{requestId}")] [Authorize(Roles = "ADMIN,EMPLOYEE,VENDOR,FINANCIAL,RENWE_APPROVER,MANAGER,PERFERMANCE_MANAGER")] public async Task Comments(long requestId, [FromBody] UpdatePqCommentsRequest requestDto) { var updatedRequest = await _requestService.UpdateRequesCommentstAsync(requestId, requestDto); if (updatedRequest == null) { return NotFound($"Request with ID {requestId} not found."); } return Ok(updatedRequest); } [HttpGet("getRequestById/{requestId}")] [Authorize(Roles = "ADMIN,EMPLOYEE,VENDOR,FINANCIAL,PERFERMANCE_MANAGER")] public async Task GetRequestById(long requestId) { var request = await _requestService.GetRequestByIdAsync(requestId); if (request == null) { return NotFound($"Request with ID {requestId} not found."); } return Ok(request); } [HttpGet("getVendorsRequests/{userId}")] [Authorize(Roles = "ADMIN,EMPLOYEE,VENDOR,FINANCIAL,PERFERMANCE_MANAGER")] public async Task GetVendorsRequests( long userId, [FromQuery] int page = 0, [FromQuery] int size = 5) { var vendor = await _vendorService.GetVendorByUserIdAsync(userId); if (vendor == null) { return StatusCode(406, $"No vendor found for User ID {userId}."); } var pagedResult = await _requestService.GetRequestsForVendorPaginatedAsync(vendor.Id, page, size); return Ok(pagedResult); } [HttpGet("getAllRequests_paginator")] [Authorize(Roles = "ADMIN,EMPLOYEE,PERFERMANCE_MANAGER")] public async Task>> GetAllRequestsPaginated( [FromQuery] int page = 0, [FromQuery] int size = 5, [FromQuery] RequestStatus? status = null, [FromQuery] long? userId = null, [FromQuery] long? employeeId = null) { var pagedResult = await _requestService.GetAllRequestsPaginatedAsync(page, size, status, userId, employeeId); return Ok(pagedResult); } [HttpGet("getAllRequests_list")] [Authorize(Roles = "ADMIN,EMPLOYEE,PERFERMANCE_MANAGER")] public async Task>> GetAllRequestsList( [FromQuery] RequestStatus? status = null, [FromQuery] long? userId = null, [FromQuery] long? employeeId = null) { var listResult = await _requestService.GetAllRequestsListAsync(status, userId, employeeId); return Ok(listResult); } [HttpPatch("update_admin_observation/{requestId}")] [Authorize(Roles = "ADMIN,EMPLOYEE,PERFERMANCE_MANAGER")] public async Task UpdateObservations(long requestId, [FromBody] List observations) { var updatedRequest = await _requestService.UpdateAdminObservationsAsync(requestId, observations); if (updatedRequest == null) { return NotFound($"PrequalificationRequest with ID {requestId} not found."); } return Ok(updatedRequest); } [HttpPatch("assign_to_employee/{requestId}/{employeeId}")] [Authorize(Roles = "ADMIN,EMPLOYEE,PERFERMANCE_MANAGER")] public async Task> AssignPrequalificationRequest( long requestId, long employeeId, [FromQuery] DateTime? deadline) { var username = User.FindFirstValue(ClaimTypes.Name); if (string.IsNullOrEmpty(username)) { return Unauthorized("Username claim not found in token."); } var currentUser = await _userService.FindByUsernameAsync(username); if (currentUser == null) { return NotFound(" current User not found."); } try { var updatedRequest = await _requestService.AssignPqRequestToEmployeeAsync( requestId, employeeId, deadline, currentUser.Id ); if (updatedRequest == null) { return NotFound($"Prequalification Request with ID {requestId} not found."); } return Ok(updatedRequest); } catch (KeyNotFoundException ex) { return BadRequest(ex.Message); } catch (Exception ex) { return StatusCode(500, "An error occurred during assignment: " + ex.Message); } } [HttpPost("send-reminder-email-deadline-approver/{pqRequestId}")] [Authorize(Roles = "ADMIN")] public async Task SendReminderWithBody( [FromRoute] long pqRequestId, [FromBody] ReminderRequestDto dto) { // Call the service method var success = await _requestService.SendManualReminderAsync(pqRequestId, dto.Comment); if (!success) { return NotFound(new { message = "Prequalification Request or Vendor Email not found." }); } return Ok(new { message = "Reminder email sent successfully." }); } [HttpPost("assign-inspectors/{requestId}")] [Authorize(Roles = "ADMIN,EMPLOYEE,PERFERMANCE_MANAGER")] public async Task AssignInspectors( long requestId, [FromBody] AssignInspectorsRequest requestBody) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var (request, statusCode, message) = await _requestService.AssignToInspectors(requestId, requestBody); if (request == null) { return StatusCode((int)statusCode, new { message }); } return Ok(request); } [HttpPatch("update-status/{requestId}")] [Authorize(Roles = "ADMIN")] public async Task> UpdateRequestStatus(long requestId, [FromBody] UpdateRequestStatus request) { var username = User.FindFirstValue(ClaimTypes.Name); if (string.IsNullOrEmpty(username)) { return Unauthorized("Username claim not found in token."); } var currentName = await _userService.FindByUsernameAsync(username); if (currentName == null) { return NotFound("User not found."); } var updated = await _requestService.UpdateRequestStatusAsync(requestId, request, currentName); if (updated == null) return NotFound($"Prequalification Request with ID {requestId} not found."); return Ok(updated); } } }