Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public record DashboardCategoryCount(int Id, string Name, int Count);

public record DashboardDailyCount(DateOnly Date, int Count);

public record DashboardOrderCount(int Id, string Name, string? NameEnglish, string? Size, int Ordered);
public record DashboardOrderCount(int Id, string Name, string? NameEnglish, string? Size, int Ordered, int? HandedOut = null);

public record DashboardRegistrations(
int Total,
Expand Down Expand Up @@ -91,7 +91,9 @@ public async Task<DashboardDto> Get(CancellationToken cancellationToken)
.ToListAsync(cancellationToken);
var food = await db.FoodTypes.AsNoTracking().OrderBy(type => type.Name)
.Select(type => new DashboardOrderCount(type.Id, type.Name, type.NameEnglish, null,
type.ParticipantFoodOrders.Where(order => !order.Participant.IsAnnulled).Sum(order => order.Quantity)))
type.ParticipantFoodOrders.Where(order => !order.Participant.IsAnnulled).Sum(order => order.Quantity),
type.ParticipantFoodOrders.Where(order => !order.Participant.IsAnnulled)
.SelectMany(order => order.Handouts).Count(handout => handout.UndoneAt == null)))
.ToListAsync(cancellationToken);

return new DashboardDto(registrations, arrivals, wear, food);
Expand Down
214 changes: 214 additions & 0 deletions backend/src/Fastasys.ApiService/Controllers/FoodController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
using System.ComponentModel.DataAnnotations;
using Fastasys.ApiService.Data;
using Fastasys.ApiService.Data.Entities;
using Fastasys.ApiService.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Npgsql;

namespace Fastasys.ApiService.Controllers;

public record FoodTypeRequest([Required, MaxLength(256)] string Name, [Required, MaxLength(256)] string NameEnglish,
[Required] decimal? Price, [Required] MealPeriod? MealPeriod, [Required] FoodDiet? Diet, [Required] int[] ServingIds);

public record FoodServingRequest([Required] DateOnly? Date, [Required] MealPeriod? MealPeriod,
[Required] TimeOnly? StartsAt, [Required] TimeOnly? EndsAt);

public record FoodServingDto(int Id, DateOnly Date, MealPeriod MealPeriod, TimeOnly StartsAt, TimeOnly EndsAt, int[] FoodTypeIds, bool IsCurrent);

public record FoodServingCount(int FoodTypeId, int Ordered, int HandedOut);

public record OrderFoodDto(int ParticipantId, int FoodTypeId, DateTime Date, int Quantity = 1);

public record SetFoodOrderDto(int ParticipantId, int FoodTypeId, [Required, Range(0, int.MaxValue)] int? Quantity);

