79 lines
2.6 KiB
C#
79 lines
2.6 KiB
C#
// src/Webshop.Application/Services/ProductService.cs
|
|
using Webshop.Application.DTOs;
|
|
using Webshop.Domain.Entities;
|
|
using Webshop.Domain.Interfaces;
|
|
|
|
namespace Webshop.Application.Services
|
|
{
|
|
public class ProductService
|
|
{
|
|
private readonly IProductRepository _productRepository;
|
|
|
|
public ProductService(IProductRepository productRepository)
|
|
{
|
|
_productRepository = productRepository;
|
|
}
|
|
|
|
public async Task<IEnumerable<ProductDto>> GetAllProductsAsync()
|
|
{
|
|
var productsFromDb = await _productRepository.GetAllProductsAsync();
|
|
|
|
var productDtos = productsFromDb.Select(p => new ProductDto
|
|
{
|
|
Id = p.Id,
|
|
Name = p.Name,
|
|
Description = p.Description,
|
|
Price = p.Price,
|
|
Sku = p.SKU
|
|
});
|
|
|
|
return productDtos;
|
|
}
|
|
|
|
public async Task<ProductDto> CreateProductAsync(ProductDto productDto)
|
|
{
|
|
var newProduct = new Product
|
|
{
|
|
// Felder aus DTO
|
|
Name = productDto.Name,
|
|
Description = productDto.Description,
|
|
Price = productDto.Price,
|
|
SKU = productDto.Sku,
|
|
ShortDescription = productDto.ShortDescription,
|
|
IsActive = productDto.IsActive,
|
|
IsInStock = productDto.IsInStock,
|
|
StockQuantity = productDto.StockQuantity,
|
|
Slug = productDto.Slug,
|
|
|
|
|
|
Id = Guid.NewGuid(),
|
|
CreatedDate = DateTimeOffset.UtcNow,
|
|
LastModifiedDate = null,
|
|
|
|
};
|
|
|
|
if (string.IsNullOrWhiteSpace(newProduct.Slug) && !string.IsNullOrWhiteSpace(newProduct.Name))
|
|
{
|
|
newProduct.Slug = GenerateSlug(newProduct.Name);
|
|
}
|
|
|
|
await _productRepository.AddProductAsync(newProduct);
|
|
|
|
productDto.Id = newProduct.Id;
|
|
return productDto;
|
|
}
|
|
|
|
private string GenerateSlug(string name)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(name)) return Guid.NewGuid().ToString(); // Fallback
|
|
var slug = name.ToLowerInvariant()
|
|
.Replace(" ", "-")
|
|
.Replace("ä", "ae").Replace("ö", "oe").Replace("ü", "ue")
|
|
.Replace("ß", "ss")
|
|
.Trim();
|
|
// Entferne ungültige Zeichen
|
|
slug = System.Text.RegularExpressions.Regex.Replace(slug, @"[^a-z0-9-]", "");
|
|
return slug;
|
|
}
|
|
}
|
|
} |