forked from sanchezvem/PyroFetes
75 lines
3.0 KiB
C#
75 lines
3.0 KiB
C#
using API.DTO.Warehouse.Response;
|
|
using FastEndpoints;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using PyroFetes.Models;
|
|
|
|
namespace PyroFetes.Endpoints.Warehouse;
|
|
|
|
public class GetAllWarehouseEndpoint(PyroFetesDbContext db)
|
|
: EndpointWithoutRequest<List<GetWarehouseDto>>
|
|
{
|
|
public override void Configure()
|
|
{
|
|
Get("/warehouses");
|
|
AllowAnonymous();
|
|
}
|
|
|
|
public override async Task HandleAsync(CancellationToken ct)
|
|
{
|
|
try
|
|
{
|
|
// 1. Chargement des entrepôts (sans tracking = plus rapide + plus safe)
|
|
var warehouses = await db.Warehouses
|
|
.AsNoTracking()
|
|
.ToListAsync(ct);
|
|
|
|
// 2. Chargement séparé des produits par entrepôt → évite l'InvalidCastException
|
|
var warehouseIds = warehouses.Select(w => w.Id).ToList();
|
|
|
|
var warehouseProducts = await db.WarehouseProducts
|
|
.Where(wp => warehouseIds.Contains(wp.WarehouseId))
|
|
.Include(wp => wp.Product)
|
|
.AsNoTracking()
|
|
.ToListAsync(ct);
|
|
|
|
// 3. Construction des DTOs avec des constructeurs ou des méthodes factory
|
|
// → compatible même si les propriétés n'ont que { get; init; }
|
|
var response = warehouses.Select(w =>
|
|
{
|
|
var dto = new GetWarehouseDto();
|
|
dto.GetType().GetProperty("Id")?.SetValue(dto, w.Id);
|
|
dto.GetType().GetProperty("Name")?.SetValue(dto, w.Name ?? string.Empty);
|
|
dto.GetType().GetProperty("MaxWeight")?.SetValue(dto, w.MaxWeight);
|
|
dto.GetType().GetProperty("Current")?.SetValue(dto, w.Current);
|
|
dto.GetType().GetProperty("MinWeight")?.SetValue(dto, w.MinWeight);
|
|
dto.GetType().GetProperty("Adress")?.SetValue(dto, w.Address ?? string.Empty);
|
|
dto.GetType().GetProperty("ZipCode")?.SetValue(dto, w.ZipCode);
|
|
dto.GetType().GetProperty("City")?.SetValue(dto, w.City ?? string.Empty);
|
|
|
|
// Products
|
|
var productsList = warehouseProducts
|
|
.Where(wp => wp.WarehouseId == w.Id)
|
|
.Select(wp =>
|
|
{
|
|
var prodDto = new WarehouseProductDto();
|
|
prodDto.GetType().GetProperty("ProductId")?.SetValue(prodDto, wp.ProductId);
|
|
prodDto.GetType().GetProperty("ProductName")?.SetValue(prodDto, wp.Product?.Name ?? "Produit inconnu");
|
|
prodDto.GetType().GetProperty("Quantity")?.SetValue(prodDto, wp.Quantity);
|
|
return prodDto;
|
|
})
|
|
.ToList();
|
|
|
|
dto.GetType().GetProperty("Products")?.SetValue(dto, productsList);
|
|
|
|
return dto;
|
|
}).ToList();
|
|
|
|
await Send.OkAsync(response, ct);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// En dev tu vois l'erreur réelle, en prod tu peux la logger
|
|
await Send.OkAsync(ct);
|
|
}
|
|
}
|
|
} |