feat: 下游 getFile 转存 COS,并修复集成事件 Outbox 事务
All checks were successful
Build and Deploy / deploy (push) Successful in 1m1s

新增获取下游文件接口;事件发布统一走事务性 UoW,避免批量预报等按钮报 Outbox 错误。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zzh 2026-10-10 18:43:32 +08:00
parent 6d085d999a
commit 6c3a094126
12 changed files with 505 additions and 9 deletions

View File

@ -0,0 +1,27 @@
namespace Oms.Application.Dtos.Orders;
/// <summary>
/// itfx getFile(ForwardWithSubscribe)标准请求体。
/// </summary>
public class ItfxGetFileBody
{
/// <summary>
/// 客户单号。
/// </summary>
public string? ClientNo { get; set; }
/// <summary>
/// 跟踪号。
/// </summary>
public string? TrackNo { get; set; }
/// <summary>
/// 服务商单号。
/// </summary>
public string? ServiceNo { get; set; }
/// <summary>
/// 文件类型:下游面单=21,末端面单=31,POD=180。
/// </summary>
public int Type { get; set; }
}

View File

@ -1,5 +1,3 @@
using Oms.Application.Dtos.Orders;
namespace Oms.Application.Dtos.Orders; namespace Oms.Application.Dtos.Orders;
/// <summary> /// <summary>
@ -43,3 +41,56 @@ public class OrderDownstreamForwardResult
/// </summary> /// </summary>
public string? TrackNo { get; set; } public string? TrackNo { get; set; }
} }
/// <summary>
/// 下游 getFile 入参。
/// </summary>
public class OrderDownstreamGetFileInput
{
/// <summary>
/// 订单 Id。
/// </summary>
public int Id { get; set; }
/// <summary>
/// 文件类型:下游面单=21,末端面单=31,POD=180。
/// </summary>
public int Type { get; set; }
}
/// <summary>
/// 下游 getFile 转发结果。
/// </summary>
public class OrderDownstreamGetFileResult
{
public bool Success { get; set; }
public string SupplierCode { get; set; } = string.Empty;
public int Type { get; set; }
public string? FileType { get; set; }
public string Url { get; set; } = string.Empty;
public string RequestJson { get; set; } = string.Empty;
public int? StatusCode { get; set; }
public string ResponseBody { get; set; } = string.Empty;
/// <summary>
/// 转存到自有 COS 后的公开地址。
/// </summary>
public string? StoredFileUrl { get; set; }
/// <summary>
/// 回写后的服务商单号(Data.serviceNo)。
/// </summary>
public string? DownstreamServiceNo { get; set; }
/// <summary>
/// 回写后的跟踪号(Data.trackNo)。
/// </summary>
public string? TrackNo { get; set; }
}

View File

