public static string ChangeGroupBuyingStatus(int orderId) { var cmt = DalMGMTools.CheckExistPinTuanOrder(orderId); if (cmt) { var dat = DalMGMTools.FetchUserInfoByOrderId(orderId); using (var client = new PinTuanClient()) { if (dat.UserStatus == 0) { if (dat.Code == 1) { var result = client.ChangeGroupBuyingStatus(dat.GroupId, dat.OrderId); if (!result.Success || !result.Result) { return($"订单{dat.OrderId}付款,且用户为团{dat.GroupId}团长,对应团状态修改出现异常,{result.Exception?.Message}"); } } var val = client.ChangeUserStatus(dat.GroupId, dat.UserId, dat.OrderId); if (!val.Success || !val.Result) { return($"订单{dat.OrderId}付款,且用户为团{dat.GroupId}成员,对应用户状态修改出现异常,{val.Exception?.Message}"); } return("设置成功"); } } return("用户状态不为‘待付款’"); } return("未找到该拼团订单"); }
private void DoJob() { const int step = 10; var start = 0; var count = DalGroupBuying.GetGroupBuyingCount(); Logger.Warn($"待刷新拼团数量为{count}个"); while (start <= count) { var productGroupIds = DalGroupBuying.GetProductGroupList(start, step); if (productGroupIds.Any()) { using (var client = new PinTuanClient()) { var result = client.UpdateGroupBuyingInfo(productGroupIds); if (!(result.Success && result.Result)) { Logger.Warn($"更新ES数据失败-->{result.Exception?.Message}"); } } } start += step; } }
public void DoJob() { using (var client = new PinTuanClient()) { var result = client.RefreshCache(); if (!(result.Success && result.Result.Code == 1)) { Logger.Warn("刷新拼团首页模块数据失败"); } var data = DalGroupBuying.GetAllPinTuanProduct(); foreach (var item in data) { var resultItem = client.RefreshCache(item); if (!(result.Success && result.Result.Code == 1)) { Logger.Warn($"刷新拼团数据-->{item}--失败"); } } } using (var client = new ShareBargainClient()) { var result = client.RefreshShareBargainCache(); if (!(result.Success && result.Result)) { Logger.Warn("砍价首页模块数据失败"); } } }
private void DoJob() { var data = DalGroupBuying.GetExpiringGroupInfo(); Logger.Info($"当前有{data.Count}个团处于拼团中状态"); var span1 = TimeSpan.FromMinutes(160); var span2 = TimeSpan.FromMinutes(190); var span3 = TimeSpan.FromMinutes(50); var span4 = TimeSpan.FromMinutes(80); foreach (var item in data) { if (item.EndTime > DateTime.Now + span1 && item.EndTime < DateTime.Now + span2 && !GetExpiringCache(item.GroupId, 3)) { Logger.Info($"团号为{item.GroupId:D}拼团将在三个小时候结束,为相关用户推送提醒"); PushMessage(item.GroupId, 1651, 3); SetExpiringCache(item.GroupId, 3); } else if (item.EndTime > DateTime.Now + span3 && item.EndTime < DateTime.Now + span4 && !GetExpiringCache(item.GroupId, 1)) { Logger.Info($"团号为{item.GroupId:D}拼团将在一个小时候结束,为相关用户推送提醒"); PushMessage(item.GroupId, 1651, 1); SetExpiringCache(item.GroupId, 1); } else if (item.EndTime < DateTime.Now) { using (var client = new PinTuanClient()) { var pinTuanAutoFinishResult = client.PinTuanAutoFinish(new PinTuanAutoFinishRequest() { GroupId = item.GroupId }); // 判断返回值 if (!pinTuanAutoFinishResult.Result) { var result = client.ExpireGroupBuying(item.GroupId); if (result.Success && result.Result.Code == 1) { Logger.Info($"团{item.GroupId}过期,取消成功"); } else { Logger.Warn($"团{item.GroupId}过期,取消失败,{result.Exception?.Message},{result.Result?.Info}"); } } else { Logger.Info($" GroupBuyingOrderJob -> DoJob -> {item.GroupId} auto finished "); } } } } }
private async void PushMessage(Guid groupId, int batchId, int flag) { using (var client = new PinTuanClient()) { var result = await client.PushPinTuanMessageAsync(groupId, batchId); if (!result.Success && result.Result) { Logger.Warn( $"GroupBuyingPushMessage==>{flag}小时推送==>fail==>{groupId}/{batchId}==>{result.Exception}"); } } }
private void DoJob() { // 获取超时的订单 var data = DalGroupBuying.GetExpiredUserList(); if (data.Any()) { using (var client = new OrderApiForCClient()) using (var clientPinTuna = new PinTuanClient()) { foreach (var item in data) { var OrderData = client.FetchOrderByOrderId(item.OrderId); var result = OrderData.Success && OrderData.Result?.Status == "7Canceled"; if (!result && OrderData.Result != null) { //判断状态能不能取消 if (new[] { "0NewPingTuan", "0New" }.Contains(OrderData.Result.Status)) { result = CancelPinTuanOrder(item.UserId, item.OrderId); } else { result = true; //调用补足服务,订单已取消 ,拼团状态未改变 clientPinTuna.RepairPinTuanOrderStatus(new List <int> { item.OrderId }); } Logger.Info($"当前订单:{item.OrderId} {OrderData.Result.Status} "); } //if (result) //{ // var ChangeResult = DalGroupBuying.ChangeUserOrderStatus(item.OrderId); // if (ChangeResult == 0) // { // Logger.Warn($"修改拼团用户状态为订单取消失败/{item.OrderId}"); // } //} if (!result) { Logger.Warn($"取消未付款订单{item.OrderId}失败"); } } } } }
public static bool NotifyEmployee(NotifyEmployeeRequest request) { try { using (var pinTuanClient = new PinTuanClient()) { var pinTuanResult = pinTuanClient.NotifyEmployee(request); pinTuanResult.ThrowIfException(true); return(pinTuanResult.Result); } } catch (Exception ex) { _logger.Error($"发送企业微信通知失败:{request.ErrorMessage}", ex); return(false); } }
public static bool RefrestPTCache(string groupId) { var result = false; try { using (var client = new PinTuanClient()) { var getResult = client.RefreshCache(groupId ?? string.Empty); getResult.ThrowIfException(true); result = getResult.Result.Code == 1; } } catch (Exception ex) { logger.Error(ex); } return(result); }
GetGroupBuyingTireProductSetById(string productGroupId) { try { using (var pinTuanClient = new PinTuanClient()) { var pinTuanResult = await pinTuanClient .GetPinTuanTireProductSetByIdAsync(productGroupId); pinTuanResult.ThrowIfException(true); return(pinTuanResult.Result); } } catch (Exception ex) { _logger.Error($"获取轮胎商品集合失败 {productGroupId}", ex); return(null); } }
/// <summary> /// 获取拼团商品数量 /// </summary> /// <param name="productGroupId">产品组Id</param> /// <returns></returns> public async Task <int> GetGroupBuyingProductCount(string productGroupId) { try { using (var pinTuanClient = new PinTuanClient()) { var pinTuanResult = await pinTuanClient .GetPinTuanProductCountAsync(productGroupId); pinTuanResult.ThrowIfException(true); return(pinTuanResult.Result); } } catch (Exception ex) { _logger.Error($"获取拼团商品数量失败 {productGroupId}", ex); throw; } }
/// <summary> /// 检查拼团是否有指定商品 /// </summary> /// <param name="productGroupId">产品组Id</param> /// <param name="pid">产品Id</param> /// <returns></returns> public async Task <bool> CheckGroupBuyingHasSpecifyProduct(string productGroupId, string pid) { try { using (var pinTuanClient = new PinTuanClient()) { var pinTuanResult = await pinTuanClient .CheckPinTuanHasSpecifyProductAsync(productGroupId, pid); pinTuanResult.ThrowIfException(true); return(pinTuanResult.Result); } } catch (Exception ex) { _logger.Error($"检查拼团指定商品失败 {productGroupId} -> {pid}", ex); throw; } }
/// <summary> /// 移除拼团轮胎商品缓存 /// </summary> /// <param name="productGroupId">产品组Id</param> /// <returns></returns> public async Task <bool> RemoveGroupBuyingTireProductsCache(string productGroupId) { try { using (var pinTuanClient = new PinTuanClient()) { var pinTuanResult = await pinTuanClient .RemovePinTuanTireProductsCacheAsync(productGroupId); pinTuanResult.ThrowIfException(true); return(pinTuanResult.Result); } } catch (Exception ex) { _logger.Error($"移除拼团轮胎商品缓存失败 {productGroupId}", ex); return(false); } }
/// <summary> /// 设置拼团默认商品 /// </summary> /// <param name="productGroupId">产品组Id</param> /// <param name="pid">产品Id</param> /// <returns></returns> public async Task <bool> SetGroupBuyingDefaultProduct(string productGroupId, string pid) { try { using (var pinTuanClient = new PinTuanClient()) { var pinTuanResult = await pinTuanClient .SetPinTuanDefaultProductAsync(productGroupId, pid); pinTuanResult.ThrowIfException(true); return(pinTuanResult.Result); } } catch (Exception ex) { _logger.Error($"设置拼团默认商品失败 {productGroupId} -> {pid}", ex); return(false); } }
/// <summary> /// 通用移除拼团Redis缓存方法 /// </summary> /// <param name="clientName"></param> /// <param name="cacheKey"></param> /// <returns></returns> public async Task <bool> RemovePinTuanRedisCache(string clientName, string cacheKey) { try { using (var pinTuanClient = new PinTuanClient()) { var pinTuanResult = await pinTuanClient .RemovePinTuanRedisCacheAsync(clientName, cacheKey); pinTuanResult.ThrowIfException(true); return(pinTuanResult.Result); } } catch (Exception ex) { _logger.Error($"移除拼团Redis缓存失败 {clientName} -> {cacheKey}", ex); return(false); } }
/// <summary> /// 删除拼团轮胎商品配置 /// </summary> /// <param name="productConfigId">产品配置Id</param> /// <returns></returns> public async Task <bool> DeleteGroupBuyingTireProductConfig(int productConfigId) { try { using (var pinTuanClient = new PinTuanClient()) { var pinTuanResult = await pinTuanClient .DeletePinTuanTireProductConfigAsync(productConfigId); pinTuanResult.ThrowIfException(true); return(pinTuanResult.Result); } } catch (Exception ex) { _logger.Error($"删除拼团轮胎商品配置失败 {productConfigId}", ex); return(false); } }
/// <summary> /// 批量更新拼团商品配置 /// </summary> /// <param name="productGroupId">产品组Id</param> /// <param name="columnName">列名</param> /// <param name="value">值</param> /// <returns></returns> public async Task <bool> BatchUpdateGroupBuyingProductConfig(string productGroupId, string columnName, object value) { try { using (var pinTuanClient = new PinTuanClient()) { var pinTuanResult = await pinTuanClient .BatchUpdatePinTuanProductConfigAsync(productGroupId, columnName, value); pinTuanResult.ThrowIfException(true); return(pinTuanResult.Result); } } catch (Exception ex) { _logger.Error($"批量更新拼团商品配置失败 {productGroupId} {columnName} {value}", ex); return(false); } }
public void DoJob() { var orderList = (DalGroupBuying.GetPinTuanOrderList()).Distinct()?.ToList() ?? new List <int>(); if (orderList.Any()) { Logger.Warn($"查出{orderList.Count}个异常订单待补偿-->{string.Join("/", orderList)}"); using (var client = new PinTuanClient()) { var result = client.RepairPinTuanOrderStatus(orderList); if (result.Success && !string.IsNullOrWhiteSpace(result.Result.Info)) { Logger.Info(result.Result.Info); Email(result.Result.Info); } else { Logger.Error($"拼团异常订单处理失败-->{string.Join("/", orderList)}"); } } } }
public static async Task <bool> RefrestPTCache(string groupId) { var result = false; try { // 延迟3秒执行 -> (读写分离) { await Task.Delay(TimeSpan.FromSeconds(3)); using (var client = new PinTuanClient()) { var getResult = client.RefreshCache(groupId ?? string.Empty); getResult.ThrowIfException(true); result = getResult.Result.Code == 1; } } } catch (Exception ex) { logger.Error(ex); } return(result); }
public static async Task <CreateOrderResult> FlashSaleCreateOrder(Order.Request.CreateOrderRequest request) { var flashrequest = new FlashSaleOrderRequest() { Products = new List <OrderItems>() }; var pintuanFlag = false; var pintuanProductGroupId = ""; var pintuanPid = ""; var pintuanCount = 0; try { if (request.Items != null && request.Items.Any()) { foreach (var item in request.Items) { if (item.ActivityId.HasValue) { var activityTypeModel = new ActivityTypeModel(); // 增加拼团校验逻辑 if (item.ActivityId != null && await GroupBuyingManager.CheckProductGroupId(item.ActivityId.Value)) { activityTypeModel = new ActivityTypeModel { ActivityId = item.ActivityId.Value, Type = 7 }; } else { // 不是拼团ActivityId activityTypeModel = ActivityManager.SelectActivityTypeByActivityIds(new List <Guid> { item.ActivityId.Value }).FirstOrDefault(); } if (activityTypeModel != null) { var temp = flashrequest.Products.ToList(); temp.Add( new OrderItems { ActivityId = item.ActivityId, Num = item.Num, PID = item.Pid, Type = activityTypeModel.Type }); flashrequest.Products = temp; if (activityTypeModel.Type == 1) { //用来控制下单是否走老逻辑 item.IsVerifyActivity = false; } if (activityTypeModel.Type == 5) { item.IsVerifyActivity = false; } //砍价 if (activityTypeModel.Type == 9) { item.IsVerifyActivity = false; } //拼团 if (activityTypeModel.Type == 7) { request.Status = "0NewPingTuan"; item.IsVerifyActivity = false; var buyLimitInfo = await GroupBuyingManager.GetBuyLimitInfo(item.ActivityId.Value, item.Pid, request.Customer.UserId); if (string.IsNullOrWhiteSpace(buyLimitInfo?.PID)) { return(new CreateOrderResult { ErrorCode = -1000, ErrorMessage = "未找到该拼团产品!" }); } if (buyLimitInfo.BuyLimitCount > 0 && buyLimitInfo.BuyLimitCount <= buyLimitInfo.CurrentOrderCount) { return(new CreateOrderResult { ErrorCode = -1000, ErrorMessage = "已达到限购单数!" }); } if (item.Num > buyLimitInfo.UpperLimitPerOrder && buyLimitInfo.UpperLimitPerOrder != 0) { return(new CreateOrderResult { ErrorCode = -1000, ErrorMessage = "购买数量不符合要求!" }); } using (var client = new PinTuanClient()) { var result = await client.IncreaseSoldCountAsync(buyLimitInfo.ProductGroupId, buyLimitInfo.PID, item.Num); if (!(result.Success && result.Result.Code == 1)) { return(new CreateOrderResult { ErrorCode = -1000, ErrorMessage = result.Result?.Info ?? "出现异常" }); } pintuanFlag = true; pintuanPid = buyLimitInfo.PID; pintuanProductGroupId = buyLimitInfo.ProductGroupId; pintuanCount = item.Num; } } } } } } flashrequest.DeviceId = request.DeviceID; flashrequest.UseTel = request.Customer.UserTel; flashrequest.UserId = request.Customer.UserId; ICounter counter = null; #region 限时抢购校验 var fsRequest = new FlashSaleOrderRequest(); var isCheckFlash = false; var flashSaleResult = new List <CheckFlashSaleResponseModel>(); if (flashrequest.Products != null && flashrequest.Products.Any()) { var fsItems = flashrequest.Products.Where(r => r.Type == 1); var orderItemses = fsItems as OrderItems[] ?? fsItems.ToArray(); if (orderItemses.Any()) { isCheckFlash = true; fsRequest.DeviceId = flashrequest.DeviceId; fsRequest.UseTel = flashrequest.UseTel; fsRequest.UserId = flashrequest.UserId; fsRequest.Products = orderItemses; flashSaleResult = await ActivityValidator.CheckFlashSaleAsync(fsRequest); if (flashSaleResult.Any(r => r.Code != Model.CheckFlashSaleStatus.Succeed)) { return(new CreateOrderResult { ErrorCode = (int)flashSaleResult.Where(r => r.Code != Model.CheckFlashSaleStatus.Succeed).Select(c => c.Code).FirstOrDefault(), ErrorMessage = flashSaleResult.Where(r => r.Code != Model.CheckFlashSaleStatus.Succeed).Select(c => c.Code).FirstOrDefault().GetRemark() }); } flashrequest.Products = orderItemses.Select(r => { r.AllPlaceLimitId = flashSaleResult.Where(p => p.PID == r.PID) .Select(_ => _.AllPlaceLimitId) .FirstOrDefault(); return(r); }); } } #endregion #region 保养校验 if (flashrequest.Products != null && flashrequest.Products.Any()) { var byRequest = flashrequest.Products.Where(r => r.Type == 5); var activityId = byRequest.FirstOrDefault(o => o.ActivityId != Guid.Empty)?.ActivityId; if (activityId != null) { List <BaoYang.Models.BaoYangVehicleFivePropertyModel> propertiesList = null; if (request.Car != null && request.Car.ExtCol != null && request.Car.ExtCol.ContainsKey("Properties") && request.Car.ExtCol["Properties"] != null) { string properties = request.Car.ExtCol["Properties"].ToString(); List <dynamic> list = JsonConvert.DeserializeObject <List <dynamic> >(properties); propertiesList = list.Select(o => new BaoYang.Models.BaoYangVehicleFivePropertyModel() { Property = o.propertyKey, PropertyValue = o.propertyValue }).ToList(); } ValidateOrderRequest validateRequest = new ValidateOrderRequest() { ActivityId = activityId.Value, UserId = flashrequest.UserId, Products = request.Items.Where( o => o.ActivityId != null && o.ActivityId.HasValue && !o.Pid.StartsWith("FU-") && !o.Pid.StartsWith("TR-")) .Select(o => new OrderProduct() { ProductId = o.Pid, Count = o.Num, ActivityId = o.ActivityId.Value, Price = o.Price, ProductType = "Product" }).ToList(), ShopId = request.Delivery.InstallShopId ?? 0, Channel = request.OrderChannel, InstallType = request.Delivery.InstallType, Vehicle = new BaoYang.Models.VehicleRequestModel() { VehicleId = request.Car.VehicleId, PaiLiang = request.Car.PaiLiang, Nian = request.Car.Nian, Tid = request.Car.Tid, Properties = propertiesList }, RegionId = 1 }; using (var client = new BaoYangClient()) { var baoyangResult = await client.ValidateFixedPriceActivityOrderAsync(validateRequest); if (!baoyangResult.Success || !baoyangResult.Result) { return(new CreateOrderResult() { ErrorCode = (int)CreateOrderErrorCode.ProductValidateFailed, ErrorMessage = CreateOrderMessageDic.GetMessage(CreateOrderErrorCode.ProductValidateFailed) }); } } // 验证活动状态 var validateResult = await ActivityValidator.ValidateBaoyang(activityId.Value); if (validateResult.Item1 == Model.CreateOrderErrorCode.ActivitySatisfied) { // 验证限购数量 counter = new BaoYangCounter(activityId.Value, validateResult.Item2, validateResult.Item3, validateResult.Item4); var countResult = await counter.CanPurchaseAndIncreaseCount(flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel); if (countResult.Code != Model.CreateOrderErrorCode.ActivitySatisfied) { return(new CreateOrderResult() { ErrorCode = (int)countResult.Code, ErrorMessage = CreateOrderMessageDic.GetMessage(countResult.Code) }); } } else { return(new CreateOrderResult() { ErrorCode = (int)validateResult.Item1, ErrorMessage = CreateOrderMessageDic.GetMessage(validateResult.Item1) }); } } } #endregion #region 分享砍价活动 bool bargainflag = false; Guid ownerId = new Guid(); string pid = ""; var parameters = new List <BuyLimitDetailModel>(); if (flashrequest.Products != null && flashrequest.Products.Any()) { var item = flashrequest.Products.FirstOrDefault(g => g.Type == 9); if (item != null) { ownerId = flashrequest.UserId; pid = item.PID; parameters.Add(new BuyLimitDetailModel { ModuleName = "sharebargain", LimitObjectId = ownerId.ToString("D"), ObjectType = LimitObjectTypeEnum.UserId.ToString(), Remark = "砍价实物商品下单" }); if (!string.IsNullOrWhiteSpace(flashrequest.DeviceId)) { parameters.Add(new BuyLimitDetailModel { ModuleName = "sharebargain", LimitObjectId = flashrequest.DeviceId, ObjectType = LimitObjectTypeEnum.DeviceId.ToString(), Remark = "砍价实物商品下单" }); } var val = await DalBargain.CheckBargainProductStatusByPID(ownerId, pid); if (!val) { return(new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = "您当前没有资格享受该优惠!" }); } bargainflag = true; } } #endregion try { using (var client = new CreateOrderClient()) { var result = await client.CreateOrderAsync(request); result.ThrowIfException(); if (result.Success) { if (counter != null) { await counter.AddOrderRecord(result.Result.OrderId, flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel); } if (bargainflag) { var tal = await DalBargain.BuyBargainProductAsync(ownerId, pid, result.Result.OrderId); if (tal > 0) { parameters.ForEach(g => { g.ModuleProductId = tal.ToString(); g.Reference = result.Result.OrderId.ToString(); }); await LimitBuyManager.AddBuyLimitInfo(parameters); Logger.Info($"UserId为{ownerId}的用户享受砍价优惠,已购买pid为{pid}的商品"); } else { Logger.Error($"UserId为{ownerId}的用户享受砍价优惠,购买pid为{pid}的商品,修改购买状态时出错"); } } flashrequest.OrderId = result.Result.OrderId; if (isCheckFlash) { Logger.Info($"下单成功订单号=>{flashrequest.OrderId}发送消息"); try { TuhuNotification.SendNotification(".FlashSaleCreateOrder.", flashrequest); } catch (Exception ex) { var str = ""; try { str = JsonConvert.SerializeObject(flashrequest); } catch (Exception) { str = result.Result.OrderId.ToString(); } Logger.Error($"request-->{str}-->mq发送失败", ex); } } return(new CreateOrderResult { OrderId = result.Result.OrderId, OrderNo = result.Result.OrderNo }); } else { // 拼团下单失败,修改虚拟库存 if (pintuanFlag) { using (var client2 = new PinTuanClient()) { var result2 = await client2.DecrementSoldCountAsync(pintuanProductGroupId, pintuanPid, pintuanCount); if (!(result2.Success && result2.Result.Code == 1)) { Logger.Error($"拼团产品下单失败,虚拟库存修改失败-->{pintuanProductGroupId}/{pintuanPid}/{pintuanCount}"); } } } if (counter != null) { await counter.DecreasePurchaseCount(flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel); } Logger.Info("调用下单接口失败" + result.ErrorCode + result.ErrorMessage); if (isCheckFlash) { await FlashSaleCounter.DecrementAllFlashCount(fsRequest, flashSaleResult); } if (result.ErrorCode == "Order_FlashSale_Error") { return(new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = CreateOrderMessageDic.GetFlashSaleErrorMessage(result.ErrorMessage) }); } if (result.ErrorCode == "Invalid_PromotionCode") { return new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = "优惠券无效!" } } ; else { return(new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = "下单失败!" }); } } } } catch (Exception ex) { if (counter != null) { await counter.DecreasePurchaseCount(flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel); } if (isCheckFlash) { await FlashSaleCounter.DecrementAllFlashCount(fsRequest, flashSaleResult); } Logger.Error("调用下单接口失败" + ex.Message + ex.InnerException); return(new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = "下单失败" }); } } catch (Exception ex) { Logger.Error(ex); return(new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = "下单失败" }); } }
public static async Task <CreateOrderResult> FlashSaleCreateOrder(Order.Request.CreateOrderRequest request) { var flashrequest = new FlashSaleOrderRequest() { Products = new List <OrderItems>() }; var pintuanFlag = false; var pintuanProductGroupId = ""; var pintuanPid = ""; var pintuanCount = 0; try { if (request.Items != null && request.Items.Any()) { foreach (var item in request.Items) { if (item.ActivityId.HasValue) { var activityTypeModel = new ActivityTypeModel(); // 增加拼团校验逻辑 if (item.ActivityId != null && await GroupBuyingManager.CheckProductGroupId(item.ActivityId.Value)) { activityTypeModel = new ActivityTypeModel { ActivityId = item.ActivityId.Value, Type = 7 }; } else if ((await DalSalePromotion.CheckActivityIsEffictive(item.ActivityId.Value.ToString())))///黎先攀的打折活动 { activityTypeModel = new ActivityTypeModel { ActivityId = item.ActivityId.Value, Type = 11 }; } else { // 不是拼团ActivityId activityTypeModel = ActivityManager.SelectActivityTypeByActivityIds(new List <Guid> { item.ActivityId.Value }).FirstOrDefault(); } if (activityTypeModel != null) { var temp = flashrequest.Products.ToList(); temp.Add( new OrderItems { ActivityId = item.ActivityId, Num = item.Num, PID = item.Pid, Type = activityTypeModel.Type, Price = item.Price, ListPrice = item.ListPrice }); flashrequest.Products = temp; if (activityTypeModel.Type == 1) { //用来控制下单是否走老逻辑 item.IsVerifyActivity = false; } if (activityTypeModel.Type == 5) { item.IsVerifyActivity = false; } //砍价 if (activityTypeModel.Type == 9) { item.IsVerifyActivity = false; } if (activityTypeModel.Type == 11) { item.IsVerifyActivity = false; } //拼团 if (activityTypeModel.Type == 7) { request.Status = "0NewPingTuan"; item.IsVerifyActivity = false; var buyLimitInfo = await GroupBuyingManager.GetBuyLimitInfo(item.ActivityId.Value, item.Pid, request.Customer.UserId); if (string.IsNullOrWhiteSpace(buyLimitInfo?.PID)) { return(new CreateOrderResult { ErrorCode = -1000, ErrorMessage = "未找到该拼团产品!" }); } if (buyLimitInfo.BuyLimitCount > 0 && buyLimitInfo.BuyLimitCount <= buyLimitInfo.CurrentOrderCount) { return(new CreateOrderResult { ErrorCode = -1000, ErrorMessage = "已达到限购单数!" }); } if (item.Num > buyLimitInfo.UpperLimitPerOrder && buyLimitInfo.UpperLimitPerOrder != 0) { return(new CreateOrderResult { ErrorCode = -1000, ErrorMessage = "购买数量不符合要求!" }); } using (var client = new PinTuanClient()) { var result = await client.IncreaseSoldCountAsync(buyLimitInfo.ProductGroupId, buyLimitInfo.PID, item.Num); if (!(result.Success && result.Result.Code == 1)) { return(new CreateOrderResult { ErrorCode = -1000, ErrorMessage = result.Result?.Info ?? "出现异常" }); } pintuanFlag = true; pintuanPid = buyLimitInfo.PID; pintuanProductGroupId = buyLimitInfo.ProductGroupId; pintuanCount = item.Num; } } //锦湖轮胎 if (item.Pid.StartsWith("TR-", StringComparison.OrdinalIgnoreCase) && !await CheckIsPassKumhoTireFlashSale(item.ActivityId?.ToString(), request.Customer.UserId)) { return(new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = "此价格为企业客户专享,无法生成订单" }); } } } } } flashrequest.DeviceId = request.DeviceID; flashrequest.UseTel = request.Customer.UserTel; flashrequest.UserId = request.Customer.UserId; ICounter counter = null; #region 限时抢购校验 var fsRequest = new FlashSaleOrderRequest(); var isCheckFlash = false; var flashSaleResult = new List <CheckFlashSaleResponseModel>(); if (flashrequest.Products != null && flashrequest.Products.Any()) { var fsItems = flashrequest.Products.Where(r => r.Type == 1); var orderItemses = fsItems as OrderItems[] ?? fsItems.ToArray(); if (orderItemses.Any()) { isCheckFlash = true; fsRequest.DeviceId = flashrequest.DeviceId; fsRequest.UseTel = flashrequest.UseTel; fsRequest.UserId = flashrequest.UserId; fsRequest.Products = orderItemses; flashSaleResult = await ActivityValidator.CheckFlashSaleAsync(fsRequest); if (flashSaleResult.Any(r => r.Code != Model.CheckFlashSaleStatus.Succeed)) { return(new CreateOrderResult { ErrorCode = (int)flashSaleResult.Where(r => r.Code != Model.CheckFlashSaleStatus.Succeed).Select(c => c.Code).FirstOrDefault(), ErrorMessage = flashSaleResult.Where(r => r.Code != Model.CheckFlashSaleStatus.Succeed).Select(c => c.Code).FirstOrDefault().GetRemark() }); } flashrequest.Products = orderItemses.Select(r => { r.AllPlaceLimitId = flashSaleResult.Where(p => p.PID == r.PID) .Select(_ => _.AllPlaceLimitId) .FirstOrDefault(); return(r); }); } } #endregion #region 保养校验 if (flashrequest.Products != null && flashrequest.Products.Any()) { var byRequest = flashrequest.Products.Where(r => r.Type == 5); var activityId = byRequest.FirstOrDefault(o => o.ActivityId != Guid.Empty)?.ActivityId; if (activityId != null) { ValidateOrderRequest validateRequest = new ValidateOrderRequest() { ActivityId = activityId.Value, UserId = flashrequest.UserId, Products = request.Items.Where( o => o.ActivityId != null && o.ActivityId.HasValue && !o.Pid.StartsWith("FU-") && !o.Pid.StartsWith("TR-")) .Select(o => new OrderProduct() { ProductId = o.Pid, Count = o.Num, ActivityId = o.ActivityId.Value, Price = o.Price, ProductType = "Product" }).ToList(), ShopId = request.Delivery.InstallShopId ?? 0, Channel = request.OrderChannel, InstallType = request.Delivery.InstallType, Vehicle = Converter.Convert(request.Car), RegionId = 1 }; using (var client = new BaoYangClient()) { var baoyangResult = await client.ValidateFixedPriceActivityOrderAsync(validateRequest); if (!baoyangResult.Success || !baoyangResult.Result) { return(new CreateOrderResult() { ErrorCode = (int)CreateOrderErrorCode.ProductValidateFailed, ErrorMessage = CreateOrderMessageDic.GetMessage(CreateOrderErrorCode.ProductValidateFailed) }); } } // 验证活动状态 var validateResult = await ActivityValidator.ValidateBaoyang(activityId.Value); if (validateResult.Item1 == Model.CreateOrderErrorCode.ActivitySatisfied) { // 验证限购数量 counter = new BaoYangCounter(activityId.Value, validateResult.Item2, validateResult.Item3, validateResult.Item4); var countResult = await counter.CanPurchaseAndIncreaseCount(flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel); if (countResult.Code != Model.CreateOrderErrorCode.ActivitySatisfied) { return(new CreateOrderResult() { ErrorCode = (int)countResult.Code, ErrorMessage = CreateOrderMessageDic.GetMessage(countResult.Code) }); } } else { return(new CreateOrderResult() { ErrorCode = (int)validateResult.Item1, ErrorMessage = CreateOrderMessageDic.GetMessage(validateResult.Item1) }); } } } #endregion #region 分享砍价活动 bool bargainflag = false; Guid ownerId = new Guid(); string pid = ""; var parameters = new List <BuyLimitDetailModel>(); if (flashrequest.Products != null && flashrequest.Products.Any()) { var item = flashrequest.Products.FirstOrDefault(g => g.Type == 9); if (item != null) { ownerId = flashrequest.UserId; pid = item.PID; parameters.Add(new BuyLimitDetailModel { ModuleName = "sharebargain", LimitObjectId = ownerId.ToString("D"), ObjectType = LimitObjectTypeEnum.UserId.ToString(), Remark = "砍价实物商品下单" }); if (!string.IsNullOrWhiteSpace(flashrequest.DeviceId)) { parameters.Add(new BuyLimitDetailModel { ModuleName = "sharebargain", LimitObjectId = flashrequest.DeviceId, ObjectType = LimitObjectTypeEnum.DeviceId.ToString(), Remark = "砍价实物商品下单" }); } var val = await DalBargain.CheckBargainProductStatusByPID(ownerId, pid); if (!val) { return(new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = "您当前没有资格享受该优惠!" }); } bargainflag = true; } } #endregion IEnumerable <OrderItems> discountProducts = null; #region 黎先攀的打折活动 if (flashrequest.Products != null && flashrequest.Products.Any()) { discountProducts = flashrequest.Products.Where(r => r.Type == 11);///打折活动商品 if (discountProducts.Any()) { var productHitDiscountManager = new ProductHitDiscountManager(discountProducts.Select(s => new DiscountActivityRequest() { Pid = s.PID, Num = s.Num, Price = s.ListPrice }).ToList(), request.Customer.UserId.ToString(), false, true); var realProductDiscounts = (await productHitDiscountManager.GetProductHitDiscountInfo()).ToList();//实时产品折扣信息 var effictiveDiscountNum = discountProducts.Join(realProductDiscounts, x => x.PID, y => y.Pid, (x, y) => { return(y.IsHit && string.Equals(y.DiscountRule?.ActivityId, x.ActivityId.ToString()) && Convert.ToInt32(y.DiscountPrice) == Convert.ToInt32(x.Price)); }).Where(s => s).Count(); if (effictiveDiscountNum != discountProducts.Count()) { var firtNotHitProduct = realProductDiscounts.FirstOrDefault(s => !s.IsHit); foreach (var item in discountProducts) { if (item.ActivityId != null && item.ActivityId != Guid.Empty) { TuhuNotification.SendNotification("DiscountActivityCreateOrder", new DiscountCreateOrderRequest() { ActivityId = item.ActivityId.ToString(), Num = item.Num, Pid = item.PID, UserId = request.Customer.UserId.ToString() }); } } var errorMsg = firtNotHitProduct != null ? firtNotHitProduct.FailMessage : "打折规则已变更"; Logger.Info($"打折活动下单失败:{errorMsg},discountProducts:{JsonConvert.SerializeObject(discountProducts)}," + $"realProductDiscounts:{JsonConvert.SerializeObject(realProductDiscounts)}"); return(new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = errorMsg }); } } } #endregion try { using (var client = new CreateOrderClient()) { var result = await client.CreateOrderAsync(request); result.ThrowIfException(); if (result.Success) { if (counter != null) { await counter.AddOrderRecord(result.Result.OrderId, flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel); } if (bargainflag) { var tal = await DalBargain.BuyBargainProductAsync(ownerId, pid, result.Result.OrderId); if (tal > 0) { parameters.ForEach(g => { g.ModuleProductId = tal.ToString(); g.Reference = result.Result.OrderId.ToString(); }); await LimitBuyManager.AddBuyLimitInfo(parameters); Logger.Info($"UserId为{ownerId}的用户享受砍价优惠,已购买pid为{pid}的商品"); } else { Logger.Error($"UserId为{ownerId}的用户享受砍价优惠,购买pid为{pid}的商品,修改购买状态时出错"); } } flashrequest.OrderId = result.Result.OrderId; if (isCheckFlash) { Logger.Info($"下单成功订单号=>{flashrequest.OrderId}发送消息"); try { TuhuNotification.SendNotification(".FlashSaleCreateOrder.", flashrequest); } catch (Exception ex) { var str = ""; try { str = JsonConvert.SerializeObject(flashrequest); } catch (Exception) { str = result.Result.OrderId.ToString(); } Logger.Error($"request-->{str}-->mq发送失败", ex); } } if (discountProducts != null && discountProducts.Any())//如果是黎先攀的打折活动 { foreach (var item in discountProducts) { if (item.ActivityId != null && item.ActivityId != Guid.Empty) { TuhuNotification.SendNotification("DiscountActivityCreateOrder", new DiscountCreateOrderRequest() { ActivityId = item.ActivityId.ToString(), Num = item.Num, OrderId = result.Result.OrderId, Pid = item.PID, UserId = request.Customer.UserId.ToString() }); } } } return(new CreateOrderResult { OrderId = result.Result.OrderId, OrderNo = result.Result.OrderNo }); } else { // 拼团下单失败,修改虚拟库存 if (pintuanFlag) { using (var client2 = new PinTuanClient()) { var result2 = await client2.DecrementSoldCountAsync(pintuanProductGroupId, pintuanPid, pintuanCount); if (!(result2.Success && result2.Result.Code == 1)) { Logger.Error($"拼团产品下单失败,虚拟库存修改失败-->{pintuanProductGroupId}/{pintuanPid}/{pintuanCount}"); } } } if (counter != null) { await counter.DecreasePurchaseCount(flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel); } Logger.Info("调用下单接口失败" + result.ErrorCode + result.ErrorMessage); if (isCheckFlash) { await FlashSaleCounter.DecrementAllFlashCount(fsRequest, flashSaleResult); } if (result.ErrorCode == "Order_FlashSale_Error") { return(new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = CreateOrderMessageDic.GetFlashSaleErrorMessage(result.ErrorMessage) }); } if (result.ErrorCode == "Invalid_PromotionCode") { return new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = "优惠券无效!" } } ; else { return(new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = "下单失败!" }); } } } } catch (Exception ex) { if (counter != null) { await counter.DecreasePurchaseCount(flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel); } if (isCheckFlash) { await FlashSaleCounter.DecrementAllFlashCount(fsRequest, flashSaleResult); } Logger.Error("调用下单接口失败" + ex.Message + ex.InnerException); return(new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = "下单失败" }); } } catch (Exception ex) { Logger.Error(ex); return(new CreateOrderResult() { ErrorCode = -1000, ErrorMessage = "下单失败" }); } }