TriggerVote.cs 13 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.Helper.Common.CollectionHelper;
  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. namespace TEAMModelFunction
  18. {
  19. public static class TriggerVote
  20. {
  21. public static async void Trigger(AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  22. CosmosClient client, Document input, TriggerData tdata, AzureRedisFactory _azureRedis)
  23. {
  24. if ((tdata.status != null && tdata.status.Value == 404)||tdata.ttl>0)
  25. {
  26. return;
  27. }
  28. var adid = tdata.id;
  29. var adcode = "";
  30. string blobcntr = null;
  31. if (tdata.scope == "school")
  32. {
  33. adcode = $"Activity-{tdata.school}";
  34. blobcntr = tdata.school;
  35. }
  36. else if (tdata.scope == "private")
  37. {
  38. adcode = $"Activity-{tdata.creatorId}";
  39. blobcntr = tdata.creatorId;
  40. }
  41. // ActivityData data = null;
  42. //try
  43. //{
  44. // if (tdata.scope == "school")
  45. // {
  46. // data = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<ActivityData>(adid, new Azure.Cosmos.PartitionKey($"{adcode}"));
  47. // }
  48. // else if (tdata.scope == "private")
  49. // {
  50. // data = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<ActivityData>(adid, new Azure.Cosmos.PartitionKey($"{adcode}"));
  51. // }
  52. //}
  53. //catch
  54. //{
  55. // data = null;
  56. //}
  57. await _dingDing.SendBotMsg($"投票活动【{tdata.name}-{tdata.id}-ttl={tdata.ttl}】正在操作", GroupNames.成都开发測試群組);
  58. Vote vote = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Vote>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
  59. List<ChangeRecord> voteRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", vote.progress } });
  60. if (vote != null) {
  61. switch (vote.progress)
  62. {
  63. case "pending":
  64. var messageVote = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
  65. messageVote.ApplicationProperties.Add("name", "Vote");
  66. if (voteRecords.Count > 0)
  67. {
  68. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
  69. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", voteRecords[0].sequenceNumber);
  70. voteRecords[0].sequenceNumber = start;
  71. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  72. }
  73. else
  74. {
  75. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
  76. ChangeRecord changeRecord = new ChangeRecord
  77. {
  78. RowKey = input.Id,
  79. PartitionKey = "pending",
  80. sequenceNumber = start,
  81. msgId = messageVote.MessageId
  82. };
  83. await _azureStorage.Save<ChangeRecord>(changeRecord);
  84. }
  85. break;
  86. case "going":
  87. (List<string> tmdids, List<Students> students) = await TriggerStuActivity.GetStuList(client, vote.classes, vote.school);
  88. List<string> tmds = vote.tmdids.IsNotEmpty() ? vote.tmdids : new List<string>() ;
  89. if (tmdids.IsNotEmpty()) {
  90. tmds.AddRange(tmdids);
  91. }
  92. List<StuActivity> stuActivities = new List<StuActivity>();
  93. List<StuActivity> tmdActivities = 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. });
  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-{vote.school}-{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. });
  134. });
  135. }
  136. await TriggerStuActivity.SaveStuActivity(client, stuActivities, tmdActivities);
  137. //向学生或醍摩豆账号发起通知
  138. #region
  139. Notice notice = new Notice()
  140. {
  141. sid=vote.id,
  142. scode=vote.code,
  143. spk=vote.pk,
  144. scope=vote.scope,
  145. school=vote.school,
  146. stime=vote.startTime,
  147. etime=vote.endTime,
  148. creatorId=vote.creatorId,
  149. stuids=students,
  150. tmdids=tmdids,
  151. type="vote-join",//投票参加通知
  152. level=1,
  153. data=new { }.ToJsonString()
  154. };
  155. //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
  156. //messageBlob.ApplicationProperties.Add("name", "Notice");
  157. //await _serviceBus.GetServiceBusClient().SendMessageAsync("active-task", messageBlob);
  158. #endregion
  159. var messageVoteEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
  160. messageVoteEnd.ApplicationProperties.Add("name", "Vote");
  161. if (voteRecords.Count > 0)
  162. {
  163. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  164. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", voteRecords[0].sequenceNumber);
  165. voteRecords[0].sequenceNumber = end;
  166. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  167. }
  168. else
  169. {
  170. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  171. ChangeRecord changeRecord = new ChangeRecord
  172. {
  173. RowKey = input.Id,
  174. PartitionKey = "going",
  175. sequenceNumber = end,
  176. msgId = messageVoteEnd.MessageId
  177. };
  178. await _azureStorage.Save<ChangeRecord>(changeRecord);
  179. }
  180. await _dingDing.SendBotMsg($"投票活动{tdata.id}将于:{tdata.etime}完成并结算!", GroupNames.成都开发測試群組);
  181. break;
  182. case "finish":
  183. await _dingDing.SendBotMsg($"投票活动{tdata.id}开始结算{tdata.etime}!", GroupNames.成都开发測試群組);
  184. //获取投票活动的所有投票记录
  185. var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Vote:Record:{vote.id}");
  186. //获取投票活动的选项及投票数
  187. var counts = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Vote:Count:{vote.id}");
  188. List<dynamic> countcds = new List<dynamic>();
  189. if (counts != null && counts.Length > 0)
  190. {
  191. foreach (var count in counts)
  192. {
  193. countcds.Add(new { code = count.Element.ToString(), count = (int)count.Score });
  194. }
  195. }
  196. List<Task<string>> tasks = new List<Task<string>>();
  197. List<VoteRecord> recordsBlob = new List<VoteRecord>();
  198. foreach (var rcd in records)
  199. {
  200. var value = rcd.Value.ToString().ToObject<VoteRecord>();
  201. recordsBlob.Add(value);
  202. }
  203. //分组每个人的
  204. var gp = recordsBlob.GroupBy(x => x.userid).Select(x => new { key = x.Key, list = x.ToList() });
  205. foreach (var g in gp)
  206. {
  207. tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, g.list.ToJsonString(), "vote", $"{vote.id}/urecord/{g.key}.json"));
  208. }
  209. //处理活动方的记录,
  210. string url = $"/vote/{vote.id}/record.json";
  211. tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, new { options = countcds, records = recordsBlob }.ToJsonString(), "vote", $"{vote.id}/record.json"));
  212. //处理投票者的记录
  213. if (string.IsNullOrEmpty(vote.recordUrl))
  214. {
  215. vote.recordUrl = url;
  216. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Vote>(vote, vote.id, new Azure.Cosmos.PartitionKey(vote.code));
  217. }
  218. else {
  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. //data.progress = "finish";
  226. //更新结束状态
  227. //if (vote.scope == "school")
  228. //{
  229. // await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  230. //}
  231. //else if (vote.scope == "private")
  232. //{
  233. // await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  234. //}
  235. //_azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{vote.id}");
  236. //_azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{vote.id}");
  237. break;
  238. }
  239. }
  240. }
  241. }
  242. }