Finalisation endpoints
This commit is contained in:
82
PyroFetes/Endpoints/Truck/UpdateTruckEndpoint.cs
Normal file
82
PyroFetes/Endpoints/Truck/UpdateTruckEndpoint.cs
Normal file
@@ -0,0 +1,82 @@
|
||||
using FastEndpoints;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PyroFetes.DTO.Truck.Request;
|
||||
using PyroFetes.DTO.Truck.Response;
|
||||
|
||||
namespace PyroFetes.Endpoints.Truck;
|
||||
|
||||
public class UpdateTruckEndpoint(PyroFetesDbContext pyroFetesDbContext) : Endpoint<UpdateTruckDto, ReadTruckDto>
|
||||
{
|
||||
public override void Configure()
|
||||
{
|
||||
Put("/api/trucks/{Id}");
|
||||
AllowAnonymous();
|
||||
}
|
||||
|
||||
public override async Task HandleAsync(UpdateTruckDto req, CancellationToken ct)
|
||||
{
|
||||
if (!req.Id.HasValue)
|
||||
{
|
||||
await Send.NotFoundAsync(ct);
|
||||
return;
|
||||
}
|
||||
|
||||
var truck = await pyroFetesDbContext.Trucks
|
||||
.Include(t => t.ShowTrucks)
|
||||
.FirstOrDefaultAsync(t => t.Id == req.Id.Value, ct);
|
||||
|
||||
if (truck is null)
|
||||
{
|
||||
await Send.NotFoundAsync(ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Mise à jour des propriétés du truck
|
||||
truck.Type = req.Type ?? truck.Type;
|
||||
if (double.TryParse(req.MaxExplosiveCapacity, out var capacity))
|
||||
{
|
||||
truck.MaxExplosiveCapacity = capacity;
|
||||
}
|
||||
truck.Sizes = req.Sizes ?? truck.Sizes;
|
||||
truck.Status = req.Statut ?? truck.Status;
|
||||
|
||||
// Gérer la relation ShowTruck
|
||||
if (req.ShowId.HasValue)
|
||||
{
|
||||
// Supprimer l'ancienne relation
|
||||
if (truck.ShowTrucks != null && truck.ShowTrucks.Any())
|
||||
{
|
||||
var existingShowTrucks = truck.ShowTrucks.ToList();
|
||||
foreach (var st in existingShowTrucks)
|
||||
{
|
||||
pyroFetesDbContext.ShowTrucks.Remove(st);
|
||||
}
|
||||
}
|
||||
|
||||
// Ajouter la nouvelle relation si ShowId n'est pas 0
|
||||
if (req.ShowId.Value != 0)
|
||||
{
|
||||
var newShowTruck = new PyroFetes.Models.ShowTruck
|
||||
{
|
||||
TruckId = truck.Id,
|
||||
ShowId = req.ShowId.Value
|
||||
};
|
||||
pyroFetesDbContext.ShowTrucks.Add(newShowTruck);
|
||||
}
|
||||
}
|
||||
|
||||
await pyroFetesDbContext.SaveChangesAsync(ct);
|
||||
|
||||
var result = new ReadTruckDto
|
||||
{
|
||||
Id = truck.Id,
|
||||
Type = truck.Type,
|
||||
MaxExplosiveCapacity = truck.MaxExplosiveCapacity,
|
||||
Sizes = truck.Sizes,
|
||||
Statut = truck.Status,
|
||||
ShowId = req.ShowId
|
||||
};
|
||||
|
||||
await Send.OkAsync(result, ct);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user