TriggerVote.cs 14 KB

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