You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3185 lines
180 KiB

using BBWYB.Common.Http;
using BBWYB.Common.Log;
2 years ago
using BBWYB.Common.Models;
2 years ago
using BBWYB.Server.Business.Extensions;
using BBWYB.Server.Business.JD;
2 years ago
using BBWYB.Server.Model;
using BBWYB.Server.Model.Core;
2 years ago
using BBWYB.Server.Model.Db;
2 years ago
using BBWYB.Server.Model.Db.Mds;
using BBWYB.Server.Model.Db.MDS;
2 years ago
using BBWYB.Server.Model.Dto;
2 years ago
using FreeSql;
2 years ago
using Microsoft.Extensions.DependencyInjection;
2 years ago
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
2 years ago
using SDKAdapter;
using SDKAdapter.OperationPlatform.Client;
using SDKAdapter.OperationPlatform.Models;
2 years ago
using SDKAdapter.PurchasePlatform.Client;
using SDKAdapter.PurchasePlatform.Models;
2 years ago
using System.Text;
using System.Text.RegularExpressions;
2 years ago
using Yitter.IdGenerator;
namespace BBWYB.Server.Business
{
public class PurchaseOrderBusiness : BaseBusiness, IDenpendency
{
private Lazy<PP_PlatformClientFactory> pplatformClientFactoryLazy;
private Lazy<TaskSchedulerManager> taskSchedulerManagerLazy;
private Lazy<FreeSqlMultiDBManager> fsqlManagerLazy;
private Lazy<ExpressCompanyNameConverter> expressCompanyNameConverterLazy;
private Lazy<KuaiDi100Manager> kuaiDi100ManagerLazy;
private Lazy<DingDingBusiness> dingDingBusinessLazy;
private Lazy<QiKuManager> qiKuManagerLazy;
private Lazy<RestApiService> restApiServiceLazy;
private Lazy<JDBusiness> jdBusinessLazy;
private Lazy<OP_PlatformClientFactory> opPlatformClientFactoryLazy;
private Lazy<VenderBusiness> venderBusinessLazy;
2 years ago
private Lazy<PurchaseSchemeBusiness> purchaseSchemeBusinessLazy;
private PP_PlatformClientFactory ppPlatformClientFactory => pplatformClientFactoryLazy.Value;
private TaskSchedulerManager taskSchedulerManager => taskSchedulerManagerLazy.Value;
private FreeSqlMultiDBManager fsqlManager => fsqlManagerLazy.Value;
private ExpressCompanyNameConverter expressCompanyNameConverter => expressCompanyNameConverterLazy.Value;
private KuaiDi100Manager kuaiDi100Manager => kuaiDi100ManagerLazy.Value;
private DingDingBusiness dingDingBusiness => dingDingBusinessLazy.Value;
private QiKuManager qiKuManager => qiKuManagerLazy.Value;
private RestApiService restApiService => restApiServiceLazy.Value;
private OP_PlatformClientFactory opPlatformClientFactory => opPlatformClientFactoryLazy.Value;
private VenderBusiness venderBusiness => venderBusinessLazy.Value;
private JDBusiness jdBusiness => jdBusinessLazy.Value;
2 years ago
private PurchaseSchemeBusiness purchaseSchemeBusiness => purchaseSchemeBusinessLazy.Value;
private IList<Enums.OrderState> cantPurchaseOrderStateList;
public PurchaseOrderBusiness(IFreeSql fsql,
NLogManager nLogManager,
IIdGenerator idGenerator,
IServiceProvider serviceProvider) : base(fsql, nLogManager, idGenerator)
2 years ago
{
pplatformClientFactoryLazy = new Lazy<PP_PlatformClientFactory>(() => serviceProvider.GetService<PP_PlatformClientFactory>());
taskSchedulerManagerLazy = new Lazy<TaskSchedulerManager>(() => serviceProvider.GetService<TaskSchedulerManager>());
fsqlManagerLazy = new Lazy<FreeSqlMultiDBManager>(() => serviceProvider.GetService<FreeSqlMultiDBManager>());
expressCompanyNameConverterLazy = new Lazy<ExpressCompanyNameConverter>(() => serviceProvider.GetService<ExpressCompanyNameConverter>());
kuaiDi100ManagerLazy = new Lazy<KuaiDi100Manager>(() => serviceProvider.GetService<KuaiDi100Manager>());
dingDingBusinessLazy = new Lazy<DingDingBusiness>(() => serviceProvider.GetService<DingDingBusiness>());
qiKuManagerLazy = new Lazy<QiKuManager>(() => serviceProvider.GetService<QiKuManager>());
restApiServiceLazy = new Lazy<RestApiService>(() => serviceProvider.GetService<RestApiService>());
jdBusinessLazy = new Lazy<JDBusiness>(() => serviceProvider.GetService<JDBusiness>());
opPlatformClientFactoryLazy = new Lazy<OP_PlatformClientFactory>(() => serviceProvider.GetService<OP_PlatformClientFactory>());
venderBusinessLazy = new Lazy<VenderBusiness>(() => serviceProvider.GetService<VenderBusiness>());
2 years ago
purchaseSchemeBusinessLazy = new Lazy<PurchaseSchemeBusiness>(() => serviceProvider.GetService<PurchaseSchemeBusiness>());
cantPurchaseOrderStateList = new List<Enums.OrderState>()
{
Enums.OrderState.,
Enums.OrderState.,
2 years ago
Enums.OrderState.
};
2 years ago
}
2 years ago
/// <summary>
/// 合并相同的采购Sku
/// </summary>
/// <param name="cargoParamList"></param>
/// <returns></returns>
private IList<PP_OrderProductParamRequest> CombineRepeatPurchaseSku(IList<CargoParamRequest> cargoParamList)
{
IList<PP_OrderProductParamRequest> orderProductParamList = new List<PP_OrderProductParamRequest>();
var samePurchaseSkuGroups = cargoParamList.GroupBy(p => p.SkuId).ToList();
foreach (var samePurchaseSkuGroup in samePurchaseSkuGroups)
{
var first = samePurchaseSkuGroup.First();
orderProductParamList.Add(new PP_OrderProductParamRequest()
{
ProductId = first.ProductId,
SkuId = first.SkuId,
SpecId = first.SpecId,
Quantity = samePurchaseSkuGroup.Sum(p => p.Quantity)
});
}
return orderProductParamList;
}
/// <summary>
/// 预览采购单
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
/// <exception cref="BusinessException"></exception>
2 years ago
public PreviewOrderResponse PreviewPurchaseOrder(PreviewOrderRequest request)
2 years ago
{
2 years ago
nLogManager.Default().Info($"PreviewPurchaseOrder {JsonConvert.SerializeObject(request)}");
2 years ago
if (request.Consignee == null ||
string.IsNullOrEmpty(request.Consignee.Address) ||
string.IsNullOrEmpty(request.Consignee.Mobile) ||
string.IsNullOrEmpty(request.Consignee.ContactName))
throw new BusinessException("缺少收货人信息");
if (request.PurchaseAccountList == null || request.PurchaseAccountList.Count() == 0)
throw new BusinessException("缺少采购账号");
if (request.CargoParamGroupList == null || request.CargoParamGroupList.Count() == 0)
throw new BusinessException("缺少报价参数");
#region 验证同一个批次中,一个订单sku不能同时拥有多个采购方案
IDictionary<string, long> schemeValidationDictionary = new Dictionary<string, long>();
foreach (var purchaseGroup in request.CargoParamGroupList)
{
foreach (var cargo in purchaseGroup.CargoParamList)
{
if (!schemeValidationDictionary.ContainsKey(cargo.BelongSkuId))
schemeValidationDictionary.TryAdd(cargo.BelongSkuId, cargo.SchemeId);
if (schemeValidationDictionary.TryGetValue(cargo.BelongSkuId, out long schemeId))
{
if (cargo.SchemeId != schemeId)
{
throw new BusinessException($"订单sku{cargo.BelongSkuId}只允许使用一个采购方案进行报价");
}
}
}
}
schemeValidationDictionary.Clear();
#endregion
2 years ago
var extJArray = new List<object>();
var freightAmount = 0M;
var productAmount = 0M;
var totalAmount = 0M;
var previewAmountGroupByPurchaserList = new List<PreviewAmountGroupByPurchaser>();
2 years ago
foreach (var cargoParamGroup in request.CargoParamGroupList)
{
var purchaseAccount = request.PurchaseAccountList.FirstOrDefault(pa => pa.PurchasePlatformId == cargoParamGroup.PurchasePlatform);
if (purchaseAccount == null)
throw new BusinessException($"缺少{cargoParamGroup.PurchasePlatform}采购平台账号,请在店铺配置中设置");
2 years ago
var orderProductParamList = CombineRepeatPurchaseSku(cargoParamGroup.CargoParamList);
2 years ago
try
{
var response = ppPlatformClientFactory.GetClient((AdapterEnums.PlatformType)cargoParamGroup.PurchasePlatform)
.PreviewOrder(new PP_PreviewOrderRequest()
{
AppKey = purchaseAccount.AppKey,
AppSecret = purchaseAccount.AppSecret,
AppToken = purchaseAccount.AppToken,
Consignee = new PP_ConsigneeRequest()
{
Address = request.Consignee.Address,
City = request.Consignee.City,
ContactName = request.Consignee.ContactName,
County = request.Consignee.County,
Mobile = request.Consignee.Mobile,
Province = request.Consignee.Province,
TelePhone = request.Consignee.TelePhone,
Town = request.Consignee.Town
},
Platform = (AdapterEnums.PlatformType)cargoParamGroup.PurchasePlatform,
PurchaseMode = (AdapterEnums.PurchaseMode)request.PurchaseOrderMode,
2 years ago
OrderProductParamList = orderProductParamList
2 years ago
});
if (cargoParamGroup.PurchasePlatform == Enums.Platform.)
extJArray.Add(new { cargoParamGroup.PurchaserId, cargoParamGroup.PurchasePlatform, OrderTradeTypeCode = response.Extensions });
freightAmount += response.FreightAmount;
productAmount += response.ProductAmount;
totalAmount += response.TotalAmount;
previewAmountGroupByPurchaserList.Add(new PreviewAmountGroupByPurchaser()
{
FreightAmount = response.FreightAmount,
ProductAmount = response.ProductAmount,
TotalAmount = response.TotalAmount,
PurchasePlatform = cargoParamGroup.PurchasePlatform,
PurchaserId = cargoParamGroup.PurchaserId,
PurchaserName = cargoParamGroup.PurchaserName
});
2 years ago
}
catch (Exception ex)
{
var errorBuilder = new StringBuilder();
2 years ago
errorBuilder.AppendLine($"采购商:{cargoParamGroup.PurchaserName}");
#region 匹配订单sku
if (ex.Message.Contains("库存不足"))
{
var match = Regex.Match(ex.Message, @"商品\[(\d+)_(\w+)\]");
if (match.Success)
{
var purchaseProductId = match.Groups[1].Value;
var purchaseSkuSpecId = match.Groups[2].Value;
var errorCargoParam = cargoParamGroup.CargoParamList.FirstOrDefault(c => c.SpecId == purchaseSkuSpecId && c.ProductId == purchaseProductId);
if (errorCargoParam != null)
{
errorBuilder.AppendLine($"订单sku[{errorCargoParam.BelongSkuId}]所使用的配件[${errorCargoParam.SkuId}]库存不足");
}
}
else
{
errorBuilder.AppendLine(ex.Message);
}
}
else
{
errorBuilder.AppendLine(ex.Message);
}
#endregion
2 years ago
throw new BusinessException(errorBuilder.ToString());
}
}
2 years ago
return new PreviewOrderResponse()
{
2 years ago
Extensions = JsonConvert.SerializeObject(extJArray),
FreightAmount = freightAmount,
ProductAmount = productAmount,
TotalAmount = totalAmount,
PreviewAmountGroupByPurchaserList = previewAmountGroupByPurchaserList
2 years ago
};
2 years ago
}
2 years ago
/// <summary>
/// 创建采购单
/// </summary>
/// <param name="request"></param>
/// <exception cref="BusinessException"></exception>
2 years ago
public void CreatePurchaseOrder(CreateOrderRequest request)
{
nLogManager.Default().Info($"CreatePurchaseOrder\r\n{JsonConvert.SerializeObject(request)}");
var dbOrder = fsql.Select<Order>(request.OrderId).ToOne();
if (dbOrder == null)
throw new BusinessException("订单不存在");
if (cantPurchaseOrderStateList.Contains(dbOrder.OrderState.Value))
throw new BusinessException($"当前订单状态:{dbOrder.OrderState},不允许采购");
2 years ago
2 years ago
if (request.Consignee == null ||
string.IsNullOrEmpty(request.Consignee.Address) ||
string.IsNullOrEmpty(request.Consignee.Mobile) ||
string.IsNullOrEmpty(request.Consignee.ContactName))
throw new BusinessException("缺少收货人信息");
if (request.PurchaseAccountList == null || request.PurchaseAccountList.Count() == 0)
throw new BusinessException("缺少采购账号");
if (request.CargoParamGroupList == null || request.CargoParamGroupList.Count() == 0)
throw new BusinessException("缺少下单商品参数");
#region 验证同一个批次中,一个订单sku不能同时拥有多个采购方案
IDictionary<string, long> schemeValidationDictionary = new Dictionary<string, long>();
foreach (var purchaseGroup in request.CargoParamGroupList)
{
foreach (var cargo in purchaseGroup.CargoParamList)
{
if (!schemeValidationDictionary.ContainsKey(cargo.BelongSkuId))
schemeValidationDictionary.TryAdd(cargo.BelongSkuId, cargo.SchemeId);
if (schemeValidationDictionary.TryGetValue(cargo.BelongSkuId, out long schemeId))
{
if (cargo.SchemeId != schemeId)
{
throw new BusinessException($"订单sku{cargo.BelongSkuId}只允许使用一个采购方案进行下单");
}
}
}
}
schemeValidationDictionary.Clear();
#endregion
2 years ago
var isRepurchase = fsql.Select<OrderCost>(dbOrder.Id).Any();
var orderSkus = fsql.Select<OrderSku>().Where(osku => osku.OrderId == request.OrderId).ToList();
var orderPurchaseInfoList = fsql.Select<OrderPurchaseInfo>().Where(opi => opi.OrderId == request.OrderId && opi.IsEnabled == true).ToList();
var orderCostDetailList = fsql.Select<OrderCostDetail>().Where(ocd => ocd.OrderId == request.OrderId && ocd.IsEnabled == true).ToList();
var orderSkuCostList = fsql.Select<OrderSkuCost>().Where(osc => osc.OrderId == request.OrderId).ToList();
foreach (var cargoParamGroup in request.CargoParamGroupList)
{
var purchaseOrder = orderPurchaseInfoList.FirstOrDefault(opi => opi.PurchaserId == cargoParamGroup.PurchaserId);
if (purchaseOrder != null)
{
foreach (var cargoParam in cargoParamGroup.CargoParamList)
{
if (purchaseOrder.BelongSkuIds.Contains(cargoParam.BelongSkuId))
{
//throw new BusinessException($"订单sku[{cargoParam.BelongSkuId}]已经存在同一个商家[{cargoParamGroup.PurchaserId}][{cargoParamGroup.PurchaserName}]的另一笔采购单中[{purchaseOrder.PurchaseOrderId}],请不要为同一笔订单sku进行同商家采购");
throw new BusinessException($"提示:请勿为同一个订单中的sku重复向同一个商家下采购单\r\n重复信息:\r\n- 订单sku:{cargoParam.BelongSkuId}\r\n- 商家:{cargoParamGroup.PurchaserName}");
}
}
}
}
2 years ago
2 years ago
var extJArray = JsonConvert.DeserializeObject<JArray>(request.Extensions);
2 years ago
List<OrderCostDetail> insertOrderCostDetails = new List<OrderCostDetail>();
2 years ago
List<OrderPurchaseInfo> insertOrderPurchaseInfos = new List<OrderPurchaseInfo>();
List<OrderPurchaseSkuInfo> insertOrderPurchaseSkuInfos = new List<OrderPurchaseSkuInfo>();
List<IUpdate<PurchaseScheme>> updatePurchaseSchemeList = new List<IUpdate<PurchaseScheme>>();
List<OrderPurchaseRelationInfo> insertOrderPurchaseRelationInfoList = new List<OrderPurchaseRelationInfo>();
List<string> updatePurchaseTimeLimitTaskOrderSkuList = new List<string>();
List<QiKuPackTaskSkuPurchaseSchemeIdRequest> notifyQikuPackSchemeParamList = null;
if (dbOrder.IntoStoreType == Enums.IntoStoreType.)
notifyQikuPackSchemeParamList = new List<QiKuPackTaskSkuPurchaseSchemeIdRequest>();
2 years ago
IInsert<OrderCost> insertOrderCost = null;
IUpdate<OrderCost> updateOrderCost = null;
List<OrderSkuCost> insertOrderSkuCostList = new List<OrderSkuCost>();
IList<IUpdate<OrderSkuCost>> updateOrderSkuCostList = new List<IUpdate<OrderSkuCost>>();
List<PP_QueryOrderDetailSkuResponse> createdPurchaseOrderItemList = new List<PP_QueryOrderDetailSkuResponse>();
2 years ago
2 years ago
foreach (var cargoParamGroup in request.CargoParamGroupList)
2 years ago
{
2 years ago
var purchaseAccount = request.PurchaseAccountList.FirstOrDefault(pa => pa.PurchasePlatformId == cargoParamGroup.PurchasePlatform);
if (purchaseAccount == null)
throw new BusinessException($"缺少{cargoParamGroup.PurchasePlatform}采购平台账号,请在店铺配置中设置");
var client = ppPlatformClientFactory.GetClient((AdapterEnums.PlatformType)cargoParamGroup.PurchasePlatform);
var extJson = extJArray.FirstOrDefault(j => j.Value<string>("PurchaserId") == cargoParamGroup.PurchaserId);
2 years ago
var orderProductParamList = CombineRepeatPurchaseSku(cargoParamGroup.CargoParamList);
2 years ago
var createOrderResponse = client.CreateOrder(new PP_CreateOrderRequest()
{
AppKey = purchaseAccount.AppKey,
AppSecret = purchaseAccount.AppSecret,
AppToken = purchaseAccount.AppToken,
Consignee = new PP_ConsigneeRequest()
{
Address = request.Consignee.Address,
City = request.Consignee.City,
ContactName = request.Consignee.ContactName,
County = request.Consignee.County,
Mobile = request.Consignee.Mobile,
Province = request.Consignee.Province,
TelePhone = request.Consignee.TelePhone,
Town = request.Consignee.Town
},
Platform = (AdapterEnums.PlatformType)purchaseAccount.PurchasePlatformId,
PurchaseMode = (AdapterEnums.PurchaseMode)request.PurchaseOrderMode,
Extensions = extJson.Value<string>("OrderTradeTypeCode"),
Remark = !string.IsNullOrEmpty(cargoParamGroup.Remark) ? cargoParamGroup.Remark : request.Remark,
2 years ago
OrderProductParamList = orderProductParamList
2 years ago
});
var purchaseOrderSimpleInfo = client.QueryOrderDetail(new PP_QueryOrderDetailRequest()
{
AppKey = purchaseAccount.AppKey,
AppSecret = purchaseAccount.AppSecret,
AppToken = purchaseAccount.AppToken,
OrderId = createOrderResponse.OrderId
});
createdPurchaseOrderItemList.AddRange(purchaseOrderSimpleInfo.ItemList);
2 years ago
//totalPurchaseProductAmount += purchaseOrderSimpleInfo.ProductAmount;
//totalPurchaseFreight += purchaseOrderSimpleInfo.FreightAmount;
#region 创建订单采购关系
foreach (var cargoParam in cargoParamGroup.CargoParamList)
{
2 years ago
var orderSku = orderSkus.FirstOrDefault(osku => osku.SkuId == cargoParam.BelongSkuId);
insertOrderPurchaseRelationInfoList.Add(new OrderPurchaseRelationInfo()
{
Id = idGenerator.NewLong(),
BelongSkuId = cargoParam.BelongSkuId,
CreateTime = DateTime.Now,
OrderId = request.OrderId,
PurchaseOrderId = purchaseOrderSimpleInfo.OrderId,
PurchaseProductId = cargoParam.ProductId,
PurchaseSkuId = cargoParam.SkuId,
PurchaseSpecId = cargoParam.SpecId,
Quantity = cargoParam.Quantity,
2 years ago
SchemeId = cargoParam.SchemeId,
SourceSkuId = orderSku?.BelongSkuId,
SchemeVersion = cargoParam.SchemeVersion ?? 1
});
}
#endregion
2 years ago
#region 等比计算采购成本
var proportionalCalculationResultList = ProportionalCalculationCost(cargoParamGroup.CargoParamList, purchaseOrderSimpleInfo);
foreach (var proportionalCalculationResult in proportionalCalculationResultList)
2 years ago
{
var skuId = proportionalCalculationResult.SkuId;
2 years ago
2 years ago
var orderSku = orderSkus.FirstOrDefault(osku => osku.SkuId == skuId);
2 years ago
var orderCostDetail = new OrderCostDetail()
{
Id = idGenerator.NewLong(),
CreateTime = DateTime.Now,
DeductionQuantity = orderSku.ItemTotal.Value,
OrderId = request.OrderId,
ProductId = orderSku.ProductId,
PurchaseOrderId = purchaseOrderSimpleInfo.OrderId,
SkuId = skuId,
IsEnabled = true
2 years ago
};
orderCostDetail.CalculationOrderCostDetailCostAndProfit(proportionalCalculationResult.ProductAmount,
proportionalCalculationResult.FreightAmount,
0M,
0M);
2 years ago
insertOrderCostDetails.Add(orderCostDetail);
}
#endregion
2 years ago
#region 采购订单信息
var belongSkuIdList = cargoParamGroup.CargoParamList.Select(c => c.BelongSkuId).Distinct().ToList();
2 years ago
var orderPurchaserInfo = new OrderPurchaseInfo()
{
Id = idGenerator.NewLong(),
OrderId = request.OrderId,
CreateTime = DateTime.Now,
PurchaseAccountId = purchaseAccount.Id,
PurchaseAccountName = purchaseAccount.AccountName,
PurchaseMethod = Enums.PurchaseMethod.线,
OrderState = Enums.PurchaseOrderState.,
2 years ago
PurchaseOrderId = createOrderResponse.OrderId,
PurchasePlatform = cargoParamGroup.PurchasePlatform,
PurchaserId = cargoParamGroup.PurchaserId,
2 years ago
PurchaserName = cargoParamGroup.PurchaserName,
2 years ago
ShopId = request.ShopId,
BelongSkuIds = string.Join(",", belongSkuIdList),
IsEnabled = true,
Remark = !string.IsNullOrEmpty(cargoParamGroup.Remark) ? cargoParamGroup.Remark : request.Remark
2 years ago
};
insertOrderPurchaseInfos.Add(orderPurchaserInfo);
#endregion
#region 采购订单Sku信息
foreach (var purchaseOrderSku in purchaseOrderSimpleInfo.ItemList)
{
var orderPurchaseSkuInfo = new OrderPurchaseSkuInfo()
{
Id = purchaseOrderSku.OrderSkuId,
CreateTime = DateTime.Now,
OrderId = request.OrderId,
PurchaseOrderId = purchaseOrderSimpleInfo.OrderId,
PurchaseProductId = purchaseOrderSku.ProductId,
PurchaseSkuId = purchaseOrderSku.SkuId,
ShopId = request.ShopId
};
insertOrderPurchaseSkuInfos.Add(orderPurchaseSkuInfo);
}
#endregion
#region 采购限时任务
foreach (var belongSkuId in belongSkuIdList)
{
if (!updatePurchaseTimeLimitTaskOrderSkuList.Any(x => x == belongSkuId))
updatePurchaseTimeLimitTaskOrderSkuList.Add(belongSkuId);
}
#endregion
#region 封装查询齐库合格证接口参数
if (dbOrder.IntoStoreType == Enums.IntoStoreType.)
{
foreach (var belongSkuId in belongSkuIdList) //订单skuId
{
var orderSku = orderSkus.FirstOrDefault(osku => osku.SkuId == belongSkuId);
if (orderSku == null)
continue;
var cargoParam = cargoParamGroup.CargoParamList.FirstOrDefault(c => c.BelongSkuId == belongSkuId);
if (cargoParam == null)
continue;
if (!notifyQikuPackSchemeParamList.Any(x => x.SkuId == orderSku.BelongSkuId))
{
notifyQikuPackSchemeParamList.Add(new QiKuPackTaskSkuPurchaseSchemeIdRequest()
{
SkuId = orderSku.BelongSkuId,
SkuPurchaseSchemeId = cargoParam.SchemeId.ToString(),
SchemeVersion = cargoParam.SchemeVersion ?? 1
});
}
}
}
#endregion
2 years ago
}
#region 更新采购方案最近采购价格
{
var allCargoParamList = new List<CargoParamRequest>();
request.CargoParamGroupList.ForEach(x => allCargoParamList.AddRange(x.CargoParamList));
var cargoParamGroupsBySchemeList = allCargoParamList.GroupBy(c => c.SchemeId);
foreach (var cargoParamGroupsByScheme in cargoParamGroupsBySchemeList)
{
var defalutCost = 0M;
var schemeId = cargoParamGroupsByScheme.Key;
defalutCost = cargoParamGroupsByScheme.Sum(cargoParam => createdPurchaseOrderItemList.Where(x => x.SkuId == cargoParam.SkuId)
.Select(x => x.Price * (cargoParam.PurchaseRatio ?? 1)).DefaultIfEmpty(0M).First());
var update = fsql.Update<PurchaseScheme>(schemeId).Set(ps => ps.LastPurchaseTime, DateTime.Now)
.Set(ps => ps.LastPurchasePriceCost, defalutCost);
updatePurchaseSchemeList.Add(update);
}
}
#endregion
#region 订单Sku成本
var allOrderCostDetail = orderCostDetailList.Union(insertOrderCostDetails).ToList();
foreach (var orderSku in orderSkus)
{
var orderSkuCost = orderSkuCostList.FirstOrDefault(osc => osc.SkuId == orderSku.SkuId);
if (orderSkuCost == null)
{
orderSkuCost = new OrderSkuCost()
{
Id = idGenerator.NewLong(),
CreateTime = DateTime.Now,
OrderId = request.OrderId,
SkuId = orderSku.SkuId
};
orderSkuCost.CalculationOrderSkuCostAndProfit(orderSku, allOrderCostDetail);
insertOrderSkuCostList.Add(orderSkuCost);
}
else
{
orderSkuCost.CalculationOrderSkuCostAndProfit(orderSku, allOrderCostDetail);
var update = fsql.Update<OrderSkuCost>().SetSource(orderSkuCost);
updateOrderSkuCostList.Add(update);
}
}
#endregion
2 years ago
#region 订单成本
var orderCost = new OrderCost()
{
OrderId = request.OrderId,
CreateTime = DateTime.Now,
IsManualEdited = false
2 years ago
};
//var totalPurchaseProductAmount = orderCostDetailList.Union(insertOrderCostDetails).Sum(ocd => ocd.SkuAmount);
//var totalPurchaseFreight = orderCostDetailList.Union(insertOrderCostDetails).Sum(ocd => ocd.PurchaseFreight);
//orderCost.CalculationOrderCostAndProfit(dbOrder.OrderTotalPrice.Value,
// totalPurchaseProductAmount ?? 0M,
// totalPurchaseFreight ?? 0M,
// 0M,
// 0M);
orderCost.CalculationOrderCostAndProfit(dbOrder.OrderTotalPrice.Value, orderSkuCostList.Union(insertOrderSkuCostList).ToList());
2 years ago
if (!isRepurchase)
{
insertOrderCost = fsql.Insert(orderCost);
}
else
{
updateOrderCost = fsql.Update<OrderCost>().SetSource(orderCost).IgnoreColumns(a => new { a.CreateTime });
}
#endregion
#region 订单状态
dbOrder.CalculationOrderState(fsql, orderSkus, orderPurchaseInfoList.Union(insertOrderPurchaseInfos).ToList());
#endregion
#region 通知C端状态
Task.Factory.StartNew(() => SendPurchaseOrderStateToC(dbOrder.Id, dbOrder.OrderState.Value), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
#endregion
#region 查询齐库合格证
if (dbOrder.IntoStoreType == Enums.IntoStoreType. &&
notifyQikuPackSchemeParamList != null &&
notifyQikuPackSchemeParamList.Count() > 0)
{
Task.Factory.StartNew(() => qiKuManager.SearchCerConfigured(dbOrder, notifyQikuPackSchemeParamList, orderSkus), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
}
#endregion
2 years ago
fsql.Transaction(() =>
{
if (updatePurchaseTimeLimitTaskOrderSkuList.Count() > 0)
{
fsql.Update<TimeLimitTask>().Set(t => t.CompletionTime, DateTime.Now)
2 years ago
.SetIf(dbOrder.PayTime != null, t => t.IsTimely == (DateTime.Now < t.ExpirationTime ? true : false))
.Where(t => t.OrderId == request.OrderId)
.Where(t => updatePurchaseTimeLimitTaskOrderSkuList.Contains(t.SkuId))
.Where(t => t.CompletionTime == null)
.Where(t => t.TaskType == Enums.TimeLimitTaskType.)
.ExecuteAffrows();
}
if (insertOrderCostDetails.Count() > 0)
fsql.Insert(insertOrderCostDetails).ExecuteAffrows();
if (insertOrderPurchaseInfos.Count() > 0)
fsql.Insert(insertOrderPurchaseInfos).ExecuteAffrows();
if (insertOrderPurchaseSkuInfos.Count() > 0)
fsql.Insert(insertOrderPurchaseSkuInfos).ExecuteAffrows();
if (insertOrderPurchaseRelationInfoList.Count() > 0)
fsql.Insert(insertOrderPurchaseRelationInfoList).ExecuteAffrows();
2 years ago
updateOrderCost?.ExecuteAffrows();
insertOrderCost?.ExecuteAffrows();
if (updatePurchaseSchemeList.Count() > 0)
{
foreach (var update in updatePurchaseSchemeList)
update.ExecuteAffrows();
}
fsql.Update<Order>(request.OrderId).Set(o => o.OrderState, dbOrder.OrderState)
2 years ago
.SetIf(!string.IsNullOrEmpty(request.Remark), o => o.PurchaseRemark, request.Remark)
2 years ago
.Set(o => o.IsPurchased, true)
.ExecuteAffrows();
if (insertOrderSkuCostList.Count() > 0)
fsql.Insert(insertOrderSkuCostList).ExecuteAffrows();
if (updateOrderSkuCostList.Count() > 0)
{
foreach (var update in updateOrderSkuCostList)
update.ExecuteAffrows();
}
2 years ago
});
//#region 更新采购方案最新价格
//Task.Factory.StartNew(() =>
//{
// try
// {
// purchaseSchemeBusiness.RefreshPurchaseScheme(new RefreshSchemeRequest()
// {
// SchemeIdList = updatePurchaseTimeSchemeIdList
// });
// }
// catch { }
//}, CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
//#endregion
2 years ago
}
/// <summary>
/// 获取关联订单列表
/// </summary>
/// <param name="orderId"></param>
/// <returns></returns>
public IList<AssociationPurchaseOrderResponse> GetAssociationPurchaseOrderList(string orderId)
{
IList<AssociationPurchaseOrderResponse> list = new List<AssociationPurchaseOrderResponse>();
var purchaseOrderList = fsql.Select<OrderPurchaseInfo>().Where(opi => opi.OrderId == orderId).ToList();
var orderSkuList = fsql.Select<OrderSku>().Where(osku => osku.OrderId == orderId).ToList();
var orderCostDetailList = fsql.Select<OrderCostDetail>().Where(ocd => ocd.OrderId == orderId).ToList();
foreach (var purchaseOrder in purchaseOrderList)
{
var associationPurchaseOrder = new AssociationPurchaseOrderResponse()
{
PurchaseAccountId = purchaseOrder.PurchaseAccountId,
PurchaseAccountName = purchaseOrder.PurchaseAccountName,
PurchasePlatform = purchaseOrder.PurchasePlatform.Value,
PurchaserId = purchaseOrder.PurchaserId,
PurchaserName = purchaseOrder.PurchaserName,
PurchaseOrderId = purchaseOrder.PurchaseOrderId,
IsEnabled = purchaseOrder.IsEnabled,
PurchaseMethod = purchaseOrder.PurchaseMethod.Value
};
var currentOrderCostDetailList = orderCostDetailList.Where(ocd => ocd.PurchaseOrderId == purchaseOrder.PurchaseOrderId).ToList();
foreach (var orderCostDetail in currentOrderCostDetailList)
{
var orderSku = orderSkuList.FirstOrDefault(osku => osku.SkuId == orderCostDetail.SkuId);
var assocationOrderCostDetail = new AssocationOrderCostDetailResponse()
{
Id = orderCostDetail.Id,
Logo = orderSku.Logo,
Title = orderSku.Title,
OrderId = orderSku.OrderId,
SkuId = orderSku.SkuId,
PurchaseQuantity = orderCostDetail.DeductionQuantity ?? 0,
PurchaseFreight = orderCostDetail.PurchaseFreight ?? 0M,
SkuAmount = orderCostDetail.SkuAmount ?? 0M,
};
if (assocationOrderCostDetail.PurchaseQuantity != 0)
assocationOrderCostDetail.PurchasePrice = assocationOrderCostDetail.SkuAmount / assocationOrderCostDetail.PurchaseQuantity;
associationPurchaseOrder.AssocationOrderCostDetailList.Add(assocationOrderCostDetail);
}
associationPurchaseOrder.PurchaseAmount = associationPurchaseOrder.AssocationOrderCostDetailList.Sum(x => x.SkuAmount);
associationPurchaseOrder.PurchaseFreight = associationPurchaseOrder.AssocationOrderCostDetailList.Sum(x => x.PurchaseFreight);
list.Add(associationPurchaseOrder);
}
return list;
}
2 years ago
/// <summary>
/// 关联订单
/// </summary>
/// <param name="request"></param>
public void AssociatePurchaseOrder(AssociationOrderRequest request)
2 years ago
{
nLogManager.Default().Info($"AssociatePurchaseOrder {JsonConvert.SerializeObject(request)}");
2 years ago
#region 数据验证
var dbOrder = fsql.Select<Order>(request.OrderId).ToOne();
if (dbOrder == null)
throw new BusinessException("订单不存在");
if (cantPurchaseOrderStateList.Contains(dbOrder.OrderState.Value))
throw new BusinessException($"当前订单状态:{dbOrder.OrderState},不允许关联");
if (request.AssociationPurchaseOrderList == null || request.AssociationPurchaseOrderList.Count() == 0)
throw new BusinessException("缺少采购单信息");
2 years ago
var validation_groups_pid = request.AssociationPurchaseOrderList.GroupBy(po => po.PurchaseOrderId);
if (validation_groups_pid.Any(x => x.Count() > 1))
throw new BusinessException("不允许包含重复的采购单");
foreach (var apo in request.AssociationPurchaseOrderList)
{
2 years ago
if (Math.Abs(apo.PurchaseAmount - apo.AssocationOrderCostDetailList.Sum(aocd => aocd.SkuAmount)) > 1)
throw new BusinessException($"采购单{apo.PurchaseOrderId}的采购货款与明细采购货款总和误差不能超过1");
}
2 years ago
var purchaseOrderIds = request.AssociationPurchaseOrderList.Select(apo => apo.PurchaseOrderId).ToList();
var dbPurchaseOrderList = fsql.Select<OrderPurchaseInfo>().Where(opi => purchaseOrderIds.Contains(opi.PurchaseOrderId)).ToList();
if (dbPurchaseOrderList.Count() > 0)
{
if (dbPurchaseOrderList.Any(opi => opi.OrderId != request.OrderId))
{
var otherUsePurchaseOrder = dbPurchaseOrderList.FirstOrDefault(opi => opi.OrderId != request.OrderId);
throw new BusinessException($"采购单{otherUsePurchaseOrder.PurchaseOrderId}的已经被其他订单{otherUsePurchaseOrder.OrderId}绑定");
}
if (dbPurchaseOrderList.Any(opi => opi.OrderState == Enums.PurchaseOrderState.))
{
var invalidPurchaseOrder = dbPurchaseOrderList.FirstOrDefault(opi => opi.OrderState == Enums.PurchaseOrderState.);
throw new BusinessException($"采购单{invalidPurchaseOrder.PurchaseOrderId}已失效,不能参与绑定");
}
}
#endregion
2 years ago
2 years ago
#region 读取采购单中的采购账号/采购方案
IList<string> purchaseAccountIdList = request.AssociationPurchaseOrderList.Select(x => string.IsNullOrEmpty(x.PurchaseAccountId) ?
x.PurchaseAccountName :
x.PurchaseAccountId).Distinct().ToList();
IList<Purchaseaccount> dbPurchaseAccountList = null;
if (purchaseAccountIdList.Count() > 0)
{
dbPurchaseAccountList = fsqlManager.MDSfsql.Select<Purchaseaccount>().Where(pa => purchaseAccountIdList.Contains(pa.Id) ||
purchaseAccountIdList.Contains(pa.AccountName)).ToList();
}
#endregion
var dbOrderSkuList = fsql.Select<OrderSku>().Where(osku => osku.OrderId == request.OrderId).ToList();
var dbOrderCostDetailList = fsql.Select<OrderCostDetail>().Where(ocd => ocd.OrderId == request.OrderId && ocd.IsEnabled == true).ToList();
2 years ago
var dbOrderCost = fsql.Select<OrderCost>(request.OrderId).ToOne();
var dbOrderSkuCostList = fsql.Select<OrderSkuCost>().Where(osc => osc.OrderId == request.OrderId).ToList();
2 years ago
List<OrderPurchaseInfo> insertOrderPurchaseInfoList = new List<OrderPurchaseInfo>();
2 years ago
List<OrderPurchaseSkuInfo> insertOrderPurchaseSkuInfoList = new List<OrderPurchaseSkuInfo>();
List<OrderPurchaseRelationInfo> insertOrderPurchaseRelationInfoList = new List<OrderPurchaseRelationInfo>();
IList<IUpdate<OrderPurchaseInfo>> updateOrderPurchaseInfoList = new List<IUpdate<OrderPurchaseInfo>>();
List<OrderCostDetail> insertOrderCostDetailList = new List<OrderCostDetail>();
IList<IUpdate<OrderCostDetail>> updateOrderCostDetailList = new List<IUpdate<OrderCostDetail>>();
IInsert<OrderCost> insertOrderCost = null;
IUpdate<OrderCost> updateOrderCost = null;
List<OrderSkuCost> insertOrderSkuCostList = new List<OrderSkuCost>();
IList<IUpdate<OrderSkuCost>> updateOrderSkuCostList = new List<IUpdate<OrderSkuCost>>();
2 years ago
List<string> updatePurchaseTimeLimitTaskOrderSkuList = new List<string>();
List<QiKuPackTaskSkuPurchaseSchemeIdRequest> notifyQikuPackSchemeParamList = new List<QiKuPackTaskSkuPurchaseSchemeIdRequest>();
2 years ago
foreach (var purchaseOrder in request.AssociationPurchaseOrderList)
{
2 years ago
//if (dbInvalidPurchaseOrderIdList.Contains(purchaseOrder.PurchaseOrderId))
// continue;
var totalQuantity = purchaseOrder.AssocationOrderCostDetailList.Sum(x => x.PurchaseQuantity);
var dbPurchaserOrder = dbPurchaseOrderList.FirstOrDefault(x => x.PurchaseOrderId == purchaseOrder.PurchaseOrderId);
if (dbPurchaserOrder == null)
{
2 years ago
if (purchaseOrder.PurchasePlatform == Enums.Platform.)
2 years ago
{
#region 补齐采购SKU和采购关系
2 years ago
var purchaseAccount = dbPurchaseAccountList.FirstOrDefault(pa => pa.Id == purchaseOrder.PurchaseAccountId ||
pa.AccountName == purchaseOrder.PurchaseAccountName);
if (purchaseAccount == null)
throw new BusinessException($"采购单{purchaseOrder.PurchaseOrderId}缺少有效的采购账号");
#region 查询1688采购单
2 years ago
var client = ppPlatformClientFactory.GetClient((AdapterEnums.PlatformType)purchaseOrder.PurchasePlatform);
var purchaseOrderSimpleInfo = client.QueryOrderDetail(new PP_QueryOrderDetailRequest()
{
AppKey = purchaseAccount.AppKey,
AppSecret = purchaseAccount.AppSecret,
AppToken = purchaseAccount.AppToken,
OrderId = purchaseOrder.PurchaseOrderId
});
#endregion
2 years ago
2 years ago
#region 处理采购商Id
var purchaserId = purchaseOrderSimpleInfo.PurchaserId;
if (string.IsNullOrEmpty(purchaserId))
2 years ago
throw new BusinessException($"采购单{purchaseOrder.PurchaseOrderId}缺少采购商Id");
purchaserId = purchaserId.Replace("b2b-", string.Empty);
var purchaserId2 = purchaserId.Substring(0, purchaserId.Length - 5);
var purchaserIds = new List<string>() { purchaserId, purchaserId2 };
var dbPurchaser = fsql.Select<Purchaser>().Where(p => p.Platform == Enums.Platform. && (purchaserIds.Contains(p.Id) ||
purchaserIds.Contains(p.Id2))).ToOne();
2 years ago
if (dbPurchaser == null)
throw new BusinessException($"采购单{purchaseOrder.PurchaseOrderId}缺少有效采购商");
purchaserId = dbPurchaser.Id;
if (string.IsNullOrEmpty(purchaseOrder.PurchaserId))
purchaseOrder.PurchaserId = purchaserId;
2 years ago
#endregion
#region 匹配采购方案
var skuIds = purchaseOrder.AssocationOrderCostDetailList.Select(ocd => ocd.SkuId).ToList();
var purchaseSchemeList = purchaseSchemeBusiness.GetPurchaseSchemeList(new QuerySchemeRequest()
2 years ago
{
ShopId = dbOrder.ShopId,
SkuIdList = skuIds
});
if (purchaseSchemeList.Count() == 0)
throw new BusinessException($"采购单{purchaseOrder.PurchaseOrderId} 采购商Id{purchaserId} 未匹配到采购方案");
2 years ago
#endregion
2 years ago
2 years ago
#region 补齐采购关系
foreach (var assOrderCostDetail in purchaseOrder.AssocationOrderCostDetailList)
{
var matchResultList = MatchPurchaseScheme(assOrderCostDetail.SkuId,
assOrderCostDetail.PurchaseQuantity,
purchaserId,
purchaseSchemeList,
purchaseOrderSimpleInfo);
if (matchResultList.Count() == 0)
2 years ago
throw new BusinessException($"采购单{purchaseOrder.PurchaseOrderId} 采购商Id {purchaserId} Sku{assOrderCostDetail.SkuId}缺少采购方案");
2 years ago
foreach (var cargoParam in matchResultList)
2 years ago
{
var dbOrderSku = dbOrderSkuList.FirstOrDefault(osku => osku.SkuId == assOrderCostDetail.SkuId);
2 years ago
var orderPurchaseRelationInfo = new OrderPurchaseRelationInfo()
{
Id = idGenerator.NewLong(),
BelongSkuId = assOrderCostDetail.SkuId,
CreateTime = DateTime.Now,
OrderId = assOrderCostDetail.OrderId,
PurchaseOrderId = purchaseOrder.PurchaseOrderId,
PurchaseSkuId = cargoParam.SkuId,
PurchaseProductId = cargoParam.ProductId,
PurchaseSpecId = cargoParam.SpecId,
SchemeId = cargoParam.SchemeId,
SchemeVersion = cargoParam.SchemeVersion ?? 1,
2 years ago
Quantity = assOrderCostDetail.PurchaseQuantity,
SourceSkuId = dbOrderSku.BelongSkuId
};
insertOrderPurchaseRelationInfoList.Add(orderPurchaseRelationInfo);
2 years ago
}
}
#region 补齐采购SKU
foreach (var purchaseOrderSku in purchaseOrderSimpleInfo.ItemList)
{
var orderPurchaseSkuInfo = new OrderPurchaseSkuInfo()
{
Id = purchaseOrderSku.OrderSkuId,
CreateTime = DateTime.Now,
OrderId = request.OrderId,
PurchaseOrderId = purchaseOrder.PurchaseOrderId,
PurchaseProductId = purchaseOrderSku.ProductId,
PurchaseSkuId = purchaseOrderSku.SkuId,
ShopId = request.ShopId
};
insertOrderPurchaseSkuInfoList.Add(orderPurchaseSkuInfo);
}
#endregion
#endregion
2 years ago
#endregion
}
2 years ago
#region 订单成本明细
2 years ago
foreach (var assOrderCostDetail in purchaseOrder.AssocationOrderCostDetailList)
{
2 years ago
2 years ago
var dbOrderSku = dbOrderSkuList.FirstOrDefault(osku => osku.SkuId == assOrderCostDetail.SkuId);
var purchaseFreight = purchaseOrder.PurchaseFreight * (1.0M * assOrderCostDetail.PurchaseQuantity / totalQuantity);
2 years ago
var orderCostDetail = new OrderCostDetail()
{
Id = idGenerator.NewLong(),
CreateTime = DateTime.Now,
DeductionQuantity = assOrderCostDetail.PurchaseQuantity,
IsEnabled = true,
OrderId = request.OrderId,
ProductId = dbOrderSku.ProductId,
SkuId = assOrderCostDetail.SkuId,
PurchaseOrderId = purchaseOrder.PurchaseOrderId
2 years ago
};
orderCostDetail.CalculationOrderCostDetailCostAndProfit(assOrderCostDetail.SkuAmount,
purchaseFreight,
0M,
0M);
2 years ago
insertOrderCostDetailList.Add(orderCostDetail);
}
2 years ago
#endregion
#region 采购单
dbPurchaserOrder = new OrderPurchaseInfo()
{
Id = idGenerator.NewLong(),
OrderId = request.OrderId,
PurchaseAccountId = purchaseOrder.PurchaseAccountId,
PurchaseAccountName = purchaseOrder.PurchaseAccountName,
IsEnabled = true,
BelongSkuIds = string.Join(",", purchaseOrder.AssocationOrderCostDetailList.Select(x => x.SkuId)),
CreateTime = DateTime.Now,
PurchaseMethod = Enums.PurchaseMethod.,
OrderState = Enums.PurchaseOrderState.,
2 years ago
PurchaseOrderId = purchaseOrder.PurchaseOrderId,
PurchasePlatform = purchaseOrder.PurchasePlatform,
PurchaserId = purchaseOrder.PurchaserId,
PurchaserName = purchaseOrder.PurchaserName,
ShopId = request.ShopId
};
insertOrderPurchaseInfoList.Add(dbPurchaserOrder);
#endregion
2 years ago
#region 采购限时任务
foreach (var ocd in purchaseOrder.AssocationOrderCostDetailList)
{
if (!updatePurchaseTimeLimitTaskOrderSkuList.Any(x => x == ocd.SkuId))
updatePurchaseTimeLimitTaskOrderSkuList.Add(ocd.SkuId);
}
#endregion
2 years ago
#region 封装查询齐库合格证参数
if (dbOrder.IntoStoreType == Enums.IntoStoreType.)
{
if (purchaseOrder.PurchasePlatform == Enums.Platform.)
{
var waitList = insertOrderPurchaseRelationInfoList.Where(r => !notifyQikuPackSchemeParamList.Any(x => x.SkuId == r.SourceSkuId &&
x.SkuPurchaseSchemeId == r.SchemeId?.ToString()))
.Select(r => new QiKuPackTaskSkuPurchaseSchemeIdRequest()
{
SkuId = r.SourceSkuId,
SkuPurchaseSchemeId = r.SchemeId?.ToString()
}).ToList();
if (waitList != null && waitList.Count() > 0)
notifyQikuPackSchemeParamList.AddRange(waitList);
}
else
{
foreach (var ocd in purchaseOrder.AssocationOrderCostDetailList)
{
var orderSku = dbOrderSkuList.FirstOrDefault(osku => osku.SkuId == ocd.SkuId);
if (orderSku == null)
continue;
if (!notifyQikuPackSchemeParamList.Any(x => x.SkuId == orderSku.BelongSkuId))
notifyQikuPackSchemeParamList.Add(new QiKuPackTaskSkuPurchaseSchemeIdRequest() { SkuId = orderSku.BelongSkuId, SkuPurchaseSchemeId = null });
}
}
}
2 years ago
#endregion
}
else
{
2 years ago
if (dbPurchaserOrder.OrderId != request.OrderId)
throw new BusinessException($"采购单{purchaseOrder.PurchaseOrderId}不属于订单{request.OrderId}");
2 years ago
dbPurchaserOrder.PurchaseAccountId = purchaseOrder.PurchaseAccountId;
dbPurchaserOrder.PurchaseAccountName = purchaseOrder.PurchaseAccountName;
//dbPurchaserOrder.BelongSkuIds = string.Join(",", purchaseOrder.AssocationOrderCostDetailList.Select(x => x.SkuId));
dbPurchaserOrder.PurchasePlatform = purchaseOrder.PurchasePlatform;
if (!string.IsNullOrEmpty(purchaseOrder.PurchaserId) && purchaseOrder.PurchaserId != dbPurchaserOrder.PurchaserId)
dbPurchaserOrder.PurchaserId = purchaseOrder.PurchaserId;
if (!string.IsNullOrEmpty(purchaseOrder.PurchaserName) && purchaseOrder.PurchaserName != dbPurchaserOrder.PurchaserName)
dbPurchaserOrder.PurchaserName = purchaseOrder.PurchaserName;
2 years ago
updateOrderPurchaseInfoList.Add(fsql.Update<OrderPurchaseInfo>().SetSource(dbPurchaserOrder));
2 years ago
foreach (var assOrderCostDetail in purchaseOrder.AssocationOrderCostDetailList)
{
var dbOrderSku = dbOrderSkuList.FirstOrDefault(osku => osku.SkuId == assOrderCostDetail.SkuId);
var orderCostDetail = dbOrderCostDetailList.FirstOrDefault(ocd => ocd.SkuId == assOrderCostDetail.SkuId &&
ocd.PurchaseOrderId == purchaseOrder.PurchaseOrderId);
var purchaseFreight = purchaseOrder.PurchaseFreight * (1.0M * assOrderCostDetail.PurchaseQuantity / totalQuantity);
var isOcdEmpty = orderCostDetail == null;
if (isOcdEmpty)
{
orderCostDetail = new OrderCostDetail()
{
Id = idGenerator.NewLong(),
CreateTime = DateTime.Now,
DeductionQuantity = assOrderCostDetail.PurchaseQuantity,
IsEnabled = true,
OrderId = request.OrderId,
ProductId = dbOrderSku.ProductId,
SkuId = assOrderCostDetail.SkuId,
2 years ago
PurchaseOrderId = purchaseOrder.PurchaseOrderId,
ShopId = request.ShopId
};
}
orderCostDetail.DeductionQuantity = assOrderCostDetail.PurchaseQuantity;
orderCostDetail.CalculationOrderCostDetailCostAndProfit(assOrderCostDetail.SkuAmount,
purchaseFreight,
orderCostDetail.OutPackAmount ?? 0M,
orderCostDetail.DeliveryExpressFreight ?? 0M);
if (isOcdEmpty)
insertOrderCostDetailList.Add(orderCostDetail);
else
updateOrderCostDetailList.Add(fsql.Update<OrderCostDetail>().SetSource(orderCostDetail));
2 years ago
}
}
}
2 years ago
#region 订单Sku成本
var allOrderCostDetail = dbOrderCostDetailList.Union(insertOrderCostDetailList).ToList();
foreach (var orderSku in dbOrderSkuList)
{
var orderSkuCost = dbOrderSkuCostList.FirstOrDefault(osc => osc.SkuId == orderSku.SkuId);
if (orderSkuCost == null)
{
orderSkuCost = new OrderSkuCost()
{
Id = idGenerator.NewLong(),
CreateTime = DateTime.Now,
OrderId = request.OrderId,
SkuId = orderSku.SkuId
};
orderSkuCost.CalculationOrderSkuCostAndProfit(orderSku, allOrderCostDetail);
insertOrderSkuCostList.Add(orderSkuCost);
}
else
{
orderSkuCost.CalculationOrderSkuCostAndProfit(orderSku, allOrderCostDetail);
var update = fsql.Update<OrderSkuCost>().SetSource(orderSkuCost);
updateOrderSkuCostList.Add(update);
}
}
#endregion
#region 订单成本
var dbOrderCostIsEmpty = dbOrderCost == null;
if (dbOrderCostIsEmpty)
2 years ago
{
dbOrderCost = new OrderCost()
{
OrderId = request.OrderId,
IsManualEdited = false,
CreateTime = DateTime.Now
2 years ago
};
}
dbOrderCost.CalculationOrderCostAndProfit(dbOrder.OrderTotalPrice.Value, dbOrderSkuCostList.Union(insertOrderSkuCostList).ToList());
//var totalPurchaseProductAmount = request.AssociationPurchaseOrderList.Sum(x => x.PurchaseAmount);
//var totalPurchaseFreight = request.AssociationPurchaseOrderList.Sum(x => x.PurchaseFreight);
//var totalOutPackAmount = dbOrderCostDetailList.Sum(ocd => ocd.OutPackAmount);
//dbOrderCost.CalculationOrderCostAndProfit(dbOrder.OrderTotalPrice.Value,
// totalPurchaseProductAmount,
// totalPurchaseFreight,
// totalOutPackAmount ?? 0M,
// 0M);
if (dbOrderCostIsEmpty)
insertOrderCost = fsql.Insert(dbOrderCost);
2 years ago
else
updateOrderCost = fsql.Update<OrderCost>().SetSource(dbOrderCost);
#endregion
2 years ago
#region 订单状态
dbOrder.CalculationOrderState(fsql, dbOrderSkuList, dbPurchaseOrderList.Union(insertOrderPurchaseInfoList).ToList());
#endregion
#region 通知C端状态
Task.Factory.StartNew(() => SendPurchaseOrderStateToC(dbOrder.Id, dbOrder.OrderState.Value), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
#endregion
#region 查询齐库合格证
if (dbOrder.IntoStoreType == Enums.IntoStoreType. &&
notifyQikuPackSchemeParamList.Count() > 0)
{
Task.Factory.StartNew(() => qiKuManager.SearchCerConfigured(dbOrder, notifyQikuPackSchemeParamList, dbOrderSkuList), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
}
#endregion
2 years ago
fsql.Transaction(() =>
{
if (insertOrderPurchaseInfoList.Count() > 0)
fsql.Insert(insertOrderPurchaseInfoList).ExecuteAffrows();
2 years ago
if (insertOrderPurchaseSkuInfoList.Count() > 0)
fsql.Insert(insertOrderPurchaseSkuInfoList).ExecuteAffrows();
if (insertOrderPurchaseRelationInfoList.Count() > 0)
fsql.Insert(insertOrderPurchaseRelationInfoList).ExecuteAffrows();
2 years ago
if (updatePurchaseTimeLimitTaskOrderSkuList.Count() > 0)
{
fsql.Update<TimeLimitTask>().Set(t => t.CompletionTime, DateTime.Now)
.SetIf(dbOrder.PayTime != null, t => t.IsTimely == (DateTime.Now < t.ExpirationTime ? true : false))
.Where(t => t.OrderId == request.OrderId)
.Where(t => updatePurchaseTimeLimitTaskOrderSkuList.Contains(t.SkuId))
.Where(t => t.CompletionTime == null)
.Where(t => t.TaskType == Enums.TimeLimitTaskType.)
2 years ago
.ExecuteAffrows();
}
2 years ago
if (updateOrderPurchaseInfoList.Count() > 0)
{
foreach (var update in updateOrderPurchaseInfoList)
update.ExecuteAffrows();
}
if (insertOrderCostDetailList.Count() > 0)
fsql.Insert(insertOrderCostDetailList).ExecuteAffrows();
if (updateOrderCostDetailList.Count() > 0)
{
foreach (var update in updateOrderCostDetailList)
update.ExecuteAffrows();
}
insertOrderCost?.ExecuteAffrows();
updateOrderCost?.ExecuteAffrows();
2 years ago
fsql.Update<Order>(dbOrder.Id).Set(o => o.OrderState, dbOrder.OrderState)
2 years ago
.Set(o => o.IsPurchased, true)
.ExecuteAffrows();
if (insertOrderSkuCostList.Count() > 0)
fsql.Insert(insertOrderSkuCostList).ExecuteAffrows();
if (updateOrderSkuCostList.Count() > 0)
{
foreach (var update in updateOrderSkuCostList)
update.ExecuteAffrows();
}
2 years ago
});
2 years ago
}
2 years ago
/// <summary>
2 years ago
/// 预览关联订单信息(不支持关联预览的平台会返回null)
2 years ago
/// </summary>
/// <param name="request"></param>
public AssociationPurchaseOrderResponse PreviewAssocationPurchaseOrder(AssocationPurchaseOrderPreviewRequest request)
2 years ago
{
if (request.PurchasePlatform != Enums.Platform.)
return null;
2 years ago
var order = fsql.Select<Order>(request.OrderId).ToOne();
if (order == null)
throw new BusinessException("订单不存在");
2 years ago
var client = ppPlatformClientFactory.GetClient((AdapterEnums.PlatformType)request.PurchasePlatform);
var purchaseOrderSimpleInfo = client.QueryOrderDetail(new PP_QueryOrderDetailRequest()
{
AppKey = request.PurchaseAccount.AppKey,
AppSecret = request.PurchaseAccount.AppSecret,
AppToken = request.PurchaseAccount.AppToken,
OrderId = request.PurchaseOrderId
});
#region 处理采购商Id
var purchaserId = purchaseOrderSimpleInfo.PurchaserId;
if (string.IsNullOrEmpty(purchaserId))
throw new BusinessException($"采购单{request.PurchaseOrderId}缺少采购商Id");
purchaserId = purchaserId.Replace("b2b-", string.Empty);
var purchaserId2 = purchaserId.Substring(0, purchaserId.Length - 5);
var purchaserIds = new List<string>() { purchaserId, purchaserId2 };
var dbPurchaser = fsql.Select<Purchaser>().Where(p => p.Platform == Enums.Platform. && (purchaserIds.Contains(p.Id) || purchaserIds.Contains(p.Id2))).ToOne();
2 years ago
if (dbPurchaser == null)
throw new BusinessException($"采购单{request.PurchaseOrderId}缺少有效采购商");
purchaserId = dbPurchaser.Id;
#endregion
#region 查询订单Sku
var dbOrderSkuList = fsql.Select<OrderSku>().Where(osku => osku.OrderId == request.OrderId).ToList();
if (dbOrderSkuList.Count() == 0)
2 years ago
throw new BusinessException("缺少订单sku信息");
#endregion
#region 查询订单sku所有采购方案
var skuIds = dbOrderSkuList.Select(osku => osku.SkuId).ToList();
2 years ago
var purchaseSchemeList = purchaseSchemeBusiness.GetPurchaseSchemeList(new QuerySchemeRequest()
{
ShopId = order.ShopId,
SkuIdList = skuIds
});
if (purchaseSchemeList.Count() == 0)
throw new BusinessException("未匹配到采购方案");
2 years ago
#endregion
#region 匹配采购单所使用到的采购方案
var cargoParamList = new List<CargoParamRequest>();
foreach (var orderSku in dbOrderSkuList)
{
var matchResultList = MatchPurchaseScheme(orderSku.SkuId, orderSku.ItemTotal ?? 1, purchaserId, purchaseSchemeList, purchaseOrderSimpleInfo);
if (matchResultList.Count() > 0)
cargoParamList.AddRange(matchResultList);
}
if (cargoParamList.Count() == 0)
throw new BusinessException("未匹配到采购方案");
#endregion
#region 等比计算采购成本
var assocationOrderCostDetailList = new List<AssocationOrderCostDetailResponse>();
//var belongSkuGroups = cargoParamList.GroupBy(p => p.BelongSkuId);
//var purchaseSkuTotalQuantity = cargoParamList.Sum(x => x.Quantity);
//foreach (var belongSkuGroup in belongSkuGroups)
//{
// var skuId = belongSkuGroup.Key;
// //var currentOrderSkuCargoParamList = cargoParamList.Where(p => p.BelongSkuId == skuId); //找当前skuId的采购skuId
// var currentOrderSkuCargoParamList = belongSkuGroup.ToList(); //找当前skuId的采购skuId
// var currentSkuAmount = 0M; //采购成本
// var currentSkuTotalPurchaseQuantity = currentOrderSkuCargoParamList.Sum(x => x.Quantity); //当前skuId的采购数量总和
// var currentPurchaseFreight = purchaseOrderSimpleInfo.FreightAmount *
// (1.0M * currentSkuTotalPurchaseQuantity / purchaseSkuTotalQuantity); //采购运费
// foreach (var currentOrderSkuCargo in currentOrderSkuCargoParamList)
// {
// var currentPurchaseSkuProductAmount = purchaseOrderSimpleInfo.ItemList.Where(p => p.SkuId == currentOrderSkuCargo.SkuId)
// .Sum(p => p.ProductAmount);
// var currentPurchaseSkuTotalQuantity = cargoParamList.Where(p => p.SkuId == currentOrderSkuCargo.SkuId)
// .Sum(p => p.Quantity);
// currentSkuAmount += currentPurchaseSkuProductAmount * (1.0M * currentOrderSkuCargo.Quantity / currentPurchaseSkuTotalQuantity);
// }
// var orderSku = dbOrderSkuList.FirstOrDefault(osku => osku.SkuId == skuId);
// var assocationOrderCostDetail = new AssocationOrderCostDetailResponse()
// {
// Logo = orderSku.Logo,
// Title = orderSku.Title,
// SkuId = skuId,
// OrderId = orderSku.OrderId,
// SkuAmount = currentSkuAmount,
// PurchaseQuantity = orderSku.ItemTotal.Value,
// PurchaseFreight = currentPurchaseFreight
// };
// assocationOrderCostDetail.PurchasePrice = assocationOrderCostDetail.SkuAmount / assocationOrderCostDetail.PurchaseQuantity;
// assocationOrderCostDetailList.Add(assocationOrderCostDetail);
//}
var proportionalCalculationResultList = ProportionalCalculationCost(cargoParamList, purchaseOrderSimpleInfo);
foreach (var proportionalCalculationResult in proportionalCalculationResultList)
{
var skuId = proportionalCalculationResult.SkuId;
var orderSku = dbOrderSkuList.FirstOrDefault(osku => osku.SkuId == skuId);
var assocationOrderCostDetail = new AssocationOrderCostDetailResponse()
{
Logo = orderSku.Logo,
Title = orderSku.Title,
SkuId = skuId,
OrderId = orderSku.OrderId,
SkuAmount = proportionalCalculationResult.ProductAmount,
PurchaseQuantity = orderSku.ItemTotal.Value,
PurchaseFreight = proportionalCalculationResult.FreightAmount
};
assocationOrderCostDetail.PurchasePrice = assocationOrderCostDetail.SkuAmount / assocationOrderCostDetail.PurchaseQuantity;
assocationOrderCostDetailList.Add(assocationOrderCostDetail);
}
if (assocationOrderCostDetailList.Count() == 0)
throw new BusinessException("没有匹配到合适的采购方案");
#endregion
2 years ago
return new AssociationPurchaseOrderResponse(assocationOrderCostDetailList)
{
2 years ago
PurchaserId = dbPurchaser.Id,
PurchaserName = dbPurchaser.Name,
PurchaseAccountId = request.PurchaseAccount.Id,
PurchaseAccountName = request.PurchaseAccount.AccountName,
PurchaseAmount = purchaseOrderSimpleInfo.ProductAmount,
PurchaseFreight = purchaseOrderSimpleInfo.FreightAmount,
PurchaseMethod = Enums.PurchaseMethod.,
PurchaseOrderId = request.PurchaseOrderId,
PurchasePlatform = request.PurchasePlatform,
IsEnabled = true
};
2 years ago
}
/// <summary>
/// 设置历史采购单
/// </summary>
/// <param name="request"></param>
public void SetHistoryPurchaseOrder(SetHistoryPurchaseOrderRequest request)
{
nLogManager.Default().Info($"SetHistoryPurchaseOrder {JsonConvert.SerializeObject(request)}");
var orderPurchaseInfoList = fsql.Select<OrderPurchaseInfo>().Where(opi => opi.OrderId == request.OrderId && opi.IsEnabled == true).ToList();
var historyPurchaseOrder = orderPurchaseInfoList.FirstOrDefault(opi => opi.PurchaseOrderId == request.PurchaseOrderId);
if (historyPurchaseOrder == null)
throw new BusinessException("未查询到采购单");
IList<IUpdate<OrderSkuCost>> updateOrderSkuCostList = new List<IUpdate<OrderSkuCost>>();
2 years ago
var dbOrderCostDetailList = fsql.Select<OrderCostDetail>().Where(ocd => ocd.OrderId == request.OrderId &&
ocd.PurchaseOrderId != request.PurchaseOrderId &&
ocd.IsEnabled == true).ToList();
var dbOrderSkuCostList = fsql.Select<OrderSkuCost>().Where(osc => osc.OrderId == request.OrderId).ToList();
var dbOrderCost = fsql.Select<OrderCost>(request.OrderId).ToOne();
var dbOrder = fsql.Select<Order>(request.OrderId).ToOne();
var dbOrderSku = fsql.Select<OrderSku>().Where(osku => osku.OrderId == request.OrderId).ToList();
foreach (var orderSkuCost in dbOrderSkuCostList)
{
var orderSku = dbOrderSku.FirstOrDefault(osku => osku.SkuId == orderSkuCost.SkuId);
if (orderSku == null)
continue;
orderSkuCost.CalculationOrderSkuCostAndProfit(orderSku, dbOrderCostDetailList);
updateOrderSkuCostList.Add(fsql.Update<OrderSkuCost>().SetSource(orderSkuCost));
}
dbOrderCost.CalculationOrderCostAndProfit(dbOrder.OrderTotalPrice ?? 0M, dbOrderSkuCostList);
2 years ago
#region 找出失效的快递单
List<string> deleteWaybillNoList = new List<string>();
//查询该采购单所使用的快递单号
var useWaybillNos = fsql.Select<ExpressOrderRelationInfo>().Where(eori => eori.PurchaseOrderId == historyPurchaseOrder.PurchaseOrderId).ToList(eori => eori.WayBillNo);
//查询使用上述快递单号的快递单关系
var expressOrderRelationList = fsql.Select<ExpressOrderRelationInfo>().Where(eori => useWaybillNos.Contains(eori.WayBillNo)).ToList();
//以快递单号进行分组
var expressOrderRelationGroups = expressOrderRelationList.GroupBy(eori => eori.WayBillNo);
foreach (var group in expressOrderRelationGroups)
{
if (group.Count() == group.Count(eori => eori.PurchaseOrderId == historyPurchaseOrder.PurchaseOrderId))
deleteWaybillNoList.Add(group.Key);
}
#endregion
2 years ago
orderPurchaseInfoList.Remove(historyPurchaseOrder);
dbOrder.CalculationOrderState(fsql, orderPurchaseInfoList: orderPurchaseInfoList);
fsql.Transaction(() =>
{
if (request.IsDelete == true)
{
fsql.Delete<OrderPurchaseInfo>(historyPurchaseOrder.Id).ExecuteAffrows();
}
else
{
fsql.Update<OrderPurchaseInfo>(historyPurchaseOrder.Id)
.Set(opi => opi.IsEnabled, false)
.Set(opi => opi.OrderState, Enums.PurchaseOrderState.)
.Set(opi => opi.HistorySettingTime, DateTime.Now)
.Where(opi => opi.PurchaseOrderId == request.PurchaseOrderId)
.ExecuteAffrows();
}
fsql.Update<OrderCostDetail>()
.Set(ocd => ocd.IsEnabled, false)
.Where(ocd => ocd.PurchaseOrderId == request.PurchaseOrderId)
.ExecuteAffrows();
fsql.Delete<OrderPurchaseSkuInfo>().Where(opsi => opsi.PurchaseOrderId == request.PurchaseOrderId).ExecuteAffrows();
fsql.Delete<OrderPurchaseRelationInfo>().Where(opri => opri.PurchaseOrderId == request.PurchaseOrderId).ExecuteAffrows();
fsql.Delete<ExpressOrderRelationInfo>().Where(eori => eori.PurchaseOrderId == historyPurchaseOrder.PurchaseOrderId).ExecuteAffrows();
if (deleteWaybillNoList.Count() > 0)
fsql.Delete<PurchaseExpressOrder>(deleteWaybillNoList).ExecuteAffrows();
fsql.Delete<InStorePurchaseOrdeRrelationInfo>().Where(i => i.OrderId == request.OrderId && i.PurchaseOrderId == request.PurchaseOrderId)
.ExecuteAffrows();
fsql.Update<OrderCost>().SetSource(dbOrderCost).ExecuteAffrows();
2 years ago
fsql.Update<Order>(dbOrder.Id).Set(o => o.OrderState, dbOrder.OrderState).ExecuteAffrows();
if (updateOrderSkuCostList.Count() > 0)
{
foreach (var update in updateOrderSkuCostList)
update.ExecuteAffrows();
}
});
}
2 years ago
/// <summary>
/// 修改采购快递单
/// </summary>
/// <param name="request"></param>
public void EditPurchaseExpressOrder(EditPurchaseExpressOrderRequest request)
{
nLogManager.Default().Info($"EditPurchaseExpressOrder {JsonConvert.SerializeObject(request)}");
var dbOrder = fsql.Select<Order>(request.OrderId).ToOne();
2 years ago
if (dbOrder == null)
throw new BusinessException($"订单号{request.OrderId}不存在");
var shopIds = dbOrder.ShopId.ToString();
var shop = fsqlManager.MDSfsql.Select<Shops>().Where(s => s.ShopId == shopIds).ToOne();
var orderPurchaseInfoList = fsql.Select<OrderPurchaseInfo>().Where(opi => opi.OrderId == request.OrderId && opi.IsEnabled == true).ToList();
var purchaseOrder = orderPurchaseInfoList.FirstOrDefault(opi => opi.PurchaseOrderId == request.PurchaseOrderId);
if (purchaseOrder == null)
throw new BusinessException($"未查询到采购单号{request.PurchaseOrderId}");
2 years ago
IInsert<PurchaseExpressOrder> insertPEO = null;
IInsert<ExpressOrderRelationInfo> insertEORI = null;
IDelete<ExpressOrderRelationInfo> deleteEORI = null;
IDelete<PurchaseExpressOrder> deletePEO = null;
IUpdate<OrderPurchaseSkuInfo> updatePurchaseOrderSku = null;
IUpdate<OrderPurchaseInfo> updatePurchaseOrder = null;
IUpdate<Order> updateOrder = null;
var waybillNos = new List<string>() { request.OldWaybillNo, request.NewWaybillNo };
var expressOrderRelationList = fsql.Select<ExpressOrderRelationInfo>().Where(eori => waybillNos.Contains(eori.WayBillNo)).ToList();
var oldWaybillNoRelationList = expressOrderRelationList.Where(eori => eori.WayBillNo == request.OldWaybillNo).ToList();
var newWaybillNoRelationList = expressOrderRelationList.Where(eori => eori.WayBillNo == request.NewWaybillNo).ToList();
#region 旧快递单号验证
if (!oldWaybillNoRelationList.Any())
throw new BusinessException("未查询到旧快递单号");
if (!oldWaybillNoRelationList.Any(eori => eori.PurchaseOrderId == request.PurchaseOrderId))
throw new BusinessException($"旧快递单号{request.OldWaybillNo}不属于采购单{request.PurchaseOrderId},无权修改");
if (oldWaybillNoRelationList.Count() == oldWaybillNoRelationList.Count(eori => eori.PurchaseOrderId == request.PurchaseOrderId))
deletePEO = fsql.Delete<PurchaseExpressOrder>(request.OldWaybillNo);
deleteEORI = fsql.Delete<ExpressOrderRelationInfo>().Where(eori => eori.PurchaseOrderId == request.PurchaseOrderId && eori.WayBillNo == request.OldWaybillNo);
#endregion
2 years ago
#region 新快递单号验证
if (!newWaybillNoRelationList.Any(eori => eori.PurchaseOrderId == request.PurchaseOrderId))
{
var eori = new ExpressOrderRelationInfo()
{
Id = idGenerator.NewLong(),
OrderId = request.OrderId,
PurchaseOrderId = request.PurchaseOrderId,
CreateTime = DateTime.Now,
ShopId = dbOrder.ShopId,
WayBillNo = request.NewWaybillNo
};
insertEORI = fsql.Insert(eori);
}
else
throw new BusinessException("请勿重复为同一采购单设置相同的快递单号");
2 years ago
PurchaseExpressOrder newPeo = null;
if (!newWaybillNoRelationList.Any())
2 years ago
{
newPeo = new PurchaseExpressOrder()
{
WaybillNo = request.NewWaybillNo,
TargetExpressId = request.NewExpressId,
TargetExpressName = request.NewExpressName,
CreateTime = DateTime.Now,
ShopId = dbOrder.ShopId.Value,
IsSubscribeKD100 = false,
ExpressState = kuaiDi100Manager.GetExpressState(1) //快递100发货状态值 默认揽收
};
try
{
kuaiDi100Manager.SubscribeKuaiDi100(request.NewWaybillNo, request.NewExpressId, "http://bbwyb.qiyue666.com/api/purchaseorder/kuaidi100publish");
newPeo.IsSubscribeKD100 = true;
}
catch (Exception ex)
{
nLogManager.Default().Error(ex, $"EditPurchaseExpressOrder,Request:{JsonConvert.SerializeObject(request)}");
#region 订阅失败发送钉钉通知
var dingdingMsg = new StringBuilder();
dingdingMsg.AppendLine($"错误:{ex.Message}");
dingdingMsg.AppendLine($"采购订单号:{request.PurchaseOrderId}");
dingdingMsg.AppendLine($"拳探订单号:{request.OrderId}");
dingdingMsg.AppendLine($"拳探订单Sn:{dbOrder.OrderSn}");
dingdingMsg.AppendLine($"源物流公司:无");
dingdingMsg.AppendLine($"目标物流公司:{request.NewExpressName} {request.NewExpressId}");
dingdingMsg.AppendLine($"快递单号:{request.NewWaybillNo}");
dingdingMsg.AppendLine("触发环节:修改物流单号");
dingdingMsg.Append($"店铺名:{shop.ShopName}");
Task.Factory.StartNew(() => SendDingDing(dingdingMsg.ToString()), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
#endregion
}
insertPEO = fsql.Insert(newPeo);
}
#endregion
#region 更新采购sku使用的快递单号
IList<OrderPurchaseSkuInfo> orderPurchaseSkuList = null;
if (purchaseOrder.PurchasePlatform == Enums.Platform.)
2 years ago
{
orderPurchaseSkuList = fsql.Select<OrderPurchaseSkuInfo>().Where(posku => posku.PurchaseOrderId == request.PurchaseOrderId).ToList();
foreach (var posku in orderPurchaseSkuList)
{
if (posku.WaybillNo == request.OldWaybillNo)
posku.WaybillNo = request.NewWaybillNo;
}
updatePurchaseOrderSku = fsql.Update<OrderPurchaseSkuInfo>().Set(psku => psku.WaybillNo, request.NewWaybillNo)
.Where(psku => psku.PurchaseOrderId == request.PurchaseOrderId)
.Where(psku => psku.WaybillNo == request.OldWaybillNo);
2 years ago
}
#endregion
#region 计算采购单状态
var purchaseExpressOrderList = fsql.Select<ExpressOrderRelationInfo, PurchaseExpressOrder>()
.InnerJoin((eori, peo) => eori.WayBillNo == peo.WaybillNo)
.Where((eori, peo) => eori.PurchaseOrderId == request.PurchaseOrderId).ToList((eori, peo) => new PurchaseExpressOrder
{
CreateTime = peo.CreateTime,
ExpressContent = peo.ExpressContent,
ExpressChangedTime = peo.ExpressChangedTime,
ExpressState = peo.ExpressState,
IsSubscribeKD100 = peo.IsSubscribeKD100,
//OrderId = eori.OrderId,
//PurchaseOrderId = eori.PurchaseOrderId,
ShopId = eori.ShopId.Value,
SourceExpressId = peo.SourceExpressId,
SourceExpressName = peo.SourceExpressName,
TargetExpressId = peo.TargetExpressId,
TargetExpressName = peo.TargetExpressName,
WaybillNo = peo.WaybillNo
});
if (newPeo != null)
purchaseExpressOrderList.Add(newPeo);
var oldPurchaseOrderState = purchaseOrder.OrderState;
purchaseOrder.CalculationOrderState(dbOrder.IntoStoreType.Value, fsql, orderPurchaseSkuList, purchaseExpressOrderList);
if (oldPurchaseOrderState != purchaseOrder.OrderState)
updatePurchaseOrder = fsql.Update<OrderPurchaseInfo>(purchaseOrder.Id).Set(opi => opi.OrderState, purchaseOrder.OrderState);
#endregion
#region 计算订单状态
var oldOrderState = dbOrder.OrderState;
dbOrder.CalculationOrderState(fsql, null, orderPurchaseInfoList);
if (oldOrderState != dbOrder.OrderState)
2 years ago
{
updateOrder = fsql.Update<Order>(dbOrder.Id).Set(o => o.OrderState, dbOrder.OrderState);
#region 通知C端状态
Task.Factory.StartNew(() => SendPurchaseOrderStateToC(dbOrder.Id, dbOrder.OrderState.Value), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
2 years ago
#endregion
}
#endregion
2 years ago
fsql.Transaction(() =>
{
insertPEO?.ExecuteAffrows();
insertEORI?.ExecuteAffrows();
deleteEORI?.ExecuteAffrows();
deletePEO?.ExecuteAffrows();
updatePurchaseOrderSku?.ExecuteAffrows();
updatePurchaseOrder?.ExecuteAffrows();
updateOrder?.ExecuteAffrows();
2 years ago
});
}
2 years ago
/// <summary>
/// 手动发货
/// </summary>
/// <param name="request"></param>
public void ManualDelivery(ManualDeliveryRequest request)
{
nLogManager.Default().Info($"ManualDelivery {JsonConvert.SerializeObject(request)}");
if (request.ExpressId == "zhuanxianwuliu" && string.IsNullOrEmpty(request.WaybillNo))
request.WaybillNo = $"wdh{idGenerator.NewLong()}";
#region 查询当前采购单的订单信息
var dbOrder = fsql.Select<OrderPurchaseInfo, Order>().InnerJoin((opi, o) => opi.OrderId == o.Id)
.Where((opi, o) => opi.PurchaseOrderId == request.PurchaseOrderId && opi.IsEnabled == true)
.ToOne((opi, o) => new Order
{
Id = o.Id,
OrderSn = o.OrderSn,
OrderState = o.OrderState,
ShopId = o.ShopId,
IntoStoreType = o.IntoStoreType
});
if (dbOrder == null)
throw new BusinessException("未查询到采购单的订单信息");
if (dbOrder.IntoStoreType == Enums.IntoStoreType.)
throw new BusinessException("厂家代发入仓订单请使用【设置快递单和入仓采购单接口(厂家代发入仓专用)】");
#endregion
2 years ago
#region 准备数据库更新对象
List<PurchaseExpressOrder> insertPurchaseExpressOrderList = new List<PurchaseExpressOrder>();
IList<IUpdate<OrderPurchaseSkuInfo>> updateOrderPurchaseSkuList = new List<IUpdate<OrderPurchaseSkuInfo>>();
IUpdate<OrderPurchaseInfo> updateOrderPurchase = null;
IUpdate<Order> updateOrder = null;
IInsert<ExpressOrderRelationInfo> insertExpressOrderRelation = null;
2 years ago
#endregion
#region 查询该笔采购单的快递单信息
//var purchaseExpressOrderList = fsql.Select<PurchaseExpressOrder>().Where(x => x.PurchaseOrderId == request.PurchaseOrderId).ToList();
var purchaseExpressOrderList = fsql.Select<ExpressOrderRelationInfo, PurchaseExpressOrder>()
.InnerJoin((eori, peo) => eori.WayBillNo == peo.WaybillNo)
.Where((eori, peo) => eori.PurchaseOrderId == request.PurchaseOrderId).ToList((eori, peo) => new PurchaseExpressOrder
{
CreateTime = peo.CreateTime,
ExpressContent = peo.ExpressContent,
ExpressChangedTime = peo.ExpressChangedTime,
ExpressState = peo.ExpressState,
IsSubscribeKD100 = peo.IsSubscribeKD100,
//OrderId = eori.OrderId,
//PurchaseOrderId = eori.PurchaseOrderId,
ShopId = eori.ShopId.Value,
SourceExpressId = peo.SourceExpressId,
SourceExpressName = peo.SourceExpressName,
TargetExpressId = peo.TargetExpressId,
TargetExpressName = peo.TargetExpressName,
WaybillNo = peo.WaybillNo
});
2 years ago
bool isExists = purchaseExpressOrderList.Any(exo => exo.WaybillNo == request.WaybillNo);
bool isDbExists = fsql.Select<PurchaseExpressOrder>(request.WaybillNo).Any();
2 years ago
#endregion
#region 店铺信息
var shop = fsqlManager.MDSfsql.Select<Shops>().Where(s => s.ShopId == dbOrder.ShopId.ToString()).ToOne();
if (shop == null)
throw new BusinessException("未查询到采购单所属店铺");
#endregion
2 years ago
#region 查询订单的全部采购单信息
var orderPurchaseInfoList = fsql.Select<OrderPurchaseInfo>().Where(opi => opi.OrderId == dbOrder.Id && opi.IsEnabled == true).ToList();
var orderPurchaseInfo = orderPurchaseInfoList.FirstOrDefault(opi => opi.PurchaseOrderId == request.PurchaseOrderId);
if (orderPurchaseInfo == null)
throw new BusinessException("未查询到采购单信息");
#endregion
IList<OrderPurchaseSkuInfo> orderPurchaseSkuList = null;
if (orderPurchaseInfo.PurchasePlatform == Enums.Platform.)
2 years ago
{
#region 查询采购关联信息
var orderPurchaseRelationList = fsql.Select<OrderPurchaseRelationInfo>().Where(opri => opri.PurchaseOrderId == request.PurchaseOrderId &&
opri.BelongSkuId == request.SkuId).ToList();
if (orderPurchaseRelationList.Count() == 0)
throw new BusinessException("未查询到采购单的关联信息");
#endregion
#region 查询该笔采购单的采购sku信息并更新快递单号
orderPurchaseSkuList = fsql.Select<OrderPurchaseSkuInfo>().Where(x => x.PurchaseOrderId == request.PurchaseOrderId).ToList();
if (orderPurchaseSkuList.Count() == 0)
2 years ago
throw new BusinessException("未查询到采购单sku信息");
foreach (var relation in orderPurchaseRelationList)
2 years ago
{
var orderPurchaseSku = orderPurchaseSkuList.FirstOrDefault(posku => posku.PurchaseSkuId == relation.PurchaseSkuId);
if (orderPurchaseSku == null)
throw new BusinessException("未查询到采购单sku信息");
if (orderPurchaseSku.WaybillNo != request.WaybillNo)
{
orderPurchaseSku.WaybillNo = request.WaybillNo;
updateOrderPurchaseSkuList.Add(fsql.Update<OrderPurchaseSkuInfo>(orderPurchaseSku.Id).Set(ps => ps.WaybillNo, request.WaybillNo));
}
2 years ago
}
#endregion
2 years ago
}
#region 订阅快递100
bool isSubscribeKD100 = false;
if (request.ExpressId != "zhuanxianwuliu" && !isDbExists)
{
#region 订阅快递100
try
{
kuaiDi100Manager.SubscribeKuaiDi100(request.WaybillNo, request.ExpressId, "http://bbwyb.qiyue666.com/api/purchaseorder/kuaidi100publish");
isSubscribeKD100 = true;
}
catch (Exception ex)
{
nLogManager.Default().Error(ex, $"ManualDelivery,Request:{JsonConvert.SerializeObject(request)}");
#region 订阅失败发送钉钉通知
var dingdingMsg = new StringBuilder();
dingdingMsg.AppendLine($"错误:{ex.Message}");
dingdingMsg.AppendLine($"采购订单号:{request.PurchaseOrderId}");
dingdingMsg.AppendLine($"拳探订单号:{dbOrder.Id}");
dingdingMsg.AppendLine($"拳探订单Sn:{dbOrder.OrderSn}");
dingdingMsg.AppendLine($"源物流公司:无");
dingdingMsg.AppendLine($"目标物流公司:{request.ExpressName} {request.ExpressId}");
dingdingMsg.AppendLine($"快递单号:{request.WaybillNo}");
2 years ago
dingdingMsg.AppendLine("触发环节:手动发货");
dingdingMsg.Append($"店铺名:{shop.ShopName}");
Task.Factory.StartNew(() => SendDingDing(dingdingMsg.ToString()), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
#endregion
}
#endregion
}
2 years ago
#endregion
#region 创建快递单
if (!isDbExists)
2 years ago
{
var purchaseExpressOrder = new PurchaseExpressOrder()
{
//OrderId = dbOrder.Id,
2 years ago
CreateTime = DateTime.Now,
//PurchaseOrderId = request.PurchaseOrderId,
2 years ago
ShopId = dbOrder.ShopId ?? 0,
TargetExpressId = request.ExpressId,
TargetExpressName = request.ExpressName,
WaybillNo = request.WaybillNo,
ExpressState = kuaiDi100Manager.GetExpressState(1), //快递100发货状态值 默认揽收
IsSubscribeKD100 = isSubscribeKD100,
ExpressContent = "手动发货",
ExpressChangedTime = DateTime.Now
2 years ago
};
insertPurchaseExpressOrderList.Add(purchaseExpressOrder);
}
#endregion
#region 创建快递单关系
if (!isExists)
{
var expressOrderRelation = new ExpressOrderRelationInfo()
{
Id = idGenerator.NewLong(),
CreateTime = DateTime.Now,
OrderId = dbOrder.Id,
PurchaseOrderId = request.PurchaseOrderId,
ShopId = dbOrder.ShopId.Value,
WayBillNo = request.WaybillNo
};
insertExpressOrderRelation = fsql.Insert(expressOrderRelation);
if (!insertPurchaseExpressOrderList.Any(p => p.WaybillNo == request.WaybillNo))
{
purchaseExpressOrderList.Add(new PurchaseExpressOrder()
{
CreateTime = DateTime.Now,
ShopId = dbOrder.ShopId ?? 0,
TargetExpressId = request.ExpressId,
TargetExpressName = request.ExpressName,
WaybillNo = request.WaybillNo,
ExpressState = kuaiDi100Manager.GetExpressState(1), //快递100发货状态值 默认揽收
IsSubscribeKD100 = isSubscribeKD100,
ExpressContent = "手动发货",
ExpressChangedTime = DateTime.Now
});
}
}
#endregion
2 years ago
#region 计算采购单状态
orderPurchaseInfo.CalculationOrderState(dbOrder.IntoStoreType.Value, fsql, orderPurchaseSkuList, purchaseExpressOrderList.Union(insertPurchaseExpressOrderList).ToList());
2 years ago
updateOrderPurchase = fsql.Update<OrderPurchaseInfo>(orderPurchaseInfo.Id)
.Set(opi => opi.OrderState, orderPurchaseInfo.OrderState);
#endregion
#region 计算订单状态
dbOrder.CalculationOrderState(fsql, null, orderPurchaseInfoList);
2 years ago
updateOrder = fsql.Update<Order>(dbOrder.Id)
.Set(o => o.OrderState, dbOrder.OrderState);
#endregion
#region 通知C端状态
Task.Factory.StartNew(() => SendPurchaseOrderStateToC(dbOrder.Id, dbOrder.OrderState.Value), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
2 years ago
#endregion
fsql.Transaction(() =>
{
if (insertPurchaseExpressOrderList.Count() > 0)
fsql.Insert(insertPurchaseExpressOrderList).ExecuteAffrows();
if (updateOrderPurchaseSkuList.Count() > 0)
{
foreach (var update in updateOrderPurchaseSkuList)
update.ExecuteAffrows();
}
updateOrderPurchase?.ExecuteAffrows();
updateOrder?.ExecuteAffrows();
insertExpressOrderRelation?.ExecuteAffrows();
2 years ago
});
}
/// <summary>
/// 厂家代入仓订单发货
/// </summary>
/// <param name="request"></param>
public void PurchaserDelivery(PurchaserDeliveryRequest request)
{
nLogManager.Default().Info($"PurchaserDelivery {JsonConvert.SerializeObject(request)}");
var dbOrder = fsql.Select<Order>(request.OrderId).ToOne();
if (dbOrder == null)
throw new BusinessException("订单不存在");
if (dbOrder.IntoStoreType != Enums.IntoStoreType.)
throw new BusinessException("此订单非厂商代发入仓");
if (request.InStorePurchaseOrderManualDeliveryList.Count() == 0)
throw new BusinessException("缺少快递信息");
if (request.InStorePurchaseOrderManualDeliveryList.Any(x => x.InStorePurchaseOrderIdList.Count() == 0))
throw new BusinessException("缺少入仓采购单信息");
if (request.InStorePurchaseOrderManualDeliveryList.Any(x => x.InStorePurchaseOrderIdList.Count() != x.InStorePurchaseOrderIdList.Distinct().Count()))
throw new BusinessException("同一个快递单下不允许出现重复的入仓采购单");
List<PurchaseExpressOrder> insertPurchaseExpressOrderList = new List<PurchaseExpressOrder>();
List<ExpressOrderRelationInfo> insertExpressOrderRelationList = new List<ExpressOrderRelationInfo>();
List<InStorePurchaseOrdeRrelationInfo> insertInStorePurchaseOrderRelationList = new List<InStorePurchaseOrdeRrelationInfo>();
//IList<IUpdate<OrderPurchaseSkuInfo>> updateOrderPurchaseSkuList = new List<IUpdate<OrderPurchaseSkuInfo>>();
IUpdate<OrderPurchaseInfo> updateOrderPurchase = null;
IUpdate<Order> updateOrder = null;
#region 查询该笔采购单的快递单信息
//var purchaseExpressOrderList = fsql.Select<PurchaseExpressOrder>().Where(x => x.PurchaseOrderId == request.PurchaseOrderId).ToList();
var purchaseExpressOrderList = fsql.Select<ExpressOrderRelationInfo, PurchaseExpressOrder>()
.InnerJoin((eori, peo) => eori.WayBillNo == peo.WaybillNo)
.Where((eori, peo) => eori.PurchaseOrderId == request.PurchaseOrderId).ToList((eori, peo) => new PurchaseExpressOrder
{
CreateTime = peo.CreateTime,
ExpressContent = peo.ExpressContent,
ExpressChangedTime = peo.ExpressChangedTime,
ExpressState = peo.ExpressState,
IsSubscribeKD100 = peo.IsSubscribeKD100,
//OrderId = eori.OrderId,
//PurchaseOrderId = eori.PurchaseOrderId,
ShopId = eori.ShopId.Value,
SourceExpressId = peo.SourceExpressId,
SourceExpressName = peo.SourceExpressName,
TargetExpressId = peo.TargetExpressId,
TargetExpressName = peo.TargetExpressName,
WaybillNo = peo.WaybillNo
});
var wayBillNos = request.InStorePurchaseOrderManualDeliveryList.Select(x => x.WaybillNo).ToList();
var dbPurchaseExpressOrderList = fsql.Select<PurchaseExpressOrder>(wayBillNos).ToList();
#endregion
#region 查询该订单的入库采购单关系
var dbInStoreRelationList = fsql.Select<InStorePurchaseOrdeRrelationInfo>().Where(x => x.OrderId == request.OrderId).ToList();
#endregion
#region 店铺信息
var shop = fsqlManager.MDSfsql.Select<Shops>().Where(s => s.ShopId == dbOrder.ShopId.ToString()).ToOne();
if (shop == null)
throw new BusinessException("未查询到采购单所属店铺");
#endregion
#region 查询订单的全部采购单信息
var orderPurchaseInfoList = fsql.Select<OrderPurchaseInfo>().Where(opi => opi.OrderId == dbOrder.Id && opi.IsEnabled == true).ToList();
var orderPurchaseInfo = orderPurchaseInfoList.FirstOrDefault(opi => opi.PurchaseOrderId == request.PurchaseOrderId);
if (orderPurchaseInfo == null)
throw new BusinessException("未查询到采购单信息");
#endregion
foreach (var peoRequest in request.InStorePurchaseOrderManualDeliveryList)
{
bool isExists = purchaseExpressOrderList.Any(exo => exo.WaybillNo == peoRequest.WaybillNo);
bool isDbExists = dbPurchaseExpressOrderList.Any(exo => exo.WaybillNo == peoRequest.WaybillNo);
#region 订阅快递100
bool isSubscribeKD100 = false;
if (peoRequest.ExpressId != "zhuanxianwuliu" && !isDbExists)
{
try
{
kuaiDi100Manager.SubscribeKuaiDi100(peoRequest.WaybillNo, peoRequest.ExpressId, "http://bbwyb.qiyue666.com/api/purchaseorder/kuaidi100publish");
isSubscribeKD100 = true;
}
catch (Exception ex)
{
if (!ex.Message.Contains("重复订阅"))
{
nLogManager.Default().Error(ex, $"ManualDelivery,Request:{JsonConvert.SerializeObject(request)}");
#region 订阅失败发送钉钉通知
var dingdingMsg = new StringBuilder();
dingdingMsg.AppendLine($"错误:{ex.Message}");
dingdingMsg.AppendLine($"采购订单号:{request.PurchaseOrderId}");
dingdingMsg.AppendLine($"拳探订单号:{dbOrder.Id}");
dingdingMsg.AppendLine($"拳探订单Sn:{dbOrder.OrderSn}");
dingdingMsg.AppendLine($"源物流公司:无");
dingdingMsg.AppendLine($"目标物流公司:{peoRequest.ExpressName} {peoRequest.ExpressId}");
dingdingMsg.AppendLine($"快递单号:{peoRequest.WaybillNo}");
dingdingMsg.AppendLine("触发环节:厂家代发入仓手动发货");
dingdingMsg.Append($"店铺名:{shop.ShopName}");
Task.Factory.StartNew(() => SendDingDing(dingdingMsg.ToString()), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
#endregion
}
}
}
#endregion
#region 创建快递单
if (!isDbExists)
{
var purchaseExpressOrder = new PurchaseExpressOrder()
{
//OrderId = dbOrder.Id,
CreateTime = DateTime.Now,
//PurchaseOrderId = request.PurchaseOrderId,
ShopId = dbOrder.ShopId ?? 0,
TargetExpressId = peoRequest.ExpressId,
TargetExpressName = peoRequest.ExpressName,
WaybillNo = peoRequest.WaybillNo,
ExpressState = kuaiDi100Manager.GetExpressState(1), //快递100发货状态值 默认揽收
IsSubscribeKD100 = isSubscribeKD100,
ExpressContent = "手动发货",
ExpressChangedTime = DateTime.Now
};
insertPurchaseExpressOrderList.Add(purchaseExpressOrder);
}
#endregion
#region 创建快递单关系
if (!isExists)
{
var expressOrderRelation = new ExpressOrderRelationInfo()
{
Id = idGenerator.NewLong(),
CreateTime = DateTime.Now,
OrderId = dbOrder.Id,
PurchaseOrderId = request.PurchaseOrderId,
ShopId = dbOrder.ShopId.Value,
WayBillNo = peoRequest.WaybillNo
};
insertExpressOrderRelationList.Add(expressOrderRelation);
if (!insertPurchaseExpressOrderList.Any(p => p.WaybillNo == peoRequest.WaybillNo))
{
purchaseExpressOrderList.Add(new PurchaseExpressOrder()
{
CreateTime = DateTime.Now,
ShopId = dbOrder.ShopId ?? 0,
TargetExpressId = peoRequest.ExpressId,
TargetExpressName = peoRequest.ExpressName,
WaybillNo = peoRequest.WaybillNo,
ExpressState = kuaiDi100Manager.GetExpressState(1), //快递100发货状态值 默认揽收
IsSubscribeKD100 = isSubscribeKD100,
ExpressContent = "手动发货",
ExpressChangedTime = DateTime.Now
});
}
}
#endregion
#region 入库采购单号
var waitInsertInStoreRelationList = peoRequest.InStorePurchaseOrderIdList.Where(x => !dbInStoreRelationList.Any(r => r.WaybillNo == peoRequest.WaybillNo &&
r.InStorePurchaseOrderId == x)).ToList();
if (waitInsertInStoreRelationList.Count() > 0)
{
insertInStorePurchaseOrderRelationList.AddRange(waitInsertInStoreRelationList.Select(x => new InStorePurchaseOrdeRrelationInfo()
{
CreateTime = DateTime.Now,
Id = idGenerator.NewLong(),
InStorePurchaseOrderId = x,
OrderId = request.OrderId,
PurchaseOrderId = request.PurchaseOrderId,
ShopId = dbOrder.ShopId,
WaybillNo = peoRequest.WaybillNo
}));
}
#endregion
}
#region 计算采购单状态
orderPurchaseInfo.CalculationOrderState(dbOrder.IntoStoreType.Value, fsql, null, purchaseExpressOrderList.Union(insertPurchaseExpressOrderList).ToList());
updateOrderPurchase = fsql.Update<OrderPurchaseInfo>(orderPurchaseInfo.Id)
.Set(opi => opi.OrderState, orderPurchaseInfo.OrderState);
#endregion
#region 计算订单状态
dbOrder.CalculationOrderState(fsql, null, orderPurchaseInfoList);
updateOrder = fsql.Update<Order>(dbOrder.Id)
.Set(o => o.OrderState, dbOrder.OrderState);
#endregion
#region 通知C端状态
Task.Factory.StartNew(() => SendPurchaseOrderStateToC(dbOrder.Id, dbOrder.OrderState.Value), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
#endregion
fsql.Transaction(() =>
{
if (insertPurchaseExpressOrderList.Count() > 0)
fsql.Insert(insertPurchaseExpressOrderList).ExecuteAffrows();
if (insertExpressOrderRelationList.Count() > 0)
fsql.Insert(insertExpressOrderRelationList).ExecuteAffrows();
if (insertInStorePurchaseOrderRelationList.Count() > 0)
fsql.Insert(insertInStorePurchaseOrderRelationList).ExecuteAffrows();
//if (updateOrderPurchaseSkuList.Count() > 0)
//{
// foreach (var update in updateOrderPurchaseSkuList)
// update.ExecuteAffrows();
//}
updateOrderPurchase?.ExecuteAffrows();
updateOrder?.ExecuteAffrows();
});
}
2 years ago
public void ManualSign(ManualSignRequest request)
{
Task.Factory.StartNew(() => OnExpressOrderChange(request.WayBillNo, "QianShou", DateTime.Now, "手动签收"),
CancellationToken.None,
TaskCreationOptions.LongRunning,
taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
}
public void BatchManualSign(BatchManualSignRequest request)
{
if (request.WayBillNoList == null || request.WayBillNoList.Count() == 0)
throw new BusinessException("缺少快递单号");
if (request.WayBillNoList.Distinct().Count() < request.WayBillNoList.Count())
throw new BusinessException("不允许重复的快递单号");
Task.Factory.StartNew(() =>
{
foreach (var waybillNo in request.WayBillNoList)
OnExpressOrderChange(waybillNo, "QianShou", DateTime.Now, "手动签收");
}, CancellationToken.None,
TaskCreationOptions.LongRunning,
taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
}
///// <summary>
///// 手动收货
///// </summary>
///// <param name="request"></param>
//public void ManualSign(ManualSignRequest request)
//{
// IList<IUpdate<PurchaseExpressOrder>> updatePurchaseExpressOrderList = new List<IUpdate<PurchaseExpressOrder>>();
// IUpdate<OrderPurchaseInfo> updateOrderPurchase = null;
// IUpdate<Order> updateOrder = null;
// #region 查询该笔采购单的快递单信息
// var purchaseExpressOrderList = fsql.Select<PurchaseExpressOrder>().Where(x => x.PurchaseOrderId == request.PurchaseOrderId).ToList();
// #endregion
// #region 查询当前采购单的订单信息
// var dbOrder = fsql.Select<OrderPurchaseInfo, Order>().InnerJoin((opi, o) => opi.OrderId == o.Id)
// .Where((opi, o) => opi.PurchaseOrderId == request.PurchaseOrderId && opi.IsEnabled == true)
// .ToOne((opi, o) => new Order
// {
// Id = o.Id,
// OrderState = o.OrderState,
// ShopId = o.ShopId
// });
// if (dbOrder == null)
// throw new BusinessException("未查询到采购单的订单信息");
// #endregion
// #region 查询订单的全部采购单信息
// var orderPurchaseInfoList = fsql.Select<OrderPurchaseInfo>().Where(opi => opi.OrderId == dbOrder.Id && opi.IsEnabled == true).ToList();
// var orderPurchaseInfo = orderPurchaseInfoList.FirstOrDefault(opi => opi.PurchaseOrderId == request.PurchaseOrderId);
// if (orderPurchaseInfo == null)
// throw new BusinessException("未查询到采购单信息");
// #endregion
// IList<OrderPurchaseSkuInfo> orderPurchaseSkuList = null;
// IList<OrderPurchaseRelationInfo> orderPurchaseRelationList = null;
// if (orderPurchaseInfo.PurchasePlatform == Enums.Platform.阿里巴巴)
// {
// #region 查询采购关联信息
// orderPurchaseRelationList = fsql.Select<OrderPurchaseRelationInfo>().Where(opri => opri.PurchaseOrderId == request.PurchaseOrderId &&
// opri.BelongSkuId == request.SkuId).ToList();
// if (orderPurchaseRelationList.Count() == 0)
// throw new BusinessException("未查询到采购单的关联信息");
// #endregion
2 years ago
// #region 查询该笔采购单的采购sku信息
// orderPurchaseSkuList = fsql.Select<OrderPurchaseSkuInfo>().Where(x => x.PurchaseOrderId == request.PurchaseOrderId).ToList();
// if (orderPurchaseSkuList.Count() == 0)
// throw new BusinessException("未查询到采购单sku信息");
// #endregion
// #region 更新采购sku的快递单状态为签收
// foreach (var relation in orderPurchaseRelationList)
// {
// var orderPurchaseSku = orderPurchaseSkuList.FirstOrDefault(posku => posku.PurchaseSkuId == relation.PurchaseSkuId);
// if (orderPurchaseSku == null)
// throw new BusinessException("未查询到采购单sku信息");
// if (!string.IsNullOrEmpty(orderPurchaseSku.WaybillNo))
// {
// var purchaseExpressOrder = purchaseExpressOrderList.FirstOrDefault(exo => exo.WaybillNo == orderPurchaseSku.WaybillNo);
// if (purchaseExpressOrder == null)
// throw new BusinessException("未查询到采购sku的快递信息");
// var expressState = kuaiDi100Manager.GetExpressState(3);
// if (purchaseExpressOrder.ExpressState != expressState)
// {
// purchaseExpressOrder.ExpressState = expressState;
// updatePurchaseExpressOrderList.Add(fsql.Update<PurchaseExpressOrder>(purchaseExpressOrder.WaybillNo)
// .Set(exo => exo.ExpressState, purchaseExpressOrder.ExpressState)
// .Set(exo => exo.ExpressChangedTime, DateTime.Now)
// .Set(exo => exo.ExpressContent, "手动签收"));
// }
// }
// }
// #endregion
// }
// else
// {
// foreach (var purchaseExpressOrder in purchaseExpressOrderList)
// {
// var expressState = kuaiDi100Manager.GetExpressState(3);
// if (purchaseExpressOrder.ExpressState != expressState)
// {
// purchaseExpressOrder.ExpressState = expressState;
// updatePurchaseExpressOrderList.Add(fsql.Update<PurchaseExpressOrder>(purchaseExpressOrder.WaybillNo)
// .Set(exo => exo.ExpressState, purchaseExpressOrder.ExpressState)
// .Set(exo => exo.ExpressChangedTime, DateTime.Now)
// .Set(exo => exo.ExpressContent, "手动签收"));
// }
// }
// }
// #region 计算采购单状态
// orderPurchaseInfo.CalculationOrderState(fsql, orderPurchaseSkuList, purchaseExpressOrderList);
// updateOrderPurchase = fsql.Update<OrderPurchaseInfo>(orderPurchaseInfo.Id)
// .Set(opi => opi.OrderState, orderPurchaseInfo.OrderState);
// #endregion
// #region 计算订单状态
// dbOrder.CalculationOrderState(fsql, null, orderPurchaseInfoList);
// updateOrder = fsql.Update<Order>(dbOrder.Id)
// .Set(o => o.OrderState, dbOrder.OrderState);
// #endregion
// #region 通知齐库打包落仓情况
// Task.Factory.StartNew(() => qiKuManager.PublishQiKu(orderPurchaseInfo, orderPurchaseRelationList, orderPurchaseSkuList, purchaseExpressOrderList),
// CancellationToken.None,
// TaskCreationOptions.LongRunning,
// taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
// #endregion
// #region 通知C端状态
// Task.Factory.StartNew(() => SendPurchaseOrderStateToC(dbOrder.Id, dbOrder.OrderState.Value), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
// #endregion
// fsql.Transaction(() =>
// {
// if (updatePurchaseExpressOrderList.Count() > 0)
// {
// foreach (var update in updatePurchaseExpressOrderList)
// update.ExecuteAffrows();
// }
// updateOrderPurchase?.ExecuteAffrows();
// updateOrder?.ExecuteAffrows();
// });
//}
2 years ago
///// <summary>
///// 签收采购单
///// </summary>
///// <param name="request"></param>
//public void SignPurchaseOrder(SignPurchaseOrderRequest request)
//{
// var dbOrder = fsql.Select<Order>(request.OrderId).ToOne();
// if (dbOrder == null)
// throw new BusinessException("无效订单号");
// if (dbOrder.OrderState == Enums.OrderState.已取消)
// throw new BusinessException("订单已取消");
// if (dbOrder.OrderState == Enums.OrderState.已完成)
// throw new BusinessException("订单已完成无需签收");
// var dbOrderPurchaseInfoList = fsql.Select<OrderPurchaseInfo>().Where(opi => opi.OrderId == request.OrderId && opi.IsEnabled == true).ToList();
// var dbOrderPurchaseInfo = dbOrderPurchaseInfoList.FirstOrDefault(opi => opi.PurchaseOrderId == request.PurchaseOrderId);
// if (dbOrderPurchaseInfo == null)
// throw new BusinessException("无效采购单号");
// if (!dbOrderPurchaseInfo.IsEnabled)
// throw new BusinessException("采购单已失效");
// if (dbOrderPurchaseInfo.OrderState == Enums.PurchaseOrderState.已签收 ||
// dbOrderPurchaseInfo.IsSign == true)
// throw new BusinessException("采购单已签收");
// dbOrderPurchaseInfo.IsSign = true;
// dbOrderPurchaseInfo.OrderState = Enums.PurchaseOrderState.已签收;
// dbOrder.CalculationOrderState(fsql, null, dbOrderPurchaseInfoList);
// fsql.Transaction(() =>
// {
// fsql.Update<OrderPurchaseInfo>().SetSource(dbOrderPurchaseInfo).ExecuteAffrows();
// fsql.Update<Order>(dbOrder.Id)
// .Set(o => o.OrderState, dbOrder.OrderState)
// .Set(o => o.IsWaitPack, true).ExecuteAffrows();
// });
//}
#region 1688CallBack
public void CallbackFrom1688(string jsonStr)
{
nLogManager.Default().Info(jsonStr);
var jObject = JObject.Parse(jsonStr);
var type = jObject.Value<string>("type").ToUpper();
switch (type)
{
case "ORDER_BUYER_VIEW_PART_PART_SENDGOODS": //部分发货
case "ORDER_BUYER_VIEW_ANNOUNCE_SENDGOODS": //发货
DeliveryCallbackFrom1688(jObject);
break;
case "ORDER_BUYER_VIEW_ORDER_PRICE_MODIFY":
OrderPriceModificationCallbackFrom1688(jObject); //订单改价
break;
case "LOGISTICS_BUYER_VIEW_TRACE":
// LogisticsUpdateCallbackFrom1688(jObject);//1688物流信息变更
break;
case "ORDER_BUYER_VIEW_ORDER_PAY":
OrderPayFrom1688(jObject);
break;
default:
break;
}
}
/// <summary>
/// 1688发货回调
/// </summary>
/// <param name="jObject"></param>
private void DeliveryCallbackFrom1688(JObject jObject)
{
var purchaseOrderId = jObject["data"].Value<string>("orderId");
Task.Factory.StartNew(() => DeliveryCallbackFrom1688(purchaseOrderId), CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
}
/// <summary>
/// 1688发货回调
/// </summary>
/// <param name="purchaseOrderId">采购单</param>
private void DeliveryCallbackFrom1688(string purchaseOrderId)
{
string orderId = string.Empty;
long? shopId = null;
string currentProgress = string.Empty;
string wayBillNoResponseInfo = string.Empty;
try
{
2 years ago
#region 查询当前采购单的订单信息
currentProgress = "查询当前采购单的订单信息";
var dbOrder = fsql.Select<OrderPurchaseInfo, Order>().InnerJoin((opi, o) => opi.OrderId == o.Id)
.Where((opi, o) => opi.PurchaseOrderId == purchaseOrderId && opi.IsEnabled == true)
.ToOne((opi, o) => new Order
{
Id = o.Id,
OrderSn = o.OrderSn,
2 years ago
OrderState = o.OrderState,
2 years ago
ShopId = o.ShopId,
IntoStoreType = o.IntoStoreType
2 years ago
});
if (dbOrder == null)
throw new Exception("未查询到采购单的订单信息");
if (dbOrder.IntoStoreType == Enums.IntoStoreType.)
return;
List<PurchaseExpressOrder> insertPurchaseExpressOrderList = new List<PurchaseExpressOrder>();
List<ExpressOrderRelationInfo> insertExpressOrderRelationInfoList = new List<ExpressOrderRelationInfo>();
IList<IUpdate<OrderPurchaseSkuInfo>> updateOrderPurchaseSkuList = new List<IUpdate<OrderPurchaseSkuInfo>>();
IUpdate<OrderPurchaseInfo> updateOrderPurchase = null;
IUpdate<Order> updateOrder = null;
2 years ago
orderId = dbOrder.Id;
shopId = dbOrder.ShopId;
#endregion
#region 店铺信息
var shop = fsqlManager.MDSfsql.Select<Shops>().Where(s => s.ShopId == dbOrder.ShopId.ToString()).ToOne();
if (shop == null)
throw new BusinessException("未查询到采购单所属店铺");
#endregion
2 years ago
#region 查询订单的全部采购单信息
currentProgress = "查询订单的全部采购单信息";
var orderPurchaseInfoList = fsql.Select<OrderPurchaseInfo>().Where(opi => opi.OrderId == orderId && opi.IsEnabled == true).ToList();
var orderPurchaseInfo = orderPurchaseInfoList.FirstOrDefault(opi => opi.PurchaseOrderId == purchaseOrderId);
#endregion
#region 查询该笔采购单的sku信息
currentProgress = "查询该笔采购单的sku信息";
var orderPurchaseSkuList = fsql.Select<OrderPurchaseSkuInfo>().Where(x => x.PurchaseOrderId == purchaseOrderId).ToList();
#endregion
#region 查询该笔采购单的快递单信息
currentProgress = "查询该笔采购单的快递单信息";
//var purchaseExpressOrderList = fsql.Select<PurchaseExpressOrder>().Where(x => x.PurchaseOrderId == purchaseOrderId).ToList();
var purchaseExpressOrderList = fsql.Select<ExpressOrderRelationInfo, PurchaseExpressOrder>()
.InnerJoin((eori, peo) => eori.WayBillNo == peo.WaybillNo)
.Where((eori, peo) => eori.PurchaseOrderId == purchaseOrderId).ToList((eori, peo) => new PurchaseExpressOrder
{
CreateTime = peo.CreateTime,
ExpressContent = peo.ExpressContent,
ExpressChangedTime = peo.ExpressChangedTime,
ExpressState = peo.ExpressState,
IsSubscribeKD100 = peo.IsSubscribeKD100,
OrderId = eori.OrderId,
PurchaseOrderId = eori.PurchaseOrderId,
ShopId = eori.ShopId.Value,
SourceExpressId = peo.SourceExpressId,
SourceExpressName = peo.SourceExpressName,
TargetExpressId = peo.TargetExpressId,
TargetExpressName = peo.TargetExpressName,
WaybillNo = peo.WaybillNo
});
#endregion
#region 查询采购账号
currentProgress = "查询采购账号";
var purchaseAccount = fsqlManager.MDSfsql.Select<Purchaseaccount>().Where(pa => pa.Id == orderPurchaseInfo.PurchaseAccountId).ToOne();
if (purchaseAccount == null)
throw new Exception($"未查询到采购账号{orderPurchaseInfo.PurchaseAccountId}");
#endregion
#region 获取采购单的物流信息
currentProgress = "获取采购单的物流信息";
var client = ppPlatformClientFactory.GetClient(AdapterEnums.PlatformType.);
var ppQueryOrderLogisticsRequest = new PP_QueryOrderLogisticsRequest()
{
AppKey = purchaseAccount.AppKey,
AppSecret = purchaseAccount.AppSecret,
AppToken = purchaseAccount.AppToken,
OrderId = purchaseOrderId,
Platform = AdapterEnums.PlatformType.
};
var logisticsList = client.QueryOrderLogistics(ppQueryOrderLogisticsRequest);
wayBillNoResponseInfo = JsonConvert.SerializeObject(new { purchaseOrderId, logisticsList });
var wayBillNos = logisticsList.Where(w => !string.IsNullOrEmpty(w.WayBillNo)).Select(w => w.WayBillNo).ToList();
var dbWayBillNos = fsql.Select<PurchaseExpressOrder>(wayBillNos).ToList(w => w.WaybillNo);
#endregion
#region 找出新发货的快递单
foreach (var logisticsInfo in logisticsList)
{
if (string.IsNullOrEmpty(logisticsInfo.WayBillNo) ||
purchaseExpressOrderList.Any(po => po.WaybillNo == logisticsInfo.WayBillNo))
continue;
2 years ago
#region 订阅快递100
currentProgress = "订阅快递100";
LogisticsCompanyRelationship kuaidi100Company = null;
bool isSubscribeKD100 = false;
try
{
kuaidi100Company = expressCompanyNameConverter.ConverterToKuaiDi100Company(logisticsInfo.ExpressName);
if (kuaidi100Company == null)
throw new Exception($"无翻译结果");
kuaiDi100Manager.SubscribeKuaiDi100(logisticsInfo.WayBillNo, kuaidi100Company.TargetCode, "http://bbwyb.qiyue666.com/api/purchaseorder/kuaidi100publish");
isSubscribeKD100 = true;
}
catch (Exception ex)
{
if (!ex.Message.Contains("重复订阅"))
{
nLogManager.Default().Error(ex, $"DeliveryCallback 回调平台1688,订单号{orderId},采购单号{purchaseOrderId},执行进度[{currentProgress}],采购单物流信息:{wayBillNoResponseInfo}");
#region 订阅失败发送钉钉通知
var dingdingMsg = new StringBuilder();
dingdingMsg.AppendLine($"错误:{ex.Message}");
dingdingMsg.AppendLine($"采购订单号:{purchaseOrderId}");
dingdingMsg.AppendLine($"拳探订单号:{orderId}");
dingdingMsg.AppendLine($"拳探订单Sn:{dbOrder.OrderSn}");
dingdingMsg.AppendLine($"源物流公司:{logisticsInfo.ExpressName}");
dingdingMsg.AppendLine($"目标物流公司:{kuaidi100Company?.TargetName} {kuaidi100Company?.TargetCode}");
dingdingMsg.AppendLine($"快递单号:{logisticsInfo.WayBillNo}");
dingdingMsg.AppendLine("触发环节:1688发货回调");
dingdingMsg.Append($"店铺名:{shop.ShopName}");
Task.Factory.StartNew(() => SendDingDing(dingdingMsg.ToString()), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
#endregion
if (ex.Message.Contains("无翻译结果"))
throw;
}
}
2 years ago
#endregion
#region 创建快递单
if (!dbWayBillNos.Contains(logisticsInfo.WayBillNo))
{
var purchaseExpressOrder = new PurchaseExpressOrder()
{
//OrderId = orderId,
CreateTime = DateTime.Now,
//PurchaseOrderId = purchaseOrderId,
ShopId = shopId ?? 0,
SourceExpressId = logisticsInfo.ExpressId,
SourceExpressName = logisticsInfo.ExpressName,
WaybillNo = logisticsInfo.WayBillNo,
TargetExpressId = kuaidi100Company?.TargetCode,
TargetExpressName = kuaidi100Company?.TargetName,
ExpressState = kuaiDi100Manager.GetExpressState(1), //快递100发货状态值 默认揽收
IsSubscribeKD100 = isSubscribeKD100
};
insertPurchaseExpressOrderList.Add(purchaseExpressOrder);
}
#endregion
#region 更新采购sku的快递单号
foreach (var orderEntryId in logisticsInfo.OrderEntryIds)
{
var purchaseSku = orderPurchaseSkuList.FirstOrDefault(x => x.Id == orderEntryId);
if (purchaseSku == null)
continue;
purchaseSku.WaybillNo = logisticsInfo.WayBillNo;
updateOrderPurchaseSkuList.Add(fsql.Update<OrderPurchaseSkuInfo>(orderEntryId).Set(ps => ps.WaybillNo, logisticsInfo.WayBillNo));
}
#endregion
#region 创建快递关系
insertExpressOrderRelationInfoList.Add(new ExpressOrderRelationInfo()
{
Id = idGenerator.NewLong(),
CreateTime = DateTime.Now,
OrderId = dbOrder.Id,
PurchaseOrderId = purchaseOrderId,
ShopId = dbOrder.ShopId,
WayBillNo = logisticsInfo.WayBillNo
});
#endregion
}
#endregion
#region 计算采购单状态
orderPurchaseInfo.CalculationOrderState(dbOrder.IntoStoreType.Value, fsql, orderPurchaseSkuList, purchaseExpressOrderList.Union(insertPurchaseExpressOrderList).ToList());
2 years ago
updateOrderPurchase = fsql.Update<OrderPurchaseInfo>(orderPurchaseInfo.Id)
.Set(opi => opi.OrderState, orderPurchaseInfo.OrderState);
#endregion
#region 计算订单状态
dbOrder.CalculationOrderState(fsql, null, orderPurchaseInfoList);
2 years ago
updateOrder = fsql.Update<Order>(dbOrder.Id)
.Set(o => o.OrderState, dbOrder.OrderState);
#endregion
#region 通知C端订单状态
Task.Factory.StartNew(() => SendPurchaseOrderStateToC(dbOrder.Id, dbOrder.OrderState.Value), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
#endregion
fsql.Transaction(() =>
{
if (insertExpressOrderRelationInfoList.Count() > 0)
fsql.Insert(insertExpressOrderRelationInfoList).ExecuteAffrows();
2 years ago
if (insertPurchaseExpressOrderList.Count() > 0)
fsql.Insert(insertPurchaseExpressOrderList).ExecuteAffrows();
if (updateOrderPurchaseSkuList.Count() > 0)
{
foreach (var update in updateOrderPurchaseSkuList)
update.ExecuteAffrows();
}
updateOrderPurchase?.ExecuteAffrows();
updateOrder?.ExecuteAffrows();
});
}
catch (Exception ex)
{
nLogManager.Default().Error(ex, $"DeliveryCallback 回调平台1688,订单号{orderId},采购单号{purchaseOrderId},执行进度[{currentProgress}],采购单物流信息:{wayBillNoResponseInfo}");
}
}
/// <summary>
/// 1688订单改价回调
/// </summary>
/// <param name="jObject"></param>
private void OrderPriceModificationCallbackFrom1688(JObject jObject)
{
2 years ago
var purchaseOrderId = jObject["data"].Value<string>("orderId");
Task.Factory.StartNew(() => OrderPriceModificationCallback(purchaseOrderId, Enums.Platform.), CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
}
private void OrderPayFrom1688(JObject jObject)
{
var purchaseOrderId = jObject["data"].Value<string>("orderId");
Task.Factory.StartNew(() => OrderPayCallback(purchaseOrderId, Enums.Platform.), CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
}
#endregion
2 years ago
/// <summary>
/// 采购平台改价回调
/// </summary>
/// <param name="purchaseOrderId"></param>
/// <param name="callbackPlatform"></param>
private void OrderPriceModificationCallback(string purchaseOrderId, Enums.Platform callbackPlatform)
{
OnSomeOnePurchaseOrderChanged(purchaseOrderId, true);
}
2 years ago
private void OrderPayCallback(string purchaseOrderId, Enums.Platform callbackPlatform)
{
OnSomeOnePurchaseOrderChanged(purchaseOrderId, false);
2 years ago
}
public void KuaiDi100Publish(string param)
{
nLogManager.GetLogger("快递100").Info($"KuaiDi100Publish {param}");
try
{
JObject jobject = JObject.Parse(param);
var waybillNo = jobject["lastResult"].Value<string>("nu");
var state = jobject["lastResult"].Value<int>("state");
var convertState = kuaiDi100Manager.GetExpressState(state);
if (convertState == "Unknow")
return;
var dataArray = jobject["lastResult"]["data"].Children().Select(d => new
{
context = d.Value<string>("context"),
ftime = d.Value<DateTime>("ftime"),
statusCode = d.Value<int>("statusCode")
}).OrderByDescending(d => d.ftime).ToList();
var lastData = dataArray.FirstOrDefault();
Task.Factory.StartNew(() => OnExpressOrderChange(waybillNo, convertState, lastData.ftime, lastData.context),
CancellationToken.None,
TaskCreationOptions.LongRunning,
taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
}
catch (Exception ex)
{
nLogManager.GetLogger("快递100").Error(ex, $"KuaiDi100Publish-{param}");
}
}
/// <summary>
/// 快递单信息变更
/// </summary>
/// <param name="wayBillNo"></param>
/// <param name="state"></param>
/// <param name="expressChangeTime"></param>
/// <param name="expressContent"></param>
private void OnExpressOrderChange(string wayBillNo, string state, DateTime expressChangeTime, string expressContent)
{
try
{
IUpdate<PurchaseExpressOrder> updatePurchaseExpressOrder = null;
List<IUpdate<OrderPurchaseInfo>> updateOrderPurchaseList = new List<IUpdate<OrderPurchaseInfo>>();
List<IUpdate<Order>> updateOrderList = new List<IUpdate<Order>>();
List<TimeLimitTask> insertTimeLimitTaskList = new List<TimeLimitTask>();
List<InStoreOrderCheckTask> insertInStoreOrderCheckTaskList = new List<InStoreOrderCheckTask>();
#region 查询该笔快递单
var tpeo = fsql.Select<PurchaseExpressOrder>(wayBillNo).ToOne();
if (tpeo == null)
throw new Exception("未查询到快递单");
#endregion
#region 查询和该快递单有关的订单 (多笔订单)
var orderIds = fsql.Select<ExpressOrderRelationInfo, PurchaseExpressOrder>()
.InnerJoin((eori, peo) => eori.WayBillNo == peo.WaybillNo)
.Where((eori, peo) => eori.WayBillNo == wayBillNo)
.GroupBy((eori, peo) => eori.OrderId)
.ToList(g => g.Key);
if (orderIds.Count() == 0)
throw new Exception("未查询到任何订单号");
#endregion
#region 查询订单
var orderList = fsql.Select<Order>(orderIds).ToList(o => new Order
{
Id = o.Id,
OrderSn = o.OrderSn,
ShopId = o.ShopId,
2 years ago
OrderState = o.OrderState,
IntoStoreType = o.IntoStoreType,
SourceShopName = o.SourceShopName
});
if (orderList.Count() == 0)
throw new Exception("未查询到任何订单");
#endregion
#region 查询订单sku
var orderSkuList = fsql.Select<OrderSku>().Where(osku => orderIds.Contains(osku.OrderId)).ToList();
if (orderSkuList.Count() == 0)
throw new Exception("未查询到任何订单sku");
#endregion
#region 查询采购单
var purchaseOrderList = fsql.Select<OrderPurchaseInfo>().Where(ori => ori.IsEnabled == true && orderIds.Contains(ori.OrderId)).ToList();
if (purchaseOrderList.Count() == 0)
throw new Exception("未查询到任何采购单");
var purchaseOrderIds = purchaseOrderList.Select(po => po.PurchaseOrderId).ToList();
#endregion
#region 查询采购SKU
IList<OrderPurchaseSkuInfo> orderPurchaseSkuList = fsql.Select<OrderPurchaseSkuInfo>()
.Where(posku => purchaseOrderIds.Contains(posku.PurchaseOrderId))
.ToList();
#endregion
#region 查询采购sku关联信息
IList<OrderPurchaseRelationInfo> orderPurchaseRelationList = fsql.Select<OrderPurchaseRelationInfo>()
.Where(ops => purchaseOrderIds.Contains(ops.PurchaseOrderId))
.ToList();
#endregion
#region 查询采购单关联的快递单
var purchaseExpressOrderList = fsql.Select<ExpressOrderRelationInfo, PurchaseExpressOrder>()
.InnerJoin((eori, peo) => eori.WayBillNo == peo.WaybillNo)
.Where((eori, peo) => orderIds.Contains(eori.OrderId)).ToList((eori, peo) => new PurchaseExpressOrder
{
CreateTime = peo.CreateTime,
ExpressContent = peo.ExpressContent,
ExpressChangedTime = peo.ExpressChangedTime,
ExpressState = peo.ExpressState,
IsSubscribeKD100 = peo.IsSubscribeKD100,
OrderId = eori.OrderId,
PurchaseOrderId = eori.PurchaseOrderId,
ShopId = eori.ShopId.Value,
SourceExpressId = peo.SourceExpressId,
SourceExpressName = peo.SourceExpressName,
TargetExpressId = peo.TargetExpressId,
TargetExpressName = peo.TargetExpressName,
WaybillNo = peo.WaybillNo
});
#endregion
#region 更新采购单信息
tpeo.ExpressState = state;
tpeo.ExpressChangedTime = expressChangeTime;
tpeo.ExpressContent = expressContent;
updatePurchaseExpressOrder = fsql.Update<PurchaseExpressOrder>().SetSource(tpeo);
#endregion
#region 查询入库单信息
IList<InStoreOrderCheckTask> inStoreOrderCheckTaskList = null;
if (orderList.Any(o => o.IntoStoreType == Enums.IntoStoreType.) && state == "QianShou")
inStoreOrderCheckTaskList = fsql.Select<InStoreOrderCheckTask>().Where(i => orderIds.Contains(i.OrderId)).ToList();
#endregion
#region 计算订单状态和采购单状态
foreach (var order in orderList)
{
var currentOrderSkuList = orderSkuList.Where(osku => osku.OrderId == order.Id).ToList();
var currentPurchaseOrderList = purchaseOrderList.Where(po => po.OrderId == order.Id).ToList();
#region 计算采购单状态
foreach (var po in currentPurchaseOrderList)
{
var currentPoSkuList = orderPurchaseSkuList.Where(posku => posku.PurchaseOrderId == po.PurchaseOrderId).ToList();
var currentPeoList = purchaseExpressOrderList.Where(peo => peo.PurchaseOrderId == po.PurchaseOrderId).ToList();
var peo = currentPeoList.FirstOrDefault(p => p.WaybillNo == wayBillNo);
if (peo != null)
peo.ExpressState = state;
var oldPurchaseOrderState = po.OrderState;
po.CalculationOrderState(order.IntoStoreType.Value, fsql, currentPoSkuList, currentPeoList);
if (po.OrderState != oldPurchaseOrderState)
{
var update = fsql.Update<OrderPurchaseInfo>(po.Id).Set(po => po.OrderState, po.OrderState);
updateOrderPurchaseList.Add(update);
}
}
#endregion
#region 推送齐库到货情况
if (order.IntoStoreType == Enums.IntoStoreType. && state == "QianShou")
{
Task.Factory.StartNew(() => qiKuManager.PublishQikuReceiveInfo(order.Id,
wayBillNo,
currentPurchaseOrderList,
currentOrderSkuList,
purchaseExpressOrderList,
orderPurchaseRelationList,
orderPurchaseSkuList), CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
}
#endregion
#region 计算订单状态
var oldOrderState = order.OrderState;
order.CalculationOrderState(fsql, currentOrderSkuList, currentPurchaseOrderList);
if (order.OrderState != oldOrderState)
{
var update = fsql.Update<Order>(order.Id).Set(o => o.OrderState, order.OrderState);
updateOrderList.Add(update);
#region 通知C端状态
Task.Factory.StartNew(() => SendPurchaseOrderStateToC(order.Id, order.OrderState.Value), CancellationToken.None, TaskCreationOptions.None, taskSchedulerManager.PurchaseOrderCallbackTaskScheduler);
#endregion
#region 创建待核算任务
if (order.OrderState == Enums.OrderState.)
{
var isExists = fsql.Select<TimeLimitTask>().Where(t => t.OrderId == order.Id && t.TaskType == Enums.TimeLimitTaskType.).Any();
if (!isExists)
{
//创建待核算任务
var t = new TimeLimitTask()
{
CreateTme = DateTime.Now,
Id = idGenerator.NewLong(),
OrderId = order.Id,
//SkuId = orderSku.SkuId,
OrderSn = order.OrderSn,
ShopId = order.ShopId,
TaskType = Enums.TimeLimitTaskType.,
ExpirationTime = DateTime.Now.AddDays(1)
};
insertTimeLimitTaskList.Add(t);
}
}
#endregion
}
#endregion
#region 创建入仓单检查任务
if (order.IntoStoreType == Enums.IntoStoreType. &&
state == "QianShou" &&
order.OrderState == Enums.OrderState. &&
inStoreOrderCheckTaskList != null &&
!inStoreOrderCheckTaskList.Any(x => x.OrderId == order.Id))
{
insertInStoreOrderCheckTaskList.Add(new InStoreOrderCheckTask()
{
Id = idGenerator.NewLong(),
CreateTime = DateTime.Now,
IsChecked = false,
OrderId = order.Id,
ShopId = order.ShopId,
OrderSn = order.OrderSn
});
}
#endregion
}
#endregion
#region 更新数据库
fsql.Transaction(() =>
{
updatePurchaseExpressOrder?.ExecuteAffrows();
if (updateOrderPurchaseList.Count() > 0)
{
foreach (var update in updateOrderPurchaseList)
update.ExecuteAffrows();
}
if (updateOrderList.Count() > 0)
{
foreach (var update in updateOrderList)
update.ExecuteAffrows();
}
if (insertTimeLimitTaskList.Count() > 0)
fsql.Insert(insertTimeLimitTaskList).ExecuteAffrows();
if (insertInStoreOrderCheckTaskList.Count() > 0)
fsql.Insert(insertInStoreOrderCheckTaskList).ExecuteAffrows();
});
#endregion
}
catch (Exception ex)
{
nLogManager.GetLogger("快递100").Error(ex, wayBillNo);
}
}
/// <summary>
/// 采购单信息变更(改价,付款)
/// </summary>
/// <param name="purchaseOrderId">采购单Id</param>
/// <param name="keepRunWhenNoEditOrderPirce">当不需要触发订单改价时是否继续走流程</param>
2 years ago
public void OnSomeOnePurchaseOrderChanged(string purchaseOrderId, bool keepRunWhenNoEditOrderPirce)
{
bool isEditOrderPrice = true;
try
{
var orderPurchaseInfo = fsql.Select<OrderPurchaseInfo>().Where(opi => opi.PurchaseOrderId == purchaseOrderId && opi.IsEnabled == true).ToOne();
if (orderPurchaseInfo == null)
throw new Exception($"采购单{purchaseOrderId}-未查询到采购单");
var dbOrder = fsql.Select<Order>(orderPurchaseInfo.OrderId).ToOne();
var dbOrderPurchaseInfoList = fsql.Select<OrderPurchaseInfo>().Where(opi => opi.OrderId == orderPurchaseInfo.OrderId && opi.IsEnabled == true).ToList();
if (dbOrderPurchaseInfoList.Count() == 0)
throw new Exception($"采购单{purchaseOrderId}-未查询到订单{orderPurchaseInfo.OrderId}的采购单集合");
isEditOrderPrice = dbOrderPurchaseInfoList.Count() == dbOrderPurchaseInfoList.Count(opi => opi.PurchasePlatform == Enums.Platform. &&
opi.PurchaseMethod == Enums.PurchaseMethod.线) &&
dbOrder.OrderState != Enums.OrderState. &&
dbOrder.OrderState != Enums.OrderState.;
if (!keepRunWhenNoEditOrderPirce && !isEditOrderPrice)
return;
var dbOrderCost = fsql.Select<OrderCost>(dbOrder.Id).ToOne();
if (dbOrderCost == null)
throw new Exception($"采购单{purchaseOrderId}-未查询到订单{dbOrder.Id}的成本");
var purchaseAccount = fsqlManager.MDSfsql.Select<Purchaseaccount>().Where(pa => pa.Id == orderPurchaseInfo.PurchaseAccountId).ToOne();
if (purchaseAccount == null)
throw new Exception($"采购单{purchaseOrderId}-未查询到采购账号{orderPurchaseInfo.PurchaseAccountId}");
var shop = fsqlManager.MDSfsql.Select<Shops>().Where(s => s.ShopId == dbOrder.ShopId.ToString()).ToOne();
var dbOrderCostDetails = fsql.Select<OrderCostDetail>().Where(ocd => ocd.OrderId == dbOrder.Id && ocd.IsEnabled == true).ToList();
if (dbOrderCostDetails.Count() == 0)
throw new Exception($"采购单{purchaseOrderId}-未查询到订单{orderPurchaseInfo.OrderId}的明细成本");
var dbPurchaseOrderIdList = dbOrderPurchaseInfoList.Select(x => x.PurchaseOrderId).ToList();
var dbOrderPurchaseRelationInfos = fsql.Select<OrderPurchaseRelationInfo>().Where(x => dbPurchaseOrderIdList.Contains(x.PurchaseOrderId)).ToList();
if (dbOrderPurchaseRelationInfos.Count() == 0)
throw new Exception($"采购单{purchaseOrderId}-未查询到采购单关联明细");
var dbOrderSkus = fsql.Select<OrderSku>().Where(osku => osku.OrderId == dbOrder.Id).ToList();
var dbOrderSkuCostList = fsql.Select<OrderSkuCost>().Where(osc => osc.OrderId == dbOrder.Id).ToList();
List<IUpdate<OrderCostDetail>> updateOrderCostDetailList = new List<IUpdate<OrderCostDetail>>();
IUpdate<OrderCost> updateOrderCost = null;
IList<IUpdate<OrderSku>> updateOrderSkuList = new List<IUpdate<OrderSku>>();
IUpdate<Order> updateOrder = null;
List<OrderSkuCost> insertOrderSkuCostList = new List<OrderSkuCost>();
IList<IUpdate<OrderSkuCost>> updateOrderSkuCostList = new List<IUpdate<OrderSkuCost>>();
IList<OP_EditPriceSkuRequest> op_EditPriceSkuRequests = new List<OP_EditPriceSkuRequest>();
IUpdate<OrderPurchaseInfo> updatePurchaseOrder = null;
IDictionary<string, OP_EditPriceSkuRequest> oskuPriceEditParamDictionary = new Dictionary<string, OP_EditPriceSkuRequest>();
var ppclient = ppPlatformClientFactory.GetClient(AdapterEnums.PlatformType.);
var totalPurchaseProductAmount = 0M;
var totalPurchaseFreight = 0M;
foreach (var opi in dbOrderPurchaseInfoList)
{
if (opi.PurchasePlatform != Enums.Platform.)
continue;
var purchaseOrderSimpleInfo = ppclient.QueryOrderDetail(new PP_QueryOrderDetailRequest()
{
AppKey = purchaseAccount.AppKey,
AppSecret = purchaseAccount.AppSecret,
AppToken = purchaseAccount.AppToken,
OrderId = opi.PurchaseOrderId
});
totalPurchaseProductAmount += purchaseOrderSimpleInfo.ProductAmount;
totalPurchaseFreight += purchaseOrderSimpleInfo.FreightAmount;
var currentPurchaseOrderRelationInfos = dbOrderPurchaseRelationInfos.Where(x => x.PurchaseOrderId == opi.PurchaseOrderId).ToList();
var cargoParamList = currentPurchaseOrderRelationInfos.Select(x => new CargoParamRequest()
{
SkuId = x.PurchaseSkuId,
BelongSkuId = x.BelongSkuId,
ProductId = x.PurchaseProductId,
Quantity = x.Quantity ?? 1,
SpecId = x.PurchaseSpecId,
SchemeId = x.SchemeId.Value
}).ToList();
#region 等比计算采购成本
var proportionalCalculationResultList = ProportionalCalculationCost(cargoParamList, purchaseOrderSimpleInfo);
foreach (var proportionalCalculationResult in proportionalCalculationResultList)
{
var skuId = proportionalCalculationResult.SkuId;
#region 订单sku平价
if (isEditOrderPrice)
{
var orderSku = dbOrderSkus.FirstOrDefault(osku => osku.SkuId == skuId);
if (!oskuPriceEditParamDictionary.TryGetValue(orderSku.SkuId, out OP_EditPriceSkuRequest editSkuPrice))
{
editSkuPrice = new OP_EditPriceSkuRequest()
{
SkuId = orderSku.SkuId,
OrderSkuId = orderSku.Id.ToString(),
InPackAmountPrice = orderSku.InPackAmount ?? 0M
};
oskuPriceEditParamDictionary.Add(orderSku.SkuId, editSkuPrice);
}
editSkuPrice.Price += proportionalCalculationResult.ProductAmount / (orderSku.ItemTotal ?? 1M);
editSkuPrice.Freight += proportionalCalculationResult.FreightAmount;
}
#endregion
#region 更新sku成本明细
var dbOrderSkuDetail = dbOrderCostDetails.FirstOrDefault(ocd => ocd.SkuId == skuId && ocd.PurchaseOrderId == opi.PurchaseOrderId);
dbOrderSkuDetail.CalculationOrderCostDetailCostAndProfit(proportionalCalculationResult.ProductAmount,
proportionalCalculationResult.FreightAmount,
dbOrderSkuDetail.OutPackAmount ?? 0M,
dbOrderSkuDetail.DeliveryExpressFreight ?? 0M);
updateOrderCostDetailList.Add(fsql.Update<OrderCostDetail>().SetSource(dbOrderSkuDetail));
#endregion
}
#endregion
//var purchaseSkuTotalQuantity = purchaseOrderSimpleInfo.ItemList.Sum(x => x.Quantity);
//var belongSkuGroups = currentPurchaseOrderRelationInfos.GroupBy(p => p.BelongSkuId);
//foreach (var belongSkuGroup in belongSkuGroups)
//{
// var belongSkuId = belongSkuGroup.Key;
// var currentOrderSkuCargoParamList = belongSkuGroup.ToList(); //找当前skuId的采购skuId
// var currentOrderSkuProductAmount = 0M; //采购成本
// var currentSkuTotalPurchaseQuantity = currentOrderSkuCargoParamList.Sum(x => x.Quantity); //当前skuId的采购数量总和
// var currentPurchaseFreight = purchaseOrderSimpleInfo.FreightAmount *
// (1.0M * currentSkuTotalPurchaseQuantity / purchaseSkuTotalQuantity); //采购运费
// foreach (var currentOrderSkuCargo in currentOrderSkuCargoParamList)
// {
// var currentPurchaseSkuProductAmount = purchaseOrderSimpleInfo.ItemList.Where(p => p.SkuId == currentOrderSkuCargo.PurchaseSkuId)
// .Sum(p => p.ProductAmount);
// var currentPurchaseSkuTotalQuantity = purchaseOrderSimpleInfo.ItemList.Where(p => p.SkuId == currentOrderSkuCargo.PurchaseSkuId)
// .Sum(p => p.Quantity);
// currentOrderSkuProductAmount += currentPurchaseSkuProductAmount * (1.0M * currentOrderSkuCargo.Quantity.Value / currentPurchaseSkuTotalQuantity);
// }
// #region 订单sku平价
// var orderSku = dbOrderSkus.FirstOrDefault(osku => osku.SkuId == belongSkuId);
// if (isEditOrderPrice)
// {
// if (!oskuPriceEditParamDictionary.TryGetValue(orderSku.SkuId, out OP_EditPriceSkuRequest editSkuPrice))
// {
// editSkuPrice = new OP_EditPriceSkuRequest()
// {
// SkuId = orderSku.SkuId,
// OrderSkuId = orderSku.Id.ToString(),
// InPackAmountPrice = orderSku.InPackAmount ?? 0M
// };
// oskuPriceEditParamDictionary.Add(orderSku.SkuId, editSkuPrice);
// }
// editSkuPrice.Price += currentOrderSkuProductAmount / (orderSku.ItemTotal ?? 1M);
// editSkuPrice.Freight += currentPurchaseFreight ?? 0M;
// //orderSku.Price =
// //orderSku.BuyerPayFreight = currentPurchaseFreight;
// //if (!op_EditPriceSkuRequests.Any(x => x.SkuId == orderSku.SkuId))
// //{
// // op_EditPriceSkuRequests.Add(new OP_EditPriceSkuRequest()
// // {
// // Freight = currentPurchaseFreight ?? 0M,
// // InPackAmountPrice = orderSku.InPackAmount ?? 0M,
// // OrderSkuId = orderSku.Id.ToString(),
// // Price = orderSku.Price ?? 0M,
// // SkuId = orderSku.SkuId
// // });
// // updateOrderSkuList.Add(fsql.Update<OrderSku>(orderSku.Id).Set(osku => osku.Price, orderSku.Price)
// // .Set(osku => osku.BuyerPayFreight, orderSku.BuyerPayFreight));
// //}
// }
// #endregion
// var dbOrderSkuDetail = dbOrderCostDetails.FirstOrDefault(ocd => ocd.SkuId == belongSkuId && ocd.PurchaseOrderId == opi.PurchaseOrderId);
// dbOrderSkuDetail.CalculationOrderCostDetailCostAndProfit(currentOrderSkuProductAmount,
// currentPurchaseFreight ?? 0M,
// dbOrderSkuDetail.OutPackAmount ?? 0M,
// dbOrderSkuDetail.DeliveryExpressFreight ?? 0M);
// updateOrderCostDetailList.Add(fsql.Update<OrderCostDetail>().SetSource(dbOrderSkuDetail));
//}
}
if (isEditOrderPrice)
{
#region 更新订单sku金额
foreach (var editSkuPriceKey in oskuPriceEditParamDictionary.Keys)
{
oskuPriceEditParamDictionary.TryGetValue(editSkuPriceKey, out var editSkuPrice);
var orderSku = dbOrderSkus.FirstOrDefault(osku => osku.SkuId == editSkuPrice.SkuId);
orderSku.Price = editSkuPrice.Price;
orderSku.BuyerPayFreight = editSkuPrice.Freight;
op_EditPriceSkuRequests.Add(editSkuPrice);
updateOrderSkuList.Add(fsql.Update<OrderSku>(orderSku.Id).Set(osku => osku.Price, orderSku.Price)
.Set(osku => osku.BuyerPayFreight, orderSku.BuyerPayFreight));
}
#endregion
#region 更新订单金额
dbOrder.OrderTotalPrice = totalPurchaseProductAmount + totalPurchaseFreight;
dbOrder.OrderSellerPrice = totalPurchaseProductAmount;
dbOrder.FreightPrice = totalPurchaseFreight;
updateOrder = fsql.Update<Order>(dbOrder.Id).Set(o => o.OrderTotalPrice, dbOrder.OrderTotalPrice)
.Set(o => o.OrderSellerPrice, dbOrder.OrderSellerPrice)
.Set(o => o.FreightPrice, dbOrder.FreightPrice);
updatePurchaseOrder = fsql.Update<OrderPurchaseInfo>(orderPurchaseInfo.Id).Set(opi => opi.IsAutoEditOrderPrice, Enums.AutoEditOrderPriceType.);
2 years ago
#endregion
}
#region 订单Sku成本
foreach (var orderSku in dbOrderSkus)
{
var orderSkuCost = dbOrderSkuCostList.FirstOrDefault(osc => osc.SkuId == orderSku.SkuId);
if (orderSkuCost == null)
{
orderSkuCost = new OrderSkuCost()
{
Id = idGenerator.NewLong(),
CreateTime = DateTime.Now,
OrderId = dbOrder.Id,
SkuId = orderSku.SkuId
};
orderSkuCost.CalculationOrderSkuCostAndProfit(orderSku, dbOrderCostDetails);
insertOrderSkuCostList.Add(orderSkuCost);
}
else
{
orderSkuCost.CalculationOrderSkuCostAndProfit(orderSku, dbOrderCostDetails);
var update = fsql.Update<OrderSkuCost>().SetSource(orderSkuCost);
updateOrderSkuCostList.Add(update);
}
}
#endregion
#region 订单成本
dbOrderCost.CalculationOrderCostAndProfit(dbOrder.OrderTotalPrice.Value, dbOrderSkuCostList.Union(insertOrderSkuCostList).ToList());
//dbOrderCost.CalculationOrderCostAndProfit(dbOrder.OrderTotalPrice ?? 0M,
// totalPurchaseProductAmount,
// totalPurchaseFreight,
// dbOrderCostDetails.Sum(ocd => ocd.OutPackAmount ?? 0M),
// dbOrderCostDetails.Sum(ocd => ocd.DeliveryExpressFreight ?? 0M));
updateOrderCost = fsql.Update<OrderCost>().SetSource(dbOrderCost);
#endregion
fsql.Transaction(() =>
{
updatePurchaseOrder?.ExecuteAffrows();
foreach (var update in updateOrderCostDetailList)
update.ExecuteAffrows();
updateOrderCost?.ExecuteAffrows();
foreach (var update in updateOrderSkuList)
update.ExecuteAffrows();
updateOrder?.ExecuteAffrows();
if (insertOrderSkuCostList.Count() > 0)
fsql.Insert(insertOrderSkuCostList).ExecuteAffrows();
if (updateOrderSkuCostList.Count() > 0)
{
foreach (var update in updateOrderSkuCostList)
update.ExecuteAffrows();
}
});
if (isEditOrderPrice)
{
#region 通知拳探改价
var opclient = opPlatformClientFactory.GetClient(AdapterEnums.PlatformType.);
opclient.EditPrice(new OP_EditPriceRequest()
{
AppKey = shop.AppKey,
AppSecret = shop.AppSecret,
AppToken = shop.AppToken,
OrderId = dbOrder.Id,
EditItems = op_EditPriceSkuRequests
});
#endregion
#region 通知C端改价
restApiService.SendRequest("https://bbwy.qiyue666.com",
"/Api/PurchaseOrder/QuanTanEditPriceCallback",
new { orderId = dbOrder.Id },
null,
HttpMethod.Post);
#endregion
}
}
catch (Exception ex)
{
nLogManager.Default().Error(ex, $"OrderPriceModificationCallback 采购单号{purchaseOrderId}");
}
}
private void SendDingDing(string content)
{
try
{
dingDingBusiness.SendDingDingBotMessage("SEC5f08a3dd6813e50bf9a3b81350ec12a8086c64b9e29ef858a17f5cc7887906d7",
"https://oapi.dingtalk.com/robot/send?access_token=7ce472411bb8dde0c3ff503fcca9ead84d39950ee3c4c65c808dbc58981eb929",
content);
}
catch { }
}
private void SendPurchaseOrderStateToC(string orderId, Enums.OrderState orderState)
{
try
{
restApiService.SendRequest("https://bbwy.qiyue666.com", "api/BatchPurchase/UpdatePurchaseOrderState", new
{
OrderId = orderId,
PurchaseOrderState = orderState
}, null, HttpMethod.Post);
}
catch
{
}
}
/// <summary>
/// 匹配采购方案
/// </summary>
/// <param name="skuId"></param>
/// <param name="itemTotal"></param>
/// <param name="purchaserId"></param>
/// <param name="purchaseSchemeList"></param>
/// <param name="purchaseOrderSimpleInfo"></param>
/// <returns></returns>
private IList<CargoParamRequest> MatchPurchaseScheme(string skuId,
int itemTotal,
string purchaserId,
IList<PurchaseSchemeResponse> purchaseSchemeList,
PP_QueryOrderDetailResponse purchaseOrderSimpleInfo)
{
List<CargoParamRequest> cargoParamList = new List<CargoParamRequest>();
var currentSkuSchemeList = purchaseSchemeList.Where(ps => ps.SkuId == skuId).ToList();
if (currentSkuSchemeList.Count() > 0)
{
foreach (var scheme in currentSkuSchemeList)
{
var samePurchaserProductList = scheme.PurchaseSchemeProductList.Where(psp => psp.PurchaserId == purchaserId).ToList();
if (samePurchaserProductList.Count() == 0)
continue;
bool isMatch = true;
foreach (var schemeProduct in samePurchaserProductList)
{
if (schemeProduct.PurchaseSchemeProductSkuList.Any(pss => purchaseOrderSimpleInfo.ItemList.Count(x => x.SkuId == pss.PurchaseSkuId) == 0))
{
isMatch = false;
break;
}
}
if (isMatch)
{
foreach (var schemeProduct in samePurchaserProductList)
{
cargoParamList.AddRange(schemeProduct.PurchaseSchemeProductSkuList.Select(pss => new CargoParamRequest()
{
BelongSkuId = pss.SkuId,
ProductId = pss.PurchaseProductId,
SkuId = pss.PurchaseSkuId,
SchemeId = pss.SkuPurchaseSchemeId,
SchemeVersion = scheme.Version,
SpecId = pss.PurchaseSkuSpecId,
Quantity = itemTotal * (pss.PurchaseRatio ?? 1)
}));
}
break;
}
}
}
return cargoParamList;
}
/// <summary>
/// 等比计算sku采购成本
/// </summary>
/// <param name="cargoParamList"></param>
/// <param name="purchaseOrderSimpleInfo"></param>
/// <returns></returns>
private IList<ProportionalCalculationCostResult> ProportionalCalculationCost(IList<CargoParamRequest> cargoParamList,
PP_QueryOrderDetailResponse purchaseOrderSimpleInfo)
{
var list = new List<ProportionalCalculationCostResult>();
var belongSkuGroups = cargoParamList.GroupBy(p => p.BelongSkuId);
var purchaseSkuTotalQuantity = cargoParamList.Sum(x => x.Quantity);
foreach (var belongSkuGroup in belongSkuGroups)
{
var skuId = belongSkuGroup.Key;
//var currentOrderSkuCargoParamList = cargoParamList.Where(p => p.BelongSkuId == skuId); //找当前skuId的采购skuId
var currentOrderSkuCargoParamList = belongSkuGroup.ToList(); //找当前skuId的采购skuId
var currentSkuAmount = 0M; //采购成本
var currentSkuTotalPurchaseQuantity = currentOrderSkuCargoParamList.Sum(x => x.Quantity); //当前skuId的采购数量总和
var currentPurchaseFreight = purchaseOrderSimpleInfo.FreightAmount *
(1.0M * currentSkuTotalPurchaseQuantity / purchaseSkuTotalQuantity); //采购运费
foreach (var currentOrderSkuCargo in currentOrderSkuCargoParamList)
{
var currentPurchaseSkuProductAmount = purchaseOrderSimpleInfo.ItemList.Where(p => p.SkuId == currentOrderSkuCargo.SkuId)
.Sum(p => p.ProductAmount);
var currentPurchaseSkuTotalQuantity = cargoParamList.Where(p => p.SkuId == currentOrderSkuCargo.SkuId)
.Sum(p => p.Quantity);
currentSkuAmount += currentPurchaseSkuProductAmount * (1.0M * currentOrderSkuCargo.Quantity / currentPurchaseSkuTotalQuantity);
}
list.Add(new ProportionalCalculationCostResult()
{
SkuId = skuId,
FreightAmount = currentPurchaseFreight,
ProductAmount = currentSkuAmount
});
}
return list;
}
2 years ago
}
}