2025-01-13 19:19:03 -05:00
|
|
|
using System.Data;
|
2025-01-10 15:59:51 -05:00
|
|
|
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;
|
2025-01-10 15:59:51 -05:00
|
|
|
using FluentValidation;
|
2025-01-13 19:19:03 -05:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
2025-01-10 15:59:51 -05:00
|
|
|
using OpenHarbor.CQRS.Abstractions;
|
|
|
|
|
|
|
|
namespace CH.CQRS.Command.Energy;
|
|
|
|
|
|
|
|
public class UpdateEnergyRateCommand
|
|
|
|
{
|
|
|
|
public long RateId { get; set; }
|
2025-01-13 19:19:03 -05:00
|
|
|
public string? Name { get; set; }
|
|
|
|
public DateTime? StartedAt { get; set; }
|
2025-01-10 15:59:51 -05:00
|
|
|
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,
|
2025-01-13 19:19:03 -05:00
|
|
|
Name = command.Name,
|
2025-01-10 15:59:51 -05:00
|
|
|
StartedAt = command.StartedAt,
|
2025-01-13 19:19:03 -05:00
|
|
|
Rate = command.Rate
|
2025-01-10 15:59:51 -05:00
|
|
|
}, cancellationToken);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class UpdateEnergyRateCommandValidator : AbstractValidator<UpdateEnergyRateCommand>
|
|
|
|
{
|
2025-01-13 19:19:03 -05:00
|
|
|
public UpdateEnergyRateCommandValidator(CHDbContext dbContext)
|
2025-01-10 15:59:51 -05:00
|
|
|
{
|
2025-01-13 19:19:03 -05:00
|
|
|
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.");
|
2025-01-10 15:59:51 -05:00
|
|
|
|
2025-01-13 19:19:03 -05:00
|
|
|
RuleFor(command => command.RateId)
|
|
|
|
.NotEmpty()
|
|
|
|
.SetValidator(new DbEntityExistValidator<EnergyRate,long>(dbContext))
|
|
|
|
.WithMessage("The provided Rate Id is invalid.");
|
|
|
|
|
|
|
|
RuleFor(command => command.Rate)
|
|
|
|
.GreaterThanOrEqualTo(0);
|
2025-01-10 15:59:51 -05:00
|
|
|
}
|
|
|
|
}
|