diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..0df8b59 --- /dev/null +++ b/docker-compose.yml @@ -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: diff --git a/scripts/order_batch_job_tables.sql b/scripts/order_batch_job_tables.sql new file mode 100644 index 0000000..5f31beb --- /dev/null +++ b/scripts/order_batch_job_tables.sql @@ -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`; diff --git a/src/Oms.Application/Dtos/Orders/OrderBatchGovernanceDtos.cs b/src/Oms.Application/Dtos/Orders/OrderBatchGovernanceDtos.cs new file mode 100644 index 0000000..d5243f7 --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/OrderBatchGovernanceDtos.cs @@ -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 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 ItemIds { get; set; } = []; +} diff --git a/src/Oms.Application/Dtos/Orders/OrderBatchJobDtos.cs b/src/Oms.Application/Dtos/Orders/OrderBatchJobDtos.cs new file mode 100644 index 0000000..1036538 --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/OrderBatchJobDtos.cs @@ -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 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; } +} diff --git a/src/Oms.Application/Dtos/Orders/OrderBatchJobListInput.cs b/src/Oms.Application/Dtos/Orders/OrderBatchJobListInput.cs new file mode 100644 index 0000000..582bf6b --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/OrderBatchJobListInput.cs @@ -0,0 +1,17 @@ +namespace Oms.Application.Dtos.Orders; + +/// +/// 批量任务列表查询入参。 +/// +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; } +} diff --git a/src/Oms.Application/Dtos/Orders/OrderBatchPayloadDtos.cs b/src/Oms.Application/Dtos/Orders/OrderBatchPayloadDtos.cs new file mode 100644 index 0000000..c987d52 --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/OrderBatchPayloadDtos.cs @@ -0,0 +1,54 @@ +namespace Oms.Application.Dtos.Orders; + +/// +/// 批量任务子项(无订单 ID,按 PayloadJson 投递)。 +/// +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 Items { get; set; } = []; +} + +/// +/// Excel 导入单行消息体。 +/// +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; +} + +/// +/// 导入 Job 级元数据,写入 OrderBatchJob.PayloadJson。 +/// +public class OrderBatchImportJobPayload +{ + public int TaskId { get; set; } + + public int TemplateId { get; set; } + + public int CustomerId { get; set; } +} diff --git a/src/Oms.Application/Dtos/Orders/OrderParcelBatchCreateOutput.cs b/src/Oms.Application/Dtos/Orders/OrderParcelBatchCreateOutput.cs index 98a74c2..1ea0ca6 100644 --- a/src/Oms.Application/Dtos/Orders/OrderParcelBatchCreateOutput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderParcelBatchCreateOutput.cs @@ -24,4 +24,19 @@ public class OrderParcelBatchCreateOutput /// 逐条处理结果。 /// public List Items { get; set; } = []; + + /// + /// 关联批量 Job(异步模式)。 + /// + public int? JobId { get; set; } + + /// + /// 是否已转为异步 Job 处理。 + /// + public bool Async { get; set; } + + /// + /// 异步任务总数。 + /// + public int Total { get; set; } } diff --git a/src/Oms.Application/Dtos/Orders/OrderUploadOutput.cs b/src/Oms.Application/Dtos/Orders/OrderUploadOutput.cs index 7ba5eee..b736848 100644 --- a/src/Oms.Application/Dtos/Orders/OrderUploadOutput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderUploadOutput.cs @@ -9,4 +9,14 @@ public class OrderUploadOutput /// 任务主键。 /// public int TaskId { get; set; } + + /// + /// 关联批量 Job(异步导入时返回)。 + /// + public int? JobId { get; set; } + + /// + /// 是否异步处理中。 + /// + public bool Async { get; set; } } diff --git a/src/Oms.Application/Integrations/SmallBagTrack/ISmallBagTrackOrderNotifier.cs b/src/Oms.Application/Integrations/SmallBagTrack/ISmallBagTrackOrderNotifier.cs index 102aea1..000217b 100644 --- a/src/Oms.Application/Integrations/SmallBagTrack/ISmallBagTrackOrderNotifier.cs +++ b/src/Oms.Application/Integrations/SmallBagTrack/ISmallBagTrackOrderNotifier.cs @@ -5,5 +5,5 @@ namespace Oms.Application.Integrations.SmallBagTrack; /// public interface ISmallBagTrackOrderNotifier { - void Enqueue(SmallBagTrackUpsertRequest request); + void Enqueue(SmallBagTrackUpsertRequest request, int orderId, int? customerId = null); } diff --git a/src/Oms.Application/Integrations/SmallBagTrack/SmallBagTrackOrderNotifier.cs b/src/Oms.Application/Integrations/SmallBagTrack/SmallBagTrackOrderNotifier.cs index 6c86365..31024d3 100644 --- a/src/Oms.Application/Integrations/SmallBagTrack/SmallBagTrackOrderNotifier.cs +++ b/src/Oms.Application/Integrations/SmallBagTrack/SmallBagTrackOrderNotifier.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Oms.Application.Services.Orders.Batch; namespace Oms.Application.Integrations.SmallBagTrack; @@ -7,20 +8,38 @@ internal sealed class SmallBagTrackOrderNotifier( IServiceScopeFactory scopeFactory, ILogger 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 client = scope.ServiceProvider.GetRequiredService(); - await client.UpsertAsync(request); + var coordinator = scope.ServiceProvider.GetRequiredService(); + await coordinator.PublishTrackUpsertAsync(request, orderId, customerId); } catch (Exception ex) { - logger.LogWarning(ex, "Async UpsertSmallBag failed for order {OrderNo}", request.OrderNo); + 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 + { + using var scope = scopeFactory.CreateScope(); + var client = scope.ServiceProvider.GetRequiredService(); + await client.UpsertAsync(request); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Fallback UpsertSmallBag failed for order {OrderNo}", request.OrderNo); + } + } } diff --git a/src/Oms.Application/Messaging/IOrderBatchJobPublisher.cs b/src/Oms.Application/Messaging/IOrderBatchJobPublisher.cs new file mode 100644 index 0000000..40054e3 --- /dev/null +++ b/src/Oms.Application/Messaging/IOrderBatchJobPublisher.cs @@ -0,0 +1,8 @@ +namespace Oms.Application.Messaging; + +public interface IOrderBatchJobPublisher +{ + Task PublishAsync(OrderBatchJobMessage message, CancellationToken cancellationToken = default); + + bool IsEnabled { get; } +} diff --git a/src/Oms.Application/Messaging/OrderBatchJobMessage.cs b/src/Oms.Application/Messaging/OrderBatchJobMessage.cs new file mode 100644 index 0000000..3a134d2 --- /dev/null +++ b/src/Oms.Application/Messaging/OrderBatchJobMessage.cs @@ -0,0 +1,25 @@ +namespace Oms.Application.Messaging; + +/// +/// 订单批量任务 RabbitMQ 消息体。 +/// +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; } +} diff --git a/src/Oms.Application/Messaging/OrderBatchJobPublisher.cs b/src/Oms.Application/Messaging/OrderBatchJobPublisher.cs new file mode 100644 index 0000000..f6b453f --- /dev/null +++ b/src/Oms.Application/Messaging/OrderBatchJobPublisher.cs @@ -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 _logger; + private readonly object _sync = new(); + private IConnection? _connection; + private bool _disposed; + + public OrderBatchJobPublisher( + IOptions options, + ILogger 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 + { + ["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(); + } +} diff --git a/src/Oms.Application/Messaging/OrderBatchQueueInitializer.cs b/src/Oms.Application/Messaging/OrderBatchQueueInitializer.cs new file mode 100644 index 0000000..06ce284 --- /dev/null +++ b/src/Oms.Application/Messaging/OrderBatchQueueInitializer.cs @@ -0,0 +1,90 @@ +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using RabbitMQ.Client; + +namespace Oms.Application.Messaging; + +/// +/// 应用启动时声明订单批量 Exchange / Queue / Binding。 +/// +public sealed class OrderBatchQueueInitializer : IHostedService +{ + private readonly OrderBatchRabbitMqOptions _options; + private readonly ILogger _logger; + + public OrderBatchQueueInitializer( + IOptions options, + ILogger 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 + { + ["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"); + } +} diff --git a/src/Oms.Application/Messaging/OrderBatchQueueInspector.cs b/src/Oms.Application/Messaging/OrderBatchQueueInspector.cs new file mode 100644 index 0000000..2540f8f --- /dev/null +++ b/src/Oms.Application/Messaging/OrderBatchQueueInspector.cs @@ -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 GetStatsAsync(CancellationToken cancellationToken = default); +} + +public sealed class OrderBatchQueueInspector : IOrderBatchQueueInspector, IDisposable +{ + private readonly OrderBatchRabbitMqOptions _options; + private readonly ILogger _logger; + private readonly object _sync = new(); + private IConnection? _connection; + + public OrderBatchQueueInspector( + IOptions options, + ILogger logger) + { + _options = options.Value; + _logger = logger; + } + + public bool IsEnabled => _options.Enabled; + + public Task 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 + { + 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(); + } +} diff --git a/src/Oms.Application/Messaging/OrderBatchQueueTopology.cs b/src/Oms.Application/Messaging/OrderBatchQueueTopology.cs new file mode 100644 index 0000000..1a278a1 --- /dev/null +++ b/src/Oms.Application/Messaging/OrderBatchQueueTopology.cs @@ -0,0 +1,92 @@ +namespace Oms.Application.Messaging; + +/// +/// RabbitMQ 交换机、队列与路由键定义。 +/// +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.*"), + ]; +} diff --git a/src/Oms.Application/Messaging/OrderBatchRabbitMqOptions.cs b/src/Oms.Application/Messaging/OrderBatchRabbitMqOptions.cs new file mode 100644 index 0000000..9e47486 --- /dev/null +++ b/src/Oms.Application/Messaging/OrderBatchRabbitMqOptions.cs @@ -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; + + /// + /// DLX 队列堆积告警阈值。 + /// + public uint DlxAlertThreshold { get; set; } = 100; + + /// + /// 队列监控轮询间隔(秒)。 + /// + public int MonitorIntervalSeconds { get; set; } = 300; +} diff --git a/src/Oms.Application/Oms.Application.csproj b/src/Oms.Application/Oms.Application.csproj index 70ea1f1..cb3937c 100644 --- a/src/Oms.Application/Oms.Application.csproj +++ b/src/Oms.Application/Oms.Application.csproj @@ -22,6 +22,7 @@ + diff --git a/src/Oms.Application/OmsApplicationModule.cs b/src/Oms.Application/OmsApplicationModule.cs index 972c800..6fdaa17 100644 --- a/src/Oms.Application/OmsApplicationModule.cs +++ b/src/Oms.Application/OmsApplicationModule.cs @@ -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(); diff --git a/src/Oms.Application/OrderBatchMessagingServiceExtensions.cs b/src/Oms.Application/OrderBatchMessagingServiceExtensions.cs new file mode 100644 index 0000000..210aed9 --- /dev/null +++ b/src/Oms.Application/OrderBatchMessagingServiceExtensions.cs @@ -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(configuration.GetSection(OrderBatchRabbitMqOptions.SectionName)); + services.AddSingleton(); + services.AddSingleton(); + services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); + return services; + } +} diff --git a/src/Oms.Application/Services/Orders/Batch/IOrderBatchActionExecutor.cs b/src/Oms.Application/Services/Orders/Batch/IOrderBatchActionExecutor.cs new file mode 100644 index 0000000..b0009ba --- /dev/null +++ b/src/Oms.Application/Services/Orders/Batch/IOrderBatchActionExecutor.cs @@ -0,0 +1,55 @@ +using Oms.Application.Messaging; + +namespace Oms.Application.Services.Orders.Batch; + +public interface IOrderBatchActionExecutor +{ + Task 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 }; +} diff --git a/src/Oms.Application/Services/Orders/Batch/OrderBatchActionExecutor.cs b/src/Oms.Application/Services/Orders/Batch/OrderBatchActionExecutor.cs new file mode 100644 index 0000000..6ab74ae --- /dev/null +++ b/src/Oms.Application/Services/Orders/Batch/OrderBatchActionExecutor.cs @@ -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 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 ExecuteTrackUpsertAsync( + OrderBatchJobMessage message, + CancellationToken cancellationToken) + { + SmallBagTrackUpsertRequest request; + if (!string.IsNullOrWhiteSpace(message.PayloadJson)) + { + request = JsonConvert.DeserializeObject(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 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 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, + } + }; + } +} diff --git a/src/Oms.Application/Services/Orders/Batch/OrderBatchCreateActionHandler.cs b/src/Oms.Application/Services/Orders/Batch/OrderBatchCreateActionHandler.cs new file mode 100644 index 0000000..b94244b --- /dev/null +++ b/src/Oms.Application/Services/Orders/Batch/OrderBatchCreateActionHandler.cs @@ -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; + +/// +/// 创建类批量操作(Excel 导入行、小包批量创建)执行器。 +/// +public sealed class OrderBatchCreateActionHandler(IServiceScopeFactory scopeFactory) : IScopedDependency +{ + public async Task ExecuteImportRowAsync( + OrderBatchJobMessage message, + CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(message.PayloadJson)) + { + return OrderBatchActionExecuteResult.BusinessFail("导入行消息体为空"); + } + + var payload = JsonConvert.DeserializeObject(message.PayloadJson); + if (payload == null) + { + return OrderBatchActionExecuteResult.BusinessFail("导入行消息体无效"); + } + + try + { + using var scope = scopeFactory.CreateScope(); + var orderService = scope.ServiceProvider.GetRequiredService(); + 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 ExecuteParcelCreateAsync( + OrderBatchJobMessage message, + CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(message.PayloadJson)) + { + return OrderBatchActionExecuteResult.BusinessFail("小包创建消息体为空"); + } + + var input = JsonConvert.DeserializeObject(message.PayloadJson); + if (input == null) + { + return OrderBatchActionExecuteResult.BusinessFail("小包创建消息体无效"); + } + + try + { + using var scope = scopeFactory.CreateScope(); + var orderService = scope.ServiceProvider.GetRequiredService(); + 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); + } + } +} diff --git a/src/Oms.Application/Services/Orders/Batch/OrderBatchJobCoordinator.cs b/src/Oms.Application/Services/Orders/Batch/OrderBatchJobCoordinator.cs new file mode 100644 index 0000000..260e458 --- /dev/null +++ b/src/Oms.Application/Services/Orders/Batch/OrderBatchJobCoordinator.cs @@ -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; + +/// +/// 创建批量任务、写入子项并发布 RabbitMQ 消息。 +/// +public sealed class OrderBatchJobCoordinator( + IOrderBatchJobRepository batchJobRepository, + IOrderRepository orderRepository, + IOrderBatchJobPublisher publisher, + ILogger logger) : IScopedDependency +{ + private const int DefaultMaxBatchSize = 200; + private const int CreateMaxBatchSize = 2000; + + public async Task 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(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); + } + + /// + /// 创建按 Payload 投递的批量任务(导入行、小包批量创建等)。 + /// + public async Task 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(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 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> 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 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 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 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> 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> 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 { [nameof(OrderBatchJob.CreateTime)] = false, [nameof(OrderBatchJob.Id)] = false }, + cancellationToken); + var total = await batchJobRepository.CountAsync(predicate, cancellationToken); + + return new OmsPageResult + { + 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, + }; + } +} diff --git a/src/Oms.Application/Services/Orders/Batch/OrderBatchJobProcessor.cs b/src/Oms.Application/Services/Orders/Batch/OrderBatchJobProcessor.cs new file mode 100644 index 0000000..b9c9e7e --- /dev/null +++ b/src/Oms.Application/Services/Orders/Batch/OrderBatchJobProcessor.cs @@ -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; + +/// +/// 消费 RabbitMQ 消息后更新任务状态并执行业务。 +/// +public sealed class OrderBatchJobProcessor( + IOrderBatchJobRepository batchJobRepository, + IOrderTaskRepository orderTaskRepository, + IOrderBatchActionExecutor actionExecutor, + IOptions rabbitMqOptions, + ILogger logger) : IScopedDependency +{ + public async Task 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 body) + { + var json = Encoding.UTF8.GetString(body.Span); + return JsonConvert.DeserializeObject(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(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(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 }; + } +} diff --git a/src/Oms.Application/Services/Orders/Batch/OrderBatchOrderActionHandler.cs b/src/Oms.Application/Services/Orders/Batch/OrderBatchOrderActionHandler.cs new file mode 100644 index 0000000..008b906 --- /dev/null +++ b/src/Oms.Application/Services/Orders/Batch/OrderBatchOrderActionHandler.cs @@ -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; + +/// +/// 订单状态/支付/异常/单据类批量操作执行器。 +/// +public sealed class OrderBatchOrderActionHandler(IServiceScopeFactory scopeFactory) : IScopedDependency +{ + public async Task ExecuteAsync( + OrderBatchJobMessage message, + CancellationToken cancellationToken = default) + { + try + { + using var scope = scopeFactory.CreateScope(); + var orderService = scope.ServiceProvider.GetRequiredService(); + + 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); + } + } +} diff --git a/src/Oms.Application/Services/Orders/OrderService.BatchCreate.cs b/src/Oms.Application/Services/Orders/OrderService.BatchCreate.cs new file mode 100644 index 0000000..da283be --- /dev/null +++ b/src/Oms.Application/Services/Orders/OrderService.BatchCreate.cs @@ -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(); + + /// + /// 批量 Worker 导入单行 Excel 数据。 + /// + public async Task ImportRowForBatchAsync( + OrderBatchImportRowPayload payload, + CancellationToken cancellationToken = default) + { + var rowDict = JsonConvert.DeserializeObject>(payload.RowDataJson) + ?? throw new BusinessException("行数据无效"); + await CreateImportOrderAsync(rowDict, payload.CustomerId); + } + + /// + /// 批量 Worker 创建小包订单。 + /// + public async Task CreateParcelForBatchAsync( + OrderParcelCreateInput input, + int operatorUserId, + CancellationToken cancellationToken = default) + { + return await CreateParcelCoreAsync(input, operatorUserId); + } +} diff --git a/src/Oms.Application/Services/Orders/OrderService.BatchJob.cs b/src/Oms.Application/Services/Orders/OrderService.BatchJob.cs new file mode 100644 index 0000000..e2124ad --- /dev/null +++ b/src/Oms.Application/Services/Orders/OrderService.BatchJob.cs @@ -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(); + + /// + /// 创建订单批量异步任务并入队 RabbitMQ。 + /// + [HttpPost("/order/batch/jobs")] + public Task CreateBatchJobAsync([FromBody] OrderBatchJobCreateInput input) + { + return BatchJobCoordinator.CreateAndEnqueueAsync(input, CurrentUser.GetId()); + } + + /// + /// 查询批量任务进度。 + /// + [HttpGet("/order/batch/jobs/{id:int}")] + public async Task GetBatchJobAsync([FromRoute] int id) + { + var job = await BatchJobCoordinator.GetJobAsync(id); + if (job == null) + { + throw new BusinessException("批量任务不存在"); + } + + return job; + } + + /// + /// 分页查询批量任务列表。 + /// + [HttpGet("/order/batch/jobs")] + public async Task> GetBatchJobListAsync([FromQuery] OrderBatchJobListInput input) + { + var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( + LazyServiceProvider.GetRequiredService(), + CurrentUser, + null); + return await BatchJobCoordinator.GetJobListAsync(input, customerId); + } + + /// + /// 查询批量任务子项明细。 + /// + [HttpGet("/order/batch/jobs/{id:int}/items")] + public async Task> GetBatchJobItemsAsync([FromRoute] int id) + { + var job = await BatchJobCoordinator.GetJobAsync(id); + if (job == null) + { + throw new BusinessException("批量任务不存在"); + } + + return await BatchJobCoordinator.GetJobItemsAsync(id); + } + + /// + /// 异步批量创建轨迹订单(替代前端逐条调用)。 + /// + [HttpPost("/order/batch/track-upsert")] + public Task BatchTrackUpsertAsync([FromBody] OrderBatchJobCreateInput input) + { + input.Action = OrderBatchActionCodes.TrackUpsertSmallBag; + return BatchJobCoordinator.CreateAndEnqueueAsync(input, CurrentUser.GetId()); + } + + /// + /// 异步批量预报下游订单。 + /// + [HttpPost("/order/batch/downstream-forward")] + public Task BatchDownstreamForwardAsync([FromBody] OrderBatchJobCreateInput input) + { + input.Action = OrderBatchActionCodes.DownstreamForwardCreateOne; + return BatchJobCoordinator.CreateAndEnqueueAsync(input, CurrentUser.GetId()); + } + + private Task EnqueueOrderBatchAsync(string action, OrderBatchJobCreateInput input) + { + input.Action = action; + return BatchJobCoordinator.CreateAndEnqueueAsync(input, CurrentUser.GetId()); + } + + [HttpPost("/order/batch/pay")] + public Task BatchPayAsync([FromBody] OrderBatchJobCreateInput input) => + EnqueueOrderBatchAsync(OrderBatchActionCodes.Pay, input); + + [HttpPost("/order/batch/pre-declare")] + public Task BatchPreDeclareAsync([FromBody] OrderBatchJobCreateInput input) => + EnqueueOrderBatchAsync(OrderBatchActionCodes.PreDeclare, input); + + [HttpPost("/order/batch/intercept")] + public Task BatchInterceptAsync([FromBody] OrderBatchJobCreateInput input) => + EnqueueOrderBatchAsync(OrderBatchActionCodes.Intercept, input); + + [HttpPost("/order/batch/cancel-intercept")] + public Task BatchCancelInterceptAsync([FromBody] OrderBatchJobCreateInput input) => + EnqueueOrderBatchAsync(OrderBatchActionCodes.CancelIntercept, input); + + [HttpPost("/order/batch/delete")] + public Task BatchDeleteAsync([FromBody] OrderBatchJobCreateInput input) => + EnqueueOrderBatchAsync(OrderBatchActionCodes.Delete, input); + + [HttpPost("/order/batch/print")] + public Task BatchPrintAsync([FromBody] OrderBatchJobCreateInput input) => + EnqueueOrderBatchAsync(OrderBatchActionCodes.Print, input); + + [HttpPost("/order/batch/mark-problematic")] + public Task BatchMarkProblematicAsync([FromBody] OrderBatchJobCreateInput input) => + EnqueueOrderBatchAsync(OrderBatchActionCodes.MarkProblematic, input); + + [HttpPost("/order/batch/mark-claimed")] + public Task BatchMarkClaimedAsync([FromBody] OrderBatchJobCreateInput input) => + EnqueueOrderBatchAsync(OrderBatchActionCodes.MarkClaimed, input); + + [HttpPost("/order/batch/handle-status-update")] + public Task BatchHandleStatusUpdateAsync([FromBody] OrderBatchJobCreateInput input) => + EnqueueOrderBatchAsync(OrderBatchActionCodes.HandleStatusUpdate, input); + + /// + /// 查询 RabbitMQ 队列与 DLX 堆积情况。 + /// + [HttpGet("/order/batch/dlx/stats")] + public Task GetBatchDlxStatsAsync() + { + var inspector = LazyServiceProvider.GetRequiredService(); + return inspector.GetStatsAsync(); + } + + /// + /// 重新投递失败子项。 + /// + [HttpPost("/order/batch/jobs/{id:int}/retry-failed")] + public Task RetryFailedBatchJobAsync( + [FromRoute] int id, + [FromBody] OrderBatchJobRetryFailedInput? input) + { + return BatchJobCoordinator.RetryFailedAsync(id, input, CurrentUser.GetId()); + } + + /// + /// 取消尚未执行的 pending 子项。 + /// + [HttpPost("/order/batch/jobs/{id:int}/cancel")] + public Task CancelBatchJobAsync([FromRoute] int id) + { + return BatchJobCoordinator.CancelPendingAsync(id, CurrentUser.GetId()); + } +} diff --git a/src/Oms.Application/Services/Orders/OrderService.BatchWorker.cs b/src/Oms.Application/Services/Orders/OrderService.BatchWorker.cs new file mode 100644 index 0000000..b8942c1 --- /dev/null +++ b/src/Oms.Application/Services/Orders/OrderService.BatchWorker.cs @@ -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 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(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(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(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(string? payloadJson) + where T : class + { + if (string.IsNullOrWhiteSpace(payloadJson)) + { + return null; + } + + return JsonConvert.DeserializeObject(payloadJson); + } +} diff --git a/src/Oms.Application/Services/Orders/OrderService.Helpers.cs b/src/Oms.Application/Services/Orders/OrderService.Helpers.cs index 686ee49..99e2337 100644 --- a/src/Oms.Application/Services/Orders/OrderService.Helpers.cs +++ b/src/Oms.Application/Services/Orders/OrderService.Helpers.cs @@ -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 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 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 rowDict) + { + parsedRows.Add((rowNumber, new Dictionary())); + 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()); + + return new OrderUploadOutput + { + TaskId = task.Id, + JobId = job.JobId, + Async = true, + }; + } + + private async Task 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(); - 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 }; diff --git a/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs b/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs index db4a712..bd4ab61 100644 --- a/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs +++ b/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs @@ -37,7 +37,9 @@ public partial class OrderService private AutoTriggerRuntimeService AutoTriggerRuntimeService => LazyServiceProvider.GetRequiredService(); - private async Task CreateParcelCoreAsync(OrderParcelCreateInput input) + private async Task 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()); + var triggerUserId = operatorUserId ?? CurrentUser.GetId(); + 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); } /// diff --git a/src/Oms.Application/Services/Orders/OrderService.cs b/src/Oms.Application/Services/Orders/OrderService.cs index a0a6191..b586715 100644 --- a/src/Oms.Application/Services/Orders/OrderService.cs +++ b/src/Oms.Application/Services/Orders/OrderService.cs @@ -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 BatchCreateParcelViaQueueAsync(OrderParcelBatchCreateInput input) + { + var batchNo = $"PCB{DateTime.Now:yyyyMMddHHmmssfff}"; + var operatorUserId = CurrentUser.GetId(); + 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 BatchCreateParcelSyncAsync(OrderParcelBatchCreateInput input) + { var batchNo = $"PCB{DateTime.Now:yyyyMMddHHmmssfff}"; var items = new List(input.Count); var successCount = 0; diff --git a/src/Oms.Application/Workers/OrderBatch/OrderBatchCreateConsumer.cs b/src/Oms.Application/Workers/OrderBatch/OrderBatchCreateConsumer.cs new file mode 100644 index 0000000..88a4d78 --- /dev/null +++ b/src/Oms.Application/Workers/OrderBatch/OrderBatchCreateConsumer.cs @@ -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; + +/// +/// 消费创建类队列(Excel 导入行、小包批量创建)。 +/// +public sealed class OrderBatchCreateConsumer : BackgroundService +{ + private readonly OrderBatchRabbitMqOptions _options; + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger _logger; + private IConnection? _connection; + private IModel? _channel; + + public OrderBatchCreateConsumer( + IOptions options, + IServiceScopeFactory scopeFactory, + ILogger 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(); + 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(); + } +} diff --git a/src/Oms.Application/Workers/OrderBatch/OrderBatchDlxMonitorHostedService.cs b/src/Oms.Application/Workers/OrderBatch/OrderBatchDlxMonitorHostedService.cs new file mode 100644 index 0000000..657cbd7 --- /dev/null +++ b/src/Oms.Application/Workers/OrderBatch/OrderBatchDlxMonitorHostedService.cs @@ -0,0 +1,78 @@ +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace Oms.Application.Messaging; + +/// +/// 周期性检查 DLX 堆积并写告警日志。 +/// +public sealed class OrderBatchDlxMonitorHostedService : BackgroundService +{ + private readonly IOrderBatchQueueInspector _inspector; + private readonly OrderBatchRabbitMqOptions _options; + private readonly ILogger _logger; + + public OrderBatchDlxMonitorHostedService( + IOrderBatchQueueInspector inspector, + IOptions options, + ILogger 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); + } +} diff --git a/src/Oms.Application/Workers/OrderBatch/OrderBatchIntegrationConsumer.cs b/src/Oms.Application/Workers/OrderBatch/OrderBatchIntegrationConsumer.cs new file mode 100644 index 0000000..2cf5803 --- /dev/null +++ b/src/Oms.Application/Workers/OrderBatch/OrderBatchIntegrationConsumer.cs @@ -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; + +/// +/// 消费外部集成队列(轨迹同步、下游预报)。 +/// +public sealed class OrderBatchIntegrationConsumer : BackgroundService +{ + private readonly OrderBatchRabbitMqOptions _options; + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger _logger; + private IConnection? _connection; + private IModel? _channel; + + public OrderBatchIntegrationConsumer( + IOptions options, + IServiceScopeFactory scopeFactory, + ILogger 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(); + 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(); + } +} diff --git a/src/Oms.Application/Workers/OrderBatch/OrderBatchQueueConsumerBase.cs b/src/Oms.Application/Workers/OrderBatch/OrderBatchQueueConsumerBase.cs new file mode 100644 index 0000000..afa52c0 --- /dev/null +++ b/src/Oms.Application/Workers/OrderBatch/OrderBatchQueueConsumerBase.cs @@ -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 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(); + 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 options, + IServiceScopeFactory scopeFactory, + ILogger 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 options, + IServiceScopeFactory scopeFactory, + ILogger 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 options, + IServiceScopeFactory scopeFactory, + ILogger 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 options, + IServiceScopeFactory scopeFactory, + ILogger logger) + : OrderBatchQueueConsumerBase(options, scopeFactory, logger) +{ + protected override string QueueName => OrderBatchQueueTopology.QueueDocument; + + protected override string ConnectionName => "oms-order-batch-document-consumer"; +} diff --git a/src/Oms.Domain/OrdersAggregate/Consts/OrderBatchJobStatusCodes.cs b/src/Oms.Domain/OrdersAggregate/Consts/OrderBatchJobStatusCodes.cs new file mode 100644 index 0000000..a403872 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Consts/OrderBatchJobStatusCodes.cs @@ -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"; +} diff --git a/src/Oms.Domain/OrdersAggregate/Entities/OrderBatchJob.cs b/src/Oms.Domain/OrdersAggregate/Entities/OrderBatchJob.cs new file mode 100644 index 0000000..cd10808 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Entities/OrderBatchJob.cs @@ -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; } +} diff --git a/src/Oms.Domain/OrdersAggregate/Entities/OrderBatchJobItem.cs b/src/Oms.Domain/OrdersAggregate/Entities/OrderBatchJobItem.cs new file mode 100644 index 0000000..ddfff27 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Entities/OrderBatchJobItem.cs @@ -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; } +} diff --git a/src/Oms.Domain/OrdersAggregate/Repositories/IOrderBatchJobRepository.cs b/src/Oms.Domain/OrdersAggregate/Repositories/IOrderBatchJobRepository.cs new file mode 100644 index 0000000..cbb8aac --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Repositories/IOrderBatchJobRepository.cs @@ -0,0 +1,21 @@ +using Fake.Domain.Repositories; +using Oms.Domain.OrdersAggregate.Entities; + +namespace Oms.Domain.OrdersAggregate.Repositories; + +public interface IOrderBatchJobRepository : IRepository +{ + Task GetByIdAsync(int id, CancellationToken cancellationToken = default); + + Task GetByRequestIdAsync(string requestId, CancellationToken cancellationToken = default); + + Task> GetItemsByJobIdAsync(int jobId, CancellationToken cancellationToken = default); + + Task GetItemByIdAsync(int itemId, CancellationToken cancellationToken = default); + + Task InsertItemsAsync(IEnumerable items, CancellationToken cancellationToken = default); + + Task UpdateItemAsync(OrderBatchJobItem item, CancellationToken cancellationToken = default); + + Task UpdateJobAsync(OrderBatchJob job, CancellationToken cancellationToken = default); +} diff --git a/src/Oms.SqlSugarCore/Orders/OrderBatchJobRepository.cs b/src/Oms.SqlSugarCore/Orders/OrderBatchJobRepository.cs new file mode 100644 index 0000000..fee46fb --- /dev/null +++ b/src/Oms.SqlSugarCore/Orders/OrderBatchJobRepository.cs @@ -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, IOrderBatchJobRepository, IScopedDependency +{ + public Task GetByIdAsync(int id, CancellationToken cancellationToken = default) + { + return FirstOrDefaultAsync(x => x.Id == id, cancellationToken); + } + + public Task GetByRequestIdAsync(string requestId, CancellationToken cancellationToken = default) + { + return FirstOrDefaultAsync(x => x.RequestId == requestId, cancellationToken); + } + + public async Task> GetItemsByJobIdAsync(int jobId, CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + return await db.Queryable() + .Where(x => x.JobId == jobId) + .OrderBy(x => x.Id) + .ToListAsync(cancellationToken); + } + + public async Task GetItemByIdAsync(int itemId, CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + return await db.Queryable() + .FirstAsync(it => it.Id == itemId, cancellationToken); + } + + public async Task InsertItemsAsync(IEnumerable 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); + } +} diff --git a/src/Oms.Tests/OrderBatchJobCoordinatorGovernanceTests.cs b/src/Oms.Tests/OrderBatchJobCoordinatorGovernanceTests.cs new file mode 100644 index 0000000..db4d4d3 --- /dev/null +++ b/src/Oms.Tests/OrderBatchJobCoordinatorGovernanceTests.cs @@ -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 _batchJobRepository = new(MockBehavior.Strict); + private readonly Mock _orderRepository = new(MockBehavior.Loose); + private readonly Mock _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.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())) + .ReturnsAsync(job); + _batchJobRepository + .Setup(x => x.GetItemsByJobIdAsync(job.Id, It.IsAny())) + .ReturnsAsync([failedItem, successItem]); + _batchJobRepository + .Setup(x => x.UpdateItemAsync(failedItem, It.IsAny())) + .Returns(Task.CompletedTask); + _batchJobRepository + .Setup(x => x.UpdateJobAsync(job, It.IsAny())) + .Returns(Task.CompletedTask); + _publisher + .Setup(x => x.PublishAsync(It.IsAny(), It.IsAny())) + .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(m => m.JobItemId == failedItem.Id), + It.IsAny()), + 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())) + .ReturnsAsync(job); + _batchJobRepository + .Setup(x => x.GetItemsByJobIdAsync(job.Id, It.IsAny())) + .ReturnsAsync([pendingItem, successItem]); + _batchJobRepository + .Setup(x => x.UpdateItemAsync(pendingItem, It.IsAny())) + .Returns(Task.CompletedTask); + _batchJobRepository + .Setup(x => x.UpdateJobAsync(job, It.IsAny())) + .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())) + .ReturnsAsync(job); + _batchJobRepository + .Setup(x => x.GetItemsByJobIdAsync(job.Id, It.IsAny())) + .ReturnsAsync([CreateItem(5, OrderBatchJobItemStatusCodes.Success)]); + + var act = () => _coordinator.RetryFailedAsync(job.Id, null, 99); + + await act.Should().ThrowAsync() + .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", + }; +} diff --git a/src/Oms.Tests/OrderBatchJobProcessorTests.cs b/src/Oms.Tests/OrderBatchJobProcessorTests.cs new file mode 100644 index 0000000..5ef6f05 --- /dev/null +++ b/src/Oms.Tests/OrderBatchJobProcessorTests.cs @@ -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 _batchJobRepository = new(MockBehavior.Strict); + private readonly Mock _orderTaskRepository = new(MockBehavior.Loose); + private readonly Mock _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.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())) + .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())) + .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())) + .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())) + .ReturnsAsync(item); + + var result = await _processor.ProcessAsync(message); + + result.Kind.Should().Be(OrderBatchJobProcessor.ProcessResultKind.Ack); + _actionExecutor.Verify( + x => x.ExecuteAsync(It.IsAny(), It.IsAny()), + Times.Never); + } + + private void SetupItemLookup(OrderBatchJobItem item) + { + _batchJobRepository + .Setup(x => x.GetItemByIdAsync(item.Id, It.IsAny())) + .ReturnsAsync(item); + _batchJobRepository + .Setup(x => x.UpdateItemAsync(item, It.IsAny())) + .Returns(Task.CompletedTask); + } + + private void SetupJobRefresh(int jobId, List items) + { + var job = new OrderBatchJob + { + Id = jobId, + Action = OrderBatchActionCodes.Pay, + Status = OrderBatchJobStatusCodes.Running, + Total = items.Count, + }; + + _batchJobRepository + .Setup(x => x.GetByIdAsync(jobId, It.IsAny())) + .ReturnsAsync(job); + _batchJobRepository + .Setup(x => x.GetItemsByJobIdAsync(jobId, It.IsAny())) + .ReturnsAsync(items); + _batchJobRepository + .Setup(x => x.UpdateJobAsync(job, It.IsAny())) + .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", + }; +} diff --git a/src/SimpleAdmin.Api.IntegrationTests/OrderBatchJobApiIntegrationTests.cs b/src/SimpleAdmin.Api.IntegrationTests/OrderBatchJobApiIntegrationTests.cs new file mode 100644 index 0000000..4b72488 --- /dev/null +++ b/src/SimpleAdmin.Api.IntegrationTests/OrderBatchJobApiIntegrationTests.cs @@ -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(MockBehavior.Strict); + inspector.SetupGet(x => x.IsEnabled).Returns(false); + inspector + .Setup(x => x.GetStatsAsync(It.IsAny())) + .ReturnsAsync(new OrderBatchDlxStatsOutput + { + Enabled = false, + DlxAlertThreshold = 100, + }); + + await using var host = await SimpleAdminApiTestHost.CreateAsync(configureServices: services => + { + services.RemoveAll(); + services.AddSingleton(inspector.Object); + }); + + var response = await host.Client.GetAsync("/order/batch/dlx/stats"); + + response.IsSuccessStatusCode.Should().BeTrue(); + var payload = await IntegrationTestJson.ReadAsync(response); + payload.Should().NotBeNull(); + payload!.Enabled.Should().BeFalse(); + payload.DlxAlertThreshold.Should().Be(100); + } + + private static void ConfigureDisabledQueueInspector(IServiceCollection services) + { + var inspector = new Mock(MockBehavior.Strict); + inspector.SetupGet(x => x.IsEnabled).Returns(false); + inspector + .Setup(x => x.GetStatsAsync(It.IsAny())) + .ReturnsAsync(new OrderBatchDlxStatsOutput { Enabled = false }); + services.RemoveAll(); + services.AddSingleton(inspector.Object); + } +} diff --git a/src/SimpleAdmin.Api/appsettings.Development.json b/src/SimpleAdmin.Api/appsettings.Development.json index 50eb436..5feb6d2 100644 --- a/src/SimpleAdmin.Api/appsettings.Development.json +++ b/src/SimpleAdmin.Api/appsettings.Development.json @@ -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 + } } } \ No newline at end of file