shoc-backend/Api.SeaHavenIndustries/Controllers/CalendarController.cs
Alexandre Brandizzi 7d245eb717
refactor: enforce backend boundaries and optimize dispatch (#30)
* refactor(api): enforce service and data-service boundaries

* refactor(api): complete feature service boundaries

* refactor(identity): enforce service and data boundaries

* refactor(vendors): enforce service and data boundaries

* refactor(workorders): enforce service and data boundaries

* refactor(backend): enforce architecture and optimize dispatch

* style(backend): format changed architecture files

* fix(architecture): address backend review follow-ups

* fix(backend): sanitize exception disclosure in changed API endpoints

Replace raw exception-message disclosure (ex.Message) returned to API
callers with a stable sanitized public message plus correlated structured
internal logging, across the endpoints changed in this PR.

- Add SanitizedErrors helper: logs the original exception at Error with a
  generated correlation id and returns a stable public message referencing
  it so support can trace without exposing internals.
- Inject ILogger<T> into the 14 changed controllers and route every
  ex.Message/dbex.Message disclosure through the helper, preserving status
  codes, response shapes, and business data (e.g. OpenWorkOrders).
- Leave FluentValidation (vex.Errors) and existing fixed-message catches
  untouched; out-of-scope controllers (Account/Contact/Employee/Asset/
  PMSchedule) are unchanged.
- Add focused tests proving internal exception text is not returned and
  that Error logging carrying the original exception is invoked.

* fix(architecture): abstract job run state access

* style: format board update service

* test: use collection assertion idiom
2026-07-24 17:35:34 -03:00

209 lines
8.2 KiB
C#

using Api.SeaHavenIndustries.DTOs;
using Api.SeaHavenIndustries.Helper;
using Data.SeaHavenIndustries;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SeaHaven.Services.DTOs;
using SeaHaven.Services.Interfaces;
namespace Api.SeaHavenIndustries.Controllers
{
[Authorize]
[ApiController]
[Route("api/Calendar")]
public class CalendarController : Controller
{
private readonly ICalendarService _calendarService;
private readonly ILogger<CalendarController> _logger;
public CalendarController(ICalendarService calendarService, ILogger<CalendarController> logger)
{
_calendarService = calendarService;
_logger = logger;
}
// ===================================================================================
// CREATE EVENT
// ===================================================================================
[HttpPost]
[Route("AddEvent")]
public async Task<IActionResult> AddEvent(EditEvent_DTO eventDto, CancellationToken cancellationToken)
{
try
{
await _calendarService.CreateEventAsync(MapToInput(eventDto), cancellationToken);
return Ok(new DataResponse { Message = "Event Created Successfully", Status = "200" });
}
catch (Exception ex)
{
return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex) });
}
}
// ===================================================================================
// UPDATE EVENT
// ===================================================================================
[HttpPost]
[Route("EditEvent")]
public async Task<IActionResult> EditEvent(EditEvent_DTO eventDto, CancellationToken cancellationToken)
{
try
{
if (!eventDto.Id.HasValue)
{
return BadRequest(new Response { Status = "Error", Message = "Event ID is required for editing" });
}
var updated = await _calendarService.UpdateEventAsync(MapToInput(eventDto), cancellationToken);
if (!updated)
{
return NotFound(new Response { Status = "Error", Message = "Event not found" });
}
return Ok(new DataResponse { Message = "Event Updated Successfully", Status = "200" });
}
catch (Exception ex)
{
return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex) });
}
}
// ===================================================================================
// GET EVENT BY ID
// ===================================================================================
[HttpGet]
[Route("GetEventById/{id}")]
public async Task<IActionResult> GetEventById(int id, CancellationToken cancellationToken)
{
try
{
var dto = await _calendarService.GetEventByIdAsync(id, cancellationToken);
if (dto == null)
{
return NotFound(new Response { Status = "Error", Message = "Event not found" });
}
return Ok(new DataResponse { Message = "Success", Status = "200", Data = MapToResponse(dto) });
}
catch (Exception ex)
{
return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex) });
}
}
// ===================================================================================
// DELETE EVENT
// ===================================================================================
[HttpDelete]
[Route("DeleteEvent/{id}")]
public async Task<IActionResult> DeleteEvent(int id, CancellationToken cancellationToken)
{
try
{
var deleted = await _calendarService.DeleteEventAsync(id, cancellationToken);
if (!deleted)
{
return NotFound(new Response { Status = "Error", Message = "Event not found" });
}
return Ok(new DataResponse { Message = "Event Deleted Successfully", Status = "200" });
}
catch (Exception ex)
{
return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex) });
}
}
// ===================================================================================
// GET EVENTS LIST (WITH PAGINATION AND FILTERS)
// ===================================================================================
[HttpGet]
[Route("GetEventList")]
public async Task<IActionResult> GetEventList(string? search = "", int page = 1, int pageSize = 10, CancellationToken cancellationToken = default)
{
try
{
var result = await _calendarService.GetEventListAsync(search, page, pageSize, cancellationToken);
var events = result.Rows.Select(MapToResponse).ToList();
return Ok(new DataResponse
{
Message = "Success",
Status = "200",
Data = new { rows = events, totalCount = result.TotalCount }
});
}
catch (Exception ex)
{
return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex) });
}
}
// ===================================================================================
// GET EVENTS FOR CALENDAR (Date Range Filter)
// ===================================================================================
[HttpGet]
[Route("GetEventsForCalendar")]
public async Task<IActionResult> GetEventsForCalendar([FromQuery] DateTime? start, [FromQuery] DateTime? end, CancellationToken cancellationToken)
{
try
{
var events = await _calendarService.GetEventsForCalendarAsync(start, end, cancellationToken);
return Ok(new DataResponse { Message = "Success", Status = "200", Data = events.Select(MapToResponse).ToList() });
}
catch (Exception ex)
{
return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex) });
}
}
private static EditEventInput MapToInput(EditEvent_DTO eventDto)
{
return new EditEventInput
{
Id = eventDto.Id,
Title = eventDto.Title,
Description = eventDto.Description,
Location = eventDto.Location,
RecordID = eventDto.RecordID,
RecordName = eventDto.RecordName,
RecordTargetType = eventDto.RecordTargetType,
ReminderMinutes = eventDto.ReminderMinutes,
EventColor = eventDto.EventColor,
StartDate = eventDto.StartDate,
StartTime = eventDto.StartTime,
EndDate = eventDto.EndDate,
EndTime = eventDto.EndTime,
AllDay = eventDto.AllDay
};
}
private static Event_DTO MapToResponse(EventDTO dto)
{
return new Event_DTO
{
Id = dto.Id,
Title = dto.Title,
Description = dto.Description,
Location = dto.Location,
RecordID = dto.RecordID,
RecordName = dto.RecordName,
RecordTargetType = dto.RecordTargetType,
ReminderMinutes = dto.ReminderMinutes,
EventColor = dto.EventColor,
StartDate = dto.StartDate,
StartTime = dto.StartTime,
EndDate = dto.EndDate,
EndTime = dto.EndTime,
AllDay = dto.AllDay,
CreatedDate = dto.CreatedDate,
createdby = dto.createdby
};
}
}
}