track/src/SJZY.Track.Application/Services/ProvideServices/OrderLinkService.cs
2024-03-02 15:34:26 +08:00

89 lines
3.0 KiB
C#

using SJZY.Track.Application.Contract.Dtos.ProvideServices;
using SJZY.Track.Domain.Aggregates.OrderAggregate;
using SJZY.Track.Domain.Queries;
namespace SJZY.Track.Application.Services.ProvideServices;
/// <summary>
/// 订单关联服务
/// </summary>
[ApiExplorerSettings(GroupName = "提供接口")]
public class OrderLinkService : ApplicationService
{
private readonly IOrderRepository _orderRepository;
private readonly IBasicQuery<OrderLinkEntity> _orderLinkQuery;
public OrderLinkService(IBasicQuery<OrderLinkEntity> orderLinkQuery, IOrderRepository orderRepository)
{
_orderLinkQuery = orderLinkQuery;
_orderRepository = orderRepository;
}
/// <summary>
/// 关联订单
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost("Order/Link")]
public async Task<bool> LinkOrderAsync(LinkOrderInput input)
{
var orderId = await _orderRepository.GetFirstAsync(x =>
x.OrderType == input.OrderType && x.OrderNo == input.OrderNo, x => x.Id);
if (orderId == default)
{
throw new BusinessException(message: $"订单:{input.OrderNo}不存在");
}
if (input.LinkOrderNos.Count < 1 || input.LinkOrderType == 0) return true;
// 单号去重
input.LinkOrderNos = input.LinkOrderNos.Distinct().ToList();
// 解绑
if (!input.IsLink) return await UnLinkOrderAsync(input);
// 关联订单
return await DoLinkOrderAsync(input, orderId);
}
private async Task<bool> DoLinkOrderAsync(LinkOrderInput input, int orderId)
{
// 获取已关联的订单
var linkOrderNos = await _orderLinkQuery.GetListAsync(x =>
x.OrderType == input.OrderType && x.OrderNo == input.OrderNo && x.LinkOrderType == input.LinkOrderType,
x => x.LinkOrderNo);
// 计算出未关联的订单
var noLinkOrderNos = input.LinkOrderNos.Except(linkOrderNos);
// 过滤掉不存在的订单
var canLinkOrders = await _orderRepository.GetListAsync(x =>
x.OrderType == input.LinkOrderType && noLinkOrderNos.Contains(x.OrderNo),
x => new { x.Id, x.OrderNo });
await _orderRepository.LinkOrderAsync(canLinkOrders.Select(x => new OrderLinkEntity
{
OrderId = orderId,
OrderNo = input.OrderNo,
OrderType = input.OrderType,
LinkOrderId = x.Id,
LinkOrderNo = x.OrderNo,
LinkOrderType = input.LinkOrderType
}).ToList());
return true;
}
private async Task<bool> UnLinkOrderAsync(LinkOrderInput input)
{
var unLinkIds = await _orderLinkQuery.GetListAsync(x =>
x.OrderType == input.OrderType && x.OrderNo == input.OrderNo &&
x.LinkOrderType == input.LinkOrderType && input.LinkOrderNos.Contains(x.LinkOrderNo),
x => x.Id);
// real del
await _orderRepository.UnLinkByIdsAsync(unLinkIds);
return true;
}
}