Utopia-Canteen-System/Services/MenuLookupService.cs

76 lines
2.8 KiB
C#

using Microsoft.EntityFrameworkCore;
using UtopiaCanteenSystem.Data;
using UtopiaCanteenSystem.Models;
namespace UtopiaCanteenSystem.Services;
/// <summary>
/// Fetches lunch menu from local SQLite cache (lunch_menu_week → lunch_menu_item → menu_item).
/// </summary>
public class MenuLookupService : IMenuLookupService
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
public MenuLookupService(IDbContextFactory<AppDbContext> dbFactory)
{
_dbFactory = dbFactory;
}
public async Task<IReadOnlyList<HrmsMenuItem>> GetMenuItemsForSiteAsync(int siteIdNumeric, CancellationToken cancellationToken = default)
{
return await GetMenuItemsForSiteAndDateAsync(
siteIdNumeric,
DateTime.Today,
"NonManagement",
"no-active-meal-session",
cancellationToken).ConfigureAwait(false);
}
public async Task<IReadOnlyList<HrmsMenuItem>> GetMenuItemsForSiteAndDateAsync(
int siteIdNumeric,
DateTime menuDateLocal,
string gradeType,
string mealName,
CancellationToken cancellationToken = default)
{
if (siteIdNumeric <= 0)
return Array.Empty<HrmsMenuItem>();
await using var db = await _dbFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
if (!await db.MenuItemCache.AnyAsync(cancellationToken).ConfigureAwait(false))
return Array.Empty<HrmsMenuItem>();
var menuDate = menuDateLocal.Date;
var itemFor = HrmsMenuItemForMapping.FromGradeType(gradeType);
var meal = mealName?.Trim() ?? string.Empty;
var query =
from w in db.LunchMenuWeekCache.AsNoTracking()
join li in db.LunchMenuItemCache.AsNoTracking() on w.HrmsId equals li.LunchMenuWeekHrmsId
join mi in db.MenuItemCache.AsNoTracking() on li.MenuItemHrmsId equals mi.HrmsId
where w.LocationSiteId == siteIdNumeric
&& w.WeekStartDate != null
&& w.WeekEndDate != null
&& menuDate >= w.WeekStartDate.Value.Date
&& menuDate <= w.WeekEndDate.Value.Date
&& li.MenuDate != null
&& li.MenuDate.Value.Date == menuDate
&& li.MealName == meal
&& mi.ItemFor == itemFor
orderby mi.ItemName
select new HrmsMenuItem
{
MenuItemId = (int)mi.HrmsId,
ItemName = mi.ItemName,
ItemType = mi.ItemType,
Price = mi.Price,
MenuDate = li.MenuDate != null ? li.MenuDate.Value.ToString("yyyy-MM-dd") : string.Empty,
DayOfWeek = li.DayOfWeek,
MealName = li.MealName
};
return await query.ToListAsync(cancellationToken).ConfigureAwait(false);
}
}