@ -0,0 +1,171 @@
using System.Text.Json;
using Oms.Domain.OrdersAggregate.Consts;
using Oms.Domain.OrdersAggregate.Entities;
namespace Oms.Application.Integrations.Itfx;
/// <summary>
/// 解析 itfx getFile 成功响应中的 Data,并回写订单单号。
/// </summary>
internal static class ItfxGetFileDataParser
{
public const string StandardCode = "getFile";
public const int TypeDownstreamLabel = 21;
public const int TypeLastMileLabel = 31;
public const int TypePod = 180;
public sealed class GetFileData
{
public string? ServiceNo { get; init; }
public string? TrackNo { get; init; }
public string? ClientNo { get; init; }
public string? Url { get; init; }
public int? Type { get; init; }
}
public static bool TryResolveFileType(int type, out string fileType)
{
fileType = type switch
{
TypeDownstreamLabel => OrderFileTypeCodes.DownstreamLabel,
TypeLastMileLabel => OrderFileTypeCodes.LastMileLabel,
TypePod => OrderFileTypeCodes.Pod,
_ => string.Empty
};
return !string.IsNullOrEmpty(fileType);
}
public static bool TryParse(string? responseBody, out GetFileData? data)
{
data = null;
if (string.IsNullOrWhiteSpace(responseBody))
{
return false;
}
try
{
using var doc = JsonDocument.Parse(responseBody);
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object)
{
return false;
}
if (!TryGetPropertyIgnoreCase(root, out var dataElement, "data", "Data")
|| dataElement.ValueKind != JsonValueKind.Object)
{
return false;
}
data = new GetFileData
{
ServiceNo = ReadString(dataElement, "serviceNo", "ServiceNo"),
TrackNo = ReadString(dataElement, "trackNo", "TrackNo"),
ClientNo = ReadString(dataElement, "clientNo", "ClientNo"),
Url = ReadString(dataElement, "url", "Url"),
Type = ReadInt(dataElement, "type", "Type"),
};
return !string.IsNullOrWhiteSpace(data.ServiceNo)
|| !string.IsNullOrWhiteSpace(data.TrackNo)
|| !string.IsNullOrWhiteSpace(data.ClientNo)
|| !string.IsNullOrWhiteSpace(data.Url);
}
catch
{
return false;
}
}
/// <summary>
/// 服务商单号 ← Data.serviceNo,跟踪号 ← Data.trackNo;空值不覆盖。
/// </summary>
public static bool ApplyToOrder(Order order, GetFileData data)
{
var changed = false;
if (!string.IsNullOrWhiteSpace(data.ServiceNo))
{
var value = data.ServiceNo.Trim();
if (!string.Equals(order.DownstreamServiceNo, value, StringComparison.Ordinal))
{
order.DownstreamServiceNo = value;
changed = true;
}
}
if (!string.IsNullOrWhiteSpace(data.TrackNo))
{
var value = data.TrackNo.Trim();
if (!string.Equals(order.TrackNo, value, StringComparison.Ordinal))
{
order.TrackNo = value;
changed = true;
}
}
return changed;
}
private static bool TryGetPropertyIgnoreCase(JsonElement root, out JsonElement value, params string[] names)
{
foreach (var name in names)
{
if (root.TryGetProperty(name, out value))
{
return true;
}
}
foreach (var prop in root.EnumerateObject())
{
foreach (var name in names)
{
if (prop.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
value = prop.Value;
return true;
}
}
}
value = default;
return false;
}
private static string? ReadString(JsonElement root, params string[] names)
{
if (!TryGetPropertyIgnoreCase(root, out var prop, names))
{
return null;
}
return prop.ValueKind switch
{
JsonValueKind.String => prop.GetString()?.Trim(),
JsonValueKind.Number => prop.GetRawText(),
JsonValueKind.Null => null,
_ => null
};
}
private static int? ReadInt(JsonElement root, params string[] names)
{
if (!TryGetPropertyIgnoreCase(root, out var prop, names))
{
return null;
}
return prop.ValueKind switch
{
JsonValueKind.Number when prop.TryGetInt32(out var n) => n,
JsonValueKind.String when int.TryParse(prop.GetString(), out var n) => n,
_ => null
};
}
}

View File

