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

1264 lines
67 KiB

using BBWY.Common.Extensions;
using BBWY.Common.Http;
3 years ago
using BBWY.Common.Models;
using BBWY.Server.Model;
using BBWY.Server.Model.Db;
3 years ago
using BBWY.Server.Model.Dto;
using FreeSql;
//using Jd.Api.Domain;
3 years ago
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
2 years ago
using Newtonsoft.Json.Linq;
using NLog.LayoutRenderers.Wrappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
2 years ago
using System.Text;
2 years ago
using System.Threading;
using System.Threading.Tasks;
3 years ago
using Yitter.IdGenerator;
namespace BBWY.Server.Business
{
public class EvaluationAssistantBusiness : BasePlatformRelayBusiness, IDenpendency
{
private IFreeSql fsql;
private IIdGenerator idGenerator;
2 years ago
private TaskSchedulerManager taskSchedulerManager;
private VenderBusiness venderBusiness;
2 years ago
private DingDingBusiness dingDingBusiness;
private NLogManager nLogManager;
private List<Enums.OrderState> validOrderStateList;
2 years ago
private List<Enums.PromitionTaskStatus> preTaskStateList;
2 years ago
private ProductBusiness productBusiness;
private FreeSqlMultiDBManager freeSqlMultiDBManager;
private char[] spliter;
2 years ago
public EvaluationAssistantBusiness(RestApiService restApiService, IOptions<GlobalConfig> options, YunDingBusiness yunDingBusiness, IFreeSql fsql, IIdGenerator idGenerator, TaskSchedulerManager taskSchedulerManager, VenderBusiness venderBusiness, DingDingBusiness dingDingBusiness, NLogManager nLogManager, ProductBusiness productBusiness, FreeSqlMultiDBManager freeSqlMultiDBManager) : base(restApiService, options, yunDingBusiness)
3 years ago
{
3 years ago
this.fsql = fsql;
this.idGenerator = idGenerator;
2 years ago
this.taskSchedulerManager = taskSchedulerManager;
this.venderBusiness = venderBusiness;
2 years ago
this.dingDingBusiness = dingDingBusiness;
this.nLogManager = nLogManager;
2 years ago
this.productBusiness = productBusiness;
this.freeSqlMultiDBManager = freeSqlMultiDBManager;
2 years ago
validOrderStateList = new List<Enums.OrderState>()
{
Enums.OrderState.,
Enums.OrderState.,
Enums.OrderState.,
Enums.OrderState.,
Enums.OrderState.,
Enums.OrderState.
};
2 years ago
preTaskStateList = new List<Enums.PromitionTaskStatus>()
{
Enums.PromitionTaskStatus.,
Enums.PromitionTaskStatus.
};
spliter = new char[] { ',' };
3 years ago
}
#region 赠品模板
3 years ago
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();
});
}
3 years ago
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();
});
3 years ago
}
#endregion
#region 评价助手任务
public void AddOrEditPromotionTask(AddOrEditPromotionTaskRequest request)
{
var shop = venderBusiness.GetShopList(request.ShopId).FirstOrDefault();
if (shop == null)
throw new BusinessException("缺少店铺Id");
var loggerName = $"评价助手-{shop.ShopName}";
nLogManager.GetLogger(loggerName).Info($"发布任务-{JsonConvert.SerializeObject(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 (request.GiftTemplateId != 0 && !string.IsNullOrEmpty(request.MainProductGiftSku))
throw new BusinessException("不能同时具备赠品模板和主商品赠品");
if (request.IsNewProduct == null)
request.IsNewProduct = 1;
if (request.IsNewProduct == 1)
{
if (string.IsNullOrEmpty(request.FullTitle))
throw new BusinessException("缺少完整标题");
if (string.IsNullOrEmpty(request.SimpleTitle))
throw new BusinessException("缺少精简标题");
}
2 years ago
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");
2 years ago
if (request.GiftTemplateId != 0 && string.IsNullOrEmpty(request.OuterId))
throw new BusinessException("使用赠品模板时必须填写外部Id");
2 years ago
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.PreTaskId == null || request.PreTaskId == 0)
request.PreTaskId = -1;
2 years ago
PromotionTask promotionTask = null;
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>().Where(pt => pt.ShopId == request.ShopId).ToAggregate(p => p.Max(p.Key.Sort));
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,
2 years ago
SpuPublishTime = spuResponse.Data.Items[0].CreateTime,
TaskCount = request.TaskCount,
2 years ago
CustomMotherSku = request.CustomMotherSku,
OuterId = request.OuterId,
IsNewProduct = request.IsNewProduct
};
fsql.Insert(promotionTask).ExecuteAffrows();
}
else
{
promotionTask = fsql.Select<PromotionTask>(request.Id).ToOne();
if (promotionTask == null)
throw new BusinessException("任务不存在");
if (promotionTask.Status != Enums.PromitionTaskStatus.)
throw new BusinessException("只能在任务处于等待状态时才能修改");
request.Map(promotionTask);
fsql.Update<PromotionTask>().SetSource(promotionTask)
.IgnoreColumns(new string[]
{
"UpdateSortTime",
"Sort", "Status",
"CreateTime",
"SpuLogo",
"SpuPublishTime",
"StartTime",
"EndTime",
"StopTime",
"CompletedTaskCount"
})
.ExecuteAffrows();
}
if (promotionTask.Status == Enums.PromitionTaskStatus.)
EditPreTask(new EditPreTaskRequest() { TaskId = promotionTask.Id, PreTaskId = request.PreTaskId.Value });
}
/// <summary>
/// 获取任务列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public PromotionTaskResponse GetPromotionTaskList(QueryPromotionTaskRequest request)
{
var list = fsql.Select<PromotionTask>().As("pt")
.Where(pt => pt.ShopId == request.ShopId)
2 years ago
.Where(pt => pt.IsEnabled == true)
.WhereIf(request.Status != null, pt => pt.Status == request.Status)
.OrderBy(pt => SqlExt.Case().When(pt.Status == Enums.PromitionTaskStatus., 0)
.When(pt.Status == Enums.PromitionTaskStatus., 1)
.When(pt.Status == Enums.PromitionTaskStatus., 2)
.When(pt.Status == Enums.PromitionTaskStatus., 3)
.End())
//.OrderBy("case when pt.status=1 then 0 when pt.status=0 then 1 when pt.status=2 then 2 when pt.status=3 then 3 end asc")
.OrderByDescending(pt => pt.Sort)
.Page(request.PageIndex, request.PageSize)
.Count(out long count)
.ToList<PromotionTaskItemResponse>();
if (list.Count() > 0)
{
var preTaskIdList = list.Where(pt => pt.PreTaskId != null && pt.PreTaskId != -1).Select(pt => pt.PreTaskId).ToArray();
if (preTaskIdList.Count() > 0)
{
var preTaskList = fsql.Select<PromotionTask>(preTaskIdList).ToList(pt => new { Id = pt.Id, ActivityName = pt.ActivityName });
foreach (var preTask in preTaskList)
{
var ptTaskList = list.Where(pt => pt.PreTaskId == preTask.Id);
foreach (var ptTask in ptTaskList)
ptTask.PreTaskName = preTask.ActivityName;
}
}
}
return new PromotionTaskResponse()
{
Count = count,
ItemList = list
};
}
2 years ago
public PromotionTaskResponse GetPrePromotionTaskList(long shopId)
{
var list = fsql.Select<PromotionTask>().As("pt")
.Where(pt => pt.ShopId == shopId)
2 years ago
.Where(pt => preTaskStateList.Contains(pt.Status.Value))
2 years ago
.Where(pt => pt.IsEnabled == true)
.OrderBy(pt => SqlExt.Case().When(pt.Status == Enums.PromitionTaskStatus., 0)
.When(pt.Status == Enums.PromitionTaskStatus., 1)
.When(pt.Status == Enums.PromitionTaskStatus., 2)
.When(pt.Status == Enums.PromitionTaskStatus., 3)
.End())
//.OrderBy("case when pt.status=1 then 0 when pt.status=0 then 1 when pt.status=2 then 2 when pt.status=3 then 3 end asc")
2 years ago
.OrderByDescending(pt => pt.Sort)
.Page(1, 1000)
2 years ago
.Count(out long count)
.ToList<PromotionTaskItemResponse>();
return new PromotionTaskResponse()
{
Count = count,
ItemList = list
};
}
/// <summary>
/// 设置前置任务
/// </summary>
/// <param name="request"></param>
/// <exception cref="BusinessException"></exception>
public void EditPreTask(EditPreTaskRequest request)
{
var pt = fsql.Select<PromotionTask>(request.TaskId).ToOne();
if (pt == null)
throw new BusinessException($"{request.TaskId}任务不存在");
2 years ago
if (pt.Status != Enums.PromitionTaskStatus.)
throw new BusinessException("任务状态必须为等待");
if (request.PreTaskId != -1)
{
var prpt = fsql.Select<PromotionTask>(request.PreTaskId).ToOne();
if (prpt == null)
throw new BusinessException($"{request.PreTaskId}前置任务不存在");
if (pt.Id == prpt.Id)
throw new BusinessException("前置任务不能设置为自己");
if (prpt.Status != Enums.PromitionTaskStatus. && prpt.Status != Enums.PromitionTaskStatus.)
throw new BusinessException("前置任务状态必须为等待或进行中");
var nextPromotionTaskList = fsql.Select<PromotionTask>().Where(pt1 => pt1.PreTaskId == request.PreTaskId && pt1.IsEnabled == true).ToList();
if (nextPromotionTaskList.Count() > 0)
{
CheckSkuRepeat(pt, nextPromotionTaskList);
}
2 years ago
}
2 years ago
#region 清空后代
var waitList = fsql.Select<PromotionTask>().Where(pt1 => pt1.ShopId == pt.ShopId &&
pt1.Id != pt.Id &&
pt1.PreTaskId != null &&
pt1.Status == Enums.PromitionTaskStatus.).ToList(pt1 => new PromotionTask { Id = pt1.Id, PreTaskId = pt1.PreTaskId });
var childIdList = GetChildTaskIdList(pt.Id, waitList, null);
#endregion
fsql.Transaction(() =>
{
fsql.Update<PromotionTask>(request.TaskId).Set(pt1 => pt1.PreTaskId, request.PreTaskId).ExecuteAffrows();
if (childIdList.Count() > 0)
fsql.Update<PromotionTask>(childIdList.ToArray()).Set(pt1 => pt1.PreTaskId, null).ExecuteAffrows();
});
}
/// <summary>
/// 递归找子级任务
/// </summary>
/// <param name="taskId"></param>
/// <param name="waitList"></param>
/// <param name="childIdList"></param>
/// <returns></returns>
public IList<long> GetChildTaskIdList(long taskId, IList<PromotionTask> waitList, IList<long> childIdList)
{
if (childIdList == null)
childIdList = new List<long>();
var childTaskList = waitList.Where(w => w.PreTaskId == taskId).ToList();
if (childTaskList.Count() != 0)
{
foreach (var childTask in childTaskList)
{
childIdList.Add(childTask.Id);
GetChildTaskIdList(childTask.Id, waitList, childIdList);
}
}
return childIdList;
2 years ago
}
private void CheckSkuRepeat(PromotionTask pt, IList<PromotionTask> waitCheckList)
{
var ptSkuList = new List<string>();
2 years ago
var waitptSkuList = new List<string>();
if (!string.IsNullOrEmpty(pt.MainProductSku))
ptSkuList.AddRange(pt.MainProductSku.Split(spliter, StringSplitOptions.RemoveEmptyEntries));
if (!string.IsNullOrEmpty(pt.CustomMotherSku))
ptSkuList.AddRange(pt.CustomMotherSku.Split(spliter, StringSplitOptions.RemoveEmptyEntries));
2 years ago
foreach (var waitPt in waitCheckList)
{
if (!string.IsNullOrEmpty(waitPt.MainProductSku))
waitptSkuList.AddRange(waitPt.MainProductSku.Split(spliter, StringSplitOptions.RemoveEmptyEntries));
if (!string.IsNullOrEmpty(waitPt.CustomMotherSku))
waitptSkuList.AddRange(waitPt.CustomMotherSku.Split(spliter, StringSplitOptions.RemoveEmptyEntries));
var intersectSkuList = ptSkuList.Intersect(waitptSkuList).ToList();
if (intersectSkuList != null && intersectSkuList.Count() > 0)
throw new BusinessException($"任务1[{pt.ActivityName}]与任务2[{waitPt.ActivityName}]之间存在sku重复,{string.Join(",", intersectSkuList)}");
}
}
/// <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();
});
}
}
3 years ago
/// <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或等待任务结束");
}
}
}
}
3 years ago
/// <summary>
/// 开始任务
3 years ago
/// </summary>
/// <param name="request"></param>
/// <param name="shop"></param>
/// <exception cref="BusinessException"></exception>
public void StartPromotionTask(StartPromotionTaskRequest request, ShopResponse shop = null)
3 years ago
{
var dbPromotionTask = fsql.Select<PromotionTask>(request.Id).ToOne();
if (dbPromotionTask == null)
throw new BusinessException("任务不存在");
if (dbPromotionTask.Status != Enums.PromitionTaskStatus.)
throw new BusinessException("只能在任务处于等待状态时才能开始");
if (shop == null)
shop = venderBusiness.GetShopList(dbPromotionTask.ShopId, Enums.Platform.)?.FirstOrDefault();
if (shop == null)
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("赠品模板不存在");
}
}
2 years ago
var runingTaskList = fsql.Select<PromotionTask>().Where(pt => pt.ShopId == dbPromotionTask.ShopId &&
pt.Status == Enums.PromitionTaskStatus. &&
pt.IsEnabled == true).ToList();
2 years ago
if (dbPromotionTask.MotherTemplateId != null && dbPromotionTask.MotherTemplateId != 0)
{
}
2 years ago
if (request.IsDebug == null || request.IsDebug == false)
{
if (!string.IsNullOrEmpty(dbPromotionTask.CustomMotherSku))
CheckRepeatSkuInRuningTask(runingTaskList, dbPromotionTask.CustomMotherSku);
2 years ago
if (!string.IsNullOrEmpty(motherTemplateSku))
CheckRepeatSkuInRuningTask(runingTaskList, motherTemplateSku);
if (!string.IsNullOrEmpty(dbPromotionTask.MainProductSku))
CheckRepeatSkuInRuningTask(runingTaskList, dbPromotionTask.MainProductSku);
}
2 years ago
var joinSkuCount = 0;
var joinSkuNoGiftList = new List<string>();
var host = GetPlatformRelayAPIHost(Enums.Platform.);
2 years ago
var haveGiftTemplateSku = giftTemplateSkuList != null && giftTemplateSkuList.Count() > 0;
string barCode = string.Empty, categoryId = string.Empty;
IList<JToken> multiCateProps = null;
var mainProductSkuInStore = false;
2 years ago
var mainSkuResult = restApiService.SendRequest(host, "api/PlatformSDK/GetProductSkuList", new SearchProductSkuRequest()
2 years ago
{
2 years ago
AppKey = request.AppKey,
AppSecret = request.AppSecret,
AppToken = request.AppToken,
IsContainSource = true,
Platform = request.Platform,
Spu = dbPromotionTask.MainProductSpu
}, GetYunDingRequestHeader(), HttpMethod.Post);
if (mainSkuResult.StatusCode != System.Net.HttpStatusCode.OK)
throw new BusinessException($"获取主商品sku失败 {mainSkuResult.Content}");
var mainSkuListResponse = JsonConvert.DeserializeObject<ApiResponse<IList<ProductSkuResponse>>>(mainSkuResult.Content);
if (!mainSkuListResponse.Success)
throw new BusinessException($"获取主商品sku失败 {mainSkuListResponse.Msg}");
joinSkuNoGiftList.AddRange(mainSkuListResponse.Data.Select(s => s.Id));
2 years ago
//开启延迟任务
if (!string.IsNullOrEmpty(dbPromotionTask.CustomMotherSku))
joinSkuNoGiftList.AddRange(dbPromotionTask.CustomMotherSku.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
2 years ago
2 years ago
if (haveGiftTemplateSku)
{
2 years ago
barCode = mainSkuListResponse.Data[0].Source.Value<string>("barCode");
categoryId = mainSkuListResponse.Data[0].Source.Value<string>("categoryId");
multiCateProps = mainSkuListResponse.Data[0].Source["multiCateProps"] != null ? mainSkuListResponse.Data[0].Source["multiCateProps"].ToList() : null;
var jyStoreIdList = fsql.Select<Storehouse>().Where(s => s.Type == Enums.StockType. || s.Name.Contains("云仓")).ToList(s => s.Id);
foreach (var sku in mainSkuListResponse.Data)
{
var stockNumApiResult = restApiService.SendRequest(host, "api/platformsdk/GetStockNumBySku", new SearchProductSkuRequest()
{
AppKey = shop.AppKey,
AppSecret = shop.AppSecret,
AppToken = shop.AppToken,
Platform = shop.PlatformId,
Sku = sku.Id
}, GetYunDingRequestHeader(), HttpMethod.Post);
if (stockNumApiResult.StatusCode != System.Net.HttpStatusCode.OK)
throw new Exception($"{sku} {stockNumApiResult.Content}");
var stockNumListResponse = JsonConvert.DeserializeObject<ApiResponse<JArray>>(stockNumApiResult.Content);
var skuStockNumList = stockNumListResponse.Data.Select(j => new
{
StockNum = j.Value<int>("stockNum"),
StoreId = j.Value<string>("storeId"),
SkuId = sku
});
mainProductSkuInStore = skuStockNumList.Any(s => jyStoreIdList.Contains(s.StoreId));
if (mainProductSkuInStore)
break;
}
}
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,
2 years ago
TaskCount = dbPromotionTask.TaskCount,
MainProductBarCode = barCode,
MainProductCategoryId = categoryId,
MainProductMultiCateProps = multiCateProps,
2 years ago
MainProductSkuInStore = mainProductSkuInStore,
1 year ago
OuterId = dbPromotionTask.OuterId,
IsNewProduct = dbPromotionTask.IsNewProduct ?? 1
}, GetYunDingRequestHeader(), HttpMethod.Post, timeOutSeconds: 800);
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);
2 years ago
//try
//{
// if (!string.IsNullOrEmpty(shop.PJZSDingDingKey) && !string.IsNullOrEmpty(shop.PJZSDingDingWebHook))
// dingDingBusiness.SendDingDingBotMessage(shop.PJZSDingDingKey, shop.PJZSDingDingWebHook, $"任务[{dbPromotionTask.ActivityName}]已开始,请及时查看任务是否正常进行");
//}
//catch { }
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();
2 years ago
//joinSkuCount = joinSkuNoGiftList.Distinct().Count();
joinSkuNoGiftList = joinSkuNoGiftList.Distinct().ToList();
Task.Factory.StartNew(() => StartPromotionDelayTask(request, startResponse, dbPromotionTask, shop, joinSkuNoGiftList), CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.JDPromotionDelayTaskScheduler);
}
2 years ago
private void StartPromotionDelayTask(StartPromotionTaskRequest request, StartPromotionTaskResponse startResponse, PromotionTask promotionTask, ShopResponse shop, List<string> joinSkuList)
{
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,
2 years ago
DeleteGiftSkuList = startResponse.DeleteGiftSkuList,
ActivityName = promotionTask.ActivityName,
2 years ago
JoinSkuCount = joinSkuList.Count(),
JoinSkuList = joinSkuList,
2 years ago
PJZSDingDingKey = shop.PJZSDingDingKey,
PJZSDingDingWebHook = shop.PJZSDingDingWebHook,
IsNewProduct = promotionTask.IsNewProduct ?? 1
2 years ago
}, GetYunDingRequestHeader(), HttpMethod.Post, timeOutSeconds: 500);
var errorBack = new Action<long, string>((id, errorMsg) =>
{
fsql.Update<PromotionTask>(id).Set(pt => pt.Status, Enums.PromitionTaskStatus.)
.Set(pt => pt.ErrorMsg, errorMsg)
.ExecuteAffrows();
2 years ago
Error(shop, $"评价助手-{shop.ShopName}", $"开始任务-延迟任务-任务Id {request.Id}", new Exception(errorMsg));
});
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;
}
#region 检测是否有后续任务
var shopId = long.Parse(shop.ShopId);
var haveNextTask = fsql.Select<PromotionTask>().Where(pt => pt.ShopId == shopId &&
pt.Status == Enums.PromitionTaskStatus. &&
pt.IsEnabled == true &&
(pt.PreTaskId == promotionTask.Id ||
pt.PreTaskId == -1)).Any();
if (!haveNextTask)
{
if (!string.IsNullOrEmpty(shop.PJZSDingDingKey) && !string.IsNullOrEmpty(shop.PJZSDingDingWebHook))
{
try
{
dingDingBusiness.SendDingDingBotMessage(shop.PJZSDingDingKey, shop.PJZSDingDingWebHook, $"评价助手\n店铺:{shop.ShopName}\n任务列表无后续任务,为避免空档请及时设置后续任务");
}
catch { }
}
}
#endregion
3 years ago
}
2 years ago
/// <summary>
/// 删除任务和京东任务
/// </summary>
/// <param name="request"></param>
public void DeletePromotionTaskAndJDTask(DeletePromotionTaskRequest request)
{
var dbPromotionTask = fsql.Select<PromotionTask>(request.TaskId).ToOne();
if (dbPromotionTask.IsEnabled == false)
return;
fsql.Transaction(() =>
{
2 years ago
//fsql.Delete<PromotionTask>(request.TaskId).ExecuteAffrows();
fsql.Update<PromotionTask>(request.TaskId).Set(p => p.IsEnabled, false).ExecuteAffrows();
//fsql.Delete<PromotionTaskSkuRecord>().Where(psr => psr.PromotionTaskId == request.TaskId).ExecuteAffrows();
});
2 years ago
//if (dbPromotionTask.Status != Enums.PromitionTaskStatus.等待)
//{
if (dbPromotionTask.PromotionId != null && dbPromotionTask.PromotionId != 0)
{
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($"【{dbPromotionTask.ActivityName}】评价助手活动删除成功,JD活动删除失败,请手动到JD后台删除,并通知技术员分析失败原因,{httpResult.Content}");
var response = JsonConvert.DeserializeObject<ApiResponse>(httpResult.Content);
if (!response.Success)
throw new BusinessException($"【{dbPromotionTask.ActivityName}】评价助手活动删除成功,JD活动删除失败,请手动到JD后台删除,并通知技术员分析失败原因,{response.Msg}");
}
2 years ago
//}
}
2 years ago
public void DeletePromotionTask(long pjzsTaskId)
{
fsql.Transaction(() =>
{
fsql.Delete<PromotionTask>(pjzsTaskId).ExecuteAffrows();
fsql.Delete<PromotionTaskSkuRecord>().Where(psr => psr.PromotionTaskId == pjzsTaskId).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.)
{
2 years ago
List<string> motherSkuIdList = new List<string>();
if (dbPromotionTask.MotherTemplateId != null)
{
2 years ago
}
if (!string.IsNullOrEmpty(dbPromotionTask.CustomMotherSku))
motherSkuIdList.AddRange(dbPromotionTask.CustomMotherSku.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
2 years ago
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);
2 years ago
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);
2 years ago
}
fsql.Transaction(() =>
{
fsql.Delete<PromotionTask>(request.TaskId).ExecuteAffrows();
fsql.Delete<PromotionTaskSkuRecord>().Where(psr => psr.PromotionTaskId == request.TaskId).ExecuteAffrows();
});
2 years ago
}
2 years ago
2 years ago
/// <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)
2 years ago
{
if (!response.Msg.Contains("促销已删除"))
throw new BusinessException(response.Msg);
}
fsql.Update<PromotionTask>(request.Id).Set(pt => pt.Status, Enums.PromitionTaskStatus.).ExecuteAffrows();
}
public void EditPJZSSettings(PJZSShopSettingRequest request)
{
var shopId = request.ShopId.ToString();
freeSqlMultiDBManager.MDSfsql.Update<Model.Db.Mds.Shops>().Set(s => s.PJZSDingDingKey, request.PJZSDingDingKey)
.Set(s => s.PJZSDingDingWebHook, request.PJZSDingDingWebHook)
.Where(s => s.ShopId == shopId)
.ExecuteAffrows();
}
#endregion
2 years ago
2 years ago
#region 自动任务
2 years ago
public void StartMonitor(long? shopId, long? taskId)
2 years ago
{
2 years ago
//查询店铺
2 years ago
var shopList = venderBusiness.GetShopList(shopId, Enums.Platform.);
#region 查询等待开始的任务
//查询没有前置的任务
2 years ago
var nextPromotionTaskList = fsql.Select<PromotionTask>().WhereIf(shopId != null, pt => pt.ShopId == shopId)
2 years ago
.Where(pt => pt.Status == Enums.PromitionTaskStatus. && pt.PreTaskId == -1 && pt.IsEnabled == true)
.ToList(pt => new { pt.Id, pt.ShopId, TaskName = pt.ActivityName });
//查询前置已完成但是还没开始的后置任务
var checkNoStartTime = DateTime.Now.AddMinutes(-30);
var preTaskJobDoneAndChildTaskNoStartList = fsql.Select<PromotionTask>()
.WhereIf(shopId != null, pt => pt.ShopId == shopId)
.Where(cpt => cpt.Status == Enums.PromitionTaskStatus. && cpt.PreTaskId != -1 && cpt.IsEnabled == true)
.Where(cpt => fsql.Select<PromotionTask>().Where(pt => pt.Id == cpt.PreTaskId &&
pt.Status == Enums.PromitionTaskStatus. &&
pt.StopTime <= checkNoStartTime).Any())
.ToList(pt => new { pt.Id, pt.ShopId, TaskName = pt.ActivityName });
if (preTaskJobDoneAndChildTaskNoStartList.Count() > 0)
nextPromotionTaskList.AddRange(preTaskJobDoneAndChildTaskNoStartList);
#endregion
//开始下一轮开始任务
2 years ago
if (nextPromotionTaskList.Count() > 0)
{
foreach (var nextTask in nextPromotionTaskList)
{
var shop = shopList.FirstOrDefault(s => s.ShopId == nextTask.ShopId.ToString());
if (shop != null)
{
2 years ago
Task.Factory.StartNew(() => AutoStart(nextTask.Id, nextTask.TaskName, shop), CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.JDPromotionAutoStartTaskScheduler);
2 years ago
}
}
}
2 years ago
//查询正在进行的任务
var runningTaskList = fsql.Select<PromotionTask>()
2 years ago
.Where(pt => pt.IsEnabled == true)
2 years ago
.WhereIf(shopId != null, pt => pt.ShopId == shopId)
2 years ago
.WhereIf(taskId != null, pt => pt.Id == taskId)
.WhereIf(taskId == null, pt => pt.Status == Enums.PromitionTaskStatus.).ToList();
2 years ago
if (runningTaskList == null || runningTaskList.Count() == 0)
return;
var runningTaskIdList = runningTaskList.Select(pt => pt.Id).ToList();
//查询订单sku
2 years ago
var querySkuTime = DateTime.Now.AddHours(-2);
2 years ago
var orderSkuList = fsql.Select<OrderSku, Order>()
.InnerJoin((osku, o) => osku.OrderId == o.Id)
.WhereIf(shopId != null, (osku, o) => o.ShopId == shopId)
.Where((osku, o) => validOrderStateList.Contains(o.OrderState.Value))
2 years ago
//.Where((osku, o) => osku.CreateTime >= querySkuTime)
.Where((osku, o) => o.ModifyTime >= querySkuTime)
2 years ago
.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();
2 years ago
foreach (var shop in shopList)
{
2 years ago
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);
2 years ago
}
}
2 years ago
/// <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)
2 years ago
{
var loggerName = $"评价助手-{shop.ShopName}";
2 years ago
List<IUpdate<PromotionTask>> updatePromotionTaskList = new List<IUpdate<PromotionTask>>();
List<PromotionTaskSkuRecord> insertPromotionTaskSkuRecordList = new List<PromotionTaskSkuRecord>();
IList<long> jobDoneTaskIdList = new List<long>();
IList<PromotionTask> jobDoneTaskList = new List<PromotionTask>();
var host = GetPlatformRelayAPIHost(Enums.Platform.);
2 years ago
foreach (var promotionTask in runningTaskList)
{
2 years ago
var productSkuList = new List<string>();
2 years ago
2 years ago
#region 读取主商品sku
{
var productResponseSkuList = productBusiness.GetProductSkuList(new SearchProductSkuRequest()
{
AppKey = shop.AppKey2,
AppSecret = shop.AppSecret2,
AppToken = shop.AppToken2,
IsContainSource = false,
Platform = Enums.Platform.,
Spu = promotionTask.MainProductSpu
});
if (productResponseSkuList == null || productResponseSkuList.Count() == 0)
{
Error(shop, loggerName, $"监控任务-查询主商品sku-任务Id {promotionTask.Id}", new Exception("未查询到主商品sku信息"));
2 years ago
continue;
}
productSkuList.AddRange(productResponseSkuList.Select(p => p.Id));
}
#endregion
2 years ago
if (!string.IsNullOrEmpty(promotionTask.GiftTemplatePutNewSku))
{
productSkuList.AddRange(promotionTask.GiftTemplatePutNewSku.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
}
2 years ago
if (!string.IsNullOrEmpty(promotionTask.MainProductGiftSku))
{
productSkuList.AddRange(promotionTask.MainProductGiftSku.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
}
2 years ago
2 years ago
var newOrderSkuList = orderSkuList.Where(osku => productSkuList.Contains(osku.SkuId) &&
2 years ago
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;
completedTaskCount += 1;
2 years ago
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;
2 years ago
var isDone = promotionTask.CompletedTaskCount >= promotionTask.TaskCount || (promotionTask.EndTime != null && DateTime.Now > promotionTask.EndTime);
2 years ago
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)
{
2 years ago
if (DateTime.Now < promotionTask.EndTime)
2 years ago
{
#region 提前完成任务量,暂停JD活动
{
2 years ago
var httpResult = restApiService.SendRequest(GetPlatformRelayAPIHost(Enums.Platform.),
"api/platformsdk/DeleteJDPromotionTask",
new DeleteJDPromotionTaskRequest()
{
AppKey = shop.AppKey2,
AppSecret = shop.AppSecret2,
AppToken = shop.AppToken2,
Platform = Enums.Platform.,
PromotionId = promotionTask.PromotionId.Value
},
GetYunDingRequestHeader(),
HttpMethod.Post);
2 years ago
if (httpResult.StatusCode != System.Net.HttpStatusCode.OK)
{
var msgBuilder = new StringBuilder();
msgBuilder.AppendLine($"店铺名称:{shop.ShopName}");
msgBuilder.AppendLine($"活动名称:{promotionTask.ActivityName}");
msgBuilder.AppendLine($"错误原因:{httpResult.Content}");
msgBuilder.AppendLine("删除活动失败,请手动到后台删除,并通知技术员分析失败原因");
dingDingBusiness.SendDingDingBotMessage(shop.PJZSDingDingKey, shop.PJZSDingDingWebHook, $"任务[{promotionTask.ActivityName}]删除任务失败,{httpResult.Content}");
}
else
{
var res = JsonConvert.DeserializeObject<ApiResponse>(httpResult.Content);
if (!res.Success)
{
var msgBuilder = new StringBuilder();
msgBuilder.AppendLine($"店铺名称:{shop.ShopName}");
msgBuilder.AppendLine($"活动名称:{promotionTask.ActivityName}");
msgBuilder.AppendLine($"错误原因:{httpResult.Content}");
msgBuilder.AppendLine("删除活动失败,请手动到后台删除,并通知技术员分析失败原因");
dingDingBusiness.SendDingDingBotMessage(shop.PJZSDingDingKey, shop.PJZSDingDingWebHook, $"任务[{promotionTask.ActivityName}]删除任务失败,{res.Msg}");
}
}
2 years ago
}
#endregion
}
jobDoneTaskIdList.Add(promotionTask.Id); //记录完成任务
jobDoneTaskList.Add(promotionTask);
2 years ago
}
}
}
2 years ago
2 years ago
fsql.Transaction(() =>
{
if (updatePromotionTaskList.Count() > 0)
foreach (var update in updatePromotionTaskList)
update.ExecuteAffrows();
if (insertPromotionTaskSkuRecordList.Count() > 0)
fsql.Insert(insertPromotionTaskSkuRecordList).ExecuteAffrows();
});
1 year ago
#region 任务结束之后的处理
if (jobDoneTaskIdList.Count() == 0)
return;
var statusList = new List<Enums.PromitionTaskStatus?>() { Enums.PromitionTaskStatus., Enums.PromitionTaskStatus. };
var effectiveTaskList = fsql.Select<PromotionTask>().Where(pt => pt.ShopId == shopId &&
statusList.Contains(pt.Status) &&
pt.IsEnabled == true)
.ToList(pt => new { pt.Id, pt.ShopId, TaskName = pt.ActivityName, pt.PreTaskId, pt.Status });
foreach (var jobDoneTask in jobDoneTaskList)
{
#region 恢复新品任务的完整标题
if (jobDoneTask.IsNewProduct == 1)
{
var httpResult = restApiService.SendRequest(host, "/api/platformsdk/SetProductTitle", new SetProductTitleRequest()
{
AppKey = shop.AppKey2,
AppSecret = shop.AppSecret2,
AppToken = shop.AppToken2,
Platform = Enums.Platform.,
Spu = jobDoneTask.MainProductSpu,
Title = jobDoneTask.FullTitle
}, null, HttpMethod.Post);
}
#endregion
#region 通知该任务结束
if (!string.IsNullOrEmpty(shop.PJZSDingDingKey) && !string.IsNullOrEmpty(shop.PJZSDingDingWebHook))
{
try
{
dingDingBusiness.SendDingDingBotMessage(shop.PJZSDingDingKey, shop.PJZSDingDingWebHook, $"任务[{jobDoneTask.ActivityName}]已结束");
}
catch { }
}
#endregion
#region 开始后续任务
var childTaskList = effectiveTaskList.Where(pt => pt.PreTaskId == jobDoneTask.Id &&
pt.Status == Enums.PromitionTaskStatus.).ToList();
if (childTaskList.Count() > 0)
{
2 years ago
foreach (var task in childTaskList)
2 years ago
{
2 years ago
Task.Factory.StartNew(() => AutoStart(task.Id, task.TaskName, shop), CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.JDPromotionAutoStartTaskScheduler);
2 years ago
}
}
#endregion
}
#region 检测是否所有任务完成
if (effectiveTaskList.Count() == 0)
{
if (!string.IsNullOrEmpty(shop.PJZSDingDingKey) && !string.IsNullOrEmpty(shop.PJZSDingDingWebHook))
{
try
{
dingDingBusiness.SendDingDingBotMessage(shop.PJZSDingDingKey, shop.PJZSDingDingWebHook, $"评价助手\n店铺:{shop.ShopName}\n任务全部执行完成,请及时设置后续任务!!");
}
catch { }
}
2 years ago
}
2 years ago
#endregion
#endregion
//#region 开始后续任务
////下一轮开始任务
//if (jobDoneTaskIdList.Count() > 0)
//{
// var childTaskList = fsql.Select<PromotionTask>().Where(pt => pt.ShopId == shopId &&
// pt.Status == Enums.PromitionTaskStatus.等待 &&
// pt.IsEnabled == true &&
// jobDoneTaskIdList.Contains(pt.PreTaskId.Value))
// .ToList(pt => new { Id = pt.Id, ShopId = pt.ShopId, TaskName = pt.ActivityName });
// if (childTaskList.Count() > 0)
// {
// foreach (var task in childTaskList)
// {
// Task.Factory.StartNew(() => AutoStart(task.Id, task.TaskName, shop), CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.JDPromotionAutoStartTaskScheduler);
// }
// }
//}
//#endregion
2 years ago
}
2 years ago
2 years ago
private void AutoStart(long taskId, string taskName, ShopResponse shop)
2 years ago
{
var loggerName = $"评价助手-{shop.ShopName}";
try
{
StartPromotionTask(new StartPromotionTaskRequest()
{
Id = taskId,
AppKey = shop.AppKey2,
AppSecret = shop.AppSecret2,
AppToken = shop.AppToken2,
Platform = Enums.Platform.
}, shop);
}
catch (Exception ex)
{
2 years ago
Error(shop, loggerName, $"AutoStart 任务[{taskName}]", ex);
}
2 years ago
}
private void Error(ShopResponse shop, string loggerName, string message, Exception ex)
2 years ago
{
nLogManager.GetLogger(loggerName).Error(ex, message);
2 years ago
//send dingding
2 years ago
if (!string.IsNullOrEmpty(shop.PJZSDingDingKey) && !string.IsNullOrEmpty(shop.PJZSDingDingWebHook))
dingDingBusiness.SendDingDingBotMessage(shop.PJZSDingDingKey, shop.PJZSDingDingWebHook, $"评价助手\n{shop.ShopName}\n{message}\n{ex.Message}");
2 years ago
}
2 years ago
#endregion
3 years ago
}
}