ReleaseStorageLocationCommandHandler.cs 2.36 KB
using MassTransit;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.MessageBus.Commands.StorageLocations;
using Rcs.Cyaninetech.Services;
using Rcs.Domain.Entities;
using Rcs.Domain.Repositories;

namespace Rcs.Infrastructure.MessageBus.Handlers.Commands.StorageLocations;

/// <summary>
/// 释放库位命令处理器
/// </summary>
public class ReleaseStorageLocationCommandHandler : IConsumer<ReleaseStorageLocationCommand>
{
    private readonly ILogger<ReleaseStorageLocationCommandHandler> _logger;
    private readonly IStorageLocationRepository _storageLocationRepository;
    private readonly ILanYinService _lanYinService;

    public ReleaseStorageLocationCommandHandler(
        ILogger<ReleaseStorageLocationCommandHandler> logger,
        IStorageLocationRepository storageLocationRepository,
        ILanYinService lanYinService)
    {
        _logger = logger;
        _storageLocationRepository = storageLocationRepository;
        _lanYinService = lanYinService;
    }

    public async Task Consume(ConsumeContext<ReleaseStorageLocationCommand> context)
    {
        var command = context.Message;

        try
        {
            var location = await _storageLocationRepository.GetByIdAsync(command.LocationId, context.CancellationToken);
            if (location == null)
            {
                await context.RespondAsync(ApiResponse.Failed($"库位不存在: {command.LocationId}"));
                return;
            }

            var releaseResult = await _lanYinService.ReleaseStoreLocationAsync(location.LocationCode, context.CancellationToken);
            if (!releaseResult.Success)
            {
                await context.RespondAsync(ApiResponse.Failed(releaseResult.Message));
                return;
            }

            location.Status = StorageLocationStatus.Empty;
            location.UpdatedAt = DateTime.Now;
            await _storageLocationRepository.UpdateAsync(location, context.CancellationToken);
            await _storageLocationRepository.SaveChangesAsync(context.CancellationToken);

            await context.RespondAsync(ApiResponse.Successful("释放库位成功"));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "释放库位失败: {LocationId}", command.LocationId);
            await context.RespondAsync(ApiResponse.Failed(ex.Message));
        }
    }
}