Files
Tizian.Breuch 32d6f4508f customerreviwew
2025-09-25 16:25:36 +02:00

74 lines
3.2 KiB
C#

// src/Webshop.Application/Services/Customers/CustomerReviewService.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using Webshop.Application;
using Webshop.Application.DTOs.Reviews;
using Webshop.Domain.Entities;
using Webshop.Domain.Interfaces;
using Webshop.Infrastructure.Data;
namespace Webshop.Application.Services.Customers
{
public class CustomerReviewService : ICustomerReviewService
{
private readonly IReviewRepository _reviewRepository;
private readonly ICustomerRepository _customerRepository;
private readonly ApplicationDbContext _context;
public CustomerReviewService(IReviewRepository reviewRepository, ICustomerRepository customerRepository, ApplicationDbContext context)
{
_reviewRepository = reviewRepository;
_customerRepository = customerRepository;
_context = context;
}
public async Task<ServiceResult<ReviewDto>> CreateReviewAsync(CreateReviewDto reviewDto, string userId)
{
var customer = await _customerRepository.GetByUserIdAsync(userId);
if (customer == null)
return ServiceResult.Fail<ReviewDto>(ServiceResultType.Unauthorized, "Kundenprofil nicht gefunden.");
// Business-Regel 1: Hat der Kunde dieses Produkt bereits bewertet?
bool hasAlreadyReviewed = await _context.Reviews
.AnyAsync(r => r.ProductId == reviewDto.ProductId && r.CustomerId == customer.Id);
if (hasAlreadyReviewed)
return ServiceResult.Fail<ReviewDto>(ServiceResultType.Conflict, "Sie haben dieses Produkt bereits bewertet.");
// Business-Regel 2: Hat der Kunde dieses Produkt überhaupt gekauft?
bool hasPurchased = await _context.OrderItems
.AnyAsync(oi => oi.ProductId == reviewDto.ProductId && oi.Order.CustomerId == customer.Id);
if (!hasPurchased)
return ServiceResult.Fail<ReviewDto>(ServiceResultType.Forbidden, "Sie können nur Produkte bewerten, die Sie auch gekauft haben.");
var newReview = new Review
{
ProductId = reviewDto.ProductId,
CustomerId = customer.Id,
Rating = reviewDto.Rating,
Title = reviewDto.Title,
Comment = reviewDto.Comment,
ReviewDate = DateTimeOffset.UtcNow,
IsApproved = false // Bewertungen müssen standardmäßig vom Admin freigegeben werden
};
await _reviewRepository.AddAsync(newReview);
// Mapping vervollständigen, um das erstellte Objekt zurückzugeben
var resultDto = new ReviewDto
{
Id = newReview.Id,
ProductId = newReview.ProductId,
CustomerName = $"{customer.FirstName} {customer.LastName}".Trim(),
Rating = newReview.Rating,
Title = newReview.Title,
Comment = newReview.Comment,
ReviewDate = newReview.ReviewDate,
IsApproved = newReview.IsApproved
};
return ServiceResult.Ok(resultDto);
}
}
}