[ApiController]
[Authorize]
[Route("api/food")]
public class FoodController(InfosysDbContext db) : ControllerBase
{
[AllowAnonymous]
[HttpGet("types")]
public Task<List<FoodType>> GetTypes(CancellationToken ct) =>
db.FoodTypes.AsNoTracking().Where(food => food.IsActive).OrderBy(food => food.Name).ToListAsync(ct);

[HttpPost("types")]
[Authorize(Policy = "FoodManagement")]
public async Task<ActionResult<FoodType>> CreateType(FoodTypeRequest request, CancellationToken ct)
{
var food = new FoodType();
if (!ApplyType(food, request)) return BadRequest(new { code = "invalidType" });
var servings = await LoadTypeServings(null, request.ServingIds, ct);
if (!ValidTypeServings(servings, request)) return BadRequest(new { code = "invalidTypeServings" });
db.FoodTypes.Add(food);
foreach (var serving in servings) serving.FoodTypes.Add(food);
await db.SaveChangesAsync(ct);
return StatusCode(StatusCodes.Status201Created, food);
}

[HttpPut("types/{id:int}")]
[Authorize(Policy = "FoodManagement")]
public async Task<ActionResult<FoodType>> UpdateType(int id, FoodTypeRequest request, CancellationToken ct)
{
await using var transaction = await FoodOrders.LockTypes(db, [id], ct);
var food = await db.FoodTypes.FindAsync([id], ct);
if (food is null) return NotFound(new { code = "typeNotFound" });
if (!ApplyType(food, request)) return BadRequest(new { code = "invalidType" });
var servings = await LoadTypeServings(id, request.ServingIds, ct);
if (!ValidTypeServings(servings, request)) return BadRequest(new { code = "invalidTypeServings" });
var removed = servings.Where(s => !request.ServingIds.Contains(s.Id)).ToArray();
if (removed.Length > 0)
{
if (transaction is not null) await FoodOrders.LockServingRows(db, removed.Select(s => s.Id).ToArray(), ct);
var dates = removed.Select(s => FoodOrders.OrderDate(s.Date)).ToArray();
if (await db.ParticipantFoods.AnyAsync(o => o.FoodTypeId == id && dates.Contains(o.Date) &&
(o.Quantity > 0 || o.Handouts.Any() || o.Offers.Any()), ct))
return Conflict(new { code = "servingHasOrders" });
}

foreach (var serving in removed) serving.FoodTypes.Remove(food);
foreach (var serving in servings.Where(s => request.ServingIds.Contains(s.Id) && !s.FoodTypes.Contains(food)))
serving.FoodTypes.Add(food);

await db.SaveChangesAsync(ct);
if (transaction is not null) await transaction.CommitAsync(ct);
return food;
}

[HttpGet("servings")]
[Authorize(Policy = "FoodServingView")]
public async Task<IReadOnlyList<FoodServingDto>> GetServings(CancellationToken ct)
{
var now = FoodOrders.LocalNow();
var servings = await db.FoodServings.AsNoTracking().Include(s => s.FoodTypes)
.OrderBy(s => s.Date).ThenBy(s => s.StartsAt).ToListAsync(ct);
return servings.Select(s => MapServing(s, now)).ToArray();
}

[HttpPost("servings")]
[Authorize(Policy = "FoodManagement")]
public async Task<ActionResult<FoodServingDto>> CreateServing(FoodServingRequest request, CancellationToken ct)
{
if (request.Date is not DateOnly date || request.MealPeriod is not MealPeriod period || !Enum.IsDefined(period) ||
request.StartsAt is not TimeOnly starts || request.EndsAt is not TimeOnly ends || ends <= starts)
return BadRequest(new { code = "invalidServing" });

if (await db.FoodServings.AnyAsync(s => s.Date == date && s.MealPeriod == period, ct))
return Conflict(new { code = "servingExists" });

var serving = new FoodServing { Date = date, MealPeriod = period, StartsAt = starts, EndsAt = ends };
db.FoodServings.Add(serving);
try
{
await db.SaveChangesAsync(ct);
}
catch (DbUpdateException e) when (e.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation })
{
return Conflict(new { code = "servingExists" });
}
return StatusCode(StatusCodes.Status201Created, MapServing(serving, FoodOrders.LocalNow()));
}

[HttpGet("servings/{id:int}/counts")]
[Authorize(Policy = "FoodServingView")]
public async Task<ActionResult<IReadOnlyList<FoodServingCount>>> GetCounts(int id, CancellationToken ct)
{
var serving = await FoodOrders.GetServing(db, id, ct);
if (serving is null) return NotFound(new { code = "servingNotFound" });
var counts = await FoodOrders.ForServing(db, serving).AsNoTracking()
.Select(order => new FoodServingCount(order.FoodTypeId, order.Quantity, order.Handouts.Count(h => h.UndoneAt == null)))
.ToListAsync(ct);
var byType = counts.ToLookup(row => row.FoodTypeId);
return Ok(serving.FoodTypes.Select(type => new FoodServingCount(type.Id, byType[type.Id].Sum(row => row.Ordered), byType[type.Id].Sum(row => row.HandedOut))));
}

