TriggerVote.cs 13 KB

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