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

61 lines
2.1 KiB
C#
Raw Normal View History

using CH.CQRS.Service.Energy;
using CH.CQRS.Service.Energy.Options;
2025-01-13 19:19:03 -05:00
using CH.Dal;
using CH.Dal.DbEntity;
using CH.Dal.Validators;
using CH.Enum;
using FluentValidation;
2025-01-13 19:19:03 -05:00
using Microsoft.EntityFrameworkCore;
using OpenHarbor.CQRS.Abstractions;
namespace CH.CQRS.Command.Energy;
public class CreateEnergyRateExceptionCommand
{
public long RateId { get; set; }
public required string Name { get; set; }
public decimal EnergyThreshold { get; set; }
2025-01-13 19:19:03 -05:00
public EnergyRateExceptionThresholdResetType ResetType { get; set; }
public DateTime? StartedAt { get; set; }
public DateTime? EndedAt { get; set; }
}
public class CreateEnergyRateExceptionCommandHandler(EnergyService energyService) : ICommandHandler<CreateEnergyRateExceptionCommand>
{
public Task HandleAsync(CreateEnergyRateExceptionCommand command,
CancellationToken cancellationToken = new CancellationToken())
{
return energyService.CreateEnergyRateExceptionAsync(new CreateEnergyRateExceptionCommandOptions
{
RateId = command.RateId,
Name = command.Name,
EnergyThreshold = command.EnergyThreshold,
ResetType = command.ResetType,
StartedAt = command.StartedAt,
EndedAt = command.EndedAt
}, cancellationToken);
}
}
public class CreateEnergyRateExceptionCommandValidator : AbstractValidator<CreateEnergyRateExceptionCommand>
{
2025-01-13 19:19:03 -05:00
public CreateEnergyRateExceptionCommandValidator(CHDbContext dbContext)
{
2025-01-13 19:19:03 -05:00
RuleFor(command => command.Name)
.NotEmpty()
.MinimumLength(3)
.MustAsync(async (name, cancellationToken) =>
{
var nameInUse = await dbContext.EnergyRateExceptions.AnyAsync(energyRateException => energyRateException.Name == name, cancellationToken);
return false == nameInUse;
})
.WithMessage("This Name is already in use by another energy rate exception.");
RuleFor(command => command.EnergyThreshold)
.GreaterThan(0);
2025-01-13 19:19:03 -05:00
RuleFor(command => command.RateId)
2025-01-13 19:19:03 -05:00
.NotEmpty()
.SetValidator(new DbEntityExistValidator<EnergyRate,long>(dbContext))
.WithMessage("The provided Rate Id is invalid.");
}
}