@ -1,6 +1,7 @@
using Fake.DependencyInjection; using Fake.DependencyInjection;
using Fake.EventBus; using Fake.EventBus;
using Fake.UnitOfWork; using Fake.UnitOfWork;
using Oms.Application.Messaging;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Oms.Application.Services.Orders.Issues; using Oms.Application.Services.Orders.Issues;
@ -26,7 +27,7 @@ public sealed class OrderAutoTriggerFireEventHandler(
return; return;
} }
using var unitOfWork = unitOfWorkManager.Begin(); using var unitOfWork = unitOfWorkManager.Begin(OmsOutboxUnitOfWork.Transactional());
try try
{ {
await autoTriggerRuntimeService.FireByOrderIdAsync( await autoTriggerRuntimeService.FireByOrderIdAsync(

View File

@ -1,6 +1,7 @@
using Fake.DependencyInjection; using Fake.DependencyInjection;
using Fake.EventBus; using Fake.EventBus;
using Fake.UnitOfWork; using Fake.UnitOfWork;
using Oms.Application.Messaging;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Oms.Application.Integrations.SmallBagTrack; using Oms.Application.Integrations.SmallBagTrack;
@ -24,7 +25,7 @@ public sealed class OrderLifecycleTrackAppendEventHandler(
return; return;
} }
using var unitOfWork = unitOfWorkManager.Begin(); using var unitOfWork = unitOfWorkManager.Begin(OmsOutboxUnitOfWork.Transactional());
try try
{ {
await trackClient.AppendLifecycleTrackAsync( await trackClient.AppendLifecycleTrackAsync(

View File

@ -1,6 +1,7 @@
using Fake.DependencyInjection; using Fake.DependencyInjection;
using Fake.EventBus; using Fake.EventBus;
using Fake.UnitOfWork; using Fake.UnitOfWork;
using Oms.Application.Messaging;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Oms.Application.Services.Orders; using Oms.Application.Services.Orders;
using Oms.Domain.OrdersAggregate.Repositories; using Oms.Domain.OrdersAggregate.Repositories;
@ -21,7 +22,7 @@ public sealed class OrderParcelCustoms9610UpsertEventHandler(
OrderParcelCustoms9610UpsertIntegrationEvent @event, OrderParcelCustoms9610UpsertIntegrationEvent @event,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
using var unitOfWork = unitOfWorkManager.Begin(); using var unitOfWork = unitOfWorkManager.Begin(OmsOutboxUnitOfWork.Transactional());
var order = await orderRepository.FirstOrDefaultAsync(x => x.Id == @event.OrderId, cancellationToken); var order = await orderRepository.FirstOrDefaultAsync(x => x.Id == @event.OrderId, cancellationToken);
if (order == null) if (order == null)
{ {

View File

@ -1,6 +1,7 @@
using Fake.DependencyInjection; using Fake.DependencyInjection;
using Fake.EventBus; using Fake.EventBus;
using Fake.UnitOfWork; using Fake.UnitOfWork;
using Oms.Application.Messaging;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Oms.Application.Services.Orders; using Oms.Application.Services.Orders;
@ -20,7 +21,7 @@ public sealed class OrderParcelLabelGenerateEventHandler(
OrderParcelLabelGenerateIntegrationEvent @event, OrderParcelLabelGenerateIntegrationEvent @event,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
using var unitOfWork = unitOfWorkManager.Begin(); using var unitOfWork = unitOfWorkManager.Begin(OmsOutboxUnitOfWork.Transactional());
using var scope = scopeFactory.CreateScope(); using var scope = scopeFactory.CreateScope();
var orderService = scope.ServiceProvider.GetRequiredService<OrderService>(); var orderService = scope.ServiceProvider.GetRequiredService<OrderService>();
var result = await orderService.GenerateLabelPdfForBatchAsync(@event.OrderId, cancellationToken); var result = await orderService.GenerateLabelPdfForBatchAsync(@event.OrderId, cancellationToken);

View File

@ -1,6 +1,7 @@
using Fake.DependencyInjection; using Fake.DependencyInjection;
using Fake.EventBus; using Fake.EventBus;
using Fake.UnitOfWork; using Fake.UnitOfWork;
using Oms.Application.Messaging;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Oms.Application.Dtos.Orders; using Oms.Application.Dtos.Orders;
using Oms.Application.Services.Orders; using Oms.Application.Services.Orders;
@ -21,7 +22,7 @@ public sealed class OrderParcelPickupAttachEventHandler(
OrderParcelPickupAttachIntegrationEvent @event, OrderParcelPickupAttachIntegrationEvent @event,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
using var unitOfWork = unitOfWorkManager.Begin(); using var unitOfWork = unitOfWorkManager.Begin(OmsOutboxUnitOfWork.Transactional());
try try
{ {
await pickupOrderService.CreateForParcelInternalAsync(new PickupOrderCreateInput await pickupOrderService.CreateForParcelInternalAsync(new PickupOrderCreateInput

View File

@ -2,6 +2,7 @@ using Fake.Application;
using Fake.DependencyInjection; using Fake.DependencyInjection;
using Fake.EventBus; using Fake.EventBus;
using Fake.UnitOfWork; using Fake.UnitOfWork;
using Oms.Application.Messaging;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Oms.Application.Integrations.SmallBagTrack; using Oms.Application.Integrations.SmallBagTrack;
@ -24,7 +25,7 @@ public sealed class OrderParcelTrackUpsertEventHandler(
OrderParcelTrackUpsertIntegrationEvent @event, OrderParcelTrackUpsertIntegrationEvent @event,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
using var unitOfWork = unitOfWorkManager.Begin(); using var unitOfWork = unitOfWorkManager.Begin(OmsOutboxUnitOfWork.Transactional());
var request = await ResolveRequestAsync(@event, cancellationToken); var request = await ResolveRequestAsync(@event, cancellationToken);
request.AppendInitialTrackOnSuccess = @event.AppendInitialTrackOnSuccess; request.AppendInitialTrackOnSuccess = @event.AppendInitialTrackOnSuccess;

View File

@ -3,6 +3,7 @@ using Fake.DependencyInjection;
using Fake.ObjectStorage; using Fake.ObjectStorage;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Oms.Application.Dtos.Orders; using Oms.Application.Dtos.Orders;
using Oms.Application.Services.Storage;
using Oms.Application.Storage; using Oms.Application.Storage;
using Oms.Domain.OrdersAggregate.Consts; using Oms.Domain.OrdersAggregate.Consts;
using Oms.Domain.OrdersAggregate.Entities; using Oms.Domain.OrdersAggregate.Entities;
@ -15,7 +16,8 @@ namespace Oms.Application.Services.Orders;
/// </summary> /// </summary>
public sealed class OrderFileManager( public sealed class OrderFileManager(
IOrderFileRepository orderFileRepository, IOrderFileRepository orderFileRepository,
IObjectStorage fileStorage) : IScopedDependency IObjectStorage fileStorage,
IHttpClientFactory httpClientFactory) : IScopedDependency
{ {
private static readonly HashSet<string> ImageExt = private static readonly HashSet<string> ImageExt =
new(StringComparer.OrdinalIgnoreCase) { ".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp" }; new(StringComparer.OrdinalIgnoreCase) { ".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp" };
@ -205,6 +207,162 @@ public sealed class OrderFileManager(
return MapItem(saved); return MapItem(saved);
} }
/// <summary>
/// 下载远端文件转存自有对象存储后写入订单附件。
/// </summary>
public async Task<OrderFileItemOutput> AddOrReplaceFromRemoteUrlAsync(
int orderId,
string fileType,
string remoteUrl,
int operatorUserId,
bool replaceExisting = true,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(remoteUrl))
{
throw new BusinessException("下游文件地址为空");
}
if (!OrderFileTypeCodes.IsValid(fileType))
{
throw new BusinessException("不支持的附件类型");
}
var type = OrderFileTypeCodes.Normalize(fileType);
var sourceUrl = remoteUrl.Trim();
var stored = await DownloadAndStoreRemoteAsync(orderId, type, sourceUrl, cancellationToken);
if (replaceExisting)
{
await orderFileRepository.SoftDeleteByOrderAndTypeAsync(orderId, type, cancellationToken);
}
else
{
var existing = await orderFileRepository.GetByOrderAndTypeListAsync(orderId, type, cancellationToken);
var dup = existing.FirstOrDefault(x =>
string.Equals(x.FileUrl, stored.Key, StringComparison.OrdinalIgnoreCase)
|| string.Equals(x.FileUrl, sourceUrl, StringComparison.OrdinalIgnoreCase));
if (dup != null)
{
return MapItem(dup);
}
if (existing.Count >= OrderFileTypeCodes.GetMaxCount(type))
{
var oldest = existing.OrderBy(x => x.Id).First();
oldest.IsDeleted = true;
oldest.UpdateTime = DateTime.Now;
await orderFileRepository.UpdateAsync(oldest, cancellationToken);
}
}
var existingAfter = replaceExisting
? []
: await orderFileRepository.GetByOrderAndTypeListAsync(orderId, type, cancellationToken);
var entity = new OrderFile
{
OrderId = orderId,
FileType = type,
FileName = stored.FileName,
FileUrl = stored.Key,
ContentType = stored.ContentType,
FileSize = stored.Size,
Sort = existingAfter.Count,
Source = OrderFileSourceCodes.Downstream,
Remark = sourceUrl.Length > 500 ? sourceUrl[..500] : sourceUrl,
CreateUserId = operatorUserId,
CreateTime = DateTime.Now
};
var saved = await orderFileRepository.InsertAsync(entity, cancellationToken);
return MapItem(saved);
}
private async Task<(string Key, string? FileName, string? ContentType, long Size)> DownloadAndStoreRemoteAsync(
int orderId,
string fileType,
string remoteUrl,
CancellationToken cancellationToken)
{
byte[] bytes;
string? contentType;
try
{
var client = httpClientFactory.CreateClient(FileStorageService.UrlFetchClientName);
using var request = new HttpRequestMessage(HttpMethod.Get, remoteUrl);
request.Headers.TryAddWithoutValidation("Accept", "*/*");
using var response = await client.SendAsync(
request,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken);
if (!response.IsSuccessStatusCode)
{
throw new BusinessException($"下载下游文件失败:HTTP {(int)response.StatusCode}");
}
bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken);
contentType = response.Content.Headers.ContentType?.MediaType;
}
catch (BusinessException)
{
throw;
}
catch (Exception ex)
{
throw new BusinessException($"下载下游文件失败:{ex.Message}");
}
if (bytes.Length == 0)
{
throw new BusinessException("下游文件内容为空");
}
if (bytes.Length > MaxPdfBytes)
{
throw new BusinessException("下游文件不能超过 10MB");
}
var ext = GuessExtension(remoteUrl, contentType);
var fileName = TryFileNameFromUrl(remoteUrl) ?? $"{fileType}{ext}";
var storedName = $"{Guid.NewGuid():N}{ext}";
var relativeKey = $"uploads/order-files/{orderId}/{fileType}/{storedName}";
await using var stream = new MemoryStream(bytes);
var key = await fileStorage.SaveObjectAsync(stream, relativeKey, contentType, cancellationToken);
return (key, fileName, contentType, bytes.Length);
}
private static string GuessExtension(string url, string? contentType)
{
var fromUrl = Path.GetExtension(
(url.Contains('?', StringComparison.Ordinal)
? url[..url.IndexOf('?', StringComparison.Ordinal)]
: url));
if (!string.IsNullOrWhiteSpace(fromUrl) && fromUrl.Length <= 8)
{
return fromUrl.ToLowerInvariant();
}
if (!string.IsNullOrWhiteSpace(contentType))
{
if (contentType.Contains("pdf", StringComparison.OrdinalIgnoreCase))
{
return ".pdf";
}
if (contentType.Contains("png", StringComparison.OrdinalIgnoreCase))
{
return ".png";
}
if (contentType.Contains("jpeg", StringComparison.OrdinalIgnoreCase)
|| contentType.Contains("jpg", StringComparison.OrdinalIgnoreCase))
{
return ".jpg";
}
}
return ".pdf";
}
public async Task<List<OrderFileItemOutput>> UploadAsync( public async Task<List<OrderFileItemOutput>> UploadAsync(
int orderId, int orderId,
string fileType, string fileType,

View File

@ -1,5 +1,6 @@
using Fake.Application; using Fake.Application;
using Fake.Security.Claims; using Fake.Security.Claims;
using Fake.UnitOfWork;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Oms.Application.Dtos.Orders; using Oms.Application.Dtos.Orders;
@ -21,6 +22,7 @@ public partial class OrderService
/// 创建订单批量异步任务并入队 RabbitMQ。 /// 创建订单批量异步任务并入队 RabbitMQ。
/// </summary> /// </summary>
[HttpPost("/order/batch/jobs")] [HttpPost("/order/batch/jobs")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> CreateBatchJobAsync([FromBody] OrderBatchJobCreateInput input) public Task<OrderBatchJobOutput> CreateBatchJobAsync([FromBody] OrderBatchJobCreateInput input)
{ {
return BatchJobCoordinator.CreateAndEnqueueAsync(input, CurrentUser.GetId<int>()); return BatchJobCoordinator.CreateAndEnqueueAsync(input, CurrentUser.GetId<int>());
@ -73,6 +75,7 @@ public partial class OrderService
/// 异步批量创建轨迹订单(替代前端逐条调用)。 /// 异步批量创建轨迹订单(替代前端逐条调用)。
/// </summary> /// </summary>
[HttpPost("/order/batch/track-upsert")] [HttpPost("/order/batch/track-upsert")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> BatchTrackUpsertAsync([FromBody] OrderBatchJobCreateInput input) public Task<OrderBatchJobOutput> BatchTrackUpsertAsync([FromBody] OrderBatchJobCreateInput input)
{ {
input.Action = OrderBatchActionCodes.TrackUpsertSmallBag; input.Action = OrderBatchActionCodes.TrackUpsertSmallBag;
@ -94,6 +97,7 @@ public partial class OrderService
/// 异步批量预报下游订单。 /// 异步批量预报下游订单。
/// </summary> /// </summary>
[HttpPost("/order/batch/downstream-forward")] [HttpPost("/order/batch/downstream-forward")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> BatchDownstreamForwardAsync([FromBody] OrderBatchJobCreateInput input) public Task<OrderBatchJobOutput> BatchDownstreamForwardAsync([FromBody] OrderBatchJobCreateInput input)
{ {
input.Action = OrderBatchActionCodes.DownstreamForwardCreateOne; input.Action = OrderBatchActionCodes.DownstreamForwardCreateOne;
@ -111,6 +115,7 @@ public partial class OrderService
string.IsNullOrWhiteSpace(authorization) ? null : authorization); string.IsNullOrWhiteSpace(authorization) ? null : authorization);
} }
[UnitOfWork(IsTransactional = true)]
private Task<OrderBatchJobOutput> EnqueueOrderBatchAsync(string action, OrderBatchJobCreateInput input) private Task<OrderBatchJobOutput> EnqueueOrderBatchAsync(string action, OrderBatchJobCreateInput input)
{ {
input.Action = action; input.Action = action;
@ -121,6 +126,7 @@ public partial class OrderService
/// 异步批量支付订单。 /// 异步批量支付订单。
/// </summary> /// </summary>
[HttpPost("/order/batch/pay")] [HttpPost("/order/batch/pay")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> BatchPayAsync([FromBody] OrderBatchJobCreateInput input) => public Task<OrderBatchJobOutput> BatchPayAsync([FromBody] OrderBatchJobCreateInput input) =>
EnqueueOrderBatchAsync(OrderBatchActionCodes.Pay, input); EnqueueOrderBatchAsync(OrderBatchActionCodes.Pay, input);
@ -128,6 +134,7 @@ public partial class OrderService
/// 异步批量预报订单。 /// 异步批量预报订单。
/// </summary> /// </summary>
[HttpPost("/order/batch/pre-declare")] [HttpPost("/order/batch/pre-declare")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> BatchPreDeclareAsync([FromBody] OrderBatchJobCreateInput input) => public Task<OrderBatchJobOutput> BatchPreDeclareAsync([FromBody] OrderBatchJobCreateInput input) =>
EnqueueOrderBatchAsync(OrderBatchActionCodes.PreDeclare, input); EnqueueOrderBatchAsync(OrderBatchActionCodes.PreDeclare, input);
@ -135,6 +142,7 @@ public partial class OrderService
/// 异步批量拦截订单。 /// 异步批量拦截订单。
/// </summary> /// </summary>
[HttpPost("/order/batch/intercept")] [HttpPost("/order/batch/intercept")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> BatchInterceptAsync([FromBody] OrderBatchJobCreateInput input) => public Task<OrderBatchJobOutput> BatchInterceptAsync([FromBody] OrderBatchJobCreateInput input) =>
EnqueueOrderBatchAsync(OrderBatchActionCodes.Intercept, input); EnqueueOrderBatchAsync(OrderBatchActionCodes.Intercept, input);
@ -142,6 +150,7 @@ public partial class OrderService
/// 异步批量取消拦截。 /// 异步批量取消拦截。
/// </summary> /// </summary>
[HttpPost("/order/batch/cancel-intercept")] [HttpPost("/order/batch/cancel-intercept")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> BatchCancelInterceptAsync([FromBody] OrderBatchJobCreateInput input) => public Task<OrderBatchJobOutput> BatchCancelInterceptAsync([FromBody] OrderBatchJobCreateInput input) =>
EnqueueOrderBatchAsync(OrderBatchActionCodes.CancelIntercept, input); EnqueueOrderBatchAsync(OrderBatchActionCodes.CancelIntercept, input);
@ -149,6 +158,7 @@ public partial class OrderService
/// 异步批量删除订单。 /// 异步批量删除订单。
/// </summary> /// </summary>
[HttpPost("/order/batch/delete")] [HttpPost("/order/batch/delete")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> BatchDeleteAsync([FromBody] OrderBatchJobCreateInput input) => public Task<OrderBatchJobOutput> BatchDeleteAsync([FromBody] OrderBatchJobCreateInput input) =>
EnqueueOrderBatchAsync(OrderBatchActionCodes.Delete, input); EnqueueOrderBatchAsync(OrderBatchActionCodes.Delete, input);
@ -156,6 +166,7 @@ public partial class OrderService
/// 异步批量打印面单。 /// 异步批量打印面单。
/// </summary> /// </summary>
[HttpPost("/order/batch/print")] [HttpPost("/order/batch/print")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> BatchPrintAsync([FromBody] OrderBatchJobCreateInput input) => public Task<OrderBatchJobOutput> BatchPrintAsync([FromBody] OrderBatchJobCreateInput input) =>
EnqueueOrderBatchAsync(OrderBatchActionCodes.Print, input); EnqueueOrderBatchAsync(OrderBatchActionCodes.Print, input);
@ -163,6 +174,7 @@ public partial class OrderService
/// 异步批量标记问题件。 /// 异步批量标记问题件。
/// </summary> /// </summary>
[HttpPost("/order/batch/mark-problematic")] [HttpPost("/order/batch/mark-problematic")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> BatchMarkProblematicAsync([FromBody] OrderBatchJobCreateInput input) => public Task<OrderBatchJobOutput> BatchMarkProblematicAsync([FromBody] OrderBatchJobCreateInput input) =>
EnqueueOrderBatchAsync(OrderBatchActionCodes.MarkProblematic, input); EnqueueOrderBatchAsync(OrderBatchActionCodes.MarkProblematic, input);
@ -170,6 +182,7 @@ public partial class OrderService
/// 异步批量重新排货。 /// 异步批量重新排货。
/// </summary> /// </summary>
[HttpPost("/order/batch/reallocate")] [HttpPost("/order/batch/reallocate")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> BatchReallocateAsync([FromBody] OrderBatchJobCreateInput input) => public Task<OrderBatchJobOutput> BatchReallocateAsync([FromBody] OrderBatchJobCreateInput input) =>
EnqueueOrderBatchAsync(OrderBatchActionCodes.Reallocate, input); EnqueueOrderBatchAsync(OrderBatchActionCodes.Reallocate, input);
@ -177,6 +190,7 @@ public partial class OrderService
/// 异步批量标记已认领。 /// 异步批量标记已认领。
/// </summary> /// </summary>
[HttpPost("/order/batch/mark-claimed")] [HttpPost("/order/batch/mark-claimed")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> BatchMarkClaimedAsync([FromBody] OrderBatchJobCreateInput input) => public Task<OrderBatchJobOutput> BatchMarkClaimedAsync([FromBody] OrderBatchJobCreateInput input) =>
EnqueueOrderBatchAsync(OrderBatchActionCodes.MarkClaimed, input); EnqueueOrderBatchAsync(OrderBatchActionCodes.MarkClaimed, input);
@ -184,6 +198,7 @@ public partial class OrderService
/// 异步批量更新处理状态。 /// 异步批量更新处理状态。
/// </summary> /// </summary>
[HttpPost("/order/batch/handle-status-update")] [HttpPost("/order/batch/handle-status-update")]
[UnitOfWork(IsTransactional = true)]
public Task<OrderBatchJobOutput> BatchHandleStatusUpdateAsync([FromBody] OrderBatchJobCreateInput input) => public Task<OrderBatchJobOutput> BatchHandleStatusUpdateAsync([FromBody] OrderBatchJobCreateInput input) =>
EnqueueOrderBatchAsync(OrderBatchActionCodes.HandleStatusUpdate, input); EnqueueOrderBatchAsync(OrderBatchActionCodes.HandleStatusUpdate, input);

View File

@ -1,5 +1,6 @@
using Fake.Application; using Fake.Application;
using Fake.Domain.Exceptions; using Fake.Domain.Exceptions;
using Fake.UnitOfWork;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Oms.Application.Dtos.Orders; using Oms.Application.Dtos.Orders;
using Oms.Application.Integrations.Itfx; using Oms.Application.Integrations.Itfx;
@ -36,6 +37,7 @@ public partial class OrderService
/// 按订单 Id 组装 createOrderOne 并转发至 itfx 下游。 /// 按订单 Id 组装 createOrderOne 并转发至 itfx 下游。
/// </summary> /// </summary>
[HttpPost("/order/downstream-forward-create-one")] [HttpPost("/order/downstream-forward-create-one")]
[UnitOfWork(IsTransactional = true)]
public async Task<OrderDownstreamForwardResult> DownstreamForwardCreateOneAsync([FromBody] OrderActionInput input) public async Task<OrderDownstreamForwardResult> DownstreamForwardCreateOneAsync([FromBody] OrderActionInput input)
{ {
var (order, body) = await LoadDownstreamCreateOneContextAsync(input.Id); var (order, body) = await LoadDownstreamCreateOneContextAsync(input.Id);
@ -82,6 +84,72 @@ public partial class OrderService
}; };
} }
/// <summary>
/// 按订单 Id 组装 getFile 并转发至 itfx 下游;成功时转存文件并回写单号。
/// </summary>
[HttpPost("/order/downstream-forward-get-file")]
public async Task<OrderDownstreamGetFileResult> DownstreamForwardGetFileAsync(
[FromBody] OrderDownstreamGetFileInput input)
{
if (!ItfxGetFileDataParser.TryResolveFileType(input.Type, out var fileType))
{
throw new BusinessException("不支持的文件类型,请选择下游面单/末端面单/POD");
}
var order = await GetOrderOrThrowAsync(input.Id);
var creds = await OrderDownstreamCredentialResolver.ResolveAsync(order);
var body = new ItfxGetFileBody
{
ClientNo = order.ClientNo?.Trim() ?? string.Empty,
TrackNo = order.TrackNo?.Trim() ?? string.Empty,
ServiceNo = order.DownstreamServiceNo?.Trim() ?? string.Empty,
Type = input.Type
};
var forward = await ItfxForwardClient.ForwardWithSubscribeAsync(
ItfxGetFileDataParser.StandardCode,
creds.SupplierCode,
creds.AppKey,
creds.AppSecret,
body);
string? storedFileUrl = null;
if (forward.Success
&& ItfxGetFileDataParser.TryParse(forward.ResponseBody, out var data)
&& data != null)
{
if (ItfxGetFileDataParser.ApplyToOrder(order, data))
{
await OrderRepository.UpdateAsync(order);
}
if (!string.IsNullOrWhiteSpace(data.Url))
{
var saved = await OrderFileManager.AddOrReplaceFromRemoteUrlAsync(
order.Id,
fileType,
data.Url!,
CurrentUser.IsAuthenticated ? CurrentUser.GetId<int>() : 0);
storedFileUrl = saved.FileUrl;
}
}
return new OrderDownstreamGetFileResult
{
Success = forward.Success,
SupplierCode = creds.SupplierCode,
Type = input.Type,
FileType = fileType,
Url = forward.Url,
RequestJson = forward.RequestJson,
StatusCode = forward.StatusCode,
ResponseBody = forward.ResponseBody,
StoredFileUrl = storedFileUrl,
DownstreamServiceNo = order.DownstreamServiceNo,
TrackNo = order.TrackNo,
};
}
private async Task<(Domain.OrdersAggregate.Entities.Order order, ItfxCreateOrderOneBody body)> LoadDownstreamCreateOneContextAsync( private async Task<(Domain.OrdersAggregate.Entities.Order order, ItfxCreateOrderOneBody body)> LoadDownstreamCreateOneContextAsync(
int orderId) int orderId)
{ {