TriggerVote.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. #if DEBUG
  58. await _dingDing.SendBotMsg($"投票活动【{tdata.name}-{tdata.id}-ttl={tdata.ttl}】正在操作", GroupNames.成都开发測試群組);
  59. #endif
  60. Vote vote = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Vote>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
  61. List<ChangeRecord> voteRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", vote.progress } });
  62. if (vote != null) {
  63. switch (vote.progress)
  64. {
  65. case "pending":
  66. var messageVote = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
  67. messageVote.ApplicationProperties.Add("name", "Vote");
  68. if (voteRecords.Count > 0)
  69. {
  70. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
  71. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", voteRecords[0].sequenceNumber);
  72. voteRecords[0].sequenceNumber = start;
  73. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  74. }
  75. else
  76. {
  77. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
  78. ChangeRecord changeRecord = new ChangeRecord
  79. {
  80. RowKey = input.Id,
  81. PartitionKey = "pending",
  82. sequenceNumber = start,
  83. msgId = messageVote.MessageId
  84. };
  85. await _azureStorage.Save<ChangeRecord>(changeRecord);
  86. }
  87. break;
  88. case "going":
  89. (List<string> tmdids, List<Students> students) = await TriggerStuActivity.GetStuList(client, vote.classes, vote.school);
  90. List<string> tmds = vote.tmdids.IsNotEmpty() ? vote.tmdids : new List<string>() ;
  91. if (tmdids.IsNotEmpty()) {
  92. tmds.AddRange(tmdids);
  93. }
  94. List<StuActivity> stuActivities = new List<StuActivity>();
  95. List<StuActivity> tmdActivities = 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. });
  115. });
  116. }
  117. if (students.IsNotEmpty())
  118. {
  119. students.ForEach(x => {
  120. stuActivities.Add(new StuActivity
  121. {
  122. pk = "Activity",
  123. id = vote.id,
  124. code = $"Activity-{vote.school}-{x.id}",
  125. type = "Vote",
  126. name = vote.name,
  127. startTime = vote.startTime,
  128. endTime = vote.endTime,
  129. scode = vote.code,
  130. scope = vote.scope,
  131. school = vote.school,
  132. creatorId = vote.creatorId,
  133. subjects = new List<string> { "" },
  134. blob=null
  135. });
  136. });
  137. }
  138. await TriggerStuActivity.SaveStuActivity(client, stuActivities, tmdActivities);
  139. //向学生或醍摩豆账号发起通知
  140. #region
  141. Notice notice = new Notice()
  142. {
  143. creation = vote.startTime,
  144. expire = vote.endTime,
  145. creatorId = vote.creatorId,
  146. stuids = students,
  147. tmdids = tmdids,
  148. type = "notice",//问卷参加参加通知
  149. priority = "normal",
  150. msgId=vote.id,
  151. school = vote.school,
  152. scope = vote.scope,
  153. //data = new { }.ToJsonString()
  154. body = new Body { sid = vote.id, scode = vote.code, spk = vote.pk, biztype = "vote-join" }
  155. };
  156. //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
  157. //messageBlob.ApplicationProperties.Add("name", "Notice");
  158. //await _serviceBus.GetServiceBusClient().SendMessageAsync("active-task", messageBlob);
  159. #endregion
  160. var messageVoteEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
  161. messageVoteEnd.ApplicationProperties.Add("name", "Vote");
  162. if (voteRecords.Count > 0)
  163. {
  164. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  165. await _serviceBus.GetServiceBusClient().cancelMessage("active-task", voteRecords[0].sequenceNumber);
  166. voteRecords[0].sequenceNumber = end;
  167. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  168. }
  169. else
  170. {
  171. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync("active-task", messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  172. ChangeRecord changeRecord = new ChangeRecord
  173. {
  174. RowKey = input.Id,
  175. PartitionKey = "going",
  176. sequenceNumber = end,
  177. msgId = messageVoteEnd.MessageId
  178. };
  179. await _azureStorage.Save<ChangeRecord>(changeRecord);
  180. }
  181. #if DEBUG
  182. await _dingDing.SendBotMsg($"投票活动{tdata.id}将于:{tdata.etime}完成并结算!", GroupNames.成都开发測試群組);
  183. #endif
  184. break;
  185. case "finish":
  186. #if DEBUG
  187. await _dingDing.SendBotMsg($"投票活动{tdata.id}开始结算{tdata.etime}!", GroupNames.成都开发測試群組);
  188. #endif
  189. //获取投票活动的所有投票记录
  190. var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Vote:Record:{vote.id}");
  191. //获取投票活动的选项及投票数
  192. var counts = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Vote:Count:{vote.id}");
  193. List<dynamic> countcds = new List<dynamic>();
  194. if (counts != null && counts.Length > 0)
  195. {
  196. foreach (var count in counts)
  197. {
  198. countcds.Add(new { code = count.Element.ToString(), count = (int)count.Score });
  199. }
  200. }
  201. List<Task<string>> tasks = new List<Task<string>>();
  202. List<VoteRecord> recordsBlob = new List<VoteRecord>();
  203. foreach (var rcd in records)
  204. {
  205. var value = rcd.Value.ToString().ToObject<VoteRecord>();
  206. recordsBlob.Add(value);
  207. }
  208. //分组每个人的
  209. var gp = recordsBlob.GroupBy(x => x.userid).Select(x => new { key = x.Key, list = x.ToList() });
  210. foreach (var g in gp)
  211. {
  212. tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, g.list.ToJsonString(), "vote", $"{vote.id}/urecord/{g.key}.json"));
  213. }
  214. //处理活动方的记录,
  215. string url = $"/vote/{vote.id}/record.json";
  216. tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, new { options = countcds, records = recordsBlob }.ToJsonString(), "vote", $"{vote.id}/record.json"));
  217. //处理投票者的记录
  218. if (string.IsNullOrEmpty(vote.recordUrl))
  219. {
  220. vote.recordUrl = url;
  221. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Vote>(vote, vote.id, new Azure.Cosmos.PartitionKey(vote.code));
  222. }
  223. else {
  224. //异动,且已经有结算记录则不必再继续。
  225. _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{vote.id}");
  226. _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{vote.id}");
  227. break;
  228. }
  229. await Task.WhenAll(tasks);
  230. //data.progress = "finish";
  231. //更新结束状态
  232. //if (vote.scope == "school")
  233. //{
  234. // await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  235. //}
  236. //else if (vote.scope == "private")
  237. //{
  238. // await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
  239. //}
  240. //_azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{vote.id}");
  241. //_azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{vote.id}");
  242. break;
  243. }
  244. }
  245. }
  246. }
  247. }