RepositoryExtension.Activity.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. using System.Threading.Tasks;
  2. using System;
  3. using Wicture.DbRESTFul.Infrastructure.Repository;
  4. using System.Linq;
  5. using Newtonsoft.Json.Linq;
  6. using System.Collections.Generic;
  7. using System.Data;
  8. using Wicture.DbRESTFul.Cache;
  9. using System.Security.Cryptography.X509Certificates;
  10. using Newtonsoft.Json;
  11. using System.Runtime.Intrinsics.X86;
  12. using JiaZhiQuan.Common.Models.VO;
  13. using JiaZhiQuan.Common.Models.PO;
  14. namespace JiaZhiQuan.Common
  15. {
  16. public static partial class RepositoryExtension
  17. {
  18. public class ActivityCzdTaskRecord
  19. {
  20. public int id { get; set; }
  21. public long userId { get; set; }
  22. public int betPoints { get; set; }
  23. public int betType { get; set; }
  24. public DateTime createAt { get; set; }
  25. public int gainPoints { get; set; }
  26. public int gameResult { get; set; }
  27. }
  28. public class ActivityCzdMockModel
  29. {
  30. public int fallUsers { get; set; }
  31. public int riseUsers { get; set; }
  32. public int points { get; set; }
  33. public DateTime execTime { get; set; }
  34. }
  35. public static async Task<List<int>> GetCzdPointListByContract(this DbRESTFulRepository repository, RedisCacheProvider cacheProvider, int contractId)
  36. {
  37. var key = CacheKeys.ActivityCzdPointList(contractId);
  38. var list = await cacheProvider.Get<List<int>>(key);
  39. if (list == null)
  40. {
  41. list = (await repository.QuerySingleOrDefaultAsync<string>($"select pointsList from n_activity_czd_contract where id={contractId}") ?? string.Empty)
  42. .Split(',', StringSplitOptions.RemoveEmptyEntries)
  43. .Select(e => int.Parse(e)).ToList();
  44. await cacheProvider.Set(key, list, CacheKeys.ActivityCzdPointListCacheSecs);
  45. }
  46. return list;
  47. }
  48. /// <summary>
  49. /// 获取随机人数和随机价值币
  50. /// </summary>
  51. /// <param name="minCount">包含</param>
  52. /// <param name="maxCount">包含</param>
  53. /// <param name="mode">0 双方都加同样的,2 仅跌的,1 仅涨的</param>
  54. public static async Task<bool> GenerateActivityCzdMockData(this DbRESTFulRepository repository, RedisCacheProvider cacheProvider, int contractId, int taskId, int minCount, int maxCount, int minutes, int mode = 0)
  55. {
  56. var pointsArr = await repository.GetCzdPointListByContract(cacheProvider, contractId);
  57. if (pointsArr.Count == 0) return false;
  58. var rand = new Random();
  59. var count = rand.Next(minCount, maxCount + 1);
  60. if (count == 0) return true;
  61. var list = new List<ActivityCzdMockModel>();
  62. var maxBatch = Math.Min(count, 10);
  63. for (var i = 0; i < count; i++)
  64. {
  65. var time = DateTime.Now.AddMinutes(rand.NextDouble() * minutes);
  66. var batch = rand.Next(1, maxBatch + 1);
  67. var model = new ActivityCzdMockModel { execTime = time };
  68. if (mode == 2 || mode == 0)
  69. {
  70. model.fallUsers = batch;
  71. }
  72. if (mode == 1 || mode == 0)
  73. {
  74. model.riseUsers = batch;
  75. }
  76. for (var j = 0; j < batch; j++)
  77. {
  78. model.points += pointsArr[rand.Next(Math.Min(3, pointsArr.Count))];
  79. }
  80. if (mode == 0)
  81. {
  82. model.points *= 2;
  83. }
  84. list.Add(model);
  85. i += batch - 1;
  86. }
  87. await repository.QueryAsync<dynamic>($"insert into n_activity_czd_mock_action (taskId, fallUsers, riseUsers, points, execTime, createAt) values ({taskId}, @fallUsers, @riseUsers, @points, @execTime, now())", list, null, null, false);
  88. return true;
  89. }
  90. /// <summary>
  91. /// 结束某一个任务
  92. /// </summary>
  93. /// <param name="contractId">合约组编号</param>
  94. /// <param name="date">yyyy-MM-dd</param>
  95. /// <param name="contractResult">1 涨 2 跌 3 平</param>
  96. public static async Task<bool> EndActivityCzdTask(this DbRESTFulRepository repository, int contractId, string date, int contractResult)
  97. {
  98. var task = await repository.QuerySingleOrDefaultAsync<dynamic>($"select t.id, t.activityId, t.contractId, c.contractName, t.date from n_activity_czd_task as t left join n_activity_czd_contract as c on t.contractId=c.id where t.contractId={contractId} and t.date='{date}' and t.contractResult=0");
  99. if (task == null) return false;
  100. // 判断是否是最新的已结束的任务
  101. var isNewTask = (await repository.QuerySingleOrDefaultAsync<int>(
  102. $"select id from n_activity_czd_task where id>{task.id} and contractResult>0 limit 1")) == 0;
  103. var activityId = task.activityId;
  104. var activityName =
  105. await repository.QuerySingleOrDefaultAsync<string>(
  106. $"select title from n_activity where id={activityId}");
  107. var pointChangeDescription = $"活动奖励-{activityName}";
  108. var allRecords = (await repository.QueryAsync<ActivityCzdTaskRecord>($"select id, userId, betType, betPoints, createAt from n_activity_czd_task_records where taskId={task.id}")).ToList();
  109. var risePoints = 0;
  110. var fallPoints = 0;
  111. foreach (var record in allRecords)
  112. {
  113. // 跌
  114. if (record.betType == 2)
  115. {
  116. fallPoints += record.betPoints;
  117. }
  118. // 涨
  119. else
  120. {
  121. risePoints += record.betPoints;
  122. }
  123. }
  124. var platformTotalPoints = 0; // 平台所出价值币
  125. var totalWinPoints = 0; // 赢方总获取的价值币(不记成本)
  126. int totalPoints = contractResult == 2 ? risePoints : fallPoints; // 瓜分总价值币
  127. int totalWinBetPoints = contractResult == 2 ? fallPoints : risePoints; // 赢方总投注价值币
  128. var rate = totalWinBetPoints > 0 ? (double)totalPoints / totalWinBetPoints : 0;
  129. var winUserIds = new List<long>();
  130. foreach (var record in allRecords)
  131. {
  132. var win = (record.betType == 2 && contractResult == 2) || (record.betType != 2 && contractResult != 2);
  133. record.gameResult = win ? 1 : 2;
  134. if (win)
  135. {
  136. var p = (int)Math.Floor(rate * record.betPoints);
  137. if (p < 20) p = 20;
  138. totalWinPoints += p;
  139. record.gainPoints = record.betPoints + p;
  140. winUserIds.Add(record.userId);
  141. }
  142. else
  143. {
  144. record.gainPoints = 0;
  145. }
  146. }
  147. platformTotalPoints = totalWinPoints - totalPoints;
  148. var updateRecords = allRecords.Select(e =>
  149. {
  150. return new
  151. {
  152. e.id,
  153. e.gainPoints,
  154. e.gameResult,
  155. };
  156. }).ToList();
  157. var updateStats = allRecords.Select(e =>
  158. {
  159. return new
  160. {
  161. e.userId,
  162. e.createAt,
  163. win = e.gameResult == 1 ? 1 : 0,
  164. points = e.gainPoints - e.betPoints,
  165. };
  166. }).ToList();
  167. var pointsRecords = allRecords.Where(e => e.gainPoints > 0).Select(e =>
  168. {
  169. return new
  170. {
  171. e.userId,
  172. points = e.gainPoints,
  173. };
  174. }).ToList();
  175. var execCount = 0;
  176. var taskEndTime = ((DateTime)task.date).ToString("yyyy-MM-dd 15:00:00");
  177. using var conn = repository.ConnectionManager.GetConnection(false);
  178. conn.Open();
  179. var trans = conn.BeginTransaction();
  180. try
  181. {
  182. execCount = await repository.QuerySingleOrDefaultAsync<int>($"update n_activity_czd_task set contractResult={contractResult}, extraPoints={platformTotalPoints} where id={task.id} and contractResult=0; select row_count() as count;", null, conn, trans);
  183. if (execCount > 0)
  184. {
  185. await repository.QueryAsync<dynamic>("update n_activity_czd_task_records set gainPoints=@gainPoints, remind=1, gameResult=@gameResult where id=@id and gameResult=0;", updateRecords, conn, trans);
  186. if (isNewTask)
  187. {
  188. await repository.QueryAsync<dynamic>(@$"update n_activity_czd_task_statistic set
  189. winTimes=winTimes+@win, continuousTimes=(case @win when 1 then continuousTimes+1 else 0 end),
  190. totalEarnPoints=totalEarnPoints+@points, lastJoinAt=(case @createAt<lastJoinAt when 1 then lastJoinAt else @createAt end),
  191. latestWinAt=(case @win when 1 then (case latestWinAt<'{taskEndTime}' when 1 then '{taskEndTime}' else latestWinAt end) else latestWinAt end) where contractId={contractId} and userId=@userId", updateStats, conn, trans);
  192. // 如果将其他未参与用户的连中次数设置成-1
  193. await repository.QueryAsync<dynamic>($"update n_activity_czd_task_statistic set continuousTimes=0 where contractId={contractId} [and userId not in @userIds]", new { userIds = winUserIds.Count > 0 ? winUserIds : null }, conn, trans);
  194. }
  195. else
  196. {
  197. await repository.QueryAsync<dynamic>(@$"update n_activity_czd_task_statistic set
  198. winTimes=winTimes+@win,
  199. totalEarnPoints=totalEarnPoints+@points, lastJoinAt=(case @createAt<lastJoinAt when 1 then lastJoinAt else @createAt end),
  200. latestWinAt=(case @win when 1 then (case latestWinAt<'{taskEndTime}' when 1 then '{taskEndTime}' else latestWinAt end) else latestWinAt end) where contractId={contractId} and userId=@userId", updateStats, conn, trans);
  201. }
  202. // 给用户添加价值币
  203. if (pointsRecords.Count > 0)
  204. {
  205. await repository.QueryAsync<dynamic>($"insert into n_user_points_record(userId, points, `way`, extra, description, createAt, createAtDate) values(@userId, @points, 'ACTIVITY', '{activityId}', '{pointChangeDescription}', now(), now())", pointsRecords, conn, trans);
  206. await repository.QueryAsync<dynamic>($"update n_user_statistic set points=points+@points where userId=@userId", pointsRecords, conn, trans);
  207. }
  208. }
  209. trans.Commit();
  210. }
  211. catch (Exception ex)
  212. {
  213. trans.Rollback();
  214. throw ex;
  215. }
  216. if (execCount > 0 && !isNewTask)
  217. {
  218. // 更新用户的连中次数,最多50次
  219. var taskIds = (await repository.QueryAsync<int>(
  220. $"select id from n_activity_czd_task where contractId={contractId} and contractResult>0 order by id desc limit 50",
  221. null, conn)).ToList();
  222. // 查询出所有参与记录
  223. var records =
  224. (await repository.QueryAsync<dynamic>(
  225. $"select taskId, userId from n_activity_czd_task_records where taskId in @taskIds and gameResult=1",
  226. new { taskIds })).ToList();
  227. // 按人进行统计
  228. var userIdCountMap = new Dictionary<long, int>();
  229. var completedUserIds = new HashSet<long>();
  230. var first = true;
  231. foreach (var taskId in taskIds)
  232. {
  233. var uids = records.Where(e => e.taskId == taskId).Select(e => (long)e.userId).ToHashSet();
  234. if (first)
  235. {
  236. records.ForEach(e =>
  237. {
  238. if (!userIdCountMap.ContainsKey(e.userId))
  239. {
  240. userIdCountMap.Add(e.userId, uids.Contains(e.userId) ? 1 : 0);
  241. }
  242. });
  243. first = false;
  244. }
  245. else
  246. {
  247. userIdCountMap.Keys.ForEach(uid =>
  248. {
  249. if (completedUserIds.Contains(uid)) return;
  250. if (uids.Contains(uid) && userIdCountMap.ContainsKey(uid) && userIdCountMap[uid] != 0) userIdCountMap[uid]++;
  251. else completedUserIds.Add(uid);
  252. });
  253. }
  254. }
  255. // 更新记录
  256. if (userIdCountMap.Count > 0)
  257. {
  258. var query = userIdCountMap.Select(e => new { userId = e.Key, count = e.Value }).ToList();
  259. await repository.QueryAsync<dynamic>(
  260. $"update n_activity_czd_task_statistic set continuousTimes=@count where contractId={contractId} and userId=@userId",
  261. query, conn, null, false);
  262. }
  263. }
  264. return execCount > 0;
  265. }
  266. /// <summary>
  267. /// 根据给定变更的奖励任务编号列表来更新活动的报名状态
  268. /// </summary>
  269. private static async Task UpdateActivitySignupState(this DbRESTFulRepository repository,
  270. List<int> rewardIds, IDbConnection conn)
  271. {
  272. var rewards = (await repository.QueryAsync<dynamic>(
  273. "select id, activityId, name, requirement, signupLimit from n_activity_reward where id in @ids and signupLimit>0", new
  274. {
  275. ids = rewardIds
  276. }, conn)).ToList();
  277. if (rewards.Count == 0) return;
  278. var allActivityIds = rewards.Select(e => (int)e.activityId).Distinct().ToList();
  279. rewardIds = rewards.Select(e => (int)e.id).ToList();
  280. var completeStat = (await repository.QueryAsync<dynamic>(
  281. @"select rewardId, count(1) as count from n_activity_reward_user_state
  282. where rewardId in @rewardIds and state in(0, 1) group by rewardId",
  283. new { rewardIds }, conn)).ToList();
  284. if (completeStat.Count == 0) return;
  285. var cannotSignupActivityIds = new HashSet<int>();
  286. var updateRecords = new List<dynamic>();
  287. rewards.ForEach(p =>
  288. {
  289. if (cannotSignupActivityIds.Contains(p.activityId)) return;
  290. var existStat = completeStat.FirstOrDefault(e => e.rewardId == p.id);
  291. if (existStat == null) return;
  292. if (existStat.count >= p.signupLimit)
  293. {
  294. cannotSignupActivityIds.Add(p.activityId);
  295. updateRecords.Add(new
  296. {
  297. p.name,
  298. p.activityId,
  299. p.requirement,
  300. existStat.count,
  301. p.signupLimit
  302. });
  303. }
  304. });
  305. var canSignupActivityIds = allActivityIds.Where(i => !cannotSignupActivityIds.Contains(i)).ToList();
  306. var activityInfos = (await repository.QueryAsync<dynamic>("select id, signupState, signupCount, signupStartAt, signupEndAt from n_activity where id in @ids", new
  307. {
  308. ids = allActivityIds
  309. }, conn)).ToList();
  310. // 过滤掉当前不可报名的活动编号,不可报名的无需更新
  311. var validCannotSignupActivityIds = cannotSignupActivityIds
  312. .Where(i => !activityInfos.Any(a => a.id == i && a.signupState == 1)).ToList();
  313. if (validCannotSignupActivityIds.Count > 0)
  314. {
  315. await repository.QueryAsync<dynamic>(
  316. $"update n_activity set signupState=1 where id in @ids", new
  317. {
  318. ids = validCannotSignupActivityIds
  319. }, conn, null, false);
  320. await repository.QueryAsync<dynamic>($"insert into n_activity_signup_state_change(activityId, `event`, createAt) values (@activityId, @eventTxt, now())", validCannotSignupActivityIds.Select(
  321. i =>
  322. {
  323. var r = updateRecords.First(r => r.activityId == i);
  324. var name = string.IsNullOrEmpty(r.name)
  325. ? $"邀请{r.requirement}人"
  326. : r.name;
  327. return new
  328. {
  329. activityId = i,
  330. eventTxt = $"停止报名(原因:任务\"{name}\"完成人数{r.count}达到上限)"
  331. };
  332. }));
  333. }
  334. if (canSignupActivityIds.Count > 0)
  335. {
  336. var now = DateTime.Now;
  337. var needCheckSignupLimitActivityIds = new List<int>();
  338. // 过滤掉当前可报名的活动编号,可报名的无需更新
  339. var validCanSignupActivityIds = canSignupActivityIds.Where(i =>
  340. {
  341. var activityInfo = activityInfos.FirstOrDefault(a => a.id == i);
  342. if (activityInfo == null) return false;
  343. // 忽略非不可报名状态
  344. if (activityInfo.signupState != 1) return false;
  345. // 如果时间不满足或者自定义报名人数不满足 也忽略
  346. if (activityInfo.signupStartAt > now || activityInfo.signupEndAt < now) return false;
  347. if (activityInfo.signupCount == 0) return false;
  348. if (activityInfo.signupCount > 0) needCheckSignupLimitActivityIds.Add(i);
  349. return true;
  350. }).ToList();
  351. // 进一步统计报名人数并判断是否满足
  352. if (needCheckSignupLimitActivityIds.Count > 0)
  353. {
  354. // 查出活动当前报名人数
  355. var userCountStat = (await repository.QueryAsync<dynamic>(
  356. "select activityId, count(1) as count from n_activity_signup_records where activityId in @activityIds and state=1",
  357. new { activityIds = needCheckSignupLimitActivityIds }, conn)).ToList();
  358. validCanSignupActivityIds = validCanSignupActivityIds.Where(i =>
  359. {
  360. var activityInfo = activityInfos.First(a => a.id == i);
  361. var userCount = userCountStat.FirstOrDefault(s => s.activityId == i)?.count ?? 0;
  362. return activityInfo.signupCount > userCount;
  363. }).ToList();
  364. }
  365. if (validCanSignupActivityIds.Count > 0)
  366. {
  367. await repository.QueryAsync<dynamic>(
  368. $"update n_activity set signupState=0 where id in @ids", new
  369. {
  370. ids = validCanSignupActivityIds
  371. }, conn, null, false);
  372. await repository.QueryAsync<dynamic>($"insert into n_activity_signup_state_change(activityId, `event`, createAt) values (@activityId, @eventTxt, now())", validCanSignupActivityIds.Select(
  373. i => new
  374. {
  375. activityId = i,
  376. eventTxt = "开始报名"
  377. }));
  378. }
  379. }
  380. }
  381. /// <summary>
  382. /// 更新邀请好友活动的统计值(各活动任务完成状态/排行数据)
  383. /// </summary>
  384. public static async Task UpdateActivityYqhyStatBySingleUser(this DbRESTFulRepository repository, long userId, IDbConnection conn)
  385. {
  386. // 如果邀请好友活动未超出领取时间,才需要更新排名数据
  387. var needUpdateActivities = (await repository.QueryAsync<dynamic>(
  388. @"select id, startTime, endTime, config, signupEnabled, rewardRule,hotValue
  389. from n_activity where state=1 and type='yqhy' and startTime<now() and (latestReceiveTime is null or latestReceiveTime>now())",
  390. null, conn)).ToList();
  391. if (needUpdateActivities.Count == 0) return;
  392. //更新热度值
  393. List<ActivityHotVO> activityInfos = needUpdateActivities.Where(a => (DateTime)a.endTime >= DateTime.Now && (int)a.signupEnabled == 0).Select(e => new ActivityHotVO
  394. {
  395. id = e.id,
  396. userId = userId,
  397. oldHotValue = e.hotValue,
  398. signupEnabled = (int)e.signupEnabled
  399. }).ToList();
  400. //活动参与热度记录
  401. await AddActivityHotRecords(repository, activityInfos, conn);
  402. var activityIds = needUpdateActivities.Where(e => e.signupEnabled == 1).Select(e => (int)e.id).ToList();
  403. var signupTimeDic = new Dictionary<int, DateTime>();
  404. // 如果启用报名的,则需要过滤掉未报名活动
  405. if (activityIds.Count > 0)
  406. {
  407. var validActivityInfos = (await repository.QueryAsync<dynamic>(
  408. $"select activityId, createAt from n_activity_signup_records where activityId in @activityIds and userId={userId} and state=1",
  409. new
  410. {
  411. activityIds
  412. }, conn)).ToList();
  413. validActivityInfos.ForEach(e =>
  414. {
  415. signupTimeDic[(int)e.activityId] = (DateTime)e.createAt;
  416. });
  417. var validActivityIds = validActivityInfos.Select(e => (int)e.activityId).ToList();
  418. needUpdateActivities = needUpdateActivities
  419. .Where(e => activityIds.All(i => i != e.id) || validActivityIds.Any(i => i == e.id))
  420. .ToList();
  421. }
  422. if (needUpdateActivities.Count == 0) return;
  423. var typedActivitiesDic = new Dictionary<int, ActivityYqhyConfig>();
  424. var activitiesDic = new Dictionary<int, dynamic>();
  425. var allRewardIds = new List<int>();
  426. var minTime = DateTime.MaxValue;
  427. var maxTime = DateTime.MinValue;
  428. var now = DateTime.Now;
  429. foreach (var activity in needUpdateActivities)
  430. {
  431. var config = JsonConvert.DeserializeObject<ActivityYqhyConfig>((string)activity.config);
  432. typedActivitiesDic[activity.id] = config;
  433. activitiesDic[activity.id] = activity;
  434. allRewardIds.AddRange(config.rewardIds);
  435. if (activity.startTime < minTime) minTime = activity.startTime;
  436. if (activity.endTime > maxTime) maxTime = activity.endTime;
  437. }
  438. // 统计此用户此期间所有的有效的邀请记录
  439. var records = (await repository.QueryAsync<dynamic>(
  440. $"select createAt, activeAt, hasProfit from n_user_invitation_record where userId={userId} and state=1 and invalid=0 and (createAt>=@minTime and createAt<=@maxTime) and (activeAt>=@minTime and activeAt<=@maxTime)",
  441. new { minTime, maxTime }, conn)).ToList();
  442. // 统计不同活动用户成功邀请次数
  443. var countDic = new Dictionary<int, int>();
  444. var lastCompletedTime = new Dictionary<int, DateTime>();
  445. records.ForEach(r =>
  446. {
  447. needUpdateActivities.ForEach(a =>
  448. {
  449. var aid = (int)a.id;
  450. var config = typedActivitiesDic[aid];
  451. var startTime = a.startTime;
  452. if (signupTimeDic.ContainsKey(aid) && signupTimeDic[aid] > startTime)
  453. {
  454. startTime = signupTimeDic[aid];
  455. }
  456. // 如果配置不允许获利邀请计入且当前条目是获利,则不计入
  457. if ((!config.ignoreProfit || r.hasProfit == 0) && (a.endTime == null || a.endTime >= r.activeAt) && startTime <= r.activeAt)
  458. {
  459. if (countDic.ContainsKey(aid))
  460. {
  461. countDic[aid]++;
  462. }
  463. else
  464. {
  465. countDic[aid] = 1;
  466. }
  467. if (!lastCompletedTime.ContainsKey(aid) || lastCompletedTime[aid] < r.activeAt)
  468. {
  469. lastCompletedTime[aid] = r.activeAt;
  470. }
  471. }
  472. });
  473. });
  474. // 更新奖励状态记录
  475. if (allRewardIds.Count > 0)
  476. {
  477. var completed = new List<dynamic>();
  478. var uncompleted = new List<int>();
  479. // 查出所有活动的奖励配置
  480. var rewards = await repository.QueryAsync<dynamic>(
  481. "select id, activityId, requirement from n_activity_reward where id in @ids and invalid=0 order by displayOrder asc",
  482. new { ids = allRewardIds }, conn);
  483. // 用于设置仅发最后一个任务的奖励
  484. var activityIdHashSet = new HashSet<int>();
  485. // 检测各活动用户奖励是否达标
  486. rewards.ForEach(r =>
  487. {
  488. int requirement = int.Parse(r.requirement);
  489. int aid = (int)r.activityId;
  490. var activityInfo = activitiesDic[aid];
  491. var count = countDic.ContainsKey(aid) ? countDic[aid] : 0;
  492. var time = lastCompletedTime.ContainsKey(aid) ? lastCompletedTime[aid] : now;
  493. if (requirement <= count)
  494. {
  495. // 如果活动设置的是只能领取最后奖励,则需要将除最高任务的其他任务设置成未达成
  496. if (activityInfo.rewardRule == 1)
  497. {
  498. if (!activityIdHashSet.Contains(aid))
  499. {
  500. completed.Add(new
  501. {
  502. rewardId = r.id,
  503. r.activityId,
  504. latestCompleteAt = time
  505. });
  506. activityIdHashSet.Add(aid);
  507. }
  508. else
  509. {
  510. uncompleted.Add(r.id);
  511. }
  512. }
  513. else
  514. {
  515. completed.Add(new
  516. {
  517. rewardId = r.id,
  518. r.activityId,
  519. latestCompleteAt = time
  520. });
  521. }
  522. }
  523. else
  524. {
  525. uncompleted.Add(r.id);
  526. }
  527. });
  528. if (completed.Count > 0)
  529. {
  530. await repository.QueryAsync<dynamic>(@$"insert into n_activity_reward_user_state
  531. (userId, rewardId, activityId, state, latestCompleteAt) values
  532. ({userId}, @rewardId, @activityId, 0, @latestCompleteAt)
  533. ON DUPLICATE KEY update state=if(state=-1, 0, state), latestCompleteAt=if(state=-1, @latestCompleteAt, latestCompleteAt)",
  534. completed, conn, null, false);
  535. }
  536. if (uncompleted.Count > 0)
  537. {
  538. await repository.QueryAsync<dynamic>(@$"update n_activity_reward_user_state
  539. set state=-1 where userId={userId} and rewardId in @ids and state=0", new { ids = uncompleted }, conn, null, false);
  540. }
  541. }
  542. if (countDic.Count > 0)
  543. {
  544. // 更新排行数据
  545. var rankingdata = countDic.Select(e => new
  546. {
  547. activityId = e.Key,
  548. score = e.Value,
  549. lastRecordTime = lastCompletedTime.ContainsKey(e.Key) ? lastCompletedTime[e.Key] : now
  550. });
  551. await repository.QueryAsync<dynamic>($@"insert into n_activity_ranking
  552. (activityId, userId, score, lastRecordTime) values
  553. (@activityId, {userId}, @score, @lastRecordTime)
  554. ON DUPLICATE KEY update score=@score, lastRecordTime=@lastRecordTime", rankingdata, conn, null, false);
  555. }
  556. // 更新报名状态
  557. if (allRewardIds.Count > 0)
  558. {
  559. await repository.UpdateActivitySignupState(allRewardIds, conn);
  560. }
  561. }
  562. /// <summary>
  563. /// 更新每日话题活动的统计值(各活动任务完成状态/排行数据)
  564. /// </summary>
  565. public static async Task UpdateActivityMrhtStatBySinglePost(this DbRESTFulRepository repository, long postId,
  566. IDbConnection conn)
  567. {
  568. // 如果每日话题活动未超出领取时间,才需要更新排名数据
  569. var needUpdateActivities = (await repository.QueryAsync<dynamic>(
  570. "select id, startTime, endTime, config, signupEnabled, rewardRule,hotValue from n_activity where type='mrht' and state=1 and startTime<now() and (latestReceiveTime is null or latestReceiveTime>now())",
  571. null, conn)).ToList();
  572. if (needUpdateActivities.Count == 0) return;
  573. var postInfo = await repository.QuerySingleOrDefaultAsync<dynamic>($"select userId, categoryType, originalTopicNames, createAt from n_post where id={postId}", null, conn);
  574. if (postInfo == null) return;
  575. var userId = (long)postInfo.userId;
  576. //更新热度值
  577. List<ActivityHotVO> activityInfos = needUpdateActivities.Where(a => (DateTime)a.endTime >= DateTime.Now && (int)a.signupEnabled == 0).Select(e => new ActivityHotVO
  578. {
  579. id = e.id,
  580. userId = userId,
  581. oldHotValue = e.hotValue,
  582. signupEnabled = (int)e.signupEnabled
  583. }).ToList();
  584. //活动参与热度记录
  585. await AddActivityHotRecords(repository, activityInfos, conn);
  586. {
  587. var activityIds = needUpdateActivities.Where(e => e.signupEnabled == 1).Select(e => (int)e.id).ToList();
  588. // 如果启用报名的,则需要过滤掉未报名活动
  589. if (activityIds.Count > 0)
  590. {
  591. var validActivityIds = (await repository.QueryAsync<int>(
  592. $"select activityId from n_activity_signup_records where activityId in @activityIds and userId={userId} and state=1",
  593. new
  594. {
  595. activityIds
  596. }, conn)).ToList();
  597. needUpdateActivities = needUpdateActivities
  598. .Where(e => !activityIds.Contains(e.id) || validActivityIds.Contains(e.id))
  599. .ToList();
  600. }
  601. }
  602. if (needUpdateActivities.Count == 0) return;
  603. var topicNames = ((string)postInfo.originalTopicNames).Split('\n', StringSplitOptions.RemoveEmptyEntries);
  604. if (topicNames.Length == 0) return;
  605. var topicIds = (await repository.QueryAsync<int>("select id from n_topic where title in @names",
  606. new { names = topicNames }, conn)).ToList();
  607. if (topicIds.Count == 0) return;
  608. var createDate = ((DateTime)postInfo.createAt).Date;
  609. // 筛选出此文章话题相关的所有活动
  610. needUpdateActivities = needUpdateActivities.Where(e =>
  611. {
  612. var config = JsonConvert.DeserializeObject<ActivityMrhtConfig>((string)e.config);
  613. if (config.topics == null) return false;
  614. var validTopicId = config.topics.LastOrDefault(i => i.date.Date <= createDate && i.topicId > 0)
  615. ?.topicId ?? 0;
  616. return validTopicId > 0 && topicIds.Contains(validTopicId);
  617. }).ToList();
  618. if (needUpdateActivities.Count == 0) return;
  619. var relativeActivityIds = needUpdateActivities.Select(e => e.id).ToList();
  620. // 找出此用户在所有有效每日话题中的活动记录
  621. var allRelativeRecords = (await repository.QueryAsync<dynamic>(
  622. $"select activityId, `date`, topicId, postId, createAt from n_activity_mrht_records where userId={userId} and state=1 and activityId in @activityIds",
  623. new { activityIds = relativeActivityIds }, conn)).ToList();
  624. if (allRelativeRecords.Count == 0) return;
  625. // 查出相关活动的奖励配置列表
  626. var rewards = (await repository.QueryAsync<dynamic>(
  627. "select id, activityId, requirement, displayOrder from n_activity_reward where activityId in @activityIds and invalid=0 order by displayOrder asc",
  628. new { activityIds = relativeActivityIds }, conn))
  629. .Select(e => new { e.id, e.activityId, requirement = int.Parse(e.requirement), e.displayOrder }).ToList();
  630. if (rewards.Count == 0) return;
  631. // 查出已达成和未达成的任务
  632. var completedRecords =
  633. (await repository.QueryAsync<dynamic>(
  634. $"select rewardId, latestCompleteAt from n_activity_reward_user_state where userId={userId} and rewardId in @rewardIds and state in (0, 1)",
  635. new { rewardIds = rewards.Select(e => e.id) }, conn)).ToList();
  636. var completed = completedRecords.Select(e => (int)e.rewardId).ToList();
  637. var uncompleted = rewards.Where(e => !completed.Contains(e.id));
  638. var insertRecords = new List<dynamic>(); // 待插入或更新的达成记录(除去了最高任务奖励类型)
  639. var singleRewardInsertRecords = new List<dynamic>(); // 待插入或更新的达成记录(仅包含最高任务奖励类型)
  640. // 判断达成情况
  641. uncompleted.ForEach(e =>
  642. {
  643. var curActivityRecords = allRelativeRecords.Where(i => i.activityId == e.activityId).ToList();
  644. // 查出此任务所有的完成的记录数量
  645. var dates = curActivityRecords.Select(i => i.date).Distinct().OrderBy(d => d).ToList();
  646. var count = dates.Count;
  647. if (count >= e.requirement && e.requirement > 0)
  648. {
  649. // 达成活动的日期
  650. var date = dates[e.requirement - 1];
  651. // 找出达成的那天最早的发布时间
  652. var latestCompleteAt = curActivityRecords.Where(i => i.date == date).Select(i => i.date).Min();
  653. // 添加到更新列表中
  654. insertRecords.Add(new { rewardId = e.id, e.activityId, latestCompleteAt });
  655. }
  656. });
  657. // 如果活动设置的是只能领取最后奖励,则需要将除最高任务的其他任务设置成未达成
  658. var singleRewardActivityList = needUpdateActivities.Where(e => e.rewardRule == 1).ToList();
  659. if (singleRewardActivityList.Count > 0)
  660. {
  661. var set = new HashSet<int>();
  662. rewards.ForEach(e =>
  663. {
  664. if (singleRewardActivityList.All(a => a.id != e.activityId)) return;
  665. var existRecord = completedRecords.FirstOrDefault(r => r.rewardId == e.id);
  666. if (existRecord == null) existRecord = insertRecords.FirstOrDefault(r => r.rewardId == e.id);
  667. if (existRecord == null) return;
  668. if (set.Contains(e.activityId)) return;
  669. set.Add(e.activityId);
  670. singleRewardInsertRecords.Add(new
  671. {
  672. rewardId = e.id,
  673. e.activityId,
  674. existRecord.latestCompleteAt
  675. });
  676. });
  677. // 先在更新列表中移除只领一个奖励的任务
  678. insertRecords = insertRecords.Where(e => singleRewardActivityList.All(a => a.id != e.activityId))
  679. .ToList();
  680. }
  681. // 更新此用户所有有效的每日话题活动总参与次数
  682. var rankingdata = new List<dynamic>();
  683. allRelativeRecords.GroupBy(e => e.activityId).ForEach(group =>
  684. {
  685. var activityId = group.Key;
  686. var list = group.ToList();
  687. var sgroup = list.GroupBy(i => i.date);
  688. var count = sgroup.Count();
  689. var minTime = sgroup.OrderBy(m => m.Key).Last().First().createAt;
  690. rankingdata.Add(new
  691. {
  692. activityId,
  693. score = count,
  694. lastRecordTime = minTime
  695. });
  696. });
  697. List<int> validUpdatedRecordIds = new List<int>();
  698. if (insertRecords.Count > 0)
  699. {
  700. await repository.QueryAsync<dynamic>(@$"insert into n_activity_reward_user_state
  701. (userId, rewardId, activityId, state, latestCompleteAt) values
  702. ({userId}, @rewardId, @activityId, 0, @latestCompleteAt)
  703. ON DUPLICATE KEY update state=if(state=-1, 0, state), latestCompleteAt=if(state=-1, @latestCompleteAt, latestCompleteAt)",
  704. insertRecords, conn, null, false);
  705. validUpdatedRecordIds.AddRange(insertRecords.Select(e => (int)e.rewardId));
  706. }
  707. if (singleRewardActivityList.Count > 0)
  708. {
  709. // 如果活动设置的是只能领取最后奖励,先重置非达成的状态,然后再插入或更新达成的状态
  710. var activityIds = singleRewardActivityList.Select(a => a.id);
  711. dynamic rewardIds = singleRewardInsertRecords.Count > 0
  712. ? singleRewardInsertRecords.Select(e => e.rewardId)
  713. : null;
  714. await repository.QueryAsync<dynamic>(
  715. $"update n_activity_reward_user_state set state=-1 where activityId in @activityIds and userId={userId} [and rewardId not in @rewardIds]", new
  716. {
  717. activityIds,
  718. rewardIds
  719. }, conn, null, false);
  720. if (singleRewardInsertRecords.Count > 0)
  721. {
  722. await repository.QueryAsync<dynamic>(@$"insert into n_activity_reward_user_state
  723. (userId, rewardId, activityId, state, latestCompleteAt) values
  724. ({userId}, @rewardId, @activityId, 0, @latestCompleteAt)
  725. ON DUPLICATE KEY update state=if(state=-1, 0, state), latestCompleteAt=if(state=-1, @latestCompleteAt, latestCompleteAt)",
  726. singleRewardInsertRecords, conn, null, false);
  727. validUpdatedRecordIds.AddRange(singleRewardInsertRecords.Select(e => (int)e.rewardId));
  728. }
  729. }
  730. if (rankingdata.Count > 0)
  731. {
  732. await repository.QueryAsync<dynamic>($@"insert into n_activity_ranking
  733. (activityId, userId, score, lastRecordTime) values
  734. (@activityId, {userId}, @score, @lastRecordTime)
  735. ON DUPLICATE KEY update score=@score, lastRecordTime=@lastRecordTime", rankingdata, conn, null, false);
  736. }
  737. // 更新报名状态
  738. if (validUpdatedRecordIds.Count > 0)
  739. {
  740. await repository.UpdateActivitySignupState(validUpdatedRecordIds, conn);
  741. }
  742. }
  743. /// <summary>
  744. /// 活动参与热度记录
  745. /// </summary>
  746. /// <param name="repository"></param>
  747. /// <param name="userId"></param>
  748. /// <param name="hotInfos"></param>
  749. /// <param name="conn"></param>
  750. /// <returns></returns>
  751. public static async Task AddActivityHotRecords(this DbRESTFulRepository repository, List<ActivityHotVO> hotInfos, IDbConnection conn)
  752. {
  753. if (hotInfos != null && hotInfos.Count > 0)
  754. {
  755. //所有活动id
  756. var ids = hotInfos.Select(s => s.id);
  757. //该用户已经参与活动已经加过热度了
  758. var activityIds = await repository.QueryAsync<int>(
  759. $"select activityId from n_activity_hot_records where activityId in @ids and userId=@userId limit 1", new { ids, hotInfos[0].userId },
  760. conn, null, false);
  761. if (activityIds != null && activityIds.Count() > 0)
  762. {
  763. hotInfos = hotInfos.Where(s => !activityIds.ToList().Contains(s.id)).ToList();
  764. }
  765. if (hotInfos != null && hotInfos.Count > 0)
  766. {
  767. //报名:每个账号报名成功时,随机加1~10;
  768. //热度:每个账号完成每个活动的第1次任务时,随机加5~15
  769. hotInfos.ForEach(item => { item.addHotValue = item.signupEnabled == 1 ? new Random().Next(1, 10) : new Random().Next(5, 15); });
  770. await repository.QueryAsync<dynamic>(
  771. "update n_activity set hotValue=hotValue+@addHotValue where id=@id;", hotInfos,
  772. conn, null, false);
  773. await repository.QueryAsync<dynamic>(
  774. $@"insert into n_activity_hot_records(activityId,userId, oldHotValue,addHotValue, createAt)
  775. values (@id,@userId, @oldHotValue,@addHotValue, now())", hotInfos, conn, null, false);
  776. }
  777. }
  778. }
  779. }
  780. }