constellation-api/CH.CQRS/Command/Energy/UpdateEnergyRateCommand.cs

57 lines
1.8 KiB
C#

using System.Data;
using CH.CQRS.Service.Energy;
using CH.CQRS.Service.Energy.Options;
using CH.Dal;
using CH.Dal.DbEntity;
using CH.Dal.Validators;
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using OpenHarbor.CQRS.Abstractions;
namespace CH.CQRS.Command.Energy;
public class UpdateEnergyRateCommand
{
public long RateId { get; set; }
public string? Name { get; set; }
public DateTime? StartedAt { get; set; }
public decimal? Rate { get; set; }
}
public class UpdateEnergyRateCommandHandler(EnergyService energyService) : ICommandHandler<UpdateEnergyRateCommand>
{
public Task HandleAsync(UpdateEnergyRateCommand command, CancellationToken cancellationToken = new CancellationToken())
{
return energyService.UpdateEnergyRateAsync(new UpdateEnergyRateCommandOptions
{
RateId = command.RateId,
Name = command.Name,
StartedAt = command.StartedAt,
Rate = command.Rate
}, cancellationToken);
}
}
public class UpdateEnergyRateCommandValidator : AbstractValidator<UpdateEnergyRateCommand>
{
public UpdateEnergyRateCommandValidator(CHDbContext dbContext)
{
RuleFor(command => command.Name)
.NotEmpty()
.MinimumLength(3)
.When(command => false == String.IsNullOrWhiteSpace(command.Name))
.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.RateId)
.NotEmpty()
.SetValidator(new DbEntityExistValidator<EnergyRate,long>(dbContext))
.WithMessage("The provided Rate Id is invalid.");
RuleFor(command => command.Rate)
.GreaterThanOrEqualTo(0);
}
}