bank-sampah/Controllers/NotificationsController.cs

106 lines
2.8 KiB
C#

using BankSampahApp.Models;
using BankSampahApp.Services;
using Microsoft.AspNetCore.Mvc;
namespace BankSampahApp.Controllers;
public class NotificationsController : Controller
{
private readonly INotificationService _notificationService;
public NotificationsController(INotificationService notificationService)
{
_notificationService = notificationService;
}
[HttpGet]
public IActionResult Index(string? tab)
{
NotificationCategory? categoryFilter = null;
if (!string.IsNullOrWhiteSpace(tab) && !tab.Equals("Semua", StringComparison.OrdinalIgnoreCase)
&& Enum.TryParse(tab, ignoreCase: true, out NotificationCategory parsedCategory))
{
categoryFilter = parsedCategory;
}
var viewModel = new NotificationListViewModel
{
ActiveCategory = categoryFilter
};
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Show(int id)
{
var notification = _notificationService.GetById(id);
if (notification is null)
{
return NotFound();
}
if (!notification.IsRead)
{
await _notificationService.UpdateReadStateAsync(id, true);
notification.IsRead = true;
}
return View(notification);
}
[HttpGet]
public async Task<IActionResult> Table(string? category)
{
NotificationCategory? categoryFilter = null;
if (!string.IsNullOrWhiteSpace(category) &&
Enum.TryParse(category, ignoreCase: true, out NotificationCategory parsedCategory))
{
categoryFilter = parsedCategory;
}
var notifications = await _notificationService.GetNotificationsAsync(categoryFilter);
var rows = notifications.Select(n => new
{
id = n.Id,
title = n.Title,
category = n.Category.ToString(),
severity = n.Severity.ToString(),
isRead = n.IsRead,
summary = n.Summary,
createdAt = n.CreatedAt.ToString("O"),
detailUrl = Url.Action("Show", "Notifications", new { id = n.Id })
});
return Json(new { data = rows });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UpdateReadStatus(int id, bool isRead)
{
var success = await _notificationService.UpdateReadStateAsync(id, isRead);
if (!success)
{
return NotFound();
}
return Json(new { success = true });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id)
{
var success = await _notificationService.DeleteAsync(id);
if (!success)
{
return NotFound();
}
return Json(new { success = true });
}
}