TriggerVote.cs 17 KB

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