adminproduct

This commit is contained in:
Tizian.Breuch
2025-09-25 14:22:29 +02:00
parent 39bd2fb5b3
commit 3447469851
3 changed files with 156 additions and 103 deletions

View File

@@ -5,8 +5,10 @@ using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Webshop.Application;
using Webshop.Application.DTOs.Products;
using Webshop.Application.Services.Admin.Interfaces;
namespace Webshop.Api.Controllers.Admin
{
[ApiController]
@@ -22,54 +24,93 @@ namespace Webshop.Api.Controllers.Admin
}
[HttpGet]
public async Task<ActionResult<IEnumerable<AdminProductDto>>> GetAdminProducts()
[ProducesResponseType(typeof(IEnumerable<AdminProductDto>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAdminProducts()
{
var products = await _adminProductService.GetAllAdminProductsAsync();
return Ok(products);
var result = await _adminProductService.GetAllAdminProductsAsync();
return Ok(result.Value);
}
[HttpGet("{id}")]
public async Task<ActionResult<AdminProductDto>> GetAdminProduct(Guid id)
[ProducesResponseType(typeof(AdminProductDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetAdminProduct(Guid id)
{
var product = await _adminProductService.GetAdminProductByIdAsync(id);
if (product == null) return NotFound();
return Ok(product);
var result = await _adminProductService.GetAdminProductByIdAsync(id);
return result.Type switch
{
ServiceResultType.Success => Ok(result.Value),
ServiceResultType.NotFound => NotFound(new { Message = result.ErrorMessage }),
_ => StatusCode(StatusCodes.Status500InternalServerError, new { Message = result.ErrorMessage ?? "Ein unerwarteter Fehler ist aufgetreten." })
};
}
[HttpPost]
[Consumes("multipart/form-data")]
public async Task<ActionResult<AdminProductDto>> CreateAdminProduct([FromForm] CreateAdminProductDto productDto)
[ProducesResponseType(typeof(AdminProductDto), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]
public async Task<IActionResult> CreateAdminProduct([FromForm] CreateAdminProductDto productDto)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
var createdProduct = await _adminProductService.CreateAdminProductAsync(productDto);
if (createdProduct == null) return BadRequest("Produkt konnte nicht erstellt werden.");
return CreatedAtAction(nameof(GetAdminProduct), new { id = createdProduct.Id }, createdProduct);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await _adminProductService.CreateAdminProductAsync(productDto);
return result.Type switch
{
ServiceResultType.Success => CreatedAtAction(nameof(GetAdminProduct), new { id = result.Value!.Id }, result.Value),
ServiceResultType.Conflict => Conflict(new { Message = result.ErrorMessage }),
ServiceResultType.InvalidInput => BadRequest(new { Message = result.ErrorMessage }),
_ => StatusCode(StatusCodes.Status500InternalServerError, new { Message = result.ErrorMessage ?? "Ein unerwarteter Fehler ist aufgetreten." })
};
}
[HttpPut("{id}")]
[Consumes("multipart/form-data")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]
public async Task<IActionResult> UpdateAdminProduct(Guid id, [FromForm] UpdateAdminProductDto productDto)
{
if (id != productDto.Id) return BadRequest("ID in URL und Body stimmen nicht <20>berein.");
if (!ModelState.IsValid) return BadRequest(ModelState);
var success = await _adminProductService.UpdateAdminProductAsync(productDto);
if (!success) return NotFound();
return NoContent();
if (id != productDto.Id)
{
return BadRequest(new { Message = "ID in der URL und im Body stimmen nicht <20>berein." });
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await _adminProductService.UpdateAdminProductAsync(productDto);
return result.Type switch
{
ServiceResultType.Success => NoContent(),
ServiceResultType.NotFound => NotFound(new { Message = result.ErrorMessage }),
ServiceResultType.Conflict => Conflict(new { Message = result.ErrorMessage }),
ServiceResultType.InvalidInput => BadRequest(new { Message = result.ErrorMessage }),
_ => StatusCode(StatusCodes.Status500InternalServerError, new { Message = result.ErrorMessage ?? "Ein unerwarteter Fehler ist aufgetreten." })
};
}
[HttpDelete("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> DeleteAdminProduct(Guid id)
{
var success = await _adminProductService.DeleteAdminProductAsync(id);
if (!success) return NotFound();
return NoContent();
var result = await _adminProductService.DeleteAdminProductAsync(id);
return result.Type switch
{
ServiceResultType.Success => NoContent(),
ServiceResultType.NotFound => NotFound(new { Message = result.ErrorMessage }),
_ => StatusCode(StatusCodes.Status500InternalServerError, new { Message = result.ErrorMessage ?? "Ein unerwarteter Fehler ist aufgetreten." })
};
}
}
}

View File

@@ -6,6 +6,7 @@ using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Webshop.Application;
using Webshop.Application.DTOs.Products;
using Webshop.Application.Services.Admin.Interfaces;
using Webshop.Infrastructure.Data;
@@ -16,7 +17,7 @@ namespace Webshop.Application.Services.Admin
{
private readonly IProductRepository _productRepository;
private readonly IFileStorageService _fileStorageService;
private readonly ApplicationDbContext _context;
private readonly ApplicationDbContext _context; // For checks that might not be in the repository
public AdminProductService(
IProductRepository productRepository,
@@ -28,7 +29,7 @@ namespace Webshop.Application.Services.Admin
_context = context;
}
public async Task<IEnumerable<AdminProductDto>> GetAllAdminProductsAsync()
public async Task<ServiceResult<IEnumerable<AdminProductDto>>> GetAllAdminProductsAsync()
{
var products = await _context.Products
.Include(p => p.Productcategories)
@@ -36,83 +37,46 @@ namespace Webshop.Application.Services.Admin
.OrderBy(p => p.Name)
.ToListAsync();
return products.Select(p => new AdminProductDto
{
Id = p.Id,
Name = p.Name,
Description = p.Description,
SKU = p.SKU,
Price = p.Price,
OldPrice = p.OldPrice,
IsActive = p.IsActive,
IsInStock = p.IsInStock,
StockQuantity = p.StockQuantity,
Weight = p.Weight,
Slug = p.Slug,
CreatedDate = p.CreatedDate,
LastModifiedDate = p.LastModifiedDate,
SupplierId = p.SupplierId,
PurchasePrice = p.PurchasePrice,
categorieIds = p.Productcategories.Select(pc => pc.categorieId).ToList(),
Images = p.Images.OrderBy(i => i.DisplayOrder).Select(img => new ProductImageDto
{
Id = img.Id,
Url = img.Url,
IsMainImage = img.IsMainImage,
DisplayOrder = img.DisplayOrder
}).ToList()
}).ToList();
var dtos = products.Select(MapToAdminDto).ToList();
return ServiceResult.Ok<IEnumerable<AdminProductDto>>(dtos);
}
public async Task<AdminProductDto?> GetAdminProductByIdAsync(Guid id)
public async Task<ServiceResult<AdminProductDto>> GetAdminProductByIdAsync(Guid id)
{
var product = await _context.Products
.Include(p => p.Productcategories)
.Include(p => p.Images)
.FirstOrDefaultAsync(p => p.Id == id);
if (product == null) return null;
return new AdminProductDto
if (product == null)
{
Id = product.Id,
Name = product.Name,
Description = product.Description,
SKU = product.SKU,
Price = product.Price,
OldPrice = product.OldPrice,
IsActive = product.IsActive,
IsInStock = product.IsInStock,
StockQuantity = product.StockQuantity,
Weight = product.Weight,
Slug = product.Slug,
CreatedDate = product.CreatedDate,
LastModifiedDate = product.LastModifiedDate,
SupplierId = product.SupplierId,
PurchasePrice = product.PurchasePrice,
categorieIds = product.Productcategories.Select(pc => pc.categorieId).ToList(),
Images = product.Images.OrderBy(i => i.DisplayOrder).Select(img => new ProductImageDto
{
Id = img.Id,
Url = img.Url,
IsMainImage = img.IsMainImage,
DisplayOrder = img.DisplayOrder
}).ToList()
};
return ServiceResult.Fail<AdminProductDto>(ServiceResultType.NotFound, $"Produkt mit ID '{id}' nicht gefunden.");
}
public async Task<AdminProductDto?> CreateAdminProductAsync(CreateAdminProductDto productDto)
{
var images = new List<ProductImage>();
return ServiceResult.Ok(MapToAdminDto(product));
}
// Hauptbild hochladen
public async Task<ServiceResult<AdminProductDto>> CreateAdminProductAsync(CreateAdminProductDto productDto)
{
var skuExists = await _context.Products.AnyAsync(p => p.SKU == productDto.SKU);
if (skuExists)
{
return ServiceResult.Fail<AdminProductDto>(ServiceResultType.Conflict, $"Ein Produkt mit der SKU '{productDto.SKU}' existiert bereits.");
}
var slugExists = await _context.Products.AnyAsync(p => p.Slug == productDto.Slug);
if (slugExists)
{
return ServiceResult.Fail<AdminProductDto>(ServiceResultType.Conflict, $"Ein Produkt mit dem Slug '{productDto.Slug}' existiert bereits.");
}
var images = new List<ProductImage>();
// Bild-Upload Logik...
if (productDto.MainImageFile != null)
{
await using var stream = productDto.MainImageFile.OpenReadStream();
var url = await _fileStorageService.SaveFileAsync(stream, productDto.MainImageFile.FileName, productDto.MainImageFile.ContentType);
images.Add(new ProductImage { Url = url, IsMainImage = true, DisplayOrder = 1 });
}
// Weitere Bilder hochladen
if (productDto.AdditionalImageFiles != null)
{
int order = 2;
@@ -137,33 +101,46 @@ namespace Webshop.Application.Services.Admin
OldPrice = productDto.OldPrice,
SupplierId = productDto.SupplierId,
PurchasePrice = productDto.PurchasePrice,
IsFeatured = productDto.IsFeatured, // << NEU >>
FeaturedDisplayOrder = productDto.FeaturedDisplayOrder, // << NEU >>
IsFeatured = productDto.IsFeatured,
FeaturedDisplayOrder = productDto.FeaturedDisplayOrder,
Images = images,
Productcategories = productDto.CategorieIds.Select(cId => new Productcategorie { categorieId = cId }).ToList()
};
await _productRepository.AddProductAsync(newProduct);
return await GetAdminProductByIdAsync(newProduct.Id);
return ServiceResult.Ok(MapToAdminDto(newProduct));
}
public async Task<bool> UpdateAdminProductAsync(UpdateAdminProductDto productDto)
public async Task<ServiceResult> UpdateAdminProductAsync(UpdateAdminProductDto productDto)
{
var existingProduct = await _context.Products
.Include(p => p.Images)
.Include(p => p.Productcategories)
.FirstOrDefaultAsync(p => p.Id == productDto.Id);
if (existingProduct == null) return false;
if (existingProduct == null)
{
return ServiceResult.Fail(ServiceResultType.NotFound, $"Produkt mit ID '{productDto.Id}' nicht gefunden.");
}
// Bilder l<>schen
var skuExists = await _context.Products.AnyAsync(p => p.SKU == productDto.SKU && p.Id != productDto.Id);
if (skuExists)
{
return ServiceResult.Fail(ServiceResultType.Conflict, $"Ein anderes Produkt mit der SKU '{productDto.SKU}' existiert bereits.");
}
var slugExists = await _context.Products.AnyAsync(p => p.Slug == productDto.Slug && p.Id != productDto.Id);
if (slugExists)
{
return ServiceResult.Fail(ServiceResultType.Conflict, $"Ein anderes Produkt mit dem Slug '{productDto.Slug}' existiert bereits.");
}
// Bild-Management Logik...
if (productDto.ImagesToDelete != null && productDto.ImagesToDelete.Any())
{
var imagesToRemove = existingProduct.Images.Where(img => productDto.ImagesToDelete.Contains(img.Id)).ToList();
_context.ProductImages.RemoveRange(imagesToRemove);
}
// Hauptbild aktualisieren/hochladen
if (productDto.MainImageFile != null)
{
var existingMainImage = existingProduct.Images.FirstOrDefault(img => img.IsMainImage);
@@ -173,7 +150,6 @@ namespace Webshop.Application.Services.Admin
var url = await _fileStorageService.SaveFileAsync(stream, productDto.MainImageFile.FileName, productDto.MainImageFile.ContentType);
existingProduct.Images.Add(new ProductImage { Url = url, IsMainImage = true, DisplayOrder = 1 });
}
// Weitere Bilder hinzuf<75>gen
if (productDto.AdditionalImageFiles != null && productDto.AdditionalImageFiles.Any())
{
int displayOrder = (existingProduct.Images.Any() ? existingProduct.Images.Max(i => i.DisplayOrder) : 0) + 1;
@@ -185,7 +161,7 @@ namespace Webshop.Application.Services.Admin
}
}
// Basisdaten aktualisieren
// Basisdaten aktualisieren...
existingProduct.Name = productDto.Name;
existingProduct.Description = productDto.Description;
existingProduct.SKU = productDto.SKU;
@@ -198,8 +174,8 @@ namespace Webshop.Application.Services.Admin
existingProduct.SupplierId = productDto.SupplierId;
existingProduct.PurchasePrice = productDto.PurchasePrice;
existingProduct.LastModifiedDate = DateTimeOffset.UtcNow;
existingProduct.IsFeatured = productDto.IsFeatured; // << NEU >>
existingProduct.FeaturedDisplayOrder = productDto.FeaturedDisplayOrder; // << NEU >>
existingProduct.IsFeatured = productDto.IsFeatured;
existingProduct.FeaturedDisplayOrder = productDto.FeaturedDisplayOrder;
// Kategorien synchronisieren
existingProduct.Productcategories.Clear();
@@ -212,16 +188,51 @@ namespace Webshop.Application.Services.Admin
}
await _productRepository.UpdateProductAsync(existingProduct);
return true;
return ServiceResult.Ok();
}
public async Task<bool> DeleteAdminProductAsync(Guid id)
public async Task<ServiceResult> DeleteAdminProductAsync(Guid id)
{
var product = await _productRepository.GetProductByIdAsync(id);
if (product == null) return false;
if (product == null)
{
return ServiceResult.Fail(ServiceResultType.NotFound, $"Produkt mit ID '{id}' nicht gefunden.");
}
await _productRepository.DeleteProductAsync(id);
return true;
return ServiceResult.Ok();
}
private AdminProductDto MapToAdminDto(Product product)
{
return new AdminProductDto
{
Id = product.Id,
Name = product.Name,
Description = product.Description,
SKU = product.SKU,
Price = product.Price,
OldPrice = product.OldPrice,
IsActive = product.IsActive,
IsInStock = product.IsInStock,
StockQuantity = product.StockQuantity,
Weight = product.Weight,
Slug = product.Slug,
CreatedDate = product.CreatedDate,
LastModifiedDate = product.LastModifiedDate,
SupplierId = product.SupplierId,
PurchasePrice = product.PurchasePrice,
IsFeatured = product.IsFeatured,
FeaturedDisplayOrder = product.FeaturedDisplayOrder,
categorieIds = product.Productcategories.Select(pc => pc.categorieId).ToList(),
Images = product.Images.OrderBy(i => i.DisplayOrder).Select(img => new ProductImageDto
{
Id = img.Id,
Url = img.Url,
IsMainImage = img.IsMainImage,
DisplayOrder = img.DisplayOrder
}).ToList()
};
}
}
}

View File

@@ -2,16 +2,17 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Webshop.Application;
using Webshop.Application.DTOs.Products;
namespace Webshop.Application.Services.Admin.Interfaces
{
public interface IAdminProductService
{
Task<IEnumerable<AdminProductDto>> GetAllAdminProductsAsync();
Task<AdminProductDto?> GetAdminProductByIdAsync(Guid id);
Task<AdminProductDto?> CreateAdminProductAsync(CreateAdminProductDto productDto); // << DTO-TYP GEÄNDERT >>
Task<bool> UpdateAdminProductAsync(UpdateAdminProductDto productDto); // << DTO-TYP GEÄNDERT >>
Task<bool> DeleteAdminProductAsync(Guid id);
Task<ServiceResult<IEnumerable<AdminProductDto>>> GetAllAdminProductsAsync();
Task<ServiceResult<AdminProductDto>> GetAdminProductByIdAsync(Guid id);
Task<ServiceResult<AdminProductDto>> CreateAdminProductAsync(CreateAdminProductDto productDto);
Task<ServiceResult> UpdateAdminProductAsync(UpdateAdminProductDto productDto);
Task<ServiceResult> DeleteAdminProductAsync(Guid id);
}
}