[HttpPut("servings/{id:int}/order")]
[Authorize(Policy = "FoodOrdering")]
public async Task<IActionResult> SetOrder(int id, SetFoodOrderDto request, CancellationToken ct)
{
await using var transaction = await FoodOrders.LockServing(db, id, ct);
var serving = await FoodOrders.GetServing(db, id, ct);
if (serving is null) return NotFound(new { code = "servingNotFound" });
if (!serving.FoodTypes.Any(type => type.Id == request.FoodTypeId) || request.Quantity is not int quantity || quantity < 0)
return BadRequest(new { code = "invalidOrder" });
if (!await db.Participants.AnyAsync(p => p.Id == request.ParticipantId && !p.IsAnnulled, ct))
return NotFound(new { code = "participantNotFound" });

var date = FoodOrders.OrderDate(serving.Date);
var order = await db.ParticipantFoods.FindAsync([request.ParticipantId, request.FoodTypeId, date], ct);
if (order is null)
{
if (quantity > 0)
db.ParticipantFoods.Add(new ParticipantFood { ParticipantId = request.ParticipantId, FoodTypeId = request.FoodTypeId, Date = date, Quantity = quantity });
}
else
{
if (quantity < await FoodOrders.AllocatedQuantity(db, order, ct)) return Conflict(new { code = "orderAlreadyAllocated" });
order.Quantity = quantity;
}

await db.SaveChangesAsync(ct);
if (transaction is not null) await transaction.CommitAsync(ct);
return NoContent();
}

[HttpPost("order")]
[Authorize(Policy = "FoodOrdering")]
public async Task<IActionResult> OrderFood(OrderFoodDto request, CancellationToken ct)
{
if (request.Quantity <= 0) return BadRequest(new { code = "invalidOrder" });
await using var transaction = await FoodOrders.LockTypes(db, [request.FoodTypeId], ct);
if (!await db.FoodTypes.AnyAsync(food => food.Id == request.FoodTypeId && food.IsActive, ct))
return NotFound(new { code = "typeNotFound" });
if (!await db.Participants.AnyAsync(p => p.Id == request.ParticipantId && !p.IsAnnulled, ct))
return NotFound(new { code = "participantNotFound" });

var date = FoodOrders.OrderDate(DateOnly.FromDateTime(request.Date));
if (await db.ParticipantFoods.AnyAsync(o => o.ParticipantId == request.ParticipantId && o.FoodTypeId == request.FoodTypeId && o.Date == date, ct))
return Conflict(new { code = "orderExists" });
db.ParticipantFoods.Add(new ParticipantFood { ParticipantId = request.ParticipantId, FoodTypeId = request.FoodTypeId, Date = date, Quantity = request.Quantity });
try
{
await db.SaveChangesAsync(ct);
if (transaction is not null) await transaction.CommitAsync(ct);
}
catch (DbUpdateException e) when (e.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation })
{
return Conflict(new { code = "orderExists" });
}
return Ok(new { message = "Food ordered successfully" });
}

private Task<List<FoodServing>> LoadTypeServings(int? typeId, int[] servingIds, CancellationToken ct) =>
db.FoodServings.Include(s => s.FoodTypes)
.Where(s => servingIds.Contains(s.Id) || s.FoodTypes.Any(type => type.Id == typeId)).ToListAsync(ct);

private static bool ValidTypeServings(List<FoodServing> servings, FoodTypeRequest request)
{
var selected = servings.Where(s => request.ServingIds.Contains(s.Id)).ToArray();
return selected.Length > 0 && selected.Length == request.ServingIds.Distinct().Count() &&
selected.All(s => s.MealPeriod == request.MealPeriod);
}

private static bool ApplyType(FoodType food, FoodTypeRequest request)
{
if (string.IsNullOrWhiteSpace(request.Name) || string.IsNullOrWhiteSpace(request.NameEnglish) ||
request.Price is not decimal price || price < 0 || price != decimal.Round(price, 2) ||
request.MealPeriod is not MealPeriod period || !Enum.IsDefined(period) ||
request.Diet is not FoodDiet diet || !Enum.IsDefined(diet)) return false;

food.Name = request.Name.Trim();
food.NameEnglish = request.NameEnglish.Trim();
food.Price = price;
food.MealPeriod = period;
food.Diet = diet;
return true;
}

private static FoodServingDto MapServing(FoodServing serving, DateTime now) => new(
serving.Id, serving.Date, serving.MealPeriod, serving.StartsAt, serving.EndsAt,
serving.FoodTypes.Select(type => type.Id).Order().ToArray(),
DateOnly.FromDateTime(now) == serving.Date && TimeOnly.FromDateTime(now) >= serving.StartsAt && TimeOnly.FromDateTime(now) < serving.EndsAt
);
}
Loading