forked from sanchezvem/PyroFetes
80 lines
2.5 KiB
C#
80 lines
2.5 KiB
C#
using PyroFetes.DTO.Product.Response;
|
||
using FastEndpoints;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using PyroFetes.DTO.Product.Request;
|
||
using PyroFetes.Models;
|
||
|
||
namespace PyroFetes.Endpoints.Product;
|
||
|
||
public class GetProductRequest
|
||
{
|
||
public int Id { get; set; }
|
||
}
|
||
|
||
public class GetProductEndpoint(PyroFetesDbContext db)
|
||
: Endpoint<GetProductRequest, GetProductDto>
|
||
{
|
||
public override void Configure()
|
||
{
|
||
Get("/api/products/{@id}", x => new { x.Id });
|
||
AllowAnonymous();
|
||
}
|
||
|
||
public override async Task HandleAsync(GetProductRequest req, CancellationToken ct)
|
||
{
|
||
// Inclure toutes les relations : Prices + WarehouseProducts + Warehouse
|
||
var product = await db.Products
|
||
.Include(p => p.Prices)
|
||
.Include(p => p.WarehouseProducts)
|
||
.ThenInclude(wp => wp.Warehouse)
|
||
.SingleOrDefaultAsync(p => p.Id == req.Id, ct);
|
||
|
||
if (product == null)
|
||
{
|
||
Console.WriteLine($"Aucun produit avec l'ID {req.Id} trouvé.");
|
||
await Send.NotFoundAsync(ct);
|
||
return;
|
||
}
|
||
|
||
var responseDto = new GetProductDto
|
||
{
|
||
Id = product.Id,
|
||
|
||
// Le modèle Product contient "Reference" (string), pas "References" (int)
|
||
Reference = int.TryParse(product.Reference, out var refInt) ? refInt : 0,
|
||
|
||
Name = product.Name,
|
||
Duration = product.Duration,
|
||
Caliber = product.Caliber,
|
||
ApprovalNumber = product.ApprovalNumber,
|
||
Weight = product.Weight,
|
||
Nec = product.Nec,
|
||
|
||
// Le prix de vente n’est pas dans Product → récupéré via Price
|
||
SellingPrice = product.Prices.FirstOrDefault()?.SellingPrice ?? 0,
|
||
|
||
Image = product.Image,
|
||
Link = product.Link,
|
||
ClassificationId = product.ClassificationId,
|
||
ProductCategoryId = product.ProductCategoryId,
|
||
|
||
// Fournisseurs liés via Price
|
||
Suppliers = product.Prices.Select(pr => new ProductSupplierPriceDto
|
||
{
|
||
SupplierId = pr.SupplierId,
|
||
SellingPrice = pr.SellingPrice
|
||
}).ToList(),
|
||
|
||
// Entrepôts liés via WarehouseProduct
|
||
Warehouses = product.WarehouseProducts.Select(wp => new GetProductWarehouseDto
|
||
{
|
||
WarehouseId = wp.WarehouseId,
|
||
WarehouseName = wp.Warehouse?.Name ?? string.Empty,
|
||
Quantity = wp.Quantity
|
||
}).ToList()
|
||
};
|
||
|
||
await Send.OkAsync(responseDto, ct);
|
||
}
|
||
}
|