using CH.CQRS.Service.Energy; using CH.CQRS.Service.Energy.Options; using CH.Dal; using CH.Dal.DbEntity; using CH.Dal.Validators; using CH.Enum; using FluentValidation; using Microsoft.EntityFrameworkCore; using OpenHarbor.CQRS.Abstractions; namespace CH.CQRS.Command.Energy; public class AddEnergyRateCommand { public long ProviderId { get; set; } public required string Name { get; set; } public decimal Rate { get; set; } public Currency Currency { get; set; } public bool Active { get; set; } } public class AddEnergyRateCommandHandler(EnergyService energyService) : ICommandHandler { public Task HandleAsync(AddEnergyRateCommand command, CancellationToken cancellationToken = new CancellationToken()) { return energyService.CreateEnergyRateAsync(new AddEnergyRateCommandOptions { ProviderId = command.ProviderId, Name = command.Name, Rate = command.Rate, Currency = command.Currency, Active = command.Active },cancellationToken); } } public class AddEnergyRateCommandValidator : AbstractValidator { public AddEnergyRateCommandValidator(CHDbContext dbContext) { RuleFor(command => command.Name) .NotEmpty() .MinimumLength(3) .MustAsync(async (name, cancellationToken) => { var nameInUse = await dbContext.EnergyRates.AnyAsync(energyRate => energyRate.Name == name, cancellationToken); return false == nameInUse; }) .WithMessage("This Name is already in use by another energy rate."); RuleFor(command => command.Rate).GreaterThanOrEqualTo(0); RuleFor(command => command.ProviderId) .NotEmpty() .SetValidator(new DbEntityExistValidator(dbContext)) .WithMessage("The provided provider Id is invalid."); } }