111 lines
3.1 KiB
C#
111 lines
3.1 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using line_gestao_api.Data;
|
|
using line_gestao_api.Dtos;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace line_gestao_api.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/notifications")]
|
|
[Authorize]
|
|
public class NotificationsController : ControllerBase
|
|
{
|
|
private readonly AppDbContext _db;
|
|
|
|
public NotificationsController(AppDbContext db)
|
|
{
|
|
_db = db;
|
|
}
|
|
|
|
[HttpGet]
|
|
[HttpGet("/notifications")]
|
|
public async Task<ActionResult<List<NotificationDto>>> GetNotifications()
|
|
{
|
|
var (userId, userName) = GetUserContext();
|
|
if (userId is null && string.IsNullOrWhiteSpace(userName))
|
|
{
|
|
return Unauthorized();
|
|
}
|
|
|
|
var userNameNormalized = userName?.Trim();
|
|
|
|
var query = _db.Notifications.AsNoTracking()
|
|
.Where(n =>
|
|
(userId != null && n.UserId == userId) ||
|
|
(userNameNormalized != null && n.Usuario != null &&
|
|
EF.Functions.ILike(n.Usuario, userNameNormalized)));
|
|
|
|
var items = await query
|
|
.OrderByDescending(n => n.Data)
|
|
.Select(n => new NotificationDto
|
|
{
|
|
Id = n.Id,
|
|
Tipo = n.Tipo,
|
|
Titulo = n.Titulo,
|
|
Mensagem = n.Mensagem,
|
|
Data = n.Data,
|
|
ReferenciaData = n.ReferenciaData,
|
|
DiasParaVencer = n.DiasParaVencer,
|
|
Lida = n.Lida,
|
|
LidaEm = n.LidaEm,
|
|
VigenciaLineId = n.VigenciaLineId,
|
|
Cliente = n.Cliente,
|
|
Linha = n.Linha
|
|
})
|
|
.ToListAsync();
|
|
|
|
return Ok(items);
|
|
}
|
|
|
|
[HttpPatch("{id:guid}/read")]
|
|
[HttpPatch("/notifications/{id:guid}/read")]
|
|
public async Task<IActionResult> MarkAsRead(Guid id)
|
|
{
|
|
var (userId, userName) = GetUserContext();
|
|
if (userId is null && string.IsNullOrWhiteSpace(userName))
|
|
{
|
|
return Unauthorized();
|
|
}
|
|
|
|
var userNameNormalized = userName?.Trim();
|
|
|
|
var notification = await _db.Notifications
|
|
.FirstOrDefaultAsync(n => n.Id == id &&
|
|
((userId != null && n.UserId == userId) ||
|
|
(userNameNormalized != null && n.Usuario != null &&
|
|
EF.Functions.ILike(n.Usuario, userNameNormalized))));
|
|
|
|
if (notification is null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
|
|
if (!notification.Lida)
|
|
{
|
|
notification.Lida = true;
|
|
notification.LidaEm = DateTime.UtcNow;
|
|
await _db.SaveChangesAsync();
|
|
}
|
|
|
|
return NoContent();
|
|
}
|
|
|
|
private (Guid? UserId, string? UserName) GetUserContext()
|
|
{
|
|
var userIdRaw = User.FindFirstValue(JwtRegisteredClaimNames.Sub)
|
|
?? User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
|
|
Guid? userId = null;
|
|
if (Guid.TryParse(userIdRaw, out var parsed))
|
|
{
|
|
userId = parsed;
|
|
}
|
|
|
|
var userName = User.FindFirstValue("name");
|
|
return (userId, userName);
|
|
}
|
|
}
|