55 lines
1.8 KiB
C#
55 lines
1.8 KiB
C#
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 CreateEnergyRateCommand
|
|
{
|
|
public long ProviderId { get; set; }
|
|
public required string Name { get; set; }
|
|
public decimal Price { get; set; }
|
|
public Currency Currency { get; set; }
|
|
public bool Active { get; set; }
|
|
}
|
|
public class CreateEnergyRateCommandHandler(EnergyService energyService) : ICommandHandler<CreateEnergyRateCommand>
|
|
{
|
|
public Task HandleAsync(CreateEnergyRateCommand command, CancellationToken cancellationToken = new CancellationToken())
|
|
{
|
|
return energyService.CreateEnergyRateAsync(new CreateEnergyRateCommandOptions
|
|
{
|
|
ProviderId = command.ProviderId,
|
|
Name = command.Name,
|
|
Price = command.Price,
|
|
Currency = command.Currency,
|
|
Active = command.Active
|
|
},cancellationToken);
|
|
}
|
|
}
|
|
|
|
public class CreateEnergyRateCommandValidator : AbstractValidator<CreateEnergyRateCommand>
|
|
{
|
|
public CreateEnergyRateCommandValidator(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.Price).GreaterThanOrEqualTo(0);
|
|
RuleFor(command => command.ProviderId)
|
|
.NotEmpty()
|
|
.SetValidator(new DbEntityExistValidator<EnergyProvider,long>(dbContext))
|
|
.WithMessage("The provided provider Id is invalid.");
|
|
}
|
|
} |