TriggerVote.cs 15 KB

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