TriggerVote.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. //if (vote.scope == "school")
  88. //{
  89. // data = new ActivityData
  90. // {
  91. // id = vote.id,
  92. // code = $"Activity-{vote.school}",
  93. // type = "vote",
  94. // name = vote.name,
  95. // startTime = vote.startTime,
  96. // endTime = vote.endTime,
  97. // scode = vote.code,
  98. // scope = vote.scope,
  99. // classes = vote.classes.IsNotEmpty() ? vote.classes : new List<string> { "" },
  100. // tmdids = vote.tmdids.IsNotEmpty() ? vote.tmdids : new List<string> { "" },
  101. // progress = "going",
  102. // subjects = new List<string> { "" }
  103. // };
  104. // await client.GetContainer("TEAMModelOS", "School").UpsertItemAsync<ActivityData>(data, new Azure.Cosmos.PartitionKey(data.code));
  105. //}
  106. //else if (vote.scope == "private")
  107. //{
  108. // data = new ActivityData
  109. // {
  110. // id = vote.id,
  111. // code = $"Activity-Common",
  112. // type = "vote",
  113. // name = vote.name,
  114. // startTime = vote.startTime,
  115. // endTime = vote.endTime,
  116. // scode = vote.code,
  117. // scope = vote.scope,
  118. // progress = "going",
  119. // classes = vote.classes.IsNotEmpty() ? vote.classes : new List<string> { "" },
  120. // tmdids = new List<string> { "" },
  121. // subjects = new List<string> { "" }
  122. // };
  123. // await client.GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync<ActivityData>(data, new Azure.Cosmos.PartitionKey(data.code));
  124. //}
  125. (List<string> tmdids, List<Students> students) = await TriggerStuActivity.GetStuList(client, vote.classes, vote.school);
  126. List<string> tmds = vote.tmdids.IsNotEmpty() ? vote.tmdids : new List<string>() ;
  127. if (tmdids.IsNotEmpty()) {
  128. tmds.AddRange(tmdids);
  129. }
  130. List<StuActivity> stuActivities = new List<StuActivity>();
  131. List<StuActivity> tmdActivities = new List<StuActivity>();
  132. if (tmds.IsNotEmpty())
  133. {
  134. tmds.ForEach(x => {
  135. tmdActivities.Add(new StuActivity
  136. {
  137. pk = "Activity",
  138. id = vote.id,
  139. code = $"Activity-{x}",
  140. type = "Vote",
  141. name = vote.name,
  142. startTime = vote.startTime,
  143. endTime = vote.endTime,
  144. scode = vote.code,
  145. scope = vote.scope,
  146. school = vote.school,
  147. creatorId = vote.creatorId,
  148. subjects = new List<string> { "" } ,
  149. blob = null
  150. });
  151. });
  152. }
  153. if (students.IsNotEmpty())
  154. {
  155. students.ForEach(x => {
  156. stuActivities.Add(new StuActivity
  157. {
  158. pk = "Activity",
  159. id = vote.id,
  160. code = $"Activity-{vote.school}-{x.id}",
  161. type = "Vote",
  162. name = vote.name,
  163. startTime = vote.startTime,
  164. endTime = vote.endTime,
  165. scode = vote.code,
  166. scope = vote.scope,
  167. school = vote.school,
  168. creatorId = vote.creatorId,
  169. subjects = new List<string> { "" },
  170. blob=null
  171. });
  172. });
  173. }
  174. await TriggerStuActivity.SaveStuActivity(client, stuActivities, tmdActivities);
  175. var messageVoteEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
  176. messageVoteEnd.ApplicationProperties.Add("name", "Vote");
  177. if (voteRecords.Count > 0)
  178. {
  179. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  180. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", voteRecords[0].sequenceNumber);
  181. voteRecords[0].sequenceNumber = end;
  182. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  183. }
  184. else
  185. {
  186. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  187. ChangeRecord changeRecord = new ChangeRecord
  188. {
  189. RowKey = input.Id,
  190. PartitionKey = "going",
  191. sequenceNumber = end,
  192. msgId = messageVoteEnd.MessageId
  193. };
  194. await _azureStorage.Save<ChangeRecord>(changeRecord);
  195. }
  196. await _dingDing.SendBotMsg($"投票活动{tdata.id}将于:{tdata.etime}完成并结算!", GroupNames.成都开发測試群組);
  197. break;
  198. case "finish":
  199. await _dingDing.SendBotMsg($"投票活动{tdata.id}开始结算{tdata.etime}!", GroupNames.成都开发測試群組);
  200. //获取投票活动的所有投票记录
  201. var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Vote:Record:{vote.id}");
  202. //获取投票活动的选项及投票数
  203. var counts = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Vote:Count:{vote.id}");
  204. List<dynamic> countcds = new List<dynamic>();
  205. if (counts != null && counts.Length > 0)
  206. {
  207. foreach (var count in counts)
  208. {
  209. countcds.Add(new { code = count.Element.ToString(), count = (int)count.Score });
  210. }
  211. }
  212. List<Task<string>> tasks = new List<Task<string>>();
  213. List<VoteRecord> recordsBlob = new List<VoteRecord>();
  214. foreach (var rcd in records)
  215. {
  216. var value = rcd.Value.ToString().ToObject<VoteRecord>();
  217. recordsBlob.Add(value);
  218. }
  219. //分组每个人的
  220. var gp = recordsBlob.GroupBy(x => x.userid).Select(x => new { key = x.Key, list = x.ToList() });
  221. foreach (var g in gp)
  222. {
  223. tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, g.list.ToJsonString(), "vote", $"{vote.id}/urecord/{g.key}.json"));
  224. }
  225. //处理活动方的记录,
  226. string url = $"/vote/{vote.id}/record.json";
  227. tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, new { options = countcds, records = recordsBlob }.ToJsonString(), "vote", $"{vote.id}/record.json"));
  228. //处理投票者的记录
  229. if (string.IsNullOrEmpty(vote.recordUrl))
  230. {
  231. vote.recordUrl = url;
  232. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Vote>(vote, vote.id, new Azure.Cosmos.PartitionKey(vote.code));
  233. }
  234. else {
  235. //异动,且已经有结算记录则不必再继续。
  236. _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{vote.id}");
  237. _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{vote.id}");
  238. break;
  239. }
  240. await Task.WhenAll(tasks);
  241. //data.progress = "finish";
  242. //更新结束状态
  243. //if (vote.scope == "school")
  244. //{
  245. // await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  246. //}
  247. //else if (vote.scope == "private")
  248. //{
  249. // await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  250. //}
  251. //_azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{vote.id}");
  252. //_azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{vote.id}");
  253. break;
  254. }
  255. }
  256. }
  257. }
  258. }