步步为盈
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.

743 lines
38 KiB

using BBWY.Common.Extensions;
using BBWY.Common.Http;
using BBWY.Common.Models;
using BBWY.Server.Model;
using BBWY.Server.Model.Db;
using BBWY.Server.Model.Dto;
using FreeSql;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Yitter.IdGenerator;
namespace BBWY.Server.Business
{
public class EvaluationAssistantBusiness : BasePlatformRelayBusiness, IDenpendency
{
private IFreeSql fsql;
private IIdGenerator idGenerator;
private TaskSchedulerManager taskSchedulerManager;
private VenderBusiness venderBusiness;
private DingDingBusiness dingDingBusiness;
private NLogManager nLogManager;
private List<Enums.OrderState> validOrderStateList;
public EvaluationAssistantBusiness(RestApiService restApiService, IOptions<GlobalConfig> options, YunDingBusiness yunDingBusiness, IFreeSql fsql, IIdGenerator idGenerator, TaskSchedulerManager taskSchedulerManager, VenderBusiness venderBusiness, DingDingBusiness dingDingBusiness, NLogManager nLogManager) : base(restApiService, options, yunDingBusiness)
{
this.fsql = fsql;
this.idGenerator = idGenerator;
this.taskSchedulerManager = taskSchedulerManager;
this.venderBusiness = venderBusiness;
this.dingDingBusiness = dingDingBusiness;
this.nLogManager = nLogManager;
validOrderStateList = new List<Enums.OrderState>()
{
Enums.OrderState.,
Enums.OrderState.,
Enums.OrderState.,
Enums.OrderState.,
Enums.OrderState.,
Enums.OrderState.
};
}
#region 赠品模板
public void AddOrEditGiftTemplate(AddOrEditGiftTemplateRequest request)
{
if (string.IsNullOrEmpty(request.TemplateName))
throw new BusinessException("缺少模板名称");
if (request.GiftSkuList == null || request.GiftSkuList.Count() == 0)
throw new BusinessException("缺少赠品SKU");
IInsert<GiftTemplate> insert = null;
IUpdate<GiftTemplate> update = null;
IDelete<GiftTemplateSku> delete = null;
List<GiftTemplateSku> inserList = null;
long giftTemplateId = request.Id;
if (giftTemplateId == 0)
{
giftTemplateId = idGenerator.NewLong();
var giftTemplate = new GiftTemplate()
{
Id = giftTemplateId,
CreateTime = DateTime.Now,
TemplateName = request.TemplateName,
Platform = Enums.Platform.,
ShopId = request.ShopId,
TemplateSpu = request.TemplateSpu,
GiftCount = request.GiftSkuList.Count()
};
insert = fsql.Insert(giftTemplate);
}
else
{
update = fsql.Update<GiftTemplate>(giftTemplateId).Set(g => g.TemplateName, request.TemplateName)
.Set(g => g.TemplateSpu, request.TemplateSpu)
.Set(g => g.GiftCount, request.GiftSkuList.Count());
delete = fsql.Delete<GiftTemplateSku>().Where(gs => gs.GiftTemplateId == giftTemplateId);
}
inserList = request.GiftSkuList.Select(gs => new GiftTemplateSku()
{
Id = idGenerator.NewLong(),
CreateTime = DateTime.Now,
GiftTemplateId = giftTemplateId,
Logo = gs.Logo,
Price = gs.Price,
Title = gs.Title,
ShopId = request.ShopId,
SkuId = gs.SkuId,
SpuId = request.TemplateSpu
}).ToList();
fsql.Transaction(() =>
{
insert?.ExecuteAffrows();
update?.ExecuteAffrows();
delete?.ExecuteAffrows();
fsql.Insert(inserList).ExecuteAffrows();
});
}
public IList<GiftTemplateResponse> GetGiftTemplateList(long shopId)
{
var templateList = fsql.Select<GiftTemplate>().Where(g => g.ShopId == shopId).ToList<GiftTemplateResponse>();
var templateIdList = templateList.Select(g => g.Id).ToList();
var templateSkuList = fsql.Select<GiftTemplateSku>().Where(gs => templateIdList.Contains(gs.GiftTemplateId.Value)).ToList<GiftTemplateSkuResponse>();
foreach (var template in templateList)
{
template.GiftSkuList = templateSkuList.Where(gs => gs.GiftTemplateId == template.Id).ToList();
}
return templateList;
}
public void DeleteGiftTemplate(long giftTemplateId)
{
fsql.Transaction(() =>
{
fsql.Delete<GiftTemplate>(giftTemplateId).ExecuteAffrows();
fsql.Delete<GiftTemplateSku>().Where(gs => gs.GiftTemplateId == giftTemplateId).ExecuteAffrows();
});
}
#endregion
#region 评价助手任务
public void AddOrEditPromotionTask(AddOrEditPromotionTaskRequest request)
{
if (string.IsNullOrEmpty(request.MainProductSpu))
throw new BusinessException("缺少主商品SPU");
if (request.MotherTemplateId == 0 && string.IsNullOrEmpty(request.MainProductSku) && string.IsNullOrEmpty(request.CustomMotherSku))
throw new BusinessException("奶妈模板,奶妈自定义SKU,主商品SKU至少具备一个");
if (request.GiftTemplateId == 0 && string.IsNullOrEmpty(request.MainProductGiftSku))
throw new BusinessException("赠品模板和主商品赠品SKU至少具备一个");
if (string.IsNullOrEmpty(request.FullTitle))
throw new BusinessException("缺少完整标题");
if (string.IsNullOrEmpty(request.ActivityName))
throw new BusinessException("缺少任务名称");
if (request.ActivityName.Length > 10)
throw new BusinessException("任务名称不能超过10个字");
if (request.TaskCount == 0)
throw new BusinessException("任务量不能为0");
request.FullTitle = request.FullTitle.Trim();
request.ActivityName = request.ActivityName.Trim();
request.MainProductSpu = request.MainProductSpu.Trim();
if (!string.IsNullOrEmpty(request.MainProductSku))
request.MainProductSku = request.MainProductSku.Trim();
if (!string.IsNullOrEmpty(request.CustomMotherSku))
request.CustomMotherSku = request.CustomMotherSku.Trim();
if (!string.IsNullOrEmpty(request.MainProductGiftSku))
request.MainProductGiftSku = request.MainProductGiftSku.Trim();
if (request.Id == 0)
{
var relayAPIHost = GetPlatformRelayAPIHost(Enums.Platform.);
var restApiResult_spu = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/GetProductList", new SearchProductRequest()
{
AppKey = request.AppKey,
AppSecret = request.AppSecret,
AppToken = request.AppToken,
PageIndex = 1,
PageSize = 10,
Platform = Enums.Platform.,
Spu = request.MainProductSpu
}, GetYunDingRequestHeader(), HttpMethod.Post);
if (restApiResult_spu.StatusCode != System.Net.HttpStatusCode.OK)
throw new BusinessException(restApiResult_spu.Content) { Code = (int)restApiResult_spu.StatusCode };
var spuResponse = JsonConvert.DeserializeObject<ApiResponse<ProductListResponse>>(restApiResult_spu.Content);
if (!spuResponse.Success)
throw new BusinessException(spuResponse.Msg) { Code = spuResponse.Code };
var sort = fsql.Select<PromotionTask>().ToAggregate(p => p.Max(p.Key.Sort));
var promotionTask = new PromotionTask()
{
Id = idGenerator.NewLong(),
ActivityName = request.ActivityName,
CreateTime = DateTime.Now,
FullTitle = request.FullTitle,
ShopId = request.ShopId,
SimpleTitle = request.SimpleTitle,
GiftTemplateId = request.GiftTemplateId,
MainProductGiftSku = request.MainProductGiftSku,
MainProductSku = request.MainProductSku,
MainProductSpu = request.MainProductSpu,
MotherTemplateId = request.MotherTemplateId,
IsEnabled = true,
Status = Enums.PromitionTaskStatus.,
PromotionId = 0,
Sort = sort + 1,
UpdateSortTime = DateTime.Now,
SpuLogo = spuResponse.Data.Items[0].Logo,
SpuPublishTime = spuResponse.Data.Items[0].CreateTime,
TaskCount = request.TaskCount,
CustomMotherSku = request.CustomMotherSku
};
fsql.Insert(promotionTask).ExecuteAffrows();
}
else
{
var dbPromotionTask = fsql.Select<PromotionTask>(request.Id).ToOne();
if (dbPromotionTask == null)
throw new BusinessException("任务不存在");
if (dbPromotionTask.Status != Enums.PromitionTaskStatus.)
throw new BusinessException("只能在任务处于等待状态时才能修改");
request.Map(dbPromotionTask);
fsql.Update<PromotionTask>().SetSource(dbPromotionTask)
.IgnoreColumns(new string[]
{
"UpdateSortTime",
"Sort", "Status",
"CreateTime",
"SpuLogo",
"SpuPublishTime",
"StartTime",
"EndTime",
"StopTime",
"CompletedTaskCount"
})
.ExecuteAffrows();
}
}
/// <summary>
/// 获取任务列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public PromotionTaskResponse GetPromotionTaskList(QueryPromotionTaskRequest request)
{
var list = fsql.Select<PromotionTask>().Where(pt => pt.ShopId == request.ShopId)
.OrderByDescending(pt => pt.Sort)
.OrderByDescending(pt => pt.UpdateSortTime)
.Page(request.PageIndex, request.PageSize)
.Count(out long count)
.ToList<PromotionTaskItemResponse>();
return new PromotionTaskResponse()
{
Count = count,
ItemList = list
};
}
/// <summary>
/// 修改任务排序
/// </summary>
/// <param name="request"></param>
public void EditPromotionTaskSort(EditPromotionTaskSortRequest request)
{
var dbPromotionTask = fsql.Select<PromotionTask>(request.Id).ToOne();
PromotionTask oldDbPromotionTask = null;
if (request.MoveType == 1)
oldDbPromotionTask = fsql.Select<PromotionTask>().Where(pt => pt.Sort > dbPromotionTask.Sort).OrderBy(pt => pt.Sort).ToOne();
else
oldDbPromotionTask = fsql.Select<PromotionTask>().Where(pt => pt.Sort < dbPromotionTask.Sort).OrderByDescending(pt => pt.Sort).ToOne();
if (oldDbPromotionTask != null)
{
fsql.Transaction(() =>
{
fsql.Update<PromotionTask>(dbPromotionTask.Id).Set(pt => pt.Sort, oldDbPromotionTask.Sort)
.Set(pt => pt.UpdateSortTime, DateTime.Now)
.ExecuteAffrows();
fsql.Update<PromotionTask>(oldDbPromotionTask.Id).Set(pt => pt.Sort, dbPromotionTask.Sort)
.Set(pt => pt.UpdateSortTime, DateTime.Now)
.ExecuteAffrows();
});
}
}
/// <summary>
/// 检查任务重复sku
/// </summary>
/// <param name="runingTaskList"></param>
/// <param name="skuIds"></param>
private void CheckRepeatSkuInRuningTask(IList<PromotionTask> runingTaskList, string skuIds)
{
var skuIdList = skuIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var pt in runingTaskList)
{
foreach (var sku in skuIdList)
{
//判断奶妈模板sku重复
//判断自定义奶妈sku重复
if ((!string.IsNullOrEmpty(pt.CustomMotherSku) && pt.CustomMotherSku.Contains(sku)) ||
(!string.IsNullOrEmpty(pt.MainProductSku) && pt.MainProductSku.Contains(sku)))
{
throw new BusinessException($"sku[{sku}]已存在于任务[{pt.ActivityName}]的奶妈sku中,请删除该sku或等待任务结束");
}
}
}
}
/// <summary>
/// 开始任务
/// </summary>
/// <param name="request"></param>
public void StartPromotionTask(StartPromotionTaskRequest request)
{
var dbPromotionTask = fsql.Select<PromotionTask>(request.Id).ToOne();
if (dbPromotionTask == null)
throw new BusinessException("任务不存在");
if (dbPromotionTask.Status != Enums.PromitionTaskStatus.)
throw new BusinessException("只能在任务处于等待状态时才能开始");
IList<GiftTemplateSkuRequest> giftTemplateSkuList = null; //赠品模板sku
var motherTemplateSku = string.Empty; //奶妈模板的sku
if (dbPromotionTask.GiftTemplateId != null && dbPromotionTask.GiftTemplateId != 0)
{
giftTemplateSkuList = fsql.Select<GiftTemplateSku>().Where(gs => gs.GiftTemplateId == dbPromotionTask.GiftTemplateId).ToList(gs => new GiftTemplateSkuRequest()
{
Logo = gs.Logo,
Price = gs.Price,
SkuId = gs.SkuId,
Title = gs.Title
});
if (giftTemplateSkuList == null || giftTemplateSkuList.Count() == 0)
throw new BusinessException("赠品模板不存在");
}
var runingTaskList = fsql.Select<PromotionTask>().Where(pt => pt.ShopId == dbPromotionTask.ShopId && pt.Status == Enums.PromitionTaskStatus.).ToList();
if (dbPromotionTask.MotherTemplateId != null && dbPromotionTask.MotherTemplateId != 0)
{
}
if (!string.IsNullOrEmpty(dbPromotionTask.CustomMotherSku))
CheckRepeatSkuInRuningTask(runingTaskList, dbPromotionTask.CustomMotherSku);
if (!string.IsNullOrEmpty(motherTemplateSku))
CheckRepeatSkuInRuningTask(runingTaskList, motherTemplateSku);
if (!string.IsNullOrEmpty(dbPromotionTask.MainProductSku))
CheckRepeatSkuInRuningTask(runingTaskList, dbPromotionTask.MainProductSku);
var host = GetPlatformRelayAPIHost(Enums.Platform.);
var httpApiResult = restApiService.SendRequest(host, "api/PlatformSDK/StartJDPromotionTask", new StartPromotionTaskRequest2()
{
Id = dbPromotionTask.Id,
ActivityName = dbPromotionTask.ActivityName,
AppKey = request.AppKey,
AppSecret = request.AppSecret,
AppToken = request.AppToken,
SimpleTitle = dbPromotionTask.SimpleTitle,
FullTitle = dbPromotionTask.FullTitle,
GiftTemplateSkuList = giftTemplateSkuList,
MainProductGiftSku = dbPromotionTask.MainProductGiftSku,
MainProductSku = dbPromotionTask.MainProductSku,
MotherTemplateSku = motherTemplateSku,
CustomMotherSku = dbPromotionTask.CustomMotherSku,
MainProductSpu = dbPromotionTask.MainProductSpu,
Platform = Enums.Platform.,
ShopId = dbPromotionTask.ShopId.Value
}, GetYunDingRequestHeader(), HttpMethod.Post);
if (httpApiResult.StatusCode != System.Net.HttpStatusCode.OK)
throw new BusinessException(httpApiResult.Content);
var response = JsonConvert.DeserializeObject<ApiResponse<StartPromotionTaskResponse>>(httpApiResult.Content);
if (!response.Success)
throw new BusinessException(response.Msg);
var startResponse = response.Data;
if (dbPromotionTask.GiftTemplateId != null &&
dbPromotionTask.GiftTemplateId != 0 &&
startResponse.DeleteGiftSkuList != null &&
startResponse.DeleteGiftSkuList.Count() != 0)
dbPromotionTask.GiftTemplatePutNewSku = string.Join(",", startResponse.DeleteGiftSkuList);
fsql.Update<PromotionTask>(request.Id).Set(pt => pt.PromotionId, startResponse.JDPromotionId)
.SetIf(!string.IsNullOrEmpty(dbPromotionTask.GiftTemplatePutNewSku), pt => pt.GiftTemplatePutNewSku, dbPromotionTask.GiftTemplatePutNewSku)
.Set(pt => pt.StartTime, DateTime.Now)
.Set(pt => pt.EndTime, DateTime.Now.AddDays(180))
.Set(pt => pt.Status, Enums.PromitionTaskStatus.)
.ExecuteAffrows();
//开启延迟任务
Task.Factory.StartNew(() => StartPromotionDelayTask(request, startResponse, dbPromotionTask), CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.JDPromotionDelayTaskScheduler);
}
private void StartPromotionDelayTask(StartPromotionTaskRequest request, StartPromotionTaskResponse startResponse, PromotionTask promotionTask)
{
var host = GetPlatformRelayAPIHost(Enums.Platform.);
var httpApiResult = restApiService.SendRequest(host, "api/PlatformSDK/StartJDPromotionDelayTask", new StartPromotionTaskDelayRequest()
{
Platform = Enums.Platform.,
AppKey = request.AppKey,
AppSecret = request.AppSecret,
AppToken = request.AppToken,
BrandName = startResponse.BrandName,
FullTitle = promotionTask.FullTitle,
JDPromotionId = startResponse.JDPromotionId,
MainProductSpu = promotionTask.MainProductSpu,
HaveGiftTemplate = promotionTask.GiftTemplateId != null && promotionTask.GiftTemplateId != 0,
DeleteGiftSkuList = startResponse.DeleteGiftSkuList
}, GetYunDingRequestHeader(), HttpMethod.Post, timeOutSeconds: 150);
var errorBack = new Action<long, string>((id, errorMsg) =>
{
fsql.Update<PromotionTask>(id).Set(pt => pt.Status, Enums.PromitionTaskStatus.)
.Set(pt => pt.ErrorMsg, errorMsg)
.ExecuteAffrows();
});
if (httpApiResult.StatusCode != System.Net.HttpStatusCode.OK)
{
errorBack(promotionTask.Id, httpApiResult.Content);
return;
}
var response = JsonConvert.DeserializeObject<ApiResponse<object>>(httpApiResult.Content);
if (!response.Success)
{
errorBack(promotionTask.Id, response.Msg);
return;
}
}
/// <summary>
/// 删除任务和京东任务
/// </summary>
/// <param name="request"></param>
public void DeletePromotionTaskAndJDTask(DeletePromotionTaskRequest request)
{
var dbPromotionTask = fsql.Select<PromotionTask>(request.TaskId).ToOne();
if (dbPromotionTask.Status != Enums.PromitionTaskStatus.)
{
var httpResult = restApiService.SendRequest(GetPlatformRelayAPIHost(Enums.Platform.),
"api/platformsdk/DeleteJDPromotionTask",
new DeleteJDPromotionTaskRequest()
{
AppKey = request.AppKey,
AppSecret = request.AppSecret,
AppToken = request.AppToken,
Platform = Enums.Platform.,
PromotionId = dbPromotionTask.PromotionId.Value
},
GetYunDingRequestHeader(),
HttpMethod.Post);
if (httpResult.StatusCode != System.Net.HttpStatusCode.OK)
throw new BusinessException(httpResult.Content);
var response = JsonConvert.DeserializeObject<ApiResponse>(httpResult.Content);
if (!response.Success)
throw new BusinessException(response.Msg);
}
fsql.Delete<PromotionTask>(request.TaskId).ExecuteAffrows();
}
/// <summary>
/// 删除任务和奶妈SKU
/// </summary>
/// <param name="request"></param>
public void DeletePromotionTaskAndMotherSku(DeletePromotionTaskRequest request)
{
var dbPromotionTask = fsql.Select<PromotionTask>(request.TaskId).ToOne();
if (dbPromotionTask.Status != Enums.PromitionTaskStatus.)
{
List<string> motherSkuIdList = new List<string>();
if (dbPromotionTask.MotherTemplateId != null)
{
}
if (!string.IsNullOrEmpty(dbPromotionTask.CustomMotherSku))
motherSkuIdList.AddRange(dbPromotionTask.CustomMotherSku.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
var httpResult = restApiService.SendRequest(GetPlatformRelayAPIHost(Enums.Platform.),
"api/platformsdk/DeleteJDPromotionTaskSku",
new DeleteJDPromotionTaskSkuRequest()
{
AppKey = request.AppKey,
AppSecret = request.AppSecret,
AppToken = request.AppToken,
Platform = Enums.Platform.,
PromotionId = dbPromotionTask.PromotionId.Value,
SkuId = string.Join(",", motherSkuIdList)
},
GetYunDingRequestHeader(),
HttpMethod.Post);
if (httpResult.StatusCode != System.Net.HttpStatusCode.OK)
throw new BusinessException(httpResult.Content);
var response = JsonConvert.DeserializeObject<ApiResponse>(httpResult.Content);
if (!response.Success)
throw new BusinessException(response.Msg);
}
fsql.Delete<PromotionTask>(request.TaskId).ExecuteAffrows();
}
/// <summary>
/// 停止任务
/// </summary>
/// <param name="request"></param>
/// <exception cref="BusinessException"></exception>
public void StopPromotionTask(StopPromotionTaskRequest request)
{
var dbPromotionTask = fsql.Select<PromotionTask>(request.Id).ToOne();
if (dbPromotionTask == null)
throw new BusinessException("任务不存在");
if (dbPromotionTask.Status != Enums.PromitionTaskStatus.)
throw new BusinessException("只能在任务处于进行中时才能停止");
var httpResult = restApiService.SendRequest(GetPlatformRelayAPIHost(Enums.Platform.),
"api/platformsdk/SuspendJDPromotionTask",
new SuspendDPromotionTaskRequest()
{
AppKey = request.AppKey,
AppSecret = request.AppSecret,
AppToken = request.AppToken,
Platform = Enums.Platform.,
PromotionId = dbPromotionTask.PromotionId.Value
},
GetYunDingRequestHeader(),
HttpMethod.Post);
if (httpResult.StatusCode != System.Net.HttpStatusCode.OK)
throw new BusinessException(httpResult.Content);
var response = JsonConvert.DeserializeObject<ApiResponse>(httpResult.Content);
if (!response.Success)
throw new BusinessException(response.Msg);
fsql.Update<PromotionTask>(request.Id).Set(pt => pt.Status, Enums.PromitionTaskStatus.).ExecuteAffrows();
}
#endregion
#region 自动任务
public void StartMonitor(long? shopId)
{
//查询店铺
var shopList = venderBusiness.GetShopList(shopId, Enums.Platform.);
//查询正在进行的任务
var runningTaskList = fsql.Select<PromotionTask>()
.WhereIf(shopId != null, pt => pt.ShopId == shopId)
.Where(pt => pt.Status == Enums.PromitionTaskStatus.).ToList();
if (runningTaskList == null || runningTaskList.Count() == 0)
return;
var runningTaskIdList = runningTaskList.Select(pt => pt.Id).ToList();
//查询订单sku
var querySkuTime = DateTime.Now.AddHours(-2);
var orderSkuList = fsql.Select<OrderSku, Order>()
.InnerJoin((osku, o) => osku.OrderId == o.Id)
.WhereIf(shopId != null, (osku, o) => o.ShopId == shopId)
.Where((osku, o) => o.StorageType != Enums.StorageType.SD && o.StorageType != null)
.Where((osku, o) => validOrderStateList.Contains(o.OrderState.Value))
.Where((osku, o) => osku.Price > 0 && osku.CreateTime >= querySkuTime)
.ToList((osku, o) => new OrderSku
{
CreateTime = osku.CreateTime,
Id = osku.Id,
IsRefund = osku.IsRefund,
ItemTotal = osku.ItemTotal,
Logo = osku.Logo,
OrderDropShippingId = osku.OrderDropShippingId,
OrderId = osku.OrderId,
Price = osku.Price,
ProductId = osku.ProductId,
SkuId = osku.SkuId,
ProductNo = osku.ProductNo,
Title = osku.Title,
ShopId = o.ShopId
});
//查询已记录的任务进度sku
var promotionTaskSkuRecordList = fsql.Select<PromotionTaskSkuRecord>()
.WhereIf(shopId != null, psr => psr.ShopId == shopId)
.Where(psr => runningTaskIdList.Contains(psr.PromotionTaskId))
.Where(psr => psr.CreateTime >= querySkuTime)
.ToList();
foreach (var shop in shopList)
{
var sId = long.Parse(shop.ShopId);
var currentShopRunningTaskList = runningTaskList.Where(pt => pt.ShopId == sId).ToList();
if (currentShopRunningTaskList == null || currentShopRunningTaskList.Count() == 0)
continue;
var currentOrderSkuList = orderSkuList.Where(osku => osku.ShopId == sId).ToList();
if (currentOrderSkuList == null || currentOrderSkuList.Count() == 0)
continue;
var currentPromotionTaskSkuRecordList = promotionTaskSkuRecordList.Where(psr => psr.ShopId == sId).ToList();
Task.Factory.StartNew(() => MonitorTaskCore(shop, sId, currentShopRunningTaskList, currentOrderSkuList, currentPromotionTaskSkuRecordList), CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.JDPromotionMonitorTaskScheduler);
}
}
/// <summary>
/// 监控
/// </summary>
/// <param name="shop"></param>
/// <param name="shopId"></param>
/// <param name="runningTaskList"></param>
/// <param name="orderSkuList"></param>
/// <param name="promotionTaskSkuRecordList"></param>
private void MonitorTaskCore(ShopResponse shop,
long shopId,
IList<PromotionTask> runningTaskList,
IList<OrderSku> orderSkuList,
IList<PromotionTaskSkuRecord> promotionTaskSkuRecordList)
{
var loggerName = $"库存预警-{shop.ShopName}";
List<IUpdate<PromotionTask>> updatePromotionTaskList = new List<IUpdate<PromotionTask>>();
List<PromotionTaskSkuRecord> insertPromotionTaskSkuRecordList = new List<PromotionTaskSkuRecord>();
IList<long> jobDoneTaskIdList = new List<long>();
foreach (var promotionTask in runningTaskList)
{
var motherSkuList = new List<string>();
if (!string.IsNullOrEmpty(promotionTask.CustomMotherSku))
motherSkuList.AddRange(promotionTask.CustomMotherSku.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
if (!string.IsNullOrEmpty(promotionTask.MainProductSku))
motherSkuList.AddRange(promotionTask.MainProductSku.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
var newOrderSkuList = orderSkuList.Where(osku => motherSkuList.Contains(osku.SkuId) &&
osku.CreateTime > promotionTask.StartTime &&
promotionTaskSkuRecordList.Count(psr => psr.PromotionTaskId == promotionTask.Id &&
psr.OrderId == osku.OrderId) == 0).ToList();
//if (newOrderSkuList.Count() == 0)
// continue;
var completedTaskCount = 0;
if (newOrderSkuList.Count() > 0)
{
foreach (var newOrderSku in newOrderSkuList)
{
completedTaskCount += newOrderSku.ItemTotal ?? 1;
insertPromotionTaskSkuRecordList.Add(new PromotionTaskSkuRecord()
{
CreateTime = DateTime.Now,
Id = idGenerator.NewLong(),
ItemTotal = newOrderSku.ItemTotal ?? 1,
OrderId = newOrderSku.OrderId,
PromotionTaskId = promotionTask.Id,
ShopId = shopId,
SkuId = newOrderSku.SkuId
});
}
}
promotionTask.CompletedTaskCount += completedTaskCount;
var isDone = promotionTask.CompletedTaskCount >= promotionTask.TaskCount || (promotionTask.EndTime != null && promotionTask.EndTime < DateTime.Now);
if (completedTaskCount > 0 || isDone)
{
var updatePromotionTask = fsql.Update<PromotionTask>(promotionTask.Id)
.Set(pt => pt.CompletedTaskCount, promotionTask.CompletedTaskCount)
.SetIf(isDone, pt => pt.Status, Enums.PromitionTaskStatus.)
.SetIf(isDone, pt => pt.StopTime, DateTime.Now);
updatePromotionTaskList.Add(updatePromotionTask);
if (isDone)
{
if (promotionTask.EndTime < DateTime.Now)
{
#region 提前完成任务量,暂停JD活动
{
var httpResult = restApiService.SendRequest(GetPlatformRelayAPIHost(Enums.Platform.),
"api/platformsdk/SuspendJDPromotionTask",
new SuspendDPromotionTaskRequest()
{
AppKey = shop.AppKey2,
AppSecret = shop.AppSecret2,
AppToken = shop.AppToken2,
Platform = Enums.Platform.,
PromotionId = promotionTask.PromotionId.Value
},
GetYunDingRequestHeader(),
HttpMethod.Post);
if (httpResult.StatusCode != System.Net.HttpStatusCode.OK)
{
LogMonitorError(shop, loggerName, "自动任务-暂停京东活动", httpResult.Content);
}
else
{
var response = JsonConvert.DeserializeObject<ApiResponse>(httpResult.Content);
if (!response.Success)
{
LogMonitorError(shop, loggerName, "自动任务-暂停京东活动", response.Msg);
}
}
}
#endregion
}
jobDoneTaskIdList.Add(promotionTask.Id); //记录完成任务
}
}
}
fsql.Transaction(() =>
{
if (updatePromotionTaskList.Count() > 0)
foreach (var update in updatePromotionTaskList)
update.ExecuteAffrows();
if (insertPromotionTaskSkuRecordList.Count() > 0)
fsql.Insert(insertPromotionTaskSkuRecordList).ExecuteAffrows();
});
#region 开始后续任务
if (jobDoneTaskIdList.Count() > 0)
{
}
#endregion
}
private void LogMonitorError(ShopResponse shop, string loggerName, string step, string error)
{
nLogManager.GetLogger(loggerName).Error($"{step},{error}");
//send dingding
}
#endregion
}
}