feat(order): 订单批量任务 RabbitMQ 异步处理与治理 API
引入批量 Job 表、RabbitMQ 队列与消费者,支持导入/小包创建及我的订单批量操作异步化,并提供任务列表、重试失败、取消 pending 与 DLX 监控接口及测试。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
dd5c82e523
commit
4f3bbd17bc
18
docker-compose.yml
Normal file
18
docker-compose.yml
Normal file
@ -0,0 +1,18 @@
|
||||
version: "3.8"
|
||||
|
||||
services:
|
||||
rabbitmq:
|
||||
image: rabbitmq:3.13-management
|
||||
container_name: oms-rabbitmq
|
||||
ports:
|
||||
- "5672:5672"
|
||||
- "15672:15672"
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: oms
|
||||
RABBITMQ_DEFAULT_PASS: oms123
|
||||
RABBITMQ_DEFAULT_VHOST: /oms
|
||||
volumes:
|
||||
- oms_rabbitmq_data:/var/lib/rabbitmq
|
||||
|
||||
volumes:
|
||||
oms_rabbitmq_data:
|
||||
52
scripts/order_batch_job_tables.sql
Normal file
52
scripts/order_batch_job_tables.sql
Normal file
@ -0,0 +1,52 @@
|
||||
-- 订单批量异步任务表(RabbitMQ 方案)
|
||||
-- 执行前请确认数据库为 oms
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `t_order_batch_job` (
|
||||
`Id` int NOT NULL AUTO_INCREMENT,
|
||||
`Action` varchar(64) NOT NULL DEFAULT '',
|
||||
`Status` varchar(32) NOT NULL DEFAULT 'pending',
|
||||
`Total` int NOT NULL DEFAULT 0,
|
||||
`SuccessCount` int NOT NULL DEFAULT 0,
|
||||
`FailCount` int NOT NULL DEFAULT 0,
|
||||
`CustomerId` int NULL,
|
||||
`PayloadJson` json NULL,
|
||||
`RequestId` varchar(64) NULL,
|
||||
`StartedAt` datetime NULL,
|
||||
`FinishedAt` datetime NULL,
|
||||
`IsDeleted` tinyint(1) NOT NULL DEFAULT 0,
|
||||
`CreateUserId` int NOT NULL DEFAULT 0,
|
||||
`CreateTime` datetime NOT NULL,
|
||||
`UpdateUserId` int NULL,
|
||||
`UpdateTime` datetime NULL,
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `idx_order_batch_job_request` (`RequestId`),
|
||||
KEY `idx_order_batch_job_status` (`Status`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `t_order_batch_job_item` (
|
||||
`Id` int NOT NULL AUTO_INCREMENT,
|
||||
`JobId` int NOT NULL,
|
||||
`OrderId` int NOT NULL,
|
||||
`ServiceNo` varchar(64) NULL,
|
||||
`Action` varchar(64) NOT NULL DEFAULT '',
|
||||
`Status` varchar(32) NOT NULL DEFAULT 'pending',
|
||||
`MessageId` varchar(128) NULL,
|
||||
`FailReason` text NULL,
|
||||
`RetryCount` int NOT NULL DEFAULT 0,
|
||||
`StartedAt` datetime NULL,
|
||||
`FinishedAt` datetime NULL,
|
||||
`IsDeleted` tinyint(1) NOT NULL DEFAULT 0,
|
||||
`CreateUserId` int NOT NULL DEFAULT 0,
|
||||
`CreateTime` datetime NOT NULL,
|
||||
`UpdateUserId` int NULL,
|
||||
`UpdateTime` datetime NULL,
|
||||
PRIMARY KEY (`Id`),
|
||||
UNIQUE KEY `uk_order_batch_job_item_message` (`MessageId`),
|
||||
KEY `idx_order_batch_job_item_job` (`JobId`),
|
||||
KEY `idx_order_batch_job_item_order` (`OrderId`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- 阶段三:若表已存在,请执行
|
||||
-- ALTER TABLE `t_order_batch_job_item` ADD COLUMN `ResultJson` text NULL AFTER `FailReason`;
|
||||
-- 阶段四:若表已存在,请执行
|
||||
-- ALTER TABLE `t_order_batch_job_item` ADD COLUMN `PayloadJson` text NULL AFTER `FailReason`;
|
||||
39
src/Oms.Application/Dtos/Orders/OrderBatchGovernanceDtos.cs
Normal file
39
src/Oms.Application/Dtos/Orders/OrderBatchGovernanceDtos.cs
Normal file
@ -0,0 +1,39 @@
|
||||
namespace Oms.Application.Dtos.Orders;
|
||||
|
||||
public class OrderBatchQueueStatOutput
|
||||
{
|
||||
public string QueueName { get; set; } = string.Empty;
|
||||
|
||||
public uint MessageCount { get; set; }
|
||||
|
||||
public uint ConsumerCount { get; set; }
|
||||
}
|
||||
|
||||
public class OrderBatchDlxStatsOutput
|
||||
{
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
public uint DeadLetterMessageCount { get; set; }
|
||||
|
||||
public uint DlxAlertThreshold { get; set; }
|
||||
|
||||
public bool Alert { get; set; }
|
||||
|
||||
public List<OrderBatchQueueStatOutput> Queues { get; set; } = [];
|
||||
}
|
||||
|
||||
public class OrderBatchJobManageOutput
|
||||
{
|
||||
public int JobId { get; set; }
|
||||
|
||||
public int RetriedCount { get; set; }
|
||||
|
||||
public int CancelledCount { get; set; }
|
||||
|
||||
public string Status { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class OrderBatchJobRetryFailedInput
|
||||
{
|
||||
public List<int> ItemIds { get; set; } = [];
|
||||
}
|
||||
56
src/Oms.Application/Dtos/Orders/OrderBatchJobDtos.cs
Normal file
56
src/Oms.Application/Dtos/Orders/OrderBatchJobDtos.cs
Normal file
@ -0,0 +1,56 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Oms.Application.Dtos.Orders;
|
||||
|
||||
public class OrderBatchJobCreateInput
|
||||
{
|
||||
[Required]
|
||||
public string Action { get; set; } = string.Empty;
|
||||
|
||||
public List<int> OrderIds { get; set; } = [];
|
||||
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
[StringLength(64)]
|
||||
public string? RequestId { get; set; }
|
||||
}
|
||||
|
||||
public class OrderBatchJobOutput
|
||||
{
|
||||
public int JobId { get; set; }
|
||||
|
||||
public string Action { get; set; } = string.Empty;
|
||||
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
public int Total { get; set; }
|
||||
|
||||
public int SuccessCount { get; set; }
|
||||
|
||||
public int FailCount { get; set; }
|
||||
|
||||
public DateTime? StartedAt { get; set; }
|
||||
|
||||
public DateTime? FinishedAt { get; set; }
|
||||
|
||||
public DateTime? CreateTime { get; set; }
|
||||
}
|
||||
|
||||
public class OrderBatchJobItemOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public int OrderId { get; set; }
|
||||
|
||||
public string? ServiceNo { get; set; }
|
||||
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
public string? FailReason { get; set; }
|
||||
|
||||
public string? ResultJson { get; set; }
|
||||
|
||||
public DateTime? StartedAt { get; set; }
|
||||
|
||||
public DateTime? FinishedAt { get; set; }
|
||||
}
|
||||
17
src/Oms.Application/Dtos/Orders/OrderBatchJobListInput.cs
Normal file
17
src/Oms.Application/Dtos/Orders/OrderBatchJobListInput.cs
Normal file
@ -0,0 +1,17 @@
|
||||
namespace Oms.Application.Dtos.Orders;
|
||||
|
||||
/// <summary>
|
||||
/// 批量任务列表查询入参。
|
||||
/// </summary>
|
||||
public class OrderBatchJobListInput
|
||||
{
|
||||
public int Page { get; set; } = 1;
|
||||
|
||||
public int PageSize { get; set; } = 30;
|
||||
|
||||
public string? Status { get; set; }
|
||||
|
||||
public string? Action { get; set; }
|
||||
|
||||
public int? JobId { get; set; }
|
||||
}
|
||||
54
src/Oms.Application/Dtos/Orders/OrderBatchPayloadDtos.cs
Normal file
54
src/Oms.Application/Dtos/Orders/OrderBatchPayloadDtos.cs
Normal file
@ -0,0 +1,54 @@
|
||||
namespace Oms.Application.Dtos.Orders;
|
||||
|
||||
/// <summary>
|
||||
/// 批量任务子项(无订单 ID,按 PayloadJson 投递)。
|
||||
/// </summary>
|
||||
public class OrderBatchPayloadItemInput
|
||||
{
|
||||
public int OrderId { get; set; }
|
||||
|
||||
public string? ServiceNo { get; set; }
|
||||
|
||||
public string PayloadJson { get; set; } = string.Empty;
|
||||
|
||||
public string? ItemKey { get; set; }
|
||||
}
|
||||
|
||||
public class OrderBatchPayloadJobCreateInput
|
||||
{
|
||||
public string Action { get; set; } = string.Empty;
|
||||
|
||||
public int? CustomerId { get; set; }
|
||||
|
||||
public string? JobPayloadJson { get; set; }
|
||||
|
||||
public string? RequestId { get; set; }
|
||||
|
||||
public List<OrderBatchPayloadItemInput> Items { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Excel 导入单行消息体。
|
||||
/// </summary>
|
||||
public class OrderBatchImportRowPayload
|
||||
{
|
||||
public int TaskId { get; set; }
|
||||
|
||||
public int RowNumber { get; set; }
|
||||
|
||||
public int CustomerId { get; set; }
|
||||
|
||||
public string RowDataJson { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 导入 Job 级元数据,写入 OrderBatchJob.PayloadJson。
|
||||
/// </summary>
|
||||
public class OrderBatchImportJobPayload
|
||||
{
|
||||
public int TaskId { get; set; }
|
||||
|
||||
public int TemplateId { get; set; }
|
||||
|
||||
public int CustomerId { get; set; }
|
||||
}
|
||||
@ -24,4 +24,19 @@ public class OrderParcelBatchCreateOutput
|
||||
/// 逐条处理结果。
|
||||
/// </summary>
|
||||
public List<OrderParcelBatchCreateItemOutput> Items { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 关联批量 Job(异步模式)。
|
||||
/// </summary>
|
||||
public int? JobId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否已转为异步 Job 处理。
|
||||
/// </summary>
|
||||
public bool Async { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 异步任务总数。
|
||||
/// </summary>
|
||||
public int Total { get; set; }
|
||||
}
|
||||
|
||||
@ -9,4 +9,14 @@ public class OrderUploadOutput
|
||||
/// 任务主键。
|
||||
/// </summary>
|
||||
public int TaskId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 关联批量 Job(异步导入时返回)。
|
||||
/// </summary>
|
||||
public int? JobId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否异步处理中。
|
||||
/// </summary>
|
||||
public bool Async { get; set; }
|
||||
}
|
||||
|
||||
@ -5,5 +5,5 @@ namespace Oms.Application.Integrations.SmallBagTrack;
|
||||
/// </summary>
|
||||
public interface ISmallBagTrackOrderNotifier
|
||||
{
|
||||
void Enqueue(SmallBagTrackUpsertRequest request);
|
||||
void Enqueue(SmallBagTrackUpsertRequest request, int orderId, int? customerId = null);
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Oms.Application.Services.Orders.Batch;
|
||||
|
||||
namespace Oms.Application.Integrations.SmallBagTrack;
|
||||
|
||||
@ -7,9 +8,28 @@ internal sealed class SmallBagTrackOrderNotifier(
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger<SmallBagTrackOrderNotifier> logger) : ISmallBagTrackOrderNotifier
|
||||
{
|
||||
public void Enqueue(SmallBagTrackUpsertRequest request)
|
||||
public void Enqueue(SmallBagTrackUpsertRequest request, int orderId, int? customerId = null)
|
||||
{
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
var coordinator = scope.ServiceProvider.GetRequiredService<OrderBatchJobCoordinator>();
|
||||
await coordinator.PublishTrackUpsertAsync(request, orderId, customerId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(
|
||||
ex,
|
||||
"RabbitMQ track upsert publish failed, fallback to direct call. orderId={OrderId}",
|
||||
orderId);
|
||||
await FallbackDirectAsync(request);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async Task FallbackDirectAsync(SmallBagTrackUpsertRequest request)
|
||||
{
|
||||
try
|
||||
{
|
||||
@ -19,8 +39,7 @@ internal sealed class SmallBagTrackOrderNotifier(
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Async UpsertSmallBag failed for order {OrderNo}", request.OrderNo);
|
||||
}
|
||||
});
|
||||
logger.LogWarning(ex, "Fallback UpsertSmallBag failed for order {OrderNo}", request.OrderNo);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
8
src/Oms.Application/Messaging/IOrderBatchJobPublisher.cs
Normal file
8
src/Oms.Application/Messaging/IOrderBatchJobPublisher.cs
Normal file
@ -0,0 +1,8 @@
|
||||
namespace Oms.Application.Messaging;
|
||||
|
||||
public interface IOrderBatchJobPublisher
|
||||
{
|
||||
Task PublishAsync(OrderBatchJobMessage message, CancellationToken cancellationToken = default);
|
||||
|
||||
bool IsEnabled { get; }
|
||||
}
|
||||
25
src/Oms.Application/Messaging/OrderBatchJobMessage.cs
Normal file
25
src/Oms.Application/Messaging/OrderBatchJobMessage.cs
Normal file
@ -0,0 +1,25 @@
|
||||
namespace Oms.Application.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 订单批量任务 RabbitMQ 消息体。
|
||||
/// </summary>
|
||||
public class OrderBatchJobMessage
|
||||
{
|
||||
public long JobId { get; set; }
|
||||
|
||||
public long JobItemId { get; set; }
|
||||
|
||||
public string Action { get; set; } = string.Empty;
|
||||
|
||||
public int OrderId { get; set; }
|
||||
|
||||
public int? CustomerId { get; set; }
|
||||
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
public int OperatorUserId { get; set; }
|
||||
|
||||
public string MessageId { get; set; } = string.Empty;
|
||||
|
||||
public int RetryCount { get; set; }
|
||||
}
|
||||
101
src/Oms.Application/Messaging/OrderBatchJobPublisher.cs
Normal file
101
src/Oms.Application/Messaging/OrderBatchJobPublisher.cs
Normal file
@ -0,0 +1,101 @@
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Newtonsoft.Json;
|
||||
using RabbitMQ.Client;
|
||||
|
||||
namespace Oms.Application.Messaging;
|
||||
|
||||
public sealed class OrderBatchJobPublisher : IOrderBatchJobPublisher, IDisposable
|
||||
{
|
||||
private readonly OrderBatchRabbitMqOptions _options;
|
||||
private readonly ILogger<OrderBatchJobPublisher> _logger;
|
||||
private readonly object _sync = new();
|
||||
private IConnection? _connection;
|
||||
private bool _disposed;
|
||||
|
||||
public OrderBatchJobPublisher(
|
||||
IOptions<OrderBatchRabbitMqOptions> options,
|
||||
ILogger<OrderBatchJobPublisher> logger)
|
||||
{
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public bool IsEnabled => _options.Enabled;
|
||||
|
||||
public Task PublishAsync(OrderBatchJobMessage message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
{
|
||||
throw new InvalidOperationException("Order batch RabbitMQ is disabled.");
|
||||
}
|
||||
|
||||
var routingKey = OrderBatchQueueTopology.ResolveRoutingKey(message.Action);
|
||||
var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
|
||||
|
||||
lock (_sync)
|
||||
{
|
||||
EnsureConnection();
|
||||
using var channel = _connection!.CreateModel();
|
||||
var props = channel.CreateBasicProperties();
|
||||
props.Persistent = true;
|
||||
props.ContentType = "application/json";
|
||||
props.MessageId = message.MessageId;
|
||||
props.Headers = new Dictionary<string, object>
|
||||
{
|
||||
["action"] = message.Action,
|
||||
["jobId"] = message.JobId,
|
||||
["jobItemId"] = message.JobItemId,
|
||||
};
|
||||
|
||||
channel.BasicPublish(
|
||||
exchange: OrderBatchQueueTopology.Exchange,
|
||||
routingKey: routingKey,
|
||||
mandatory: false,
|
||||
basicProperties: props,
|
||||
body: body);
|
||||
}
|
||||
|
||||
_logger.LogDebug(
|
||||
"Published order batch message {MessageId} action={Action} routingKey={RoutingKey}",
|
||||
message.MessageId,
|
||||
message.Action,
|
||||
routingKey);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void EnsureConnection()
|
||||
{
|
||||
if (_connection is { IsOpen: true })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var factory = new ConnectionFactory
|
||||
{
|
||||
HostName = _options.HostName,
|
||||
Port = _options.Port,
|
||||
UserName = _options.UserName,
|
||||
Password = _options.Password,
|
||||
VirtualHost = _options.VirtualHost,
|
||||
DispatchConsumersAsync = true,
|
||||
AutomaticRecoveryEnabled = true,
|
||||
};
|
||||
|
||||
_connection?.Dispose();
|
||||
_connection = factory.CreateConnection("oms-order-batch-publisher");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
_connection?.Dispose();
|
||||
}
|
||||
}
|
||||
90
src/Oms.Application/Messaging/OrderBatchQueueInitializer.cs
Normal file
90
src/Oms.Application/Messaging/OrderBatchQueueInitializer.cs
Normal file
@ -0,0 +1,90 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using RabbitMQ.Client;
|
||||
|
||||
namespace Oms.Application.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 应用启动时声明订单批量 Exchange / Queue / Binding。
|
||||
/// </summary>
|
||||
public sealed class OrderBatchQueueInitializer : IHostedService
|
||||
{
|
||||
private readonly OrderBatchRabbitMqOptions _options;
|
||||
private readonly ILogger<OrderBatchQueueInitializer> _logger;
|
||||
|
||||
public OrderBatchQueueInitializer(
|
||||
IOptions<OrderBatchRabbitMqOptions> options,
|
||||
ILogger<OrderBatchQueueInitializer> logger)
|
||||
{
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
{
|
||||
_logger.LogInformation("Order batch RabbitMQ disabled, skip queue initialization.");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = CreateConnection();
|
||||
using var channel = connection.CreateModel();
|
||||
|
||||
channel.ExchangeDeclare(OrderBatchQueueTopology.DeadLetterExchange, ExchangeType.Topic, durable: true);
|
||||
channel.QueueDeclare(
|
||||
OrderBatchQueueTopology.QueueDeadLetter,
|
||||
durable: true,
|
||||
exclusive: false,
|
||||
autoDelete: false);
|
||||
channel.QueueBind(
|
||||
OrderBatchQueueTopology.QueueDeadLetter,
|
||||
OrderBatchQueueTopology.DeadLetterExchange,
|
||||
OrderBatchQueueTopology.RoutingDeadLetter);
|
||||
|
||||
channel.ExchangeDeclare(OrderBatchQueueTopology.Exchange, ExchangeType.Topic, durable: true);
|
||||
|
||||
var queueArgs = new Dictionary<string, object>
|
||||
{
|
||||
["x-dead-letter-exchange"] = OrderBatchQueueTopology.DeadLetterExchange,
|
||||
["x-dead-letter-routing-key"] = OrderBatchQueueTopology.RoutingDeadLetter,
|
||||
};
|
||||
|
||||
foreach (var (queue, routingKey) in OrderBatchQueueTopology.Bindings)
|
||||
{
|
||||
channel.QueueDeclare(queue, durable: true, exclusive: false, autoDelete: false, arguments: queueArgs);
|
||||
channel.QueueBind(queue, OrderBatchQueueTopology.Exchange, routingKey);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Order batch RabbitMQ topology initialized.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to initialize order batch RabbitMQ topology.");
|
||||
throw;
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
|
||||
private IConnection CreateConnection()
|
||||
{
|
||||
var factory = new ConnectionFactory
|
||||
{
|
||||
HostName = _options.HostName,
|
||||
Port = _options.Port,
|
||||
UserName = _options.UserName,
|
||||
Password = _options.Password,
|
||||
VirtualHost = _options.VirtualHost,
|
||||
DispatchConsumersAsync = true,
|
||||
AutomaticRecoveryEnabled = true,
|
||||
};
|
||||
|
||||
return factory.CreateConnection("oms-order-batch-init");
|
||||
}
|
||||
}
|
||||
115
src/Oms.Application/Messaging/OrderBatchQueueInspector.cs
Normal file
115
src/Oms.Application/Messaging/OrderBatchQueueInspector.cs
Normal file
@ -0,0 +1,115 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using RabbitMQ.Client;
|
||||
|
||||
namespace Oms.Application.Messaging;
|
||||
|
||||
public interface IOrderBatchQueueInspector
|
||||
{
|
||||
bool IsEnabled { get; }
|
||||
|
||||
Task<OrderBatchDlxStatsOutput> GetStatsAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public sealed class OrderBatchQueueInspector : IOrderBatchQueueInspector, IDisposable
|
||||
{
|
||||
private readonly OrderBatchRabbitMqOptions _options;
|
||||
private readonly ILogger<OrderBatchQueueInspector> _logger;
|
||||
private readonly object _sync = new();
|
||||
private IConnection? _connection;
|
||||
|
||||
public OrderBatchQueueInspector(
|
||||
IOptions<OrderBatchRabbitMqOptions> options,
|
||||
ILogger<OrderBatchQueueInspector> logger)
|
||||
{
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public bool IsEnabled => _options.Enabled;
|
||||
|
||||
public Task<OrderBatchDlxStatsOutput> GetStatsAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
{
|
||||
return Task.FromResult(new OrderBatchDlxStatsOutput
|
||||
{
|
||||
Enabled = false,
|
||||
DlxAlertThreshold = _options.DlxAlertThreshold,
|
||||
});
|
||||
}
|
||||
|
||||
lock (_sync)
|
||||
{
|
||||
EnsureConnection();
|
||||
using var channel = _connection!.CreateModel();
|
||||
var queues = new List<OrderBatchQueueStatOutput>
|
||||
{
|
||||
InspectQueue(channel, OrderBatchQueueTopology.QueueDeadLetter),
|
||||
InspectQueue(channel, OrderBatchQueueTopology.QueueIntegration),
|
||||
InspectQueue(channel, OrderBatchQueueTopology.QueueCreate),
|
||||
InspectQueue(channel, OrderBatchQueueTopology.QueueAccount),
|
||||
InspectQueue(channel, OrderBatchQueueTopology.QueueState),
|
||||
InspectQueue(channel, OrderBatchQueueTopology.QueueException),
|
||||
InspectQueue(channel, OrderBatchQueueTopology.QueueDocument),
|
||||
};
|
||||
|
||||
var dlxCount = queues.First(x => x.QueueName == OrderBatchQueueTopology.QueueDeadLetter).MessageCount;
|
||||
return Task.FromResult(new OrderBatchDlxStatsOutput
|
||||
{
|
||||
Enabled = true,
|
||||
DeadLetterMessageCount = dlxCount,
|
||||
DlxAlertThreshold = _options.DlxAlertThreshold,
|
||||
Alert = dlxCount >= _options.DlxAlertThreshold,
|
||||
Queues = queues,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static OrderBatchQueueStatOutput InspectQueue(IModel channel, string queueName)
|
||||
{
|
||||
try
|
||||
{
|
||||
var declare = channel.QueueDeclarePassive(queueName);
|
||||
return new OrderBatchQueueStatOutput
|
||||
{
|
||||
QueueName = queueName,
|
||||
MessageCount = declare.MessageCount,
|
||||
ConsumerCount = declare.ConsumerCount,
|
||||
};
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return new OrderBatchQueueStatOutput { QueueName = queueName };
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureConnection()
|
||||
{
|
||||
if (_connection is { IsOpen: true })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var factory = new ConnectionFactory
|
||||
{
|
||||
HostName = _options.HostName,
|
||||
Port = _options.Port,
|
||||
UserName = _options.UserName,
|
||||
Password = _options.Password,
|
||||
VirtualHost = _options.VirtualHost,
|
||||
DispatchConsumersAsync = true,
|
||||
AutomaticRecoveryEnabled = true,
|
||||
};
|
||||
|
||||
_connection?.Dispose();
|
||||
_connection = factory.CreateConnection("oms-order-batch-inspector");
|
||||
_logger.LogDebug("Order batch queue inspector connected.");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_connection?.Dispose();
|
||||
}
|
||||
}
|
||||
92
src/Oms.Application/Messaging/OrderBatchQueueTopology.cs
Normal file
92
src/Oms.Application/Messaging/OrderBatchQueueTopology.cs
Normal file
@ -0,0 +1,92 @@
|
||||
namespace Oms.Application.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// RabbitMQ 交换机、队列与路由键定义。
|
||||
/// </summary>
|
||||
public static class OrderBatchQueueTopology
|
||||
{
|
||||
public const string Exchange = "oms.order.batch";
|
||||
public const string DeadLetterExchange = "oms.order.batch.dlx";
|
||||
|
||||
public const string QueueIntegration = "oms.order.batch.integration";
|
||||
public const string QueueCreate = "oms.order.batch.create";
|
||||
public const string QueueAccount = "oms.order.batch.account";
|
||||
public const string QueueState = "oms.order.batch.state";
|
||||
public const string QueueException = "oms.order.batch.exception";
|
||||
public const string QueueDocument = "oms.order.batch.document";
|
||||
public const string QueueDeadLetter = "oms.order.batch.dlx";
|
||||
|
||||
public const string RoutingIntegrationTrack = "integration.track-upsert";
|
||||
public const string RoutingIntegrationDownstream = "integration.downstream-forward";
|
||||
public const string RoutingCreateParcel = "create.parcel-create";
|
||||
public const string RoutingCreateImport = "create.import-row";
|
||||
public const string RoutingAccountPay = "account.pay";
|
||||
public const string RoutingStatePrefix = "state.";
|
||||
public const string RoutingExceptionPrefix = "exception.";
|
||||
public const string RoutingDocumentPrefix = "document.";
|
||||
public const string RoutingDeadLetter = "dead";
|
||||
|
||||
public static string ResolveRoutingKey(string action) => action switch
|
||||
{
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.TrackUpsertSmallBag => RoutingIntegrationTrack,
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.DownstreamForwardCreateOne => RoutingIntegrationDownstream,
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.Pay => RoutingAccountPay,
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.ParcelCreate => RoutingCreateParcel,
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.ImportRow => RoutingCreateImport,
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.PreDeclare => RoutingStatePrefix + "pre-declare",
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.Intercept => RoutingStatePrefix + "intercept",
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.CancelIntercept => RoutingStatePrefix + "cancel-intercept",
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.Delete => RoutingStatePrefix + "delete",
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.HandleStatusUpdate => RoutingStatePrefix + "handle-status-update",
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.MarkProblematic => RoutingExceptionPrefix + "mark-problematic",
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.MarkClaimed => RoutingExceptionPrefix + "mark-claimed",
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.Print => RoutingDocumentPrefix + "print",
|
||||
Domain.OrdersAggregate.Consts.OrderBatchActionCodes.Export => RoutingDocumentPrefix + "export",
|
||||
_ => "unknown." + action
|
||||
};
|
||||
|
||||
public static string ResolveQueueName(string routingKey)
|
||||
{
|
||||
if (routingKey.StartsWith("integration.", StringComparison.Ordinal))
|
||||
{
|
||||
return QueueIntegration;
|
||||
}
|
||||
|
||||
if (routingKey.StartsWith("create.", StringComparison.Ordinal))
|
||||
{
|
||||
return QueueCreate;
|
||||
}
|
||||
|
||||
if (routingKey.StartsWith("account.", StringComparison.Ordinal))
|
||||
{
|
||||
return QueueAccount;
|
||||
}
|
||||
|
||||
if (routingKey.StartsWith("state.", StringComparison.Ordinal))
|
||||
{
|
||||
return QueueState;
|
||||
}
|
||||
|
||||
if (routingKey.StartsWith("exception.", StringComparison.Ordinal))
|
||||
{
|
||||
return QueueException;
|
||||
}
|
||||
|
||||
if (routingKey.StartsWith("document.", StringComparison.Ordinal))
|
||||
{
|
||||
return QueueDocument;
|
||||
}
|
||||
|
||||
return QueueIntegration;
|
||||
}
|
||||
|
||||
public static IReadOnlyList<(string Queue, string RoutingKey)> Bindings { get; } =
|
||||
[
|
||||
(QueueIntegration, "integration.*"),
|
||||
(QueueCreate, "create.*"),
|
||||
(QueueAccount, "account.*"),
|
||||
(QueueState, "state.*"),
|
||||
(QueueException, "exception.*"),
|
||||
(QueueDocument, "document.*"),
|
||||
];
|
||||
}
|
||||
32
src/Oms.Application/Messaging/OrderBatchRabbitMqOptions.cs
Normal file
32
src/Oms.Application/Messaging/OrderBatchRabbitMqOptions.cs
Normal file
@ -0,0 +1,32 @@
|
||||
namespace Oms.Application.Messaging;
|
||||
|
||||
public class OrderBatchRabbitMqOptions
|
||||
{
|
||||
public const string SectionName = "OrderBatch:RabbitMq";
|
||||
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
public string HostName { get; set; } = "localhost";
|
||||
|
||||
public int Port { get; set; } = 5672;
|
||||
|
||||
public string UserName { get; set; } = "oms";
|
||||
|
||||
public string Password { get; set; } = "oms123";
|
||||
|
||||
public string VirtualHost { get; set; } = "/oms";
|
||||
|
||||
public ushort PrefetchCount { get; set; } = 5;
|
||||
|
||||
public int MaxRetryCount { get; set; } = 3;
|
||||
|
||||
/// <summary>
|
||||
/// DLX 队列堆积告警阈值。
|
||||
/// </summary>
|
||||
public uint DlxAlertThreshold { get; set; } = 100;
|
||||
|
||||
/// <summary>
|
||||
/// 队列监控轮询间隔(秒)。
|
||||
/// </summary>
|
||||
public int MonitorIntervalSeconds { get; set; } = 300;
|
||||
}
|
||||
@ -22,6 +22,7 @@
|
||||
<PackageReference Include="Fake.Rbac.Application" Version="$(FakePackageVersion)" />
|
||||
<PackageReference Include="Fake.Rbac.Infrastructure" Version="$(FakePackageVersion)" />
|
||||
<PackageReference Include="MiniExcel" Version="1.43.1" />
|
||||
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@ -28,6 +28,7 @@ public class OmsApplicationModule : FakeModule
|
||||
});
|
||||
context.Services.AddOmsSmallBagTrack(context.Services.GetConfiguration());
|
||||
context.Services.AddOmsItfxIntegration(context.Services.GetConfiguration());
|
||||
context.Services.AddOmsOrderBatchMessaging(context.Services.GetConfiguration());
|
||||
context.Services.AddXhsLlmClient();
|
||||
context.Services.AddDistributedMemoryCache();
|
||||
context.Services.AddHostedService<XhsScheduledPublishWorker>();
|
||||
|
||||
25
src/Oms.Application/OrderBatchMessagingServiceExtensions.cs
Normal file
25
src/Oms.Application/OrderBatchMessagingServiceExtensions.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Application.Workers.OrderBatch;
|
||||
|
||||
namespace Oms.Application;
|
||||
|
||||
public static class OrderBatchMessagingServiceExtensions
|
||||
{
|
||||
public static IServiceCollection AddOmsOrderBatchMessaging(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.Configure<OrderBatchRabbitMqOptions>(configuration.GetSection(OrderBatchRabbitMqOptions.SectionName));
|
||||
services.AddSingleton<IOrderBatchJobPublisher, OrderBatchJobPublisher>();
|
||||
services.AddSingleton<IOrderBatchQueueInspector, OrderBatchQueueInspector>();
|
||||
services.AddHostedService<OrderBatchQueueInitializer>();
|
||||
services.AddHostedService<OrderBatchDlxMonitorHostedService>();
|
||||
services.AddHostedService<OrderBatchIntegrationConsumer>();
|
||||
services.AddHostedService<OrderBatchCreateConsumer>();
|
||||
services.AddHostedService<OrderBatchAccountConsumer>();
|
||||
services.AddHostedService<OrderBatchStateConsumer>();
|
||||
services.AddHostedService<OrderBatchExceptionConsumer>();
|
||||
services.AddHostedService<OrderBatchDocumentConsumer>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,55 @@
|
||||
using Oms.Application.Messaging;
|
||||
|
||||
namespace Oms.Application.Services.Orders.Batch;
|
||||
|
||||
public interface IOrderBatchActionExecutor
|
||||
{
|
||||
Task<OrderBatchActionExecuteResult> ExecuteAsync(
|
||||
OrderBatchJobMessage message,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public sealed class OrderBatchActionExecuteResult
|
||||
{
|
||||
public bool Success { get; init; }
|
||||
|
||||
public bool IsBusinessFailure { get; init; }
|
||||
|
||||
public string? FailReason { get; init; }
|
||||
|
||||
public int? CreatedOrderId { get; init; }
|
||||
|
||||
public string? ServiceNo { get; init; }
|
||||
|
||||
public string? ClientNo { get; init; }
|
||||
|
||||
public string? TrackNo { get; init; }
|
||||
|
||||
public string? LabelUrl { get; init; }
|
||||
|
||||
public string? ResultJson { get; init; }
|
||||
|
||||
public static OrderBatchActionExecuteResult Ok(
|
||||
int? createdOrderId = null,
|
||||
string? serviceNo = null,
|
||||
string? clientNo = null,
|
||||
string? trackNo = null,
|
||||
string? labelUrl = null,
|
||||
string? resultJson = null) =>
|
||||
new()
|
||||
{
|
||||
Success = true,
|
||||
CreatedOrderId = createdOrderId,
|
||||
ServiceNo = serviceNo,
|
||||
ClientNo = clientNo,
|
||||
TrackNo = trackNo,
|
||||
LabelUrl = labelUrl,
|
||||
ResultJson = resultJson,
|
||||
};
|
||||
|
||||
public static OrderBatchActionExecuteResult BusinessFail(string reason) =>
|
||||
new() { Success = false, IsBusinessFailure = true, FailReason = reason };
|
||||
|
||||
public static OrderBatchActionExecuteResult SystemFail(string reason) =>
|
||||
new() { Success = false, IsBusinessFailure = false, FailReason = reason };
|
||||
}
|
||||
@ -0,0 +1,157 @@
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Newtonsoft.Json;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Integrations.Itfx;
|
||||
using Oms.Application.Integrations.SmallBagTrack;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
using Oms.Domain.OrdersAggregate.Repositories;
|
||||
using Oms.Domain.SystemAggregate.Repositories;
|
||||
|
||||
namespace Oms.Application.Services.Orders.Batch;
|
||||
|
||||
public sealed class OrderBatchActionExecutor(
|
||||
IOrderRepository orderRepository,
|
||||
ICountryRepository countryRepository,
|
||||
ISmallBagTrackOrderClient smallBagTrackOrderClient,
|
||||
OrderDownstreamCredentialResolver downstreamCredentialResolver,
|
||||
IItfxForwardClient itfxForwardClient,
|
||||
OrderBatchCreateActionHandler createActionHandler,
|
||||
OrderBatchOrderActionHandler orderActionHandler) : IOrderBatchActionExecutor, IScopedDependency
|
||||
{
|
||||
public async Task<OrderBatchActionExecuteResult> ExecuteAsync(
|
||||
OrderBatchJobMessage message,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
return message.Action switch
|
||||
{
|
||||
OrderBatchActionCodes.TrackUpsertSmallBag => await ExecuteTrackUpsertAsync(message, cancellationToken),
|
||||
OrderBatchActionCodes.DownstreamForwardCreateOne => await ExecuteDownstreamForwardAsync(message, cancellationToken),
|
||||
OrderBatchActionCodes.ImportRow => await createActionHandler.ExecuteImportRowAsync(message, cancellationToken),
|
||||
OrderBatchActionCodes.ParcelCreate => await createActionHandler.ExecuteParcelCreateAsync(message, cancellationToken),
|
||||
OrderBatchActionCodes.Pay => await orderActionHandler.ExecuteAsync(message, cancellationToken),
|
||||
OrderBatchActionCodes.PreDeclare => await orderActionHandler.ExecuteAsync(message, cancellationToken),
|
||||
OrderBatchActionCodes.Intercept => await orderActionHandler.ExecuteAsync(message, cancellationToken),
|
||||
OrderBatchActionCodes.CancelIntercept => await orderActionHandler.ExecuteAsync(message, cancellationToken),
|
||||
OrderBatchActionCodes.Delete => await orderActionHandler.ExecuteAsync(message, cancellationToken),
|
||||
OrderBatchActionCodes.Print => await orderActionHandler.ExecuteAsync(message, cancellationToken),
|
||||
OrderBatchActionCodes.MarkProblematic => await orderActionHandler.ExecuteAsync(message, cancellationToken),
|
||||
OrderBatchActionCodes.MarkClaimed => await orderActionHandler.ExecuteAsync(message, cancellationToken),
|
||||
OrderBatchActionCodes.HandleStatusUpdate => await orderActionHandler.ExecuteAsync(message, cancellationToken),
|
||||
_ => OrderBatchActionExecuteResult.BusinessFail($"未实现的批量操作: {message.Action}")
|
||||
};
|
||||
}
|
||||
catch (BusinessException ex)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail(ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.SystemFail(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<OrderBatchActionExecuteResult> ExecuteTrackUpsertAsync(
|
||||
OrderBatchJobMessage message,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
SmallBagTrackUpsertRequest request;
|
||||
if (!string.IsNullOrWhiteSpace(message.PayloadJson))
|
||||
{
|
||||
request = JsonConvert.DeserializeObject<SmallBagTrackUpsertRequest>(message.PayloadJson!)
|
||||
?? throw new BusinessException("轨迹同步消息体无效");
|
||||
}
|
||||
else
|
||||
{
|
||||
var order = await orderRepository.FirstOrDefaultAsync(x => x.Id == message.OrderId, cancellationToken);
|
||||
if (order == null)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail("订单不存在");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(order.ServiceNo))
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail("订单运单号为空,无法同步轨迹");
|
||||
}
|
||||
|
||||
request = await BuildTrackRequestAsync(order, cancellationToken);
|
||||
}
|
||||
|
||||
await smallBagTrackOrderClient.UpsertAsync(request, cancellationToken);
|
||||
return OrderBatchActionExecuteResult.Ok();
|
||||
}
|
||||
|
||||
private async Task<OrderBatchActionExecuteResult> ExecuteDownstreamForwardAsync(
|
||||
OrderBatchJobMessage message,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var order = await orderRepository.FirstOrDefaultAsync(x => x.Id == message.OrderId, cancellationToken);
|
||||
if (order == null)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail("订单不存在");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(order.ServiceNo))
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail("订单运单号为空,无法预报下游");
|
||||
}
|
||||
|
||||
var orderIds = new[] { order.Id };
|
||||
var senders = await orderRepository.GetSendersByOrderIdsAsync(orderIds, cancellationToken);
|
||||
var recipients = await orderRepository.GetRecipientsByOrderIdsAsync(orderIds, cancellationToken);
|
||||
var declarations = await orderRepository.GetDeclarationsByOrderIdsAsync(orderIds, cancellationToken);
|
||||
var weights = await orderRepository.GetWeightsByOrderIdsAsync(orderIds, cancellationToken);
|
||||
|
||||
var body = await OrderDownstreamCreateOneBodyBuilder.BuildAsync(
|
||||
order,
|
||||
senders.FirstOrDefault(),
|
||||
recipients.FirstOrDefault(),
|
||||
declarations,
|
||||
weights,
|
||||
countryRepository);
|
||||
|
||||
var creds = await downstreamCredentialResolver.ResolveAsync(order, cancellationToken);
|
||||
var forward = await itfxForwardClient.ForwardCreateOrderOneAsync(
|
||||
creds.SupplierCode,
|
||||
creds.AppKey,
|
||||
creds.AppSecret,
|
||||
body,
|
||||
cancellationToken);
|
||||
|
||||
if (!forward.Success)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail(
|
||||
$"下游预报失败: HTTP {forward.StatusCode} {forward.ResponseBody}");
|
||||
}
|
||||
|
||||
return OrderBatchActionExecuteResult.Ok();
|
||||
}
|
||||
|
||||
private async Task<SmallBagTrackUpsertRequest> BuildTrackRequestAsync(
|
||||
Domain.OrdersAggregate.Entities.Order order,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var recipients = await orderRepository.GetRecipientsByOrderIdsAsync([order.Id], cancellationToken);
|
||||
var recipient = recipients.FirstOrDefault();
|
||||
|
||||
return new SmallBagTrackUpsertRequest
|
||||
{
|
||||
OrderNo = order.ServiceNo ?? string.Empty,
|
||||
TrackNo = order.TrackNo?.Trim() ?? string.Empty,
|
||||
OtherNo = order.ClientNo?.Trim() ?? string.Empty,
|
||||
Channel = order.ChannelCode?.Trim() ?? string.Empty,
|
||||
Product = order.ProductCode?.Trim() ?? string.Empty,
|
||||
ApiCode = order.DownstreamSupplierCode?.Trim() ?? string.Empty,
|
||||
Consignee = new SmallBagTrackConsigneeRequest
|
||||
{
|
||||
CountryCode = order.ConsigneeCountry?.Trim() ?? string.Empty,
|
||||
Province = recipient?.Province?.Trim() ?? string.Empty,
|
||||
Postcode = recipient?.ZipCode?.Trim() ?? string.Empty,
|
||||
City = recipient?.City?.Trim() ?? string.Empty,
|
||||
Email = recipient?.Email?.Trim() ?? string.Empty,
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,88 @@
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Newtonsoft.Json;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
|
||||
namespace Oms.Application.Services.Orders.Batch;
|
||||
|
||||
/// <summary>
|
||||
/// 创建类批量操作(Excel 导入行、小包批量创建)执行器。
|
||||
/// </summary>
|
||||
public sealed class OrderBatchCreateActionHandler(IServiceScopeFactory scopeFactory) : IScopedDependency
|
||||
{
|
||||
public async Task<OrderBatchActionExecuteResult> ExecuteImportRowAsync(
|
||||
OrderBatchJobMessage message,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message.PayloadJson))
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail("导入行消息体为空");
|
||||
}
|
||||
|
||||
var payload = JsonConvert.DeserializeObject<OrderBatchImportRowPayload>(message.PayloadJson);
|
||||
if (payload == null)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail("导入行消息体无效");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
var orderService = scope.ServiceProvider.GetRequiredService<OrderService>();
|
||||
await orderService.ImportRowForBatchAsync(payload, cancellationToken);
|
||||
return OrderBatchActionExecuteResult.Ok();
|
||||
}
|
||||
catch (BusinessException ex)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail(ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.SystemFail(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<OrderBatchActionExecuteResult> ExecuteParcelCreateAsync(
|
||||
OrderBatchJobMessage message,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message.PayloadJson))
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail("小包创建消息体为空");
|
||||
}
|
||||
|
||||
var input = JsonConvert.DeserializeObject<OrderParcelCreateInput>(message.PayloadJson);
|
||||
if (input == null)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail("小包创建消息体无效");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
var orderService = scope.ServiceProvider.GetRequiredService<OrderService>();
|
||||
var output = await orderService.CreateParcelForBatchAsync(
|
||||
input,
|
||||
message.OperatorUserId,
|
||||
cancellationToken);
|
||||
|
||||
return OrderBatchActionExecuteResult.Ok(
|
||||
createdOrderId: null,
|
||||
serviceNo: output.ServiceNo,
|
||||
clientNo: output.ClientNo,
|
||||
trackNo: output.TrackNo,
|
||||
labelUrl: output.LabelUrl);
|
||||
}
|
||||
catch (BusinessException ex)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail(ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.SystemFail(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,502 @@
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Integrations.SmallBagTrack;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
using System.Linq.Expressions;
|
||||
using Oms.Domain.OrdersAggregate.Entities;
|
||||
using Oms.Domain.OrdersAggregate.Repositories;
|
||||
|
||||
namespace Oms.Application.Services.Orders.Batch;
|
||||
|
||||
/// <summary>
|
||||
/// 创建批量任务、写入子项并发布 RabbitMQ 消息。
|
||||
/// </summary>
|
||||
public sealed class OrderBatchJobCoordinator(
|
||||
IOrderBatchJobRepository batchJobRepository,
|
||||
IOrderRepository orderRepository,
|
||||
IOrderBatchJobPublisher publisher,
|
||||
ILogger<OrderBatchJobCoordinator> logger) : IScopedDependency
|
||||
{
|
||||
private const int DefaultMaxBatchSize = 200;
|
||||
private const int CreateMaxBatchSize = 2000;
|
||||
|
||||
public async Task<OrderBatchJobOutput> CreateAndEnqueueAsync(
|
||||
OrderBatchJobCreateInput input,
|
||||
int operatorUserId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!publisher.IsEnabled)
|
||||
{
|
||||
throw new BusinessException("订单批量队列未启用,请检查 RabbitMQ 配置");
|
||||
}
|
||||
|
||||
var action = input.Action?.Trim() ?? string.Empty;
|
||||
if (string.IsNullOrWhiteSpace(action))
|
||||
{
|
||||
throw new BusinessException("批量操作类型不能为空");
|
||||
}
|
||||
|
||||
var orderIds = (input.OrderIds ?? [])
|
||||
.Where(x => x > 0)
|
||||
.Distinct()
|
||||
.ToList();
|
||||
if (orderIds.Count == 0)
|
||||
{
|
||||
throw new BusinessException("订单列表不能为空");
|
||||
}
|
||||
|
||||
if (orderIds.Count > DefaultMaxBatchSize)
|
||||
{
|
||||
throw new BusinessException($"单次最多处理 {DefaultMaxBatchSize} 条订单");
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(input.RequestId))
|
||||
{
|
||||
var existing = await batchJobRepository.GetByRequestIdAsync(input.RequestId.Trim(), cancellationToken);
|
||||
if (existing != null)
|
||||
{
|
||||
return await MapJobOutputAsync(existing, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
var now = DateTime.Now;
|
||||
var job = new OrderBatchJob
|
||||
{
|
||||
Action = action,
|
||||
Status = OrderBatchJobStatusCodes.Pending,
|
||||
Total = orderIds.Count,
|
||||
SuccessCount = 0,
|
||||
FailCount = 0,
|
||||
PayloadJson = input.PayloadJson,
|
||||
RequestId = input.RequestId?.Trim(),
|
||||
StartedAt = now,
|
||||
CreateUserId = operatorUserId,
|
||||
CreateTime = now,
|
||||
UpdateUserId = operatorUserId,
|
||||
UpdateTime = now,
|
||||
};
|
||||
|
||||
job = await batchJobRepository.InsertAsync(job, cancellationToken: cancellationToken);
|
||||
job.Status = OrderBatchJobStatusCodes.Running;
|
||||
await batchJobRepository.UpdateJobAsync(job, cancellationToken);
|
||||
|
||||
var items = new List<OrderBatchJobItem>(orderIds.Count);
|
||||
foreach (var orderId in orderIds)
|
||||
{
|
||||
var order = await orderRepository.FirstOrDefaultAsync(x => x.Id == orderId, cancellationToken);
|
||||
var item = new OrderBatchJobItem
|
||||
{
|
||||
JobId = job.Id,
|
||||
OrderId = orderId,
|
||||
ServiceNo = order?.ServiceNo,
|
||||
Action = action,
|
||||
Status = OrderBatchJobItemStatusCodes.Pending,
|
||||
MessageId = $"{job.Id}:{orderId}:{action}",
|
||||
PayloadJson = input.PayloadJson,
|
||||
CreateUserId = operatorUserId,
|
||||
CreateTime = now,
|
||||
UpdateUserId = operatorUserId,
|
||||
UpdateTime = now,
|
||||
};
|
||||
items.Add(item);
|
||||
}
|
||||
|
||||
await batchJobRepository.InsertItemsAsync(items, cancellationToken);
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
var order = await orderRepository.FirstOrDefaultAsync(x => x.Id == item.OrderId, cancellationToken);
|
||||
var message = new OrderBatchJobMessage
|
||||
{
|
||||
JobId = job.Id,
|
||||
JobItemId = item.Id,
|
||||
Action = action,
|
||||
OrderId = item.OrderId,
|
||||
CustomerId = order?.CustomerId,
|
||||
PayloadJson = input.PayloadJson,
|
||||
OperatorUserId = operatorUserId,
|
||||
MessageId = item.MessageId ?? $"{job.Id}:{item.OrderId}:{action}",
|
||||
};
|
||||
|
||||
await publisher.PublishAsync(message, cancellationToken);
|
||||
}
|
||||
|
||||
logger.LogInformation(
|
||||
"Created order batch job {JobId} action={Action} total={Total}",
|
||||
job.Id,
|
||||
action,
|
||||
job.Total);
|
||||
|
||||
return await MapJobOutputAsync(job, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建按 Payload 投递的批量任务(导入行、小包批量创建等)。
|
||||
/// </summary>
|
||||
public async Task<OrderBatchJobOutput> CreatePayloadJobAsync(
|
||||
OrderBatchPayloadJobCreateInput input,
|
||||
int operatorUserId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!publisher.IsEnabled)
|
||||
{
|
||||
throw new BusinessException("订单批量队列未启用,请检查 RabbitMQ 配置");
|
||||
}
|
||||
|
||||
var action = input.Action?.Trim() ?? string.Empty;
|
||||
if (string.IsNullOrWhiteSpace(action))
|
||||
{
|
||||
throw new BusinessException("批量操作类型不能为空");
|
||||
}
|
||||
|
||||
var itemsInput = (input.Items ?? [])
|
||||
.Where(x => !string.IsNullOrWhiteSpace(x.PayloadJson))
|
||||
.ToList();
|
||||
if (itemsInput.Count == 0)
|
||||
{
|
||||
throw new BusinessException("批量任务子项不能为空");
|
||||
}
|
||||
|
||||
if (itemsInput.Count > CreateMaxBatchSize)
|
||||
{
|
||||
throw new BusinessException($"单次最多处理 {CreateMaxBatchSize} 条");
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(input.RequestId))
|
||||
{
|
||||
var existing = await batchJobRepository.GetByRequestIdAsync(input.RequestId.Trim(), cancellationToken);
|
||||
if (existing != null)
|
||||
{
|
||||
return await MapJobOutputAsync(existing, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
var now = DateTime.Now;
|
||||
var job = new OrderBatchJob
|
||||
{
|
||||
Action = action,
|
||||
Status = OrderBatchJobStatusCodes.Pending,
|
||||
Total = itemsInput.Count,
|
||||
SuccessCount = 0,
|
||||
FailCount = 0,
|
||||
PayloadJson = input.JobPayloadJson,
|
||||
RequestId = input.RequestId?.Trim(),
|
||||
CustomerId = input.CustomerId,
|
||||
StartedAt = now,
|
||||
CreateUserId = operatorUserId,
|
||||
CreateTime = now,
|
||||
UpdateUserId = operatorUserId,
|
||||
UpdateTime = now,
|
||||
};
|
||||
|
||||
job = await batchJobRepository.InsertAsync(job, cancellationToken: cancellationToken);
|
||||
job.Status = OrderBatchJobStatusCodes.Running;
|
||||
await batchJobRepository.UpdateJobAsync(job, cancellationToken);
|
||||
|
||||
var items = new List<OrderBatchJobItem>(itemsInput.Count);
|
||||
for (var index = 0; index < itemsInput.Count; index++)
|
||||
{
|
||||
var source = itemsInput[index];
|
||||
var itemKey = source.ItemKey?.Trim();
|
||||
if (string.IsNullOrWhiteSpace(itemKey))
|
||||
{
|
||||
itemKey = $"{job.Id}:{index + 1}:{action}";
|
||||
}
|
||||
|
||||
items.Add(new OrderBatchJobItem
|
||||
{
|
||||
JobId = job.Id,
|
||||
OrderId = source.OrderId,
|
||||
ServiceNo = source.ServiceNo,
|
||||
Action = action,
|
||||
Status = OrderBatchJobItemStatusCodes.Pending,
|
||||
MessageId = itemKey,
|
||||
PayloadJson = source.PayloadJson,
|
||||
CreateUserId = operatorUserId,
|
||||
CreateTime = now,
|
||||
UpdateUserId = operatorUserId,
|
||||
UpdateTime = now,
|
||||
});
|
||||
}
|
||||
|
||||
await batchJobRepository.InsertItemsAsync(items, cancellationToken);
|
||||
|
||||
for (var index = 0; index < items.Count; index++)
|
||||
{
|
||||
var item = items[index];
|
||||
var source = itemsInput[index];
|
||||
var message = new OrderBatchJobMessage
|
||||
{
|
||||
JobId = job.Id,
|
||||
JobItemId = item.Id,
|
||||
Action = action,
|
||||
OrderId = item.OrderId,
|
||||
CustomerId = input.CustomerId,
|
||||
PayloadJson = source.PayloadJson,
|
||||
OperatorUserId = operatorUserId,
|
||||
MessageId = item.MessageId ?? $"{job.Id}:{index + 1}:{action}",
|
||||
};
|
||||
|
||||
await publisher.PublishAsync(message, cancellationToken);
|
||||
}
|
||||
|
||||
logger.LogInformation(
|
||||
"Created payload batch job {JobId} action={Action} total={Total}",
|
||||
job.Id,
|
||||
action,
|
||||
job.Total);
|
||||
|
||||
return await MapJobOutputAsync(job, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task PublishTrackUpsertAsync(SmallBagTrackUpsertRequest request, int orderId, int? customerId)
|
||||
{
|
||||
if (!publisher.IsEnabled)
|
||||
{
|
||||
logger.LogDebug("RabbitMQ disabled, skip track upsert publish for order {OrderId}", orderId);
|
||||
return;
|
||||
}
|
||||
|
||||
var message = new OrderBatchJobMessage
|
||||
{
|
||||
JobId = 0,
|
||||
JobItemId = 0,
|
||||
Action = OrderBatchActionCodes.TrackUpsertSmallBag,
|
||||
OrderId = orderId,
|
||||
CustomerId = customerId,
|
||||
PayloadJson = JsonConvert.SerializeObject(request),
|
||||
OperatorUserId = 0,
|
||||
MessageId = $"track:{orderId}:{Guid.NewGuid():N}",
|
||||
};
|
||||
|
||||
await publisher.PublishAsync(message);
|
||||
}
|
||||
|
||||
public async Task<OrderBatchJobOutput?> GetJobAsync(int jobId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var job = await batchJobRepository.GetByIdAsync(jobId, cancellationToken);
|
||||
if (job == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return await MapJobOutputAsync(job, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<List<OrderBatchJobItemOutput>> GetJobItemsAsync(int jobId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var items = await batchJobRepository.GetItemsByJobIdAsync(jobId, cancellationToken);
|
||||
return items.Select(x => new OrderBatchJobItemOutput
|
||||
{
|
||||
Id = x.Id,
|
||||
OrderId = x.OrderId,
|
||||
ServiceNo = x.ServiceNo,
|
||||
Status = x.Status,
|
||||
FailReason = x.FailReason,
|
||||
ResultJson = x.ResultJson,
|
||||
StartedAt = x.StartedAt,
|
||||
FinishedAt = x.FinishedAt,
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
public async Task<OrderBatchJobManageOutput> RetryFailedAsync(
|
||||
int jobId,
|
||||
OrderBatchJobRetryFailedInput? input,
|
||||
int operatorUserId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!publisher.IsEnabled)
|
||||
{
|
||||
throw new BusinessException("订单批量队列未启用,请检查 RabbitMQ 配置");
|
||||
}
|
||||
|
||||
var job = await batchJobRepository.GetByIdAsync(jobId, cancellationToken)
|
||||
?? throw new BusinessException("批量任务不存在");
|
||||
|
||||
var items = await batchJobRepository.GetItemsByJobIdAsync(jobId, cancellationToken);
|
||||
var filterIds = (input?.ItemIds ?? [])
|
||||
.Where(x => x > 0)
|
||||
.Distinct()
|
||||
.ToHashSet();
|
||||
var retryItems = items
|
||||
.Where(x => x.Status == OrderBatchJobItemStatusCodes.Failed
|
||||
&& (filterIds.Count == 0 || filterIds.Contains(x.Id)))
|
||||
.ToList();
|
||||
if (retryItems.Count == 0)
|
||||
{
|
||||
throw new BusinessException("没有可重试的失败子项");
|
||||
}
|
||||
|
||||
var now = DateTime.Now;
|
||||
foreach (var item in retryItems)
|
||||
{
|
||||
item.Status = OrderBatchJobItemStatusCodes.Pending;
|
||||
item.FailReason = null;
|
||||
item.ResultJson = null;
|
||||
item.RetryCount = 0;
|
||||
item.StartedAt = null;
|
||||
item.FinishedAt = null;
|
||||
item.UpdateTime = now;
|
||||
item.UpdateUserId = operatorUserId;
|
||||
await batchJobRepository.UpdateItemAsync(item, cancellationToken);
|
||||
|
||||
await publisher.PublishAsync(BuildMessageFromJobItem(job, item, operatorUserId), cancellationToken);
|
||||
}
|
||||
|
||||
job.Status = OrderBatchJobStatusCodes.Running;
|
||||
job.FinishedAt = null;
|
||||
job.UpdateTime = now;
|
||||
job.UpdateUserId = operatorUserId;
|
||||
await batchJobRepository.UpdateJobAsync(job, cancellationToken);
|
||||
|
||||
var output = await MapJobOutputAsync(job, cancellationToken);
|
||||
return new OrderBatchJobManageOutput
|
||||
{
|
||||
JobId = jobId,
|
||||
RetriedCount = retryItems.Count,
|
||||
Status = output.Status,
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<OrderBatchJobManageOutput> CancelPendingAsync(
|
||||
int jobId,
|
||||
int operatorUserId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var job = await batchJobRepository.GetByIdAsync(jobId, cancellationToken)
|
||||
?? throw new BusinessException("批量任务不存在");
|
||||
|
||||
var items = await batchJobRepository.GetItemsByJobIdAsync(jobId, cancellationToken);
|
||||
var pendingItems = items
|
||||
.Where(x => x.Status == OrderBatchJobItemStatusCodes.Pending)
|
||||
.ToList();
|
||||
if (pendingItems.Count == 0)
|
||||
{
|
||||
throw new BusinessException("没有可取消的待处理子项");
|
||||
}
|
||||
|
||||
var now = DateTime.Now;
|
||||
foreach (var item in pendingItems)
|
||||
{
|
||||
item.Status = OrderBatchJobItemStatusCodes.Cancelled;
|
||||
item.FailReason = "任务已取消";
|
||||
item.FinishedAt = now;
|
||||
item.UpdateTime = now;
|
||||
item.UpdateUserId = operatorUserId;
|
||||
await batchJobRepository.UpdateItemAsync(item, cancellationToken);
|
||||
}
|
||||
|
||||
var output = await MapJobOutputAsync(job, cancellationToken);
|
||||
return new OrderBatchJobManageOutput
|
||||
{
|
||||
JobId = jobId,
|
||||
CancelledCount = pendingItems.Count,
|
||||
Status = output.Status,
|
||||
};
|
||||
}
|
||||
|
||||
private static OrderBatchJobMessage BuildMessageFromJobItem(
|
||||
OrderBatchJob job,
|
||||
OrderBatchJobItem item,
|
||||
int operatorUserId) =>
|
||||
new()
|
||||
{
|
||||
JobId = job.Id,
|
||||
JobItemId = item.Id,
|
||||
Action = item.Action,
|
||||
OrderId = item.OrderId,
|
||||
CustomerId = job.CustomerId,
|
||||
PayloadJson = item.PayloadJson ?? job.PayloadJson,
|
||||
OperatorUserId = operatorUserId,
|
||||
MessageId = item.MessageId ?? $"{job.Id}:{item.Id}:{item.Action}",
|
||||
};
|
||||
|
||||
private async Task<OrderBatchJobOutput> MapJobOutputAsync(OrderBatchJob job, CancellationToken cancellationToken)
|
||||
{
|
||||
var items = await batchJobRepository.GetItemsByJobIdAsync(job.Id, cancellationToken);
|
||||
var successCount = items.Count(x => x.Status == OrderBatchJobItemStatusCodes.Success);
|
||||
var failCount = items.Count(x => x.Status == OrderBatchJobItemStatusCodes.Failed);
|
||||
|
||||
if (job.SuccessCount != successCount || job.FailCount != failCount)
|
||||
{
|
||||
job.SuccessCount = successCount;
|
||||
job.FailCount = failCount;
|
||||
}
|
||||
|
||||
if (items.Count > 0 && items.All(x =>
|
||||
x.Status is OrderBatchJobItemStatusCodes.Success
|
||||
or OrderBatchJobItemStatusCodes.Failed
|
||||
or OrderBatchJobItemStatusCodes.Cancelled))
|
||||
{
|
||||
job.Status = failCount > 0 && successCount == 0
|
||||
? OrderBatchJobStatusCodes.Failed
|
||||
: OrderBatchJobStatusCodes.Completed;
|
||||
job.FinishedAt ??= DateTime.Now;
|
||||
await batchJobRepository.UpdateJobAsync(job, cancellationToken);
|
||||
}
|
||||
|
||||
return new OrderBatchJobOutput
|
||||
{
|
||||
JobId = job.Id,
|
||||
Action = job.Action,
|
||||
Status = job.Status,
|
||||
Total = job.Total,
|
||||
SuccessCount = job.SuccessCount,
|
||||
FailCount = job.FailCount,
|
||||
StartedAt = job.StartedAt,
|
||||
FinishedAt = job.FinishedAt,
|
||||
CreateTime = job.CreateTime,
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<OmsPageResult<OrderBatchJobOutput>> GetJobListAsync(
|
||||
OrderBatchJobListInput input,
|
||||
int? customerId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var page = OmsDocHelper.NormalizePage(input.Page);
|
||||
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize);
|
||||
var status = input.Status?.Trim();
|
||||
var action = input.Action?.Trim();
|
||||
var hasCustomerFilter = customerId.HasValue;
|
||||
var customerIdValue = customerId.GetValueOrDefault();
|
||||
var jobId = input.JobId;
|
||||
|
||||
Expression<Func<OrderBatchJob, bool>> predicate = x =>
|
||||
(!jobId.HasValue || jobId.Value <= 0 || x.Id == jobId.Value) &&
|
||||
(string.IsNullOrWhiteSpace(status) || x.Status == status) &&
|
||||
(string.IsNullOrWhiteSpace(action) || x.Action == action) &&
|
||||
(!hasCustomerFilter || x.CustomerId == customerIdValue);
|
||||
|
||||
var jobs = await batchJobRepository.GetPagedListAsync(
|
||||
predicate,
|
||||
page,
|
||||
pageSize,
|
||||
new Dictionary<string, bool> { [nameof(OrderBatchJob.CreateTime)] = false, [nameof(OrderBatchJob.Id)] = false },
|
||||
cancellationToken);
|
||||
var total = await batchJobRepository.CountAsync(predicate, cancellationToken);
|
||||
|
||||
return new OmsPageResult<OrderBatchJobOutput>
|
||||
{
|
||||
Items = jobs.Select(x => new OrderBatchJobOutput
|
||||
{
|
||||
JobId = x.Id,
|
||||
Action = x.Action,
|
||||
Status = x.Status,
|
||||
Total = x.Total,
|
||||
SuccessCount = x.SuccessCount,
|
||||
FailCount = x.FailCount,
|
||||
StartedAt = x.StartedAt,
|
||||
FinishedAt = x.FinishedAt,
|
||||
CreateTime = x.CreateTime,
|
||||
}).ToList(),
|
||||
Total = total,
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,269 @@
|
||||
using System.Text;
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Newtonsoft.Json;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
using Oms.Domain.OrdersAggregate.Entities;
|
||||
using Oms.Domain.OrdersAggregate.Repositories;
|
||||
|
||||
namespace Oms.Application.Services.Orders.Batch;
|
||||
|
||||
/// <summary>
|
||||
/// 消费 RabbitMQ 消息后更新任务状态并执行业务。
|
||||
/// </summary>
|
||||
public sealed class OrderBatchJobProcessor(
|
||||
IOrderBatchJobRepository batchJobRepository,
|
||||
IOrderTaskRepository orderTaskRepository,
|
||||
IOrderBatchActionExecutor actionExecutor,
|
||||
IOptions<OrderBatchRabbitMqOptions> rabbitMqOptions,
|
||||
ILogger<OrderBatchJobProcessor> logger) : IScopedDependency
|
||||
{
|
||||
public async Task<ProcessResult> ProcessAsync(
|
||||
OrderBatchJobMessage message,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
OrderBatchJobItem? item = null;
|
||||
if (message.JobItemId > 0)
|
||||
{
|
||||
item = await batchJobRepository.GetItemByIdAsync((int)message.JobItemId, cancellationToken);
|
||||
if (item == null)
|
||||
{
|
||||
logger.LogWarning("Job item {JobItemId} not found, ack message {MessageId}", message.JobItemId, message.MessageId);
|
||||
return ProcessResult.Ack;
|
||||
}
|
||||
|
||||
if (item.Status == OrderBatchJobItemStatusCodes.Success)
|
||||
{
|
||||
return ProcessResult.Ack;
|
||||
}
|
||||
|
||||
if (item.Status == OrderBatchJobItemStatusCodes.Cancelled)
|
||||
{
|
||||
logger.LogInformation("Skip cancelled job item {JobItemId}", item.Id);
|
||||
return ProcessResult.Ack;
|
||||
}
|
||||
|
||||
item.Status = OrderBatchJobItemStatusCodes.Running;
|
||||
item.StartedAt ??= DateTime.Now;
|
||||
item.UpdateTime = DateTime.Now;
|
||||
await batchJobRepository.UpdateItemAsync(item, cancellationToken);
|
||||
}
|
||||
|
||||
var result = await actionExecutor.ExecuteAsync(message, cancellationToken);
|
||||
|
||||
if (message.JobItemId <= 0)
|
||||
{
|
||||
return result.Success ? ProcessResult.Ack : ProcessResult.Reject(result.IsBusinessFailure);
|
||||
}
|
||||
|
||||
item = await batchJobRepository.GetItemByIdAsync((int)message.JobItemId, cancellationToken);
|
||||
if (item == null)
|
||||
{
|
||||
return ProcessResult.Ack;
|
||||
}
|
||||
|
||||
item.FinishedAt = DateTime.Now;
|
||||
item.UpdateTime = DateTime.Now;
|
||||
if (result.Success)
|
||||
{
|
||||
item.Status = OrderBatchJobItemStatusCodes.Success;
|
||||
item.FailReason = null;
|
||||
if (result.CreatedOrderId is > 0)
|
||||
{
|
||||
item.OrderId = result.CreatedOrderId.Value;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(result.ServiceNo))
|
||||
{
|
||||
item.ServiceNo = result.ServiceNo;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(result.ResultJson))
|
||||
{
|
||||
item.ResultJson = result.ResultJson;
|
||||
}
|
||||
|
||||
await batchJobRepository.UpdateItemAsync(item, cancellationToken);
|
||||
await RefreshJobSummaryAsync(item.JobId, cancellationToken);
|
||||
return ProcessResult.Ack;
|
||||
}
|
||||
|
||||
if (result.IsBusinessFailure)
|
||||
{
|
||||
item.Status = OrderBatchJobItemStatusCodes.Failed;
|
||||
item.FailReason = result.FailReason;
|
||||
await batchJobRepository.UpdateItemAsync(item, cancellationToken);
|
||||
if (message.Action == OrderBatchActionCodes.ImportRow)
|
||||
{
|
||||
await RecordImportTaskFailAsync(message, result.FailReason, cancellationToken);
|
||||
}
|
||||
|
||||
await RefreshJobSummaryAsync(item.JobId, cancellationToken);
|
||||
return ProcessResult.Ack;
|
||||
}
|
||||
|
||||
item.RetryCount++;
|
||||
var maxRetryCount = Math.Max(1, rabbitMqOptions.Value.MaxRetryCount);
|
||||
if (item.RetryCount >= maxRetryCount)
|
||||
{
|
||||
item.Status = OrderBatchJobItemStatusCodes.Failed;
|
||||
item.FailReason = string.IsNullOrWhiteSpace(result.FailReason)
|
||||
? "系统重试次数已耗尽"
|
||||
: result.FailReason;
|
||||
item.FinishedAt = DateTime.Now;
|
||||
item.UpdateTime = DateTime.Now;
|
||||
await batchJobRepository.UpdateItemAsync(item, cancellationToken);
|
||||
if (message.Action == OrderBatchActionCodes.ImportRow)
|
||||
{
|
||||
await RecordImportTaskFailAsync(message, item.FailReason, cancellationToken);
|
||||
}
|
||||
|
||||
await RefreshJobSummaryAsync(item.JobId, cancellationToken);
|
||||
logger.LogWarning(
|
||||
"Job item {JobItemId} retry exhausted after {RetryCount} attempts",
|
||||
item.Id,
|
||||
item.RetryCount);
|
||||
return ProcessResult.Ack;
|
||||
}
|
||||
|
||||
item.Status = OrderBatchJobItemStatusCodes.Pending;
|
||||
item.FailReason = null;
|
||||
item.FinishedAt = null;
|
||||
item.UpdateTime = DateTime.Now;
|
||||
await batchJobRepository.UpdateItemAsync(item, cancellationToken);
|
||||
return ProcessResult.Reject(isBusinessFailure: false);
|
||||
}
|
||||
|
||||
public static OrderBatchJobMessage? Deserialize(ReadOnlyMemory<byte> body)
|
||||
{
|
||||
var json = Encoding.UTF8.GetString(body.Span);
|
||||
return JsonConvert.DeserializeObject<OrderBatchJobMessage>(json);
|
||||
}
|
||||
|
||||
private async Task RefreshJobSummaryAsync(int jobId, CancellationToken cancellationToken)
|
||||
{
|
||||
var job = await batchJobRepository.GetByIdAsync(jobId, cancellationToken);
|
||||
if (job == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var items = await batchJobRepository.GetItemsByJobIdAsync(jobId, cancellationToken);
|
||||
job.SuccessCount = items.Count(x => x.Status == OrderBatchJobItemStatusCodes.Success);
|
||||
job.FailCount = items.Count(x => x.Status == OrderBatchJobItemStatusCodes.Failed);
|
||||
job.UpdateTime = DateTime.Now;
|
||||
|
||||
if (items.All(x => x.Status is OrderBatchJobItemStatusCodes.Success
|
||||
or OrderBatchJobItemStatusCodes.Failed
|
||||
or OrderBatchJobItemStatusCodes.Cancelled))
|
||||
{
|
||||
job.Status = job.FailCount > 0 && job.SuccessCount == 0
|
||||
? OrderBatchJobStatusCodes.Failed
|
||||
: OrderBatchJobStatusCodes.Completed;
|
||||
job.FinishedAt = DateTime.Now;
|
||||
}
|
||||
else
|
||||
{
|
||||
job.Status = OrderBatchJobStatusCodes.Running;
|
||||
}
|
||||
|
||||
await batchJobRepository.UpdateJobAsync(job, cancellationToken);
|
||||
await SyncOrderTaskFromJobAsync(job, cancellationToken);
|
||||
}
|
||||
|
||||
private async Task SyncOrderTaskFromJobAsync(OrderBatchJob job, CancellationToken cancellationToken)
|
||||
{
|
||||
if (job.Action != OrderBatchActionCodes.ImportRow || string.IsNullOrWhiteSpace(job.PayloadJson))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var meta = JsonConvert.DeserializeObject<OrderBatchImportJobPayload>(job.PayloadJson);
|
||||
if (meta == null || meta.TaskId <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var task = await orderTaskRepository.FirstOrDefaultAsync(x => x.Id == meta.TaskId, cancellationToken);
|
||||
if (task == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
task.SuccessCount = job.SuccessCount;
|
||||
task.FailCount = job.FailCount;
|
||||
task.UpdateTime = DateTime.Now;
|
||||
|
||||
if (job.Status is OrderBatchJobStatusCodes.Completed or OrderBatchJobStatusCodes.Failed)
|
||||
{
|
||||
task.Status = "completed";
|
||||
}
|
||||
else if (job.Status == OrderBatchJobStatusCodes.Running)
|
||||
{
|
||||
task.Status = "processing";
|
||||
}
|
||||
|
||||
await orderTaskRepository.UpdateAsync(task, cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
private async Task RecordImportTaskFailAsync(
|
||||
OrderBatchJobMessage message,
|
||||
string? reason,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message.PayloadJson))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var payload = JsonConvert.DeserializeObject<OrderBatchImportRowPayload>(message.PayloadJson);
|
||||
if (payload == null || payload.TaskId <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
object? rawData;
|
||||
try
|
||||
{
|
||||
rawData = JsonConvert.DeserializeObject(payload.RowDataJson) ?? payload.RowDataJson;
|
||||
}
|
||||
catch
|
||||
{
|
||||
rawData = payload.RowDataJson;
|
||||
}
|
||||
|
||||
await orderTaskRepository.InsertFailListAsync([
|
||||
new OrderTaskFail
|
||||
{
|
||||
TaskId = payload.TaskId,
|
||||
RowNumber = payload.RowNumber,
|
||||
Reason = reason ?? "导入失败",
|
||||
RawDataJson = JsonConvert.SerializeObject(rawData),
|
||||
CreateUserId = message.OperatorUserId > 0 ? message.OperatorUserId : 0,
|
||||
CreateTime = DateTime.Now,
|
||||
}
|
||||
], cancellationToken);
|
||||
}
|
||||
|
||||
public enum ProcessResultKind
|
||||
{
|
||||
Ack,
|
||||
Reject,
|
||||
}
|
||||
|
||||
public readonly struct ProcessResult
|
||||
{
|
||||
public ProcessResultKind Kind { get; init; }
|
||||
|
||||
public bool Requeue { get; init; }
|
||||
|
||||
public static ProcessResult Ack => new() { Kind = ProcessResultKind.Ack };
|
||||
|
||||
public static ProcessResult Reject(bool isBusinessFailure) =>
|
||||
new() { Kind = ProcessResultKind.Reject, Requeue = !isBusinessFailure };
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,89 @@
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Newtonsoft.Json;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
|
||||
namespace Oms.Application.Services.Orders.Batch;
|
||||
|
||||
/// <summary>
|
||||
/// 订单状态/支付/异常/单据类批量操作执行器。
|
||||
/// </summary>
|
||||
public sealed class OrderBatchOrderActionHandler(IServiceScopeFactory scopeFactory) : IScopedDependency
|
||||
{
|
||||
public async Task<OrderBatchActionExecuteResult> ExecuteAsync(
|
||||
OrderBatchJobMessage message,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
var orderService = scope.ServiceProvider.GetRequiredService<OrderService>();
|
||||
|
||||
switch (message.Action)
|
||||
{
|
||||
case OrderBatchActionCodes.Pay:
|
||||
await orderService.PayForBatchAsync(message.OrderId, cancellationToken);
|
||||
return OrderBatchActionExecuteResult.Ok();
|
||||
|
||||
case OrderBatchActionCodes.PreDeclare:
|
||||
await orderService.PreDeclareForBatchAsync(message.OrderId, cancellationToken);
|
||||
return OrderBatchActionExecuteResult.Ok();
|
||||
|
||||
case OrderBatchActionCodes.Intercept:
|
||||
await orderService.InterceptForBatchAsync(message.OrderId, cancellationToken);
|
||||
return OrderBatchActionExecuteResult.Ok();
|
||||
|
||||
case OrderBatchActionCodes.CancelIntercept:
|
||||
await orderService.CancelInterceptForBatchAsync(message.OrderId, cancellationToken);
|
||||
return OrderBatchActionExecuteResult.Ok();
|
||||
|
||||
case OrderBatchActionCodes.Delete:
|
||||
await orderService.DeleteForBatchAsync(message.OrderId, cancellationToken);
|
||||
return OrderBatchActionExecuteResult.Ok();
|
||||
|
||||
case OrderBatchActionCodes.Print:
|
||||
{
|
||||
var print = await orderService.PrintForBatchAsync(message.OrderId, cancellationToken);
|
||||
return OrderBatchActionExecuteResult.Ok(
|
||||
resultJson: JsonConvert.SerializeObject(new { printUrl = print.PrintUrl }));
|
||||
}
|
||||
|
||||
case OrderBatchActionCodes.MarkProblematic:
|
||||
await orderService.MarkProblematicForBatchAsync(
|
||||
message.OrderId,
|
||||
message.PayloadJson,
|
||||
message.OperatorUserId,
|
||||
cancellationToken);
|
||||
return OrderBatchActionExecuteResult.Ok();
|
||||
|
||||
case OrderBatchActionCodes.MarkClaimed:
|
||||
await orderService.MarkClaimedForBatchAsync(
|
||||
message.OrderId,
|
||||
message.PayloadJson,
|
||||
cancellationToken);
|
||||
return OrderBatchActionExecuteResult.Ok();
|
||||
|
||||
case OrderBatchActionCodes.HandleStatusUpdate:
|
||||
await orderService.UpdateHandleStatusForBatchAsync(
|
||||
message.OrderId,
|
||||
message.PayloadJson,
|
||||
cancellationToken);
|
||||
return OrderBatchActionExecuteResult.Ok();
|
||||
|
||||
default:
|
||||
return OrderBatchActionExecuteResult.BusinessFail($"未实现的批量操作: {message.Action}");
|
||||
}
|
||||
}
|
||||
catch (BusinessException ex)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.BusinessFail(ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return OrderBatchActionExecuteResult.SystemFail(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
using Fake.Application;
|
||||
using Newtonsoft.Json;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Application.Services.Orders.Batch;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
|
||||
namespace Oms.Application.Services.Orders;
|
||||
|
||||
public partial class OrderService
|
||||
{
|
||||
private IOrderBatchJobPublisher BatchJobPublisher =>
|
||||
LazyServiceProvider.GetRequiredService<IOrderBatchJobPublisher>();
|
||||
|
||||
/// <summary>
|
||||
/// 批量 Worker 导入单行 Excel 数据。
|
||||
/// </summary>
|
||||
public async Task ImportRowForBatchAsync(
|
||||
OrderBatchImportRowPayload payload,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var rowDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(payload.RowDataJson)
|
||||
?? throw new BusinessException("行数据无效");
|
||||
await CreateImportOrderAsync(rowDict, payload.CustomerId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 批量 Worker 创建小包订单。
|
||||
/// </summary>
|
||||
public async Task<OrderParcelCreateOutput> CreateParcelForBatchAsync(
|
||||
OrderParcelCreateInput input,
|
||||
int operatorUserId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await CreateParcelCoreAsync(input, operatorUserId);
|
||||
}
|
||||
}
|
||||
162
src/Oms.Application/Services/Orders/OrderService.BatchJob.cs
Normal file
162
src/Oms.Application/Services/Orders/OrderService.BatchJob.cs
Normal file
@ -0,0 +1,162 @@
|
||||
using Fake.Application;
|
||||
using Fake.Security.Claims;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Services.Orders.Batch;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.CustomersAggregate.Repositories;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
|
||||
namespace Oms.Application.Services.Orders;
|
||||
|
||||
public partial class OrderService
|
||||
{
|
||||
private OrderBatchJobCoordinator BatchJobCoordinator =>
|
||||
LazyServiceProvider.GetRequiredService<OrderBatchJobCoordinator>();
|
||||
|
||||
/// <summary>
|
||||
/// 创建订单批量异步任务并入队 RabbitMQ。
|
||||
/// </summary>
|
||||
[HttpPost("/order/batch/jobs")]
|
||||
public Task<OrderBatchJobOutput> CreateBatchJobAsync([FromBody] OrderBatchJobCreateInput input)
|
||||
{
|
||||
return BatchJobCoordinator.CreateAndEnqueueAsync(input, CurrentUser.GetId<int>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询批量任务进度。
|
||||
/// </summary>
|
||||
[HttpGet("/order/batch/jobs/{id:int}")]
|
||||
public async Task<OrderBatchJobOutput> GetBatchJobAsync([FromRoute] int id)
|
||||
{
|
||||
var job = await BatchJobCoordinator.GetJobAsync(id);
|
||||
if (job == null)
|
||||
{
|
||||
throw new BusinessException("批量任务不存在");
|
||||
}
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分页查询批量任务列表。
|
||||
/// </summary>
|
||||
[HttpGet("/order/batch/jobs")]
|
||||
public async Task<OmsPageResult<OrderBatchJobOutput>> GetBatchJobListAsync([FromQuery] OrderBatchJobListInput input)
|
||||
{
|
||||
var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync(
|
||||
LazyServiceProvider.GetRequiredService<ICustomerRepository>(),
|
||||
CurrentUser,
|
||||
null);
|
||||
return await BatchJobCoordinator.GetJobListAsync(input, customerId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询批量任务子项明细。
|
||||
/// </summary>
|
||||
[HttpGet("/order/batch/jobs/{id:int}/items")]
|
||||
public async Task<List<OrderBatchJobItemOutput>> GetBatchJobItemsAsync([FromRoute] int id)
|
||||
{
|
||||
var job = await BatchJobCoordinator.GetJobAsync(id);
|
||||
if (job == null)
|
||||
{
|
||||
throw new BusinessException("批量任务不存在");
|
||||
}
|
||||
|
||||
return await BatchJobCoordinator.GetJobItemsAsync(id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步批量创建轨迹订单(替代前端逐条调用)。
|
||||
/// </summary>
|
||||
[HttpPost("/order/batch/track-upsert")]
|
||||
public Task<OrderBatchJobOutput> BatchTrackUpsertAsync([FromBody] OrderBatchJobCreateInput input)
|
||||
{
|
||||
input.Action = OrderBatchActionCodes.TrackUpsertSmallBag;
|
||||
return BatchJobCoordinator.CreateAndEnqueueAsync(input, CurrentUser.GetId<int>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步批量预报下游订单。
|
||||
/// </summary>
|
||||
[HttpPost("/order/batch/downstream-forward")]
|
||||
public Task<OrderBatchJobOutput> BatchDownstreamForwardAsync([FromBody] OrderBatchJobCreateInput input)
|
||||
{
|
||||
input.Action = OrderBatchActionCodes.DownstreamForwardCreateOne;
|
||||
return BatchJobCoordinator.CreateAndEnqueueAsync(input, CurrentUser.GetId<int>());
|
||||
}
|
||||
|
||||
private Task<OrderBatchJobOutput> EnqueueOrderBatchAsync(string action, OrderBatchJobCreateInput input)
|
||||
{
|
||||
input.Action = action;
|
||||
return BatchJobCoordinator.CreateAndEnqueueAsync(input, CurrentUser.GetId<int>());
|
||||
}
|
||||
|
||||
[HttpPost("/order/batch/pay")]
|
||||
public Task<OrderBatchJobOutput> BatchPayAsync([FromBody] OrderBatchJobCreateInput input) =>
|
||||
EnqueueOrderBatchAsync(OrderBatchActionCodes.Pay, input);
|
||||
|
||||
[HttpPost("/order/batch/pre-declare")]
|
||||
public Task<OrderBatchJobOutput> BatchPreDeclareAsync([FromBody] OrderBatchJobCreateInput input) =>
|
||||
EnqueueOrderBatchAsync(OrderBatchActionCodes.PreDeclare, input);
|
||||
|
||||
[HttpPost("/order/batch/intercept")]
|
||||
public Task<OrderBatchJobOutput> BatchInterceptAsync([FromBody] OrderBatchJobCreateInput input) =>
|
||||
EnqueueOrderBatchAsync(OrderBatchActionCodes.Intercept, input);
|
||||
|
||||
[HttpPost("/order/batch/cancel-intercept")]
|
||||
public Task<OrderBatchJobOutput> BatchCancelInterceptAsync([FromBody] OrderBatchJobCreateInput input) =>
|
||||
EnqueueOrderBatchAsync(OrderBatchActionCodes.CancelIntercept, input);
|
||||
|
||||
[HttpPost("/order/batch/delete")]
|
||||
public Task<OrderBatchJobOutput> BatchDeleteAsync([FromBody] OrderBatchJobCreateInput input) =>
|
||||
EnqueueOrderBatchAsync(OrderBatchActionCodes.Delete, input);
|
||||
|
||||
[HttpPost("/order/batch/print")]
|
||||
public Task<OrderBatchJobOutput> BatchPrintAsync([FromBody] OrderBatchJobCreateInput input) =>
|
||||
EnqueueOrderBatchAsync(OrderBatchActionCodes.Print, input);
|
||||
|
||||
[HttpPost("/order/batch/mark-problematic")]
|
||||
public Task<OrderBatchJobOutput> BatchMarkProblematicAsync([FromBody] OrderBatchJobCreateInput input) =>
|
||||
EnqueueOrderBatchAsync(OrderBatchActionCodes.MarkProblematic, input);
|
||||
|
||||
[HttpPost("/order/batch/mark-claimed")]
|
||||
public Task<OrderBatchJobOutput> BatchMarkClaimedAsync([FromBody] OrderBatchJobCreateInput input) =>
|
||||
EnqueueOrderBatchAsync(OrderBatchActionCodes.MarkClaimed, input);
|
||||
|
||||
[HttpPost("/order/batch/handle-status-update")]
|
||||
public Task<OrderBatchJobOutput> BatchHandleStatusUpdateAsync([FromBody] OrderBatchJobCreateInput input) =>
|
||||
EnqueueOrderBatchAsync(OrderBatchActionCodes.HandleStatusUpdate, input);
|
||||
|
||||
/// <summary>
|
||||
/// 查询 RabbitMQ 队列与 DLX 堆积情况。
|
||||
/// </summary>
|
||||
[HttpGet("/order/batch/dlx/stats")]
|
||||
public Task<OrderBatchDlxStatsOutput> GetBatchDlxStatsAsync()
|
||||
{
|
||||
var inspector = LazyServiceProvider.GetRequiredService<IOrderBatchQueueInspector>();
|
||||
return inspector.GetStatsAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重新投递失败子项。
|
||||
/// </summary>
|
||||
[HttpPost("/order/batch/jobs/{id:int}/retry-failed")]
|
||||
public Task<OrderBatchJobManageOutput> RetryFailedBatchJobAsync(
|
||||
[FromRoute] int id,
|
||||
[FromBody] OrderBatchJobRetryFailedInput? input)
|
||||
{
|
||||
return BatchJobCoordinator.RetryFailedAsync(id, input, CurrentUser.GetId<int>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取消尚未执行的 pending 子项。
|
||||
/// </summary>
|
||||
[HttpPost("/order/batch/jobs/{id:int}/cancel")]
|
||||
public Task<OrderBatchJobManageOutput> CancelBatchJobAsync([FromRoute] int id)
|
||||
{
|
||||
return BatchJobCoordinator.CancelPendingAsync(id, CurrentUser.GetId<int>());
|
||||
}
|
||||
}
|
||||
160
src/Oms.Application/Services/Orders/OrderService.BatchWorker.cs
Normal file
160
src/Oms.Application/Services/Orders/OrderService.BatchWorker.cs
Normal file
@ -0,0 +1,160 @@
|
||||
using Fake.Application;
|
||||
using Newtonsoft.Json;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Services.Orders.Issues;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
using Oms.Domain.OrdersAggregate.Entities;
|
||||
|
||||
namespace Oms.Application.Services.Orders;
|
||||
|
||||
public partial class OrderService
|
||||
{
|
||||
public Task PayForBatchAsync(int orderId, CancellationToken cancellationToken = default) =>
|
||||
PayAsync(new OrderActionInput { Id = orderId });
|
||||
|
||||
public Task PreDeclareForBatchAsync(int orderId, CancellationToken cancellationToken = default) =>
|
||||
PreDeclareAsync(new OrderActionInput { Id = orderId });
|
||||
|
||||
public Task InterceptForBatchAsync(int orderId, CancellationToken cancellationToken = default) =>
|
||||
InterceptAsync(new OrderActionInput { Id = orderId });
|
||||
|
||||
public Task CancelInterceptForBatchAsync(int orderId, CancellationToken cancellationToken = default) =>
|
||||
CancelInterceptAsync(new OrderActionInput { Id = orderId });
|
||||
|
||||
public Task DeleteForBatchAsync(int orderId, CancellationToken cancellationToken = default) =>
|
||||
DeleteAsync(new OrderActionInput { Id = orderId });
|
||||
|
||||
public Task<OrderPrintOutput> PrintForBatchAsync(int orderId, CancellationToken cancellationToken = default) =>
|
||||
PrintAsync(new OrderActionInput { Id = orderId });
|
||||
|
||||
public async Task MarkProblematicForBatchAsync(
|
||||
int orderId,
|
||||
string? payloadJson,
|
||||
int operatorUserId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var input = DeserializeBatchPayload<OrderMarkProblematicInput>(payloadJson)
|
||||
?? throw new BusinessException("问题件参数无效");
|
||||
input.OrderIds = [orderId];
|
||||
|
||||
var payload = await ResolveProblematicPayloadAsync(input);
|
||||
var request = new ProblematicMarkRequest
|
||||
{
|
||||
IssueType = payload.IssueType,
|
||||
Title = payload.Title,
|
||||
Content = payload.Content,
|
||||
IssueTemplateId = payload.IssueTemplateId,
|
||||
NotifyMethod = payload.NotifyMethod,
|
||||
Remark = payload.Remark,
|
||||
};
|
||||
|
||||
var order = await GetOrderOrThrowAsync(orderId);
|
||||
var sendNotification = !string.IsNullOrWhiteSpace(request.NotifyMethod);
|
||||
var reason = await ExceptionWorkflowService.TryMarkProblematicAsync(
|
||||
order,
|
||||
request,
|
||||
operatorUserId,
|
||||
sendNotification);
|
||||
if (!string.IsNullOrWhiteSpace(reason))
|
||||
{
|
||||
throw new BusinessException(reason);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task MarkClaimedForBatchAsync(
|
||||
int orderId,
|
||||
string? payloadJson,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var input = DeserializeBatchPayload<OrderMarkClaimedInput>(payloadJson)
|
||||
?? throw new BusinessException("理赔件参数无效");
|
||||
var payload = NormalizeClaimedPayload(input);
|
||||
var order = await GetOrderOrThrowAsync(orderId);
|
||||
|
||||
if (!OrderExceptionStatusRules.CanMarkException(order.OrderStatus))
|
||||
{
|
||||
throw new BusinessException(OrderExceptionStatusRules.GetForbiddenReason(order.OrderStatus));
|
||||
}
|
||||
|
||||
var fromStatus = order.OrderStatus;
|
||||
order.PreviousOrderStatus = fromStatus;
|
||||
order.OrderStatus = OrderStatusCodes.Claimed;
|
||||
order.HandleStatus = OrderHandleStatusCodes.Pending;
|
||||
order.ClaimType = payload.ClaimType;
|
||||
order.ClaimAmount = payload.ClaimAmount;
|
||||
order.ClaimCurrency = payload.ClaimCurrency;
|
||||
order.ClaimReason = payload.ClaimReason;
|
||||
order.ClaimTime = DateTime.Now;
|
||||
order.IssueType = null;
|
||||
order.IssueTitle = null;
|
||||
order.IssueContent = null;
|
||||
order.IssueTemplateId = null;
|
||||
order.IssueRemark = null;
|
||||
order.IssueTime = null;
|
||||
|
||||
await OrderRepository.UpdateAsync(order);
|
||||
await OrderExceptionEventRepository.InsertAsync(new OrderExceptionEvent
|
||||
{
|
||||
OrderId = order.Id,
|
||||
EventType = OrderExceptionEventTypeCodes.MarkClaimed,
|
||||
FromStatus = fromStatus,
|
||||
ToStatus = OrderStatusCodes.Claimed,
|
||||
FromHandleStatus = null,
|
||||
ToHandleStatus = OrderHandleStatusCodes.Pending,
|
||||
ClaimType = payload.ClaimType,
|
||||
ClaimAmount = payload.ClaimAmount,
|
||||
ClaimCurrency = payload.ClaimCurrency,
|
||||
ClaimReason = payload.ClaimReason,
|
||||
Remark = payload.Remark,
|
||||
});
|
||||
}
|
||||
|
||||
public async Task UpdateHandleStatusForBatchAsync(
|
||||
int orderId,
|
||||
string? payloadJson,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var input = DeserializeBatchPayload<OrderHandleStatusUpdateInput>(payloadJson)
|
||||
?? throw new BusinessException("处理状态参数无效");
|
||||
var targetStatus = input.HandleStatus?.Trim().ToLowerInvariant();
|
||||
if (!string.Equals(targetStatus, OrderHandleStatusCodes.Processed, StringComparison.Ordinal))
|
||||
{
|
||||
throw new BusinessException("仅支持标记为已处理");
|
||||
}
|
||||
|
||||
var order = await GetOrderOrThrowAsync(orderId);
|
||||
if (order.OrderStatus is not (OrderStatusCodes.Problematic or OrderStatusCodes.Claimed))
|
||||
{
|
||||
throw new BusinessException("仅问题件或理赔件可更新处理状态");
|
||||
}
|
||||
|
||||
if (OrderHandleStatusCodes.IsProcessed(order.HandleStatus))
|
||||
{
|
||||
throw new BusinessException("订单已处理");
|
||||
}
|
||||
|
||||
order.HandleStatus = OrderHandleStatusCodes.Processed;
|
||||
await OrderRepository.UpdateAsync(order);
|
||||
await OrderExceptionEventRepository.InsertAsync(new OrderExceptionEvent
|
||||
{
|
||||
OrderId = order.Id,
|
||||
EventType = OrderExceptionEventTypeCodes.HandleProcessed,
|
||||
FromStatus = order.OrderStatus,
|
||||
ToStatus = order.OrderStatus,
|
||||
FromHandleStatus = OrderHandleStatusCodes.Pending,
|
||||
ToHandleStatus = OrderHandleStatusCodes.Processed,
|
||||
Remark = input.Remark?.Trim(),
|
||||
});
|
||||
}
|
||||
|
||||
private static T? DeserializeBatchPayload<T>(string? payloadJson)
|
||||
where T : class
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(payloadJson))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return JsonConvert.DeserializeObject<T>(payloadJson);
|
||||
}
|
||||
}
|
||||
@ -5,9 +5,12 @@ using Fake.Application;
|
||||
using Fake.Users;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MiniExcelLibs;
|
||||
using Newtonsoft.Json;
|
||||
using Oms.Application.DataPerm;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Application.Services.Orders.Batch;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.OrdersAggregate;
|
||||
using Oms.Domain.ChannelsAggregate.Consts;
|
||||
@ -301,6 +304,103 @@ public partial class OrderService
|
||||
throw new BusinessException("上传文件不能为空");
|
||||
}
|
||||
|
||||
if (BatchJobPublisher.IsEnabled)
|
||||
{
|
||||
return await ImportOrdersViaQueueAsync(input);
|
||||
}
|
||||
|
||||
return await ImportOrdersSyncAsync(input);
|
||||
}
|
||||
|
||||
private async Task<OrderUploadOutput> ImportOrdersViaQueueAsync(OrderUploadInput input)
|
||||
{
|
||||
var template = await OrderTemplateRepository.FirstOrDefaultAsync(x => x.Id == input.TemplateId);
|
||||
if (template == null)
|
||||
{
|
||||
throw new BusinessException("模板不存在");
|
||||
}
|
||||
|
||||
var effectiveCustomer = await ResolveEffectiveCustomerAsync();
|
||||
EnsureTemplateAccessible(template, effectiveCustomer.Id);
|
||||
|
||||
var parsedRows = new List<(int RowNumber, IDictionary<string, object> RowDict)>();
|
||||
var rowNumber = 1;
|
||||
var rows = await MiniExcel.QueryAsync(input.File!.OpenReadStream(), useHeaderRow: true);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
rowNumber++;
|
||||
if (row is not IDictionary<string, object> rowDict)
|
||||
{
|
||||
parsedRows.Add((rowNumber, new Dictionary<string, object>()));
|
||||
continue;
|
||||
}
|
||||
|
||||
parsedRows.Add((rowNumber, rowDict));
|
||||
}
|
||||
|
||||
if (parsedRows.Count == 0)
|
||||
{
|
||||
throw new BusinessException("Excel 中未读取到可用数据");
|
||||
}
|
||||
|
||||
if (parsedRows.Count > ParcelBatchMaxCount)
|
||||
{
|
||||
throw new BusinessException($"单次最多导入 {ParcelBatchMaxCount} 行");
|
||||
}
|
||||
|
||||
var task = await OrderTaskRepository.InsertAsync(new OrderTask
|
||||
{
|
||||
TaskName = $"批量下单_{DateTime.Now:yyyyMMddHHmmss}",
|
||||
Quantity = parsedRows.Count,
|
||||
SuccessCount = 0,
|
||||
FailCount = 0,
|
||||
Status = "processing",
|
||||
TemplateId = template.Id,
|
||||
CustomerId = effectiveCustomer.Id
|
||||
});
|
||||
|
||||
var jobPayload = JsonConvert.SerializeObject(new OrderBatchImportJobPayload
|
||||
{
|
||||
TaskId = task.Id,
|
||||
TemplateId = template.Id,
|
||||
CustomerId = effectiveCustomer.Id,
|
||||
});
|
||||
|
||||
var payloadItems = parsedRows.Select(row => new OrderBatchPayloadItemInput
|
||||
{
|
||||
OrderId = 0,
|
||||
ServiceNo = GetStringCell(row.RowDict, "ServiceNo"),
|
||||
ItemKey = $"import:{task.Id}:{row.RowNumber}",
|
||||
PayloadJson = JsonConvert.SerializeObject(new OrderBatchImportRowPayload
|
||||
{
|
||||
TaskId = task.Id,
|
||||
RowNumber = row.RowNumber,
|
||||
CustomerId = effectiveCustomer.Id,
|
||||
RowDataJson = JsonConvert.SerializeObject(row.RowDict),
|
||||
}),
|
||||
}).ToList();
|
||||
|
||||
var job = await BatchJobCoordinator.CreatePayloadJobAsync(
|
||||
new OrderBatchPayloadJobCreateInput
|
||||
{
|
||||
Action = OrderBatchActionCodes.ImportRow,
|
||||
CustomerId = effectiveCustomer.Id,
|
||||
JobPayloadJson = jobPayload,
|
||||
RequestId = $"import-task-{task.Id}",
|
||||
Items = payloadItems,
|
||||
},
|
||||
CurrentUser.GetId<int>());
|
||||
|
||||
return new OrderUploadOutput
|
||||
{
|
||||
TaskId = task.Id,
|
||||
JobId = job.JobId,
|
||||
Async = true,
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<OrderUploadOutput> ImportOrdersSyncAsync(OrderUploadInput input)
|
||||
{
|
||||
var template = await OrderTemplateRepository.FirstOrDefaultAsync(x => x.Id == input.TemplateId);
|
||||
if (template == null)
|
||||
{
|
||||
@ -327,7 +427,7 @@ public partial class OrderService
|
||||
var rowNumber = 1;
|
||||
var failList = new List<OrderTaskFail>();
|
||||
|
||||
var rows = await MiniExcel.QueryAsync(input.File.OpenReadStream(), useHeaderRow: true);
|
||||
var rows = await MiniExcel.QueryAsync(input.File!.OpenReadStream(), useHeaderRow: true);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
rowNumber++;
|
||||
@ -689,7 +789,7 @@ public partial class OrderService
|
||||
TaskId = taskId,
|
||||
RowNumber = rowNumber,
|
||||
Reason = reason,
|
||||
RawDataJson = JsonSerializer.Serialize(rawData),
|
||||
RawDataJson = JsonConvert.SerializeObject(rawData),
|
||||
CreateUserId = 0,
|
||||
CreateTime = DateTime.Now
|
||||
};
|
||||
|
||||
@ -37,7 +37,9 @@ public partial class OrderService
|
||||
private AutoTriggerRuntimeService AutoTriggerRuntimeService =>
|
||||
LazyServiceProvider.GetRequiredService<AutoTriggerRuntimeService>();
|
||||
|
||||
private async Task<OrderParcelCreateOutput> CreateParcelCoreAsync(OrderParcelCreateInput input)
|
||||
private async Task<OrderParcelCreateOutput> CreateParcelCoreAsync(
|
||||
OrderParcelCreateInput input,
|
||||
int? operatorUserId = null)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(input.RequestId))
|
||||
{
|
||||
@ -141,7 +143,8 @@ public partial class OrderService
|
||||
|
||||
try
|
||||
{
|
||||
await AutoTriggerRuntimeService.FireAsync(order, AutoTriggerTiming.OrderCreate, CurrentUser.GetId<int>());
|
||||
var triggerUserId = operatorUserId ?? CurrentUser.GetId<int>();
|
||||
await AutoTriggerRuntimeService.FireAsync(order, AutoTriggerTiming.OrderCreate, triggerUserId);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@ -1470,7 +1473,7 @@ public partial class OrderService
|
||||
request.Authorization = authorization;
|
||||
}
|
||||
|
||||
SmallBagTrackOrderNotifier.Enqueue(request);
|
||||
SmallBagTrackOrderNotifier.Enqueue(request, order.Id, customer?.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -7,6 +7,8 @@ using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.DataPerm;
|
||||
using Oms.Application.Shared;
|
||||
using Newtonsoft.Json;
|
||||
using Oms.Application.Services.Orders.Batch;
|
||||
using Oms.Domain.ChannelsAggregate.Repositories;
|
||||
using Oms.Domain.CustomersAggregate.Repositories;
|
||||
using Oms.Domain.OrdersAggregate;
|
||||
@ -346,6 +348,51 @@ public partial class OrderService : ApplicationService
|
||||
throw new BusinessException($"单次批量创建不能超过{ParcelBatchMaxCount}条");
|
||||
}
|
||||
|
||||
if (BatchJobPublisher.IsEnabled)
|
||||
{
|
||||
return await BatchCreateParcelViaQueueAsync(input);
|
||||
}
|
||||
|
||||
return await BatchCreateParcelSyncAsync(input);
|
||||
}
|
||||
|
||||
private async Task<OrderParcelBatchCreateOutput> BatchCreateParcelViaQueueAsync(OrderParcelBatchCreateInput input)
|
||||
{
|
||||
var batchNo = $"PCB{DateTime.Now:yyyyMMddHHmmssfff}";
|
||||
var operatorUserId = CurrentUser.GetId<int>();
|
||||
var payloadItems = input.Select((request, index) => new OrderBatchPayloadItemInput
|
||||
{
|
||||
OrderId = 0,
|
||||
ServiceNo = request.ServiceNo,
|
||||
ItemKey = !string.IsNullOrWhiteSpace(request.RequestId)
|
||||
? $"parcel:{request.RequestId}"
|
||||
: $"parcel:{batchNo}:{index + 1}",
|
||||
PayloadJson = JsonConvert.SerializeObject(request),
|
||||
}).ToList();
|
||||
|
||||
var job = await BatchJobCoordinator.CreatePayloadJobAsync(
|
||||
new OrderBatchPayloadJobCreateInput
|
||||
{
|
||||
Action = OrderBatchActionCodes.ParcelCreate,
|
||||
RequestId = batchNo,
|
||||
Items = payloadItems,
|
||||
},
|
||||
operatorUserId);
|
||||
|
||||
return new OrderParcelBatchCreateOutput
|
||||
{
|
||||
BatchNo = batchNo,
|
||||
JobId = job.JobId,
|
||||
Async = true,
|
||||
Total = input.Count,
|
||||
SuccessCount = 0,
|
||||
FailCount = 0,
|
||||
Items = [],
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<OrderParcelBatchCreateOutput> BatchCreateParcelSyncAsync(OrderParcelBatchCreateInput input)
|
||||
{
|
||||
var batchNo = $"PCB{DateTime.Now:yyyyMMddHHmmssfff}";
|
||||
var items = new List<OrderParcelBatchCreateItemOutput>(input.Count);
|
||||
var successCount = 0;
|
||||
|
||||
@ -0,0 +1,136 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Application.Services.Orders.Batch;
|
||||
using RabbitMQ.Client;
|
||||
using RabbitMQ.Client.Events;
|
||||
|
||||
namespace Oms.Application.Workers.OrderBatch;
|
||||
|
||||
/// <summary>
|
||||
/// 消费创建类队列(Excel 导入行、小包批量创建)。
|
||||
/// </summary>
|
||||
public sealed class OrderBatchCreateConsumer : BackgroundService
|
||||
{
|
||||
private readonly OrderBatchRabbitMqOptions _options;
|
||||
private readonly IServiceScopeFactory _scopeFactory;
|
||||
private readonly ILogger<OrderBatchCreateConsumer> _logger;
|
||||
private IConnection? _connection;
|
||||
private IModel? _channel;
|
||||
|
||||
public OrderBatchCreateConsumer(
|
||||
IOptions<OrderBatchRabbitMqOptions> options,
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger<OrderBatchCreateConsumer> logger)
|
||||
{
|
||||
_options = options.Value;
|
||||
_scopeFactory = scopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
{
|
||||
_logger.LogInformation("Order batch RabbitMQ disabled, create consumer not started.");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var factory = new ConnectionFactory
|
||||
{
|
||||
HostName = _options.HostName,
|
||||
Port = _options.Port,
|
||||
UserName = _options.UserName,
|
||||
Password = _options.Password,
|
||||
VirtualHost = _options.VirtualHost,
|
||||
DispatchConsumersAsync = true,
|
||||
AutomaticRecoveryEnabled = true,
|
||||
};
|
||||
|
||||
_connection = factory.CreateConnection("oms-order-batch-create-consumer");
|
||||
_channel = _connection.CreateModel();
|
||||
_channel.BasicQos(0, _options.PrefetchCount, false);
|
||||
|
||||
var consumer = new AsyncEventingBasicConsumer(_channel);
|
||||
consumer.Received += OnReceivedAsync;
|
||||
|
||||
_channel.BasicConsume(
|
||||
queue: OrderBatchQueueTopology.QueueCreate,
|
||||
autoAck: false,
|
||||
consumer: consumer);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Order batch create consumer started on {Queue}.",
|
||||
OrderBatchQueueTopology.QueueCreate);
|
||||
|
||||
stoppingToken.Register(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
_channel?.Close();
|
||||
_connection?.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "Error closing RabbitMQ create consumer.");
|
||||
}
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task OnReceivedAsync(object sender, BasicDeliverEventArgs ea)
|
||||
{
|
||||
if (_channel == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var message = OrderBatchJobProcessor.Deserialize(ea.Body);
|
||||
if (message == null)
|
||||
{
|
||||
_channel.BasicAck(ea.DeliveryTag, false);
|
||||
return;
|
||||
}
|
||||
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var processor = scope.ServiceProvider.GetRequiredService<OrderBatchJobProcessor>();
|
||||
var result = await processor.ProcessAsync(message);
|
||||
|
||||
switch (result.Kind)
|
||||
{
|
||||
case OrderBatchJobProcessor.ProcessResultKind.Ack:
|
||||
_channel.BasicAck(ea.DeliveryTag, false);
|
||||
break;
|
||||
case OrderBatchJobProcessor.ProcessResultKind.Reject:
|
||||
if (result.Requeue && message.RetryCount < _options.MaxRetryCount)
|
||||
{
|
||||
message.RetryCount++;
|
||||
_channel.BasicNack(ea.DeliveryTag, false, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
_channel.BasicAck(ea.DeliveryTag, false);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Order batch create consumer failed.");
|
||||
_channel.BasicNack(ea.DeliveryTag, false, true);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_channel?.Dispose();
|
||||
_connection?.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,78 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Oms.Application.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// 周期性检查 DLX 堆积并写告警日志。
|
||||
/// </summary>
|
||||
public sealed class OrderBatchDlxMonitorHostedService : BackgroundService
|
||||
{
|
||||
private readonly IOrderBatchQueueInspector _inspector;
|
||||
private readonly OrderBatchRabbitMqOptions _options;
|
||||
private readonly ILogger<OrderBatchDlxMonitorHostedService> _logger;
|
||||
|
||||
public OrderBatchDlxMonitorHostedService(
|
||||
IOrderBatchQueueInspector inspector,
|
||||
IOptions<OrderBatchRabbitMqOptions> options,
|
||||
ILogger<OrderBatchDlxMonitorHostedService> logger)
|
||||
{
|
||||
_inspector = inspector;
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var interval = TimeSpan.FromSeconds(Math.Max(60, _options.MonitorIntervalSeconds));
|
||||
using var timer = new PeriodicTimer(interval);
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await CheckAsync(stoppingToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "Order batch DLX monitor check failed.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await timer.WaitForNextTickAsync(stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CheckAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var stats = await _inspector.GetStatsAsync(cancellationToken);
|
||||
if (!stats.Enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (stats.Alert)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Order batch DLX alert: deadLetterMessages={DeadLetterCount} threshold={Threshold}",
|
||||
stats.DeadLetterMessageCount,
|
||||
stats.DlxAlertThreshold);
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogDebug(
|
||||
"Order batch queue health ok, dlxMessages={DeadLetterCount}",
|
||||
stats.DeadLetterMessageCount);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,136 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Application.Services.Orders.Batch;
|
||||
using RabbitMQ.Client;
|
||||
using RabbitMQ.Client.Events;
|
||||
|
||||
namespace Oms.Application.Workers.OrderBatch;
|
||||
|
||||
/// <summary>
|
||||
/// 消费外部集成队列(轨迹同步、下游预报)。
|
||||
/// </summary>
|
||||
public sealed class OrderBatchIntegrationConsumer : BackgroundService
|
||||
{
|
||||
private readonly OrderBatchRabbitMqOptions _options;
|
||||
private readonly IServiceScopeFactory _scopeFactory;
|
||||
private readonly ILogger<OrderBatchIntegrationConsumer> _logger;
|
||||
private IConnection? _connection;
|
||||
private IModel? _channel;
|
||||
|
||||
public OrderBatchIntegrationConsumer(
|
||||
IOptions<OrderBatchRabbitMqOptions> options,
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger<OrderBatchIntegrationConsumer> logger)
|
||||
{
|
||||
_options = options.Value;
|
||||
_scopeFactory = scopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
{
|
||||
_logger.LogInformation("Order batch RabbitMQ disabled, integration consumer not started.");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var factory = new ConnectionFactory
|
||||
{
|
||||
HostName = _options.HostName,
|
||||
Port = _options.Port,
|
||||
UserName = _options.UserName,
|
||||
Password = _options.Password,
|
||||
VirtualHost = _options.VirtualHost,
|
||||
DispatchConsumersAsync = true,
|
||||
AutomaticRecoveryEnabled = true,
|
||||
};
|
||||
|
||||
_connection = factory.CreateConnection("oms-order-batch-integration-consumer");
|
||||
_channel = _connection.CreateModel();
|
||||
_channel.BasicQos(0, _options.PrefetchCount, false);
|
||||
|
||||
var consumer = new AsyncEventingBasicConsumer(_channel);
|
||||
consumer.Received += OnReceivedAsync;
|
||||
|
||||
_channel.BasicConsume(
|
||||
queue: OrderBatchQueueTopology.QueueIntegration,
|
||||
autoAck: false,
|
||||
consumer: consumer);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Order batch integration consumer started on {Queue}.",
|
||||
OrderBatchQueueTopology.QueueIntegration);
|
||||
|
||||
stoppingToken.Register(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
_channel?.Close();
|
||||
_connection?.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "Error closing RabbitMQ consumer.");
|
||||
}
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task OnReceivedAsync(object sender, BasicDeliverEventArgs ea)
|
||||
{
|
||||
if (_channel == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var message = OrderBatchJobProcessor.Deserialize(ea.Body);
|
||||
if (message == null)
|
||||
{
|
||||
_channel.BasicAck(ea.DeliveryTag, false);
|
||||
return;
|
||||
}
|
||||
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var processor = scope.ServiceProvider.GetRequiredService<OrderBatchJobProcessor>();
|
||||
var result = await processor.ProcessAsync(message);
|
||||
|
||||
switch (result.Kind)
|
||||
{
|
||||
case OrderBatchJobProcessor.ProcessResultKind.Ack:
|
||||
_channel.BasicAck(ea.DeliveryTag, false);
|
||||
break;
|
||||
case OrderBatchJobProcessor.ProcessResultKind.Reject:
|
||||
if (result.Requeue && message.RetryCount < _options.MaxRetryCount)
|
||||
{
|
||||
message.RetryCount++;
|
||||
_channel.BasicNack(ea.DeliveryTag, false, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
_channel.BasicAck(ea.DeliveryTag, false);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Order batch integration consumer failed.");
|
||||
_channel.BasicNack(ea.DeliveryTag, false, true);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_channel?.Dispose();
|
||||
_connection?.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,177 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Application.Services.Orders.Batch;
|
||||
using RabbitMQ.Client;
|
||||
using RabbitMQ.Client.Events;
|
||||
|
||||
namespace Oms.Application.Workers.OrderBatch;
|
||||
|
||||
public abstract class OrderBatchQueueConsumerBase : BackgroundService
|
||||
{
|
||||
private readonly OrderBatchRabbitMqOptions _options;
|
||||
private readonly IServiceScopeFactory _scopeFactory;
|
||||
private readonly ILogger _logger;
|
||||
private IConnection? _connection;
|
||||
private IModel? _channel;
|
||||
|
||||
protected OrderBatchQueueConsumerBase(
|
||||
IOptions<OrderBatchRabbitMqOptions> options,
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger logger)
|
||||
{
|
||||
_options = options.Value;
|
||||
_scopeFactory = scopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected abstract string QueueName { get; }
|
||||
|
||||
protected abstract string ConnectionName { get; }
|
||||
|
||||
protected override Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Order batch RabbitMQ disabled, consumer for {Queue} not started.",
|
||||
QueueName);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var factory = new ConnectionFactory
|
||||
{
|
||||
HostName = _options.HostName,
|
||||
Port = _options.Port,
|
||||
UserName = _options.UserName,
|
||||
Password = _options.Password,
|
||||
VirtualHost = _options.VirtualHost,
|
||||
DispatchConsumersAsync = true,
|
||||
AutomaticRecoveryEnabled = true,
|
||||
};
|
||||
|
||||
_connection = factory.CreateConnection(ConnectionName);
|
||||
_channel = _connection.CreateModel();
|
||||
_channel.BasicQos(0, _options.PrefetchCount, false);
|
||||
|
||||
var consumer = new AsyncEventingBasicConsumer(_channel);
|
||||
consumer.Received += OnReceivedAsync;
|
||||
|
||||
_channel.BasicConsume(queue: QueueName, autoAck: false, consumer: consumer);
|
||||
|
||||
_logger.LogInformation("Order batch consumer started on {Queue}.", QueueName);
|
||||
|
||||
stoppingToken.Register(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
_channel?.Close();
|
||||
_connection?.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "Error closing RabbitMQ consumer {Queue}.", QueueName);
|
||||
}
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task OnReceivedAsync(object sender, BasicDeliverEventArgs ea)
|
||||
{
|
||||
if (_channel == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var message = OrderBatchJobProcessor.Deserialize(ea.Body);
|
||||
if (message == null)
|
||||
{
|
||||
_channel.BasicAck(ea.DeliveryTag, false);
|
||||
return;
|
||||
}
|
||||
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var processor = scope.ServiceProvider.GetRequiredService<OrderBatchJobProcessor>();
|
||||
var result = await processor.ProcessAsync(message);
|
||||
|
||||
switch (result.Kind)
|
||||
{
|
||||
case OrderBatchJobProcessor.ProcessResultKind.Ack:
|
||||
_channel.BasicAck(ea.DeliveryTag, false);
|
||||
break;
|
||||
case OrderBatchJobProcessor.ProcessResultKind.Reject:
|
||||
if (result.Requeue)
|
||||
{
|
||||
_channel.BasicNack(ea.DeliveryTag, false, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
_channel.BasicAck(ea.DeliveryTag, false);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Order batch consumer failed on queue {Queue}.", QueueName);
|
||||
_channel.BasicNack(ea.DeliveryTag, false, true);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_channel?.Dispose();
|
||||
_connection?.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class OrderBatchAccountConsumer(
|
||||
IOptions<OrderBatchRabbitMqOptions> options,
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger<OrderBatchAccountConsumer> logger)
|
||||
: OrderBatchQueueConsumerBase(options, scopeFactory, logger)
|
||||
{
|
||||
protected override string QueueName => OrderBatchQueueTopology.QueueAccount;
|
||||
|
||||
protected override string ConnectionName => "oms-order-batch-account-consumer";
|
||||
}
|
||||
|
||||
public sealed class OrderBatchStateConsumer(
|
||||
IOptions<OrderBatchRabbitMqOptions> options,
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger<OrderBatchStateConsumer> logger)
|
||||
: OrderBatchQueueConsumerBase(options, scopeFactory, logger)
|
||||
{
|
||||
protected override string QueueName => OrderBatchQueueTopology.QueueState;
|
||||
|
||||
protected override string ConnectionName => "oms-order-batch-state-consumer";
|
||||
}
|
||||
|
||||
public sealed class OrderBatchExceptionConsumer(
|
||||
IOptions<OrderBatchRabbitMqOptions> options,
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger<OrderBatchExceptionConsumer> logger)
|
||||
: OrderBatchQueueConsumerBase(options, scopeFactory, logger)
|
||||
{
|
||||
protected override string QueueName => OrderBatchQueueTopology.QueueException;
|
||||
|
||||
protected override string ConnectionName => "oms-order-batch-exception-consumer";
|
||||
}
|
||||
|
||||
public sealed class OrderBatchDocumentConsumer(
|
||||
IOptions<OrderBatchRabbitMqOptions> options,
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger<OrderBatchDocumentConsumer> logger)
|
||||
: OrderBatchQueueConsumerBase(options, scopeFactory, logger)
|
||||
{
|
||||
protected override string QueueName => OrderBatchQueueTopology.QueueDocument;
|
||||
|
||||
protected override string ConnectionName => "oms-order-batch-document-consumer";
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
namespace Oms.Domain.OrdersAggregate.Consts;
|
||||
|
||||
public static class OrderBatchJobStatusCodes
|
||||
{
|
||||
public const string Pending = "pending";
|
||||
public const string Running = "running";
|
||||
public const string Completed = "completed";
|
||||
public const string Failed = "failed";
|
||||
public const string Cancelled = "cancelled";
|
||||
}
|
||||
|
||||
public static class OrderBatchJobItemStatusCodes
|
||||
{
|
||||
public const string Pending = "pending";
|
||||
public const string Running = "running";
|
||||
public const string Success = "success";
|
||||
public const string Failed = "failed";
|
||||
public const string Cancelled = "cancelled";
|
||||
}
|
||||
|
||||
public static class OrderBatchActionCodes
|
||||
{
|
||||
public const string TrackUpsertSmallBag = "track-upsert-small-bag";
|
||||
public const string DownstreamForwardCreateOne = "downstream-forward-create-one";
|
||||
public const string Pay = "pay";
|
||||
public const string PreDeclare = "pre-declare";
|
||||
public const string Intercept = "intercept";
|
||||
public const string CancelIntercept = "cancel-intercept";
|
||||
public const string Delete = "delete";
|
||||
public const string MarkProblematic = "mark-problematic";
|
||||
public const string MarkClaimed = "mark-claimed";
|
||||
public const string HandleStatusUpdate = "handle-status-update";
|
||||
public const string Print = "print";
|
||||
public const string Export = "export";
|
||||
public const string ParcelCreate = "parcel-create";
|
||||
public const string ImportRow = "import-row";
|
||||
}
|
||||
32
src/Oms.Domain/OrdersAggregate/Entities/OrderBatchJob.cs
Normal file
32
src/Oms.Domain/OrdersAggregate/Entities/OrderBatchJob.cs
Normal file
@ -0,0 +1,32 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.OrdersAggregate.Entities;
|
||||
|
||||
[SugarTable("t_order_batch_job")]
|
||||
public class OrderBatchJob : OmsAuditedAggregateRoot
|
||||
{
|
||||
public string Action { get; set; } = string.Empty;
|
||||
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
public int Total { get; set; }
|
||||
|
||||
public int SuccessCount { get; set; }
|
||||
|
||||
public int FailCount { get; set; }
|
||||
|
||||
public int? CustomerId { get; set; }
|
||||
|
||||
[SugarColumn(ColumnDataType = "json", IsNullable = true)]
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? RequestId { get; set; }
|
||||
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public DateTime? StartedAt { get; set; }
|
||||
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public DateTime? FinishedAt { get; set; }
|
||||
}
|
||||
39
src/Oms.Domain/OrdersAggregate/Entities/OrderBatchJobItem.cs
Normal file
39
src/Oms.Domain/OrdersAggregate/Entities/OrderBatchJobItem.cs
Normal file
@ -0,0 +1,39 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.OrdersAggregate.Entities;
|
||||
|
||||
[SugarTable("t_order_batch_job_item")]
|
||||
public class OrderBatchJobItem : OmsAuditedEntity
|
||||
{
|
||||
public int JobId { get; set; }
|
||||
|
||||
public int OrderId { get; set; }
|
||||
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? ServiceNo { get; set; }
|
||||
|
||||
public string Action { get; set; } = string.Empty;
|
||||
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
[SugarColumn(Length = 128, IsNullable = true)]
|
||||
public string? MessageId { get; set; }
|
||||
|
||||
[SugarColumn(ColumnDataType = "text", IsNullable = true)]
|
||||
public string? FailReason { get; set; }
|
||||
|
||||
[SugarColumn(ColumnDataType = "text", IsNullable = true)]
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
[SugarColumn(ColumnDataType = "text", IsNullable = true)]
|
||||
public string? ResultJson { get; set; }
|
||||
|
||||
public int RetryCount { get; set; }
|
||||
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public DateTime? StartedAt { get; set; }
|
||||
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public DateTime? FinishedAt { get; set; }
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
using Fake.Domain.Repositories;
|
||||
using Oms.Domain.OrdersAggregate.Entities;
|
||||
|
||||
namespace Oms.Domain.OrdersAggregate.Repositories;
|
||||
|
||||
public interface IOrderBatchJobRepository : IRepository<OrderBatchJob>
|
||||
{
|
||||
Task<OrderBatchJob?> GetByIdAsync(int id, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<OrderBatchJob?> GetByRequestIdAsync(string requestId, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<List<OrderBatchJobItem>> GetItemsByJobIdAsync(int jobId, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<OrderBatchJobItem?> GetItemByIdAsync(int itemId, CancellationToken cancellationToken = default);
|
||||
|
||||
Task InsertItemsAsync(IEnumerable<OrderBatchJobItem> items, CancellationToken cancellationToken = default);
|
||||
|
||||
Task UpdateItemAsync(OrderBatchJobItem item, CancellationToken cancellationToken = default);
|
||||
|
||||
Task UpdateJobAsync(OrderBatchJob job, CancellationToken cancellationToken = default);
|
||||
}
|
||||
58
src/Oms.SqlSugarCore/Orders/OrderBatchJobRepository.cs
Normal file
58
src/Oms.SqlSugarCore/Orders/OrderBatchJobRepository.cs
Normal file
@ -0,0 +1,58 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Domain.OrdersAggregate.Entities;
|
||||
using Oms.Domain.OrdersAggregate.Repositories;
|
||||
using Oms.SqlSugarCore.Repositories;
|
||||
|
||||
namespace Oms.SqlSugarCore.Orders;
|
||||
|
||||
public class OrderBatchJobRepository : OmsSqlSugarRepository<OrderBatchJob>, IOrderBatchJobRepository, IScopedDependency
|
||||
{
|
||||
public Task<OrderBatchJob?> GetByIdAsync(int id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||||
}
|
||||
|
||||
public Task<OrderBatchJob?> GetByRequestIdAsync(string requestId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return FirstOrDefaultAsync(x => x.RequestId == requestId, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<List<OrderBatchJobItem>> GetItemsByJobIdAsync(int jobId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var db = await GetDbContextAsync(cancellationToken);
|
||||
return await db.Queryable<OrderBatchJobItem>()
|
||||
.Where(x => x.JobId == jobId)
|
||||
.OrderBy(x => x.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<OrderBatchJobItem?> GetItemByIdAsync(int itemId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var db = await GetDbContextAsync(cancellationToken);
|
||||
return await db.Queryable<OrderBatchJobItem>()
|
||||
.FirstAsync(it => it.Id == itemId, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task InsertItemsAsync(IEnumerable<OrderBatchJobItem> items, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var list = items.ToArray();
|
||||
if (list.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var db = await GetDbContextAsync(cancellationToken);
|
||||
await db.Insertable(list).ExecuteCommandAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task UpdateItemAsync(OrderBatchJobItem item, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var db = await GetDbContextAsync(cancellationToken);
|
||||
await db.Updateable(item).ExecuteCommandAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public Task UpdateJobAsync(OrderBatchJob job, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return UpdateAsync(job, cancellationToken);
|
||||
}
|
||||
}
|
||||
137
src/Oms.Tests/OrderBatchJobCoordinatorGovernanceTests.cs
Normal file
137
src/Oms.Tests/OrderBatchJobCoordinatorGovernanceTests.cs
Normal file
@ -0,0 +1,137 @@
|
||||
using FluentAssertions;
|
||||
using Fake.Application;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Application.Services.Orders.Batch;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
using Oms.Domain.OrdersAggregate.Entities;
|
||||
using Oms.Domain.OrdersAggregate.Repositories;
|
||||
|
||||
namespace Oms.Tests;
|
||||
|
||||
public class OrderBatchJobCoordinatorGovernanceTests
|
||||
{
|
||||
private readonly Mock<IOrderBatchJobRepository> _batchJobRepository = new(MockBehavior.Strict);
|
||||
private readonly Mock<IOrderRepository> _orderRepository = new(MockBehavior.Loose);
|
||||
private readonly Mock<IOrderBatchJobPublisher> _publisher = new(MockBehavior.Strict);
|
||||
private readonly OrderBatchJobCoordinator _coordinator;
|
||||
|
||||
public OrderBatchJobCoordinatorGovernanceTests()
|
||||
{
|
||||
_publisher.SetupGet(x => x.IsEnabled).Returns(true);
|
||||
_coordinator = new OrderBatchJobCoordinator(
|
||||
_batchJobRepository.Object,
|
||||
_orderRepository.Object,
|
||||
_publisher.Object,
|
||||
NullLogger<OrderBatchJobCoordinator>.Instance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RetryFailedAsync_ShouldResetFailedItemsAndPublish()
|
||||
{
|
||||
var job = CreateJob();
|
||||
var failedItem = CreateItem(1, OrderBatchJobItemStatusCodes.Failed, "网络错误");
|
||||
var successItem = CreateItem(2, OrderBatchJobItemStatusCodes.Success);
|
||||
|
||||
_batchJobRepository
|
||||
.Setup(x => x.GetByIdAsync(job.Id, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(job);
|
||||
_batchJobRepository
|
||||
.Setup(x => x.GetItemsByJobIdAsync(job.Id, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync([failedItem, successItem]);
|
||||
_batchJobRepository
|
||||
.Setup(x => x.UpdateItemAsync(failedItem, It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
_batchJobRepository
|
||||
.Setup(x => x.UpdateJobAsync(job, It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
_publisher
|
||||
.Setup(x => x.PublishAsync(It.IsAny<OrderBatchJobMessage>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
var output = await _coordinator.RetryFailedAsync(job.Id, null, 99);
|
||||
|
||||
output.JobId.Should().Be(job.Id);
|
||||
output.RetriedCount.Should().Be(1);
|
||||
failedItem.Status.Should().Be(OrderBatchJobItemStatusCodes.Pending);
|
||||
failedItem.RetryCount.Should().Be(0);
|
||||
failedItem.FailReason.Should().BeNull();
|
||||
job.Status.Should().Be(OrderBatchJobStatusCodes.Running);
|
||||
_publisher.Verify(
|
||||
x => x.PublishAsync(
|
||||
It.Is<OrderBatchJobMessage>(m => m.JobItemId == failedItem.Id),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CancelPendingAsync_ShouldMarkPendingAsCancelled()
|
||||
{
|
||||
var job = CreateJob();
|
||||
var pendingItem = CreateItem(3, OrderBatchJobItemStatusCodes.Pending);
|
||||
var successItem = CreateItem(4, OrderBatchJobItemStatusCodes.Success);
|
||||
|
||||
_batchJobRepository
|
||||
.Setup(x => x.GetByIdAsync(job.Id, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(job);
|
||||
_batchJobRepository
|
||||
.Setup(x => x.GetItemsByJobIdAsync(job.Id, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync([pendingItem, successItem]);
|
||||
_batchJobRepository
|
||||
.Setup(x => x.UpdateItemAsync(pendingItem, It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
_batchJobRepository
|
||||
.Setup(x => x.UpdateJobAsync(job, It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
var output = await _coordinator.CancelPendingAsync(job.Id, 99);
|
||||
|
||||
output.JobId.Should().Be(job.Id);
|
||||
output.CancelledCount.Should().Be(1);
|
||||
pendingItem.Status.Should().Be(OrderBatchJobItemStatusCodes.Cancelled);
|
||||
pendingItem.FailReason.Should().Be("任务已取消");
|
||||
job.Status.Should().Be(OrderBatchJobStatusCodes.Completed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RetryFailedAsync_WhenNoFailedItems_ShouldThrow()
|
||||
{
|
||||
var job = CreateJob();
|
||||
_batchJobRepository
|
||||
.Setup(x => x.GetByIdAsync(job.Id, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(job);
|
||||
_batchJobRepository
|
||||
.Setup(x => x.GetItemsByJobIdAsync(job.Id, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync([CreateItem(5, OrderBatchJobItemStatusCodes.Success)]);
|
||||
|
||||
var act = () => _coordinator.RetryFailedAsync(job.Id, null, 99);
|
||||
|
||||
await act.Should().ThrowAsync<BusinessException>()
|
||||
.WithMessage("没有可重试的失败子项");
|
||||
}
|
||||
|
||||
private static OrderBatchJob CreateJob() =>
|
||||
new()
|
||||
{
|
||||
Id = 501,
|
||||
Action = OrderBatchActionCodes.Pay,
|
||||
Status = OrderBatchJobStatusCodes.Completed,
|
||||
Total = 2,
|
||||
SuccessCount = 1,
|
||||
FailCount = 1,
|
||||
};
|
||||
|
||||
private static OrderBatchJobItem CreateItem(int id, string status, string? failReason = null) =>
|
||||
new()
|
||||
{
|
||||
Id = id,
|
||||
JobId = 501,
|
||||
OrderId = 9000 + id,
|
||||
Action = OrderBatchActionCodes.Pay,
|
||||
Status = status,
|
||||
FailReason = failReason,
|
||||
MessageId = $"501:{id}:pay",
|
||||
};
|
||||
}
|
||||
156
src/Oms.Tests/OrderBatchJobProcessorTests.cs
Normal file
156
src/Oms.Tests/OrderBatchJobProcessorTests.cs
Normal file
@ -0,0 +1,156 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Moq;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Application.Services.Orders.Batch;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
using Oms.Domain.OrdersAggregate.Entities;
|
||||
using Oms.Domain.OrdersAggregate.Repositories;
|
||||
|
||||
namespace Oms.Tests;
|
||||
|
||||
public class OrderBatchJobProcessorTests
|
||||
{
|
||||
private readonly Mock<IOrderBatchJobRepository> _batchJobRepository = new(MockBehavior.Strict);
|
||||
private readonly Mock<IOrderTaskRepository> _orderTaskRepository = new(MockBehavior.Loose);
|
||||
private readonly Mock<IOrderBatchActionExecutor> _actionExecutor = new(MockBehavior.Strict);
|
||||
private readonly OrderBatchJobProcessor _processor;
|
||||
|
||||
public OrderBatchJobProcessorTests()
|
||||
{
|
||||
_processor = new OrderBatchJobProcessor(
|
||||
_batchJobRepository.Object,
|
||||
_orderTaskRepository.Object,
|
||||
_actionExecutor.Object,
|
||||
Options.Create(new OrderBatchRabbitMqOptions { MaxRetryCount = 3 }),
|
||||
NullLogger<OrderBatchJobProcessor>.Instance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProcessAsync_BusinessFailure_ShouldMarkFailedAndAck()
|
||||
{
|
||||
var item = CreateItem(id: 10, status: OrderBatchJobItemStatusCodes.Pending);
|
||||
var message = CreateMessage(item.Id);
|
||||
SetupItemLookup(item);
|
||||
_actionExecutor
|
||||
.Setup(x => x.ExecuteAsync(message, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(OrderBatchActionExecuteResult.BusinessFail("订单不存在"));
|
||||
SetupJobRefresh(item.JobId, [item]);
|
||||
|
||||
var result = await _processor.ProcessAsync(message);
|
||||
|
||||
result.Kind.Should().Be(OrderBatchJobProcessor.ProcessResultKind.Ack);
|
||||
item.Status.Should().Be(OrderBatchJobItemStatusCodes.Failed);
|
||||
item.FailReason.Should().Be("订单不存在");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProcessAsync_SystemFailure_WithRetriesRemaining_ShouldResetPendingAndReject()
|
||||
{
|
||||
var item = CreateItem(id: 11, status: OrderBatchJobItemStatusCodes.Pending, retryCount: 1);
|
||||
var message = CreateMessage(item.Id);
|
||||
SetupItemLookup(item);
|
||||
_actionExecutor
|
||||
.Setup(x => x.ExecuteAsync(message, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(OrderBatchActionExecuteResult.SystemFail("下游超时"));
|
||||
|
||||
var result = await _processor.ProcessAsync(message);
|
||||
|
||||
result.Kind.Should().Be(OrderBatchJobProcessor.ProcessResultKind.Reject);
|
||||
result.Requeue.Should().BeTrue();
|
||||
item.Status.Should().Be(OrderBatchJobItemStatusCodes.Pending);
|
||||
item.RetryCount.Should().Be(2);
|
||||
item.FailReason.Should().BeNull();
|
||||
item.FinishedAt.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProcessAsync_SystemFailure_WhenRetryExhausted_ShouldMarkFailedAndAck()
|
||||
{
|
||||
var item = CreateItem(id: 12, status: OrderBatchJobItemStatusCodes.Pending, retryCount: 2);
|
||||
var message = CreateMessage(item.Id);
|
||||
SetupItemLookup(item);
|
||||
_actionExecutor
|
||||
.Setup(x => x.ExecuteAsync(message, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(OrderBatchActionExecuteResult.SystemFail("下游超时"));
|
||||
SetupJobRefresh(item.JobId, [item]);
|
||||
|
||||
var result = await _processor.ProcessAsync(message);
|
||||
|
||||
result.Kind.Should().Be(OrderBatchJobProcessor.ProcessResultKind.Ack);
|
||||
item.Status.Should().Be(OrderBatchJobItemStatusCodes.Failed);
|
||||
item.RetryCount.Should().Be(3);
|
||||
item.FailReason.Should().Be("下游超时");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProcessAsync_CancelledItem_ShouldAckWithoutExecuting()
|
||||
{
|
||||
var item = CreateItem(id: 13, status: OrderBatchJobItemStatusCodes.Cancelled);
|
||||
var message = CreateMessage(item.Id);
|
||||
_batchJobRepository
|
||||
.Setup(x => x.GetItemByIdAsync(item.Id, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(item);
|
||||
|
||||
var result = await _processor.ProcessAsync(message);
|
||||
|
||||
result.Kind.Should().Be(OrderBatchJobProcessor.ProcessResultKind.Ack);
|
||||
_actionExecutor.Verify(
|
||||
x => x.ExecuteAsync(It.IsAny<OrderBatchJobMessage>(), It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
private void SetupItemLookup(OrderBatchJobItem item)
|
||||
{
|
||||
_batchJobRepository
|
||||
.Setup(x => x.GetItemByIdAsync(item.Id, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(item);
|
||||
_batchJobRepository
|
||||
.Setup(x => x.UpdateItemAsync(item, It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
}
|
||||
|
||||
private void SetupJobRefresh(int jobId, List<OrderBatchJobItem> items)
|
||||
{
|
||||
var job = new OrderBatchJob
|
||||
{
|
||||
Id = jobId,
|
||||
Action = OrderBatchActionCodes.Pay,
|
||||
Status = OrderBatchJobStatusCodes.Running,
|
||||
Total = items.Count,
|
||||
};
|
||||
|
||||
_batchJobRepository
|
||||
.Setup(x => x.GetByIdAsync(jobId, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(job);
|
||||
_batchJobRepository
|
||||
.Setup(x => x.GetItemsByJobIdAsync(jobId, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(items);
|
||||
_batchJobRepository
|
||||
.Setup(x => x.UpdateJobAsync(job, It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
}
|
||||
|
||||
private static OrderBatchJobItem CreateItem(int id, string status, int retryCount = 0) =>
|
||||
new()
|
||||
{
|
||||
Id = id,
|
||||
JobId = 100,
|
||||
OrderId = 2000 + id,
|
||||
Action = OrderBatchActionCodes.Pay,
|
||||
Status = status,
|
||||
RetryCount = retryCount,
|
||||
};
|
||||
|
||||
private static OrderBatchJobMessage CreateMessage(int jobItemId) =>
|
||||
new()
|
||||
{
|
||||
JobId = 100,
|
||||
JobItemId = jobItemId,
|
||||
Action = OrderBatchActionCodes.Pay,
|
||||
OrderId = 2000 + jobItemId,
|
||||
OperatorUserId = 1,
|
||||
MessageId = $"100:{jobItemId}:pay",
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,65 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Moq;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Messaging;
|
||||
using SimpleAdmin.Api.IntegrationTests.Support;
|
||||
|
||||
namespace SimpleAdmin.Api.IntegrationTests;
|
||||
|
||||
public class OrderBatchJobApiIntegrationTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task BatchGovernanceRoutes_ShouldBeRegistered()
|
||||
{
|
||||
await using var host = await SimpleAdminApiTestHost.CreateAsync(configureServices: ConfigureDisabledQueueInspector);
|
||||
|
||||
host.RoutePatterns.Should().Contain("order/batch/dlx/stats");
|
||||
host.RoutePatterns.Should().Contain("order/batch/jobs/{id:int}/retry-failed");
|
||||
host.RoutePatterns.Should().Contain("order/batch/jobs/{id:int}/cancel");
|
||||
host.RoutePatterns.Should().Contain("order/batch/jobs");
|
||||
host.GetHttpMethods("order/batch/dlx/stats").Should().Contain("GET");
|
||||
host.GetHttpMethods("order/batch/jobs/{id:int}/retry-failed").Should().Contain("POST");
|
||||
host.GetHttpMethods("order/batch/jobs/{id:int}/cancel").Should().Contain("POST");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBatchDlxStats_ShouldReturnDisabledPayloadWhenQueueDisabled()
|
||||
{
|
||||
var inspector = new Mock<IOrderBatchQueueInspector>(MockBehavior.Strict);
|
||||
inspector.SetupGet(x => x.IsEnabled).Returns(false);
|
||||
inspector
|
||||
.Setup(x => x.GetStatsAsync(It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new OrderBatchDlxStatsOutput
|
||||
{
|
||||
Enabled = false,
|
||||
DlxAlertThreshold = 100,
|
||||
});
|
||||
|
||||
await using var host = await SimpleAdminApiTestHost.CreateAsync(configureServices: services =>
|
||||
{
|
||||
services.RemoveAll<IOrderBatchQueueInspector>();
|
||||
services.AddSingleton(inspector.Object);
|
||||
});
|
||||
|
||||
var response = await host.Client.GetAsync("/order/batch/dlx/stats");
|
||||
|
||||
response.IsSuccessStatusCode.Should().BeTrue();
|
||||
var payload = await IntegrationTestJson.ReadAsync<OrderBatchDlxStatsOutput>(response);
|
||||
payload.Should().NotBeNull();
|
||||
payload!.Enabled.Should().BeFalse();
|
||||
payload.DlxAlertThreshold.Should().Be(100);
|
||||
}
|
||||
|
||||
private static void ConfigureDisabledQueueInspector(IServiceCollection services)
|
||||
{
|
||||
var inspector = new Mock<IOrderBatchQueueInspector>(MockBehavior.Strict);
|
||||
inspector.SetupGet(x => x.IsEnabled).Returns(false);
|
||||
inspector
|
||||
.Setup(x => x.GetStatsAsync(It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new OrderBatchDlxStatsOutput { Enabled = false });
|
||||
services.RemoveAll<IOrderBatchQueueInspector>();
|
||||
services.AddSingleton(inspector.Object);
|
||||
}
|
||||
}
|
||||
@ -45,7 +45,7 @@
|
||||
"WeChat": {
|
||||
"Mp": {
|
||||
"AppId": "wxd5141ba46c856e1f",
|
||||
"Secret": "",
|
||||
"Secret": "379f51a89419dc36fbb9167feef6f89a",
|
||||
"Token": "c6ca74013df823c0e1da0feaaaf8bf66",
|
||||
"EncodingAesKey": "",
|
||||
"OAuthRedirectBase": "https://oms.nanafa.com"
|
||||
@ -63,5 +63,17 @@
|
||||
"BaseUrl": "http://api.nanafa.com/itfx",
|
||||
"TimeoutSeconds": 30
|
||||
}
|
||||
},
|
||||
"OrderBatch": {
|
||||
"RabbitMq": {
|
||||
"Enabled": false,
|
||||
"HostName": "127.0.0.1",
|
||||
"Port": 5672,
|
||||
"UserName": "oms",
|
||||
"Password": "oms123",
|
||||
"VirtualHost": "/oms",
|
||||
"PrefetchCount": 5,
|
||||
"MaxRetryCount": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user