Spaces:
Sleeping
Sleeping
File size: 3,465 Bytes
c8d434a b0a0ed0 c8d434a b0a0ed0 c8d434a b0a0ed0 c8d434a b0a0ed0 c8d434a b0a0ed0 c8d434a b0a0ed0 c8d434a c312181 6f32ae8 c312181 b0a0ed0 c312181 b0a0ed0 c312181 1a7e978 c312181 1a7e978 b0a0ed0 c312181 b0a0ed0 c8d434a 6f32ae8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | using Microsoft.AspNetCore.Mvc;
using Frontend.Services;
using System.Diagnostics;
using Frontend.Models;
namespace Frontend.Controllers
{
public class HomeController : Controller
{
private readonly LibraryApiClient _apiClient;
private readonly ILogger<HomeController> _logger;
public HomeController(LibraryApiClient apiClient, ILogger<HomeController> logger)
{
_apiClient = apiClient;
_logger = logger;
}
public async Task<IActionResult> Index()
{
// Set defaults to avoid nulls
ViewBag.TotalBooks = 0;
ViewBag.ActiveLoans = 0;
ViewBag.OverdueLoans = 0;
ViewBag.TotalMembers = 0;
ViewBag.LoyaltyPoints = 0;
ViewBag.LoyaltyStatus = "Not Authenticated";
ViewBag.RecentBooks = Enumerable.Empty<LibraryManagement.Shared.Models.BookDto>();
try
{
// 1. Basic Stats (Public)
var books = await _apiClient.GetBooksAsync();
ViewBag.TotalBooks = books.Count();
ViewBag.RecentBooks = books.Take(6);
// 2. Personal/Authenticated Stats
if (User.Identity?.IsAuthenticated == true)
{
// Fetch borrowings
try {
var borrowings = await _apiClient.GetMyBorrowingsAsync();
ViewBag.ActiveLoans = borrowings.Count(b => !b.ReturnDate.HasValue);
ViewBag.OverdueLoans = borrowings.Count(b => !b.ReturnDate.HasValue && b.DueDate < DateTime.UtcNow);
} catch { /* Ignore personal stats failure */ }
// Fetch loyalty
try {
var loyaltyAccount = await _apiClient.GetMyLoyaltyAccountAsync();
if (loyaltyAccount != null)
{
ViewBag.LoyaltyPoints = loyaltyAccount.CurrentBalance;
ViewBag.LoyaltyTier = loyaltyAccount.Tier;
ViewBag.LoyaltyStatus = "Connected";
}
else {
ViewBag.LoyaltyStatus = "Account Not Linked";
}
} catch {
ViewBag.LoyaltyStatus = "Loyalty System Unavailable";
}
// 3. Librarian Only Stats
if (User.IsInRole("Librarian"))
{
try {
var members = await _apiClient.GetUsersAsync();
ViewBag.TotalMembers = members.Count();
} catch { /* Ignore member list failure for non-librarians */ }
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Critical failure on dashboard. Some data might be missing.");
}
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|