forked from sanchezvem/PyroFetes
87 lines
3.0 KiB
C#
87 lines
3.0 KiB
C#
using API.DTO.Warehouse.Request;
|
|
using API.DTO.Warehouse.Response;
|
|
using FastEndpoints;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using PyroFetes.Models;
|
|
|
|
namespace PyroFetes.Endpoints.Warehouse;
|
|
|
|
public class UpdateWarehouseEndpoint(PyroFetesDbContext db)
|
|
: Endpoint<UpdateWarehouseDto, GetWarehouseDto>
|
|
{
|
|
public override void Configure()
|
|
{
|
|
// Utilise {id} plutôt que {@id}
|
|
Put("/api/warehouses/{@id}", x => new { x.Id });
|
|
AllowAnonymous();
|
|
}
|
|
|
|
public override async Task HandleAsync(UpdateWarehouseDto req, CancellationToken ct)
|
|
{
|
|
// 🔹 On inclut les produits existants pour pouvoir les modifier
|
|
var warehouseToEdit = await db.Warehouses
|
|
.Include(w => w.WarehouseProducts)
|
|
.SingleOrDefaultAsync(w => w.Id == req.Id, cancellationToken: ct);
|
|
|
|
if (warehouseToEdit == null)
|
|
{
|
|
Console.WriteLine($"Aucun entrepôt avec l'ID {req.Id} trouvé.");
|
|
await Send.NotFoundAsync(ct);
|
|
return;
|
|
}
|
|
|
|
// 🔹 Mise à jour des champs de base
|
|
warehouseToEdit.Name = req.Name;
|
|
warehouseToEdit.MaxWeight = req.MaxWeight;
|
|
warehouseToEdit.Current = req.Current;
|
|
warehouseToEdit.MinWeight = req.MinWeight;
|
|
warehouseToEdit.Address = req.Adress;
|
|
warehouseToEdit.ZipCode = req.ZipCode;
|
|
warehouseToEdit.City = req.City;
|
|
|
|
// 🔹 Gestion des produits associés
|
|
if (req.Products is not null)
|
|
{
|
|
// On supprime les anciens liens pour recréer proprement
|
|
var existingLinks = warehouseToEdit.WarehouseProducts.ToList();
|
|
if (existingLinks.Any())
|
|
db.WarehouseProducts.RemoveRange(existingLinks);
|
|
|
|
foreach (var p in req.Products)
|
|
{
|
|
var newLink = new WarehouseProduct
|
|
{
|
|
WarehouseId = warehouseToEdit.Id,
|
|
ProductId = p.ProductId,
|
|
Quantity = p.Quantity
|
|
};
|
|
db.WarehouseProducts.Add(newLink);
|
|
}
|
|
}
|
|
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
// 🔹 On renvoie la version mise à jour
|
|
var response = new GetWarehouseDto
|
|
{
|
|
Id = warehouseToEdit.Id,
|
|
Name = warehouseToEdit.Name,
|
|
MaxWeight = warehouseToEdit.MaxWeight,
|
|
Current = warehouseToEdit.Current,
|
|
MinWeight = warehouseToEdit.MinWeight,
|
|
Adress = warehouseToEdit.Address,
|
|
ZipCode = warehouseToEdit.ZipCode,
|
|
City = warehouseToEdit.City,
|
|
Products = warehouseToEdit.WarehouseProducts.Select(wp => new WarehouseProductDto
|
|
{
|
|
ProductId = wp.ProductId,
|
|
ProductName = wp.Product?.Name,
|
|
Quantity = wp.Quantity
|
|
}).ToList()
|
|
};
|
|
|
|
Console.WriteLine($"Entrepôt {warehouseToEdit.Name} mis à jour avec succès.");
|
|
await Send.OkAsync(response, ct);
|
|
}
|
|
}
|