TriggerVote.cs 17 KB

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