TriggerVote.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. using Azure.Cosmos;
  2. using Azure.Messaging.ServiceBus;
  3. using Microsoft.Azure.Documents;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.Json;
  9. using System.Threading.Tasks;
  10. using TEAMModelOS.SDK.DI;
  11. using TEAMModelOS.SDK.Extension;
  12. using TEAMModelOS.SDK;
  13. using TEAMModelOS.SDK.Models;
  14. using TEAMModelOS.SDK.Models.Cosmos;
  15. using TEAMModelOS.SDK.Models.Cosmos.Common;
  16. using TEAMModelOS.SDK.Models.Cosmos.Common.Inner;
  17. using TEAMModelOS.SDK.Models.Service;
  18. using HTEXLib.COMM.Helpers;
  19. namespace TEAMModelFunction
  20. {
  21. public static class TriggerVote
  22. {
  23. public static async void Trigger( AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  24. CosmosClient client, Document input, TriggerData tdata, AzureRedisFactory _azureRedis)
  25. {
  26. try {
  27. if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0)
  28. {
  29. //异动,且已经有结算记录则不必再继续。
  30. _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{tdata.id}");
  31. _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{tdata.id}");
  32. return;
  33. }
  34. var adid = tdata.id;
  35. var adcode = "";
  36. string blobcntr = null;
  37. if (tdata.scope .Equals("school"))
  38. {
  39. adcode = $"Activity-{tdata.school}";
  40. blobcntr = tdata.school;
  41. }
  42. else
  43. {
  44. adcode = $"Activity-{tdata.creatorId}";
  45. blobcntr = tdata.creatorId;
  46. }
  47. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动【{tdata.name}-{tdata.id}-ttl={tdata.ttl}】正在操作", GroupNames.成都开发測試群組);
  48. Vote vote = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Vote>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
  49. if (vote != null)
  50. {
  51. string PartitionKey = string.Format("{0}{1}{2}", vote.code, "-", vote.progress);
  52. List<ChangeRecord> voteRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", PartitionKey } });
  53. switch (vote.progress)
  54. {
  55. case "pending":
  56. var messageVote = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
  57. messageVote.ApplicationProperties.Add("name", "Vote");
  58. if (voteRecords.Count > 0)
  59. {
  60. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
  61. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
  62. voteRecords[0].sequenceNumber = start;
  63. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  64. }
  65. else
  66. {
  67. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
  68. ChangeRecord changeRecord = new ChangeRecord
  69. {
  70. RowKey = input.Id,
  71. PartitionKey = PartitionKey,
  72. sequenceNumber = start,
  73. msgId = messageVote.MessageId
  74. };
  75. await _azureStorage.Save<ChangeRecord>(changeRecord);
  76. }
  77. break;
  78. case "going":
  79. List<string> classes = ExamService.getClasses(vote.classes, vote.stuLists);
  80. (List<TmdInfo> tmdids, List<StuInfo> students, List<ClassListInfo> classLists) = await TriggerStuActivity.GetStuList(client, _dingDing, classes, vote.school);
  81. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动" +
  82. // $"{tmdids.ToJsonString()}\n" +
  83. // $"{students.ToJsonString()}\n" +
  84. // $"{classLists.ToJsonString()}\n" +
  85. // $"{classes.ToJsonString()}\n", GroupNames.成都开发測試群組);
  86. List<string> tmds = new List<string>();
  87. if (tmdids.IsNotEmpty())
  88. {
  89. tmds.AddRange(tmdids.Select(x => x.id).ToList());
  90. }
  91. List<StuActivity> stuActivities = new List<StuActivity>();
  92. List<StuActivity> tmdActivities = new List<StuActivity>();
  93. List<StuActivity> tchActivities = new List<StuActivity>();
  94. if (tmds.IsNotEmpty())
  95. {
  96. tmds.ForEach(x => {
  97. tmdActivities.Add(new StuActivity
  98. {
  99. pk = "Activity",
  100. id = vote.id,
  101. code = $"Activity-{x}",
  102. type = "Vote",
  103. name = vote.name,
  104. startTime = vote.startTime,
  105. endTime = vote.endTime,
  106. scode = vote.code,
  107. scope = vote.scope,
  108. school = vote.school,
  109. creatorId = vote.creatorId,
  110. subjects = new List<string> { "" },
  111. blob = null,
  112. owner = vote.owner,
  113. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  114. taskStatus = -1,
  115. classIds = classes
  116. });
  117. });
  118. }
  119. if (students.IsNotEmpty())
  120. {
  121. students.ForEach(x => {
  122. stuActivities.Add(new StuActivity
  123. {
  124. pk = "Activity",
  125. id = vote.id,
  126. code = $"Activity-{x.code.Replace("Base-","")}-{x.id}",
  127. type = "Vote",
  128. name = vote.name,
  129. startTime = vote.startTime,
  130. endTime = vote.endTime,
  131. scode = vote.code,
  132. scope = vote.scope,
  133. school = vote.school,
  134. creatorId = vote.creatorId,
  135. subjects = new List<string> { "" },
  136. blob = null,
  137. owner = vote.owner,
  138. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  139. taskStatus = -1,
  140. classIds = classes
  141. });
  142. });
  143. }
  144. (List<TmdInfo> tchList, _) = await TriggerStuActivity.GetTchList(client, _dingDing, vote.tchLists, vote.school);
  145. if (tchList.IsNotEmpty())
  146. {
  147. tchList.ForEach(x => {
  148. tchActivities.Add(new StuActivity
  149. {
  150. pk = "Activity",
  151. id = vote.id,
  152. code = $"Activity-{x.id}",
  153. type = "Vote",
  154. name = vote.name,
  155. startTime = vote.startTime,
  156. endTime = vote.endTime,
  157. scode = vote.code,
  158. scope = vote.scope,
  159. school = vote.school,
  160. creatorId = vote.creatorId,
  161. subjects = new List<string> { "" },
  162. blob = null,
  163. owner = vote.owner,
  164. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  165. taskStatus = -1,
  166. classIds = classes
  167. });
  168. });
  169. }
  170. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动,:教研组活动:" +
  171. $"{tchActivities.ToJsonString()}\n", GroupNames.成都开发測試群組);
  172. await TriggerStuActivity.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, tchActivities);
  173. //向学生或醍摩豆账号发起通知
  174. #region
  175. //Notice notice = new Notice()
  176. //{
  177. // creation = vote.startTime,
  178. // expire = vote.endTime,
  179. // creatorId = vote.creatorId,
  180. // stuids = students,
  181. // tmdids = tmdids,
  182. // type = "notice",//问卷参加参加通知
  183. // priority = "normal",
  184. // msgId=vote.id,
  185. // school = vote.school,
  186. // scope = vote.scope,
  187. // //data = new { }.ToJsonString()
  188. // body = new Body { sid = vote.id, scode = vote.code, spk = vote.pk, biztype = "vote-join" }
  189. //};
  190. //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
  191. //messageBlob.ApplicationProperties.Add("name", "Notice");
  192. //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:NoticeTask"), messageBlob);
  193. #endregion
  194. var messageVoteEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
  195. messageVoteEnd.ApplicationProperties.Add("name", "Vote");
  196. if (voteRecords.Count > 0)
  197. {
  198. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  199. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
  200. voteRecords[0].sequenceNumber = end;
  201. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  202. }
  203. else
  204. {
  205. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  206. ChangeRecord changeRecord = new ChangeRecord
  207. {
  208. RowKey = input.Id,
  209. PartitionKey = PartitionKey,
  210. sequenceNumber = end,
  211. msgId = messageVoteEnd.MessageId
  212. };
  213. await _azureStorage.Save<ChangeRecord>(changeRecord);
  214. }
  215. #if DEBUG
  216. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动{tdata.id}将于:{tdata.etime}完成并结算!", GroupNames.成都开发測試群組);
  217. #endif
  218. break;
  219. case "finish":
  220. #if DEBUG
  221. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动{tdata.id}开始结算{tdata.etime}!", GroupNames.成都开发測試群組);
  222. #endif
  223. //获取投票活动的所有投票记录
  224. var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Vote:Record:{vote.id}");
  225. //获取投票活动的选项及投票数
  226. var counts = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Vote:Count:{vote.id}");
  227. List<dynamic> countcds = new List<dynamic>();
  228. if (counts != null && counts.Length > 0)
  229. {
  230. foreach (var count in counts)
  231. {
  232. countcds.Add(new { code = count.Element.ToString(), count = (int)count.Score });
  233. }
  234. }
  235. List<Task<string>> tasks = new List<Task<string>>();
  236. List<VoteRecord> recordsBlob = new List<VoteRecord>();
  237. foreach (var rcd in records)
  238. {
  239. var value = rcd.Value.ToString().ToObject<VoteRecord>();
  240. recordsBlob.Add(value);
  241. }
  242. //分组每个人的
  243. var gp = recordsBlob.GroupBy(x => x.userid).Select(x => new { key = x.Key, list = x.ToList() });
  244. foreach (var g in gp)
  245. {
  246. tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, g.list.ToJsonString(), "vote", $"{vote.id}/urecord/{g.key}.json"));
  247. }
  248. //处理活动方的记录,
  249. string url = $"/vote/{vote.id}/record.json";
  250. tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, new { options = countcds, records = recordsBlob }.ToJsonString(), "vote", $"{vote.id}/record.json"));
  251. //处理投票者的记录
  252. if (string.IsNullOrEmpty(vote.recordUrl))
  253. {
  254. vote.recordUrl = url;
  255. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Vote>(vote, vote.id, new Azure.Cosmos.PartitionKey(vote.code));
  256. }
  257. else
  258. {
  259. //异动,且已经有结算记录则不必再继续。
  260. _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{vote.id}");
  261. _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{vote.id}");
  262. break;
  263. }
  264. await Task.WhenAll(tasks);
  265. break;
  266. }
  267. }
  268. } catch (Exception ex) {
  269. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动异常{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  270. }
  271. }
  272. }
  273. }