Files
PyroFetes-Sujet1/PyroFetes/Endpoints/Product/UpdateProductEndpoint.cs

101 lines
3.1 KiB
C#

using PyroFetes.DTO.Product.Request;
using PyroFetes.DTO.Product.Response;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using PyroFetes.Models;
namespace PyroFetes.Endpoints.Product;
public class UpdateProductEndpoint(PyroFetesDbContext db)
: Endpoint<UpdateProductDto, GetProductDto>
{
public override void Configure()
{
Put("/products/{@id}", x => new { x.Id });
}
public override async Task HandleAsync(UpdateProductDto req, CancellationToken ct)
{
var product = await db.Products
.Include(p => p.Prices)
.Include(p => p.WarehouseProducts)
.SingleOrDefaultAsync(p => p.Id == req.Id, ct);
if (product is null)
{
await Send.NotFoundAsync(ct);
return;
}
product.Reference = req.Reference;
product.Name = req.Name;
product.Duration = req.Duration;
product.Caliber = req.Caliber;
product.ApprovalNumber = req.ApprovalNumber;
product.Weight = req.Weight;
product.Nec = req.Nec;
product.Image = req.Image;
product.Link = req.Link;
product.ClassificationId = req.ClassificationId;
product.ProductCategoryId = req.ProductCategoryId;
db.Prices.RemoveRange(product.Prices);
foreach (var s in req.Suppliers)
{
db.Prices.Add(new Price
{
ProductId = product.Id,
SupplierId = s.SupplierId,
SellingPrice = s.SellingPrice
});
}
db.WarehouseProducts.RemoveRange(product.WarehouseProducts);
foreach (var w in req.Warehouses)
{
db.WarehouseProducts.Add(new WarehouseProduct
{
ProductId = product.Id,
WarehouseId = w.WarehouseId,
Quantity = w.Quantity
});
}
await db.SaveChangesAsync(ct);
var response = new GetProductDto
{
Id = product.Id,
Reference = req.Reference,
Name = req.Name,
Duration = req.Duration,
Caliber = req.Caliber,
ApprovalNumber = req.ApprovalNumber,
Weight = req.Weight,
Nec = req.Nec,
SellingPrice = req.Suppliers.FirstOrDefault()?.SellingPrice ?? 0,
Image = req.Image,
Link = req.Link,
ClassificationId = req.ClassificationId,
ProductCategoryId = req.ProductCategoryId,
Suppliers = req.Suppliers.Select(s => new ProductSupplierPriceDto
{
SupplierId = s.SupplierId,
SellingPrice = s.SellingPrice
}).ToList(),
Warehouses = req.Warehouses.Select(w => new GetProductWarehouseDto
{
WarehouseId = w.WarehouseId,
Quantity = w.Quantity,
WarehouseName = db.Warehouses
.FirstOrDefault(x => x.Id == w.WarehouseId)?.Name ?? string.Empty
}).ToList()
};
await Send.OkAsync(response, ct);
}
}