Files
PyroFetes-Sujet1/PyroFetes/Endpoints/Supplier/UpdateSupplierEndpoint.cs
2025-10-09 17:17:42 +02:00

71 lines
2.2 KiB
C#

using PyroFetes.DTO.Supplier.Request;
using PyroFetes.DTO.Supplier.Response;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using PyroFetes.Models;
namespace PyroFetes.Endpoints.Supplier;
public class UpdateSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<UpdateSupplierDto, GetSupplierDto>
{
public override void Configure()
{
Put("/api/suppliers/{@id}", x => new { x.Id });
AllowAnonymous();
}
public override async Task HandleAsync(UpdateSupplierDto req, CancellationToken ct)
{
var supplierToEdit = await pyrofetesdbcontext
.Suppliers
.Include(s => s.Prices)
.SingleOrDefaultAsync(s => s.Id == req.Id, ct);
if (supplierToEdit is null)
{
await Send.NotFoundAsync(ct);
return;
}
supplierToEdit.Name = req.Name;
supplierToEdit.Email = req.Email;
supplierToEdit.Phone = req.PhoneNumber;
supplierToEdit.Address = req.Adress;
supplierToEdit.ZipCode = req.ZipCode;
supplierToEdit.City = req.City;
if (req.Products is not null)
{
// Supprimer les anciennes liaisons
var existingPrices = pyrofetesdbcontext.Prices
.Where(p => p.SupplierId == supplierToEdit.Id);
pyrofetesdbcontext.Prices.RemoveRange(existingPrices);
// Ajouter les nouvelles liaisons
foreach (var p in req.Products)
{
pyrofetesdbcontext.Prices.Add(new Price
{
SupplierId = supplierToEdit.Id,
ProductId = p.ProductId,
SellingPrice = p.SellingPrice
});
}
}
await pyrofetesdbcontext.SaveChangesAsync(ct);
var response = new GetSupplierDto
{
Id = supplierToEdit.Id,
Name = supplierToEdit.Name,
Email = supplierToEdit.Email,
PhoneNumber = supplierToEdit.Phone,
Adress = supplierToEdit.Address,
ZipCode = supplierToEdit.ZipCode,
City = supplierToEdit.City
};
await Send.OkAsync(response, ct);
}
}