TriggerVote.cs 14 KB

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