71 lines
2.5 KiB
C#
71 lines
2.5 KiB
C#
using MediatR;
|
|
using InventoryService.Domain.AggregatesModel.SampleAggregate;
|
|
|
|
namespace InventoryService.API.Application.Commands;
|
|
|
|
/// <summary>
|
|
/// EN: Handler for ChangeSampleStatusCommand.
|
|
/// VI: Handler cho ChangeSampleStatusCommand.
|
|
/// </summary>
|
|
public class ChangeSampleStatusCommandHandler : IRequestHandler<ChangeSampleStatusCommand, bool>
|
|
{
|
|
private readonly ISampleRepository _sampleRepository;
|
|
private readonly ILogger<ChangeSampleStatusCommandHandler> _logger;
|
|
|
|
public ChangeSampleStatusCommandHandler(
|
|
ISampleRepository sampleRepository,
|
|
ILogger<ChangeSampleStatusCommandHandler> logger)
|
|
{
|
|
_sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository));
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
}
|
|
|
|
public async Task<bool> Handle(
|
|
ChangeSampleStatusCommand request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
_logger.LogInformation(
|
|
"Changing status of sample {SampleId} to {NewStatus} / Thay đổi trạng thái sample {SampleId} thành {NewStatus}",
|
|
request.SampleId, request.NewStatus);
|
|
|
|
// EN: Get existing sample / VI: Lấy sample đã tồn tại
|
|
var sample = await _sampleRepository.GetAsync(request.SampleId);
|
|
|
|
if (sample is null)
|
|
{
|
|
_logger.LogWarning(
|
|
"Sample {SampleId} not found / Sample {SampleId} không tìm thấy",
|
|
request.SampleId);
|
|
return false;
|
|
}
|
|
|
|
// EN: Change status based on action / VI: Thay đổi trạng thái dựa trên action
|
|
switch (request.NewStatus.ToLowerInvariant())
|
|
{
|
|
case "activate":
|
|
sample.Activate();
|
|
break;
|
|
case "complete":
|
|
sample.Complete();
|
|
break;
|
|
case "cancel":
|
|
sample.Cancel();
|
|
break;
|
|
default:
|
|
_logger.LogWarning(
|
|
"Invalid status action: {NewStatus} / Action trạng thái không hợp lệ: {NewStatus}",
|
|
request.NewStatus);
|
|
return false;
|
|
}
|
|
|
|
// EN: Save changes / VI: Lưu thay đổi
|
|
await _sampleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
|
|
|
_logger.LogInformation(
|
|
"Sample {SampleId} status changed to {NewStatus} / Trạng thái sample {SampleId} đã đổi thành {NewStatus}",
|
|
request.SampleId, request.NewStatus);
|
|
|
|
return true;
|
|
}
|
|
}
|