TriggerVote.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. using TEAMModelOS.SDK.Models.Service;
  18. using HTEXLib.COMM.Helpers;
  19. using Microsoft.Extensions.Configuration;
  20. namespace TEAMModelFunction
  21. {
  22. public static class TriggerVote
  23. {
  24. public static async void Trigger( AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  25. CosmosClient client, Document input, TriggerData tdata, AzureRedisFactory _azureRedis, IConfiguration _configuration)
  26. {
  27. try {
  28. if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0)
  29. {
  30. //异动,且已经有结算记录则不必再继续。
  31. _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{tdata.id}");
  32. _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{tdata.id}");
  33. return;
  34. }
  35. var adid = tdata.id;
  36. var adcode = "";
  37. string blobcntr = null;
  38. if (tdata.scope .Equals("school"))
  39. {
  40. adcode = $"Activity-{tdata.school}";
  41. blobcntr = tdata.school;
  42. }
  43. else
  44. {
  45. adcode = $"Activity-{tdata.creatorId}";
  46. blobcntr = tdata.creatorId;
  47. }
  48. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动【{tdata.name}-{tdata.id}-ttl={tdata.ttl}】正在操作", GroupNames.成都开发測試群組);
  49. Vote vote = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Vote>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
  50. if (vote != null)
  51. {
  52. string PartitionKey = string.Format("{0}{1}{2}", vote.code, "-", vote.progress);
  53. List<ChangeRecord> voteRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", PartitionKey } });
  54. switch (vote.progress)
  55. {
  56. case "pending":
  57. var messageVote = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
  58. messageVote.ApplicationProperties.Add("name", "Vote");
  59. if (voteRecords.Count > 0)
  60. {
  61. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
  62. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
  63. voteRecords[0].sequenceNumber = start;
  64. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  65. }
  66. else
  67. {
  68. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
  69. ChangeRecord changeRecord = new ChangeRecord
  70. {
  71. RowKey = input.Id,
  72. PartitionKey = PartitionKey,
  73. sequenceNumber = start,
  74. msgId = messageVote.MessageId
  75. };
  76. await _azureStorage.Save<ChangeRecord>(changeRecord);
  77. }
  78. break;
  79. case "going":
  80. List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
  81. if (vote.groupLists.Count > 0)
  82. {
  83. var group = vote.groupLists;
  84. foreach (var keys in group)
  85. {
  86. foreach (KeyValuePair<string, List<string>> pp in keys)
  87. {
  88. ps.Add((pp.Key, pp.Value));
  89. }
  90. }
  91. }
  92. List<string> classes = ExamService.getClasses(vote.classes, vote.stuLists);
  93. (List<RMember> tmdIds, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(client, _dingDing, classes, vote.school,ps);
  94. var addStudentsCls = tmdIds.FindAll(x => x.type == 2);
  95. var addTmdidsCls = tmdIds.FindAll(x => x.type == 1);
  96. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动" +
  97. // $"{tmdids.ToJsonString()}\n" +
  98. // $"{students.ToJsonString()}\n" +
  99. // $"{classLists.ToJsonString()}\n" +
  100. // $"{classes.ToJsonString()}\n", GroupNames.成都开发測試群組);
  101. List<string> tmds = new List<string>();
  102. if (addTmdidsCls.IsNotEmpty())
  103. {
  104. tmds.AddRange(addTmdidsCls.Select(x => x.id).ToList());
  105. }
  106. List<StuActivity> stuActivities = new List<StuActivity>();
  107. List<StuActivity> tmdActivities = new List<StuActivity>();
  108. List<StuActivity> tchActivities = new List<StuActivity>();
  109. if (tmds.IsNotEmpty())
  110. {
  111. tmds.ForEach(x => {
  112. tmdActivities.Add(new StuActivity
  113. {
  114. pk = "Activity",
  115. id = vote.id,
  116. code = $"Activity-{x}",
  117. type = "Vote",
  118. name = vote.name,
  119. startTime = vote.startTime,
  120. endTime = vote.endTime,
  121. scode = vote.code,
  122. scope = vote.scope,
  123. school = vote.school,
  124. creatorId = vote.creatorId,
  125. subjects = new List<string> { "" },
  126. blob = null,
  127. owner = vote.owner,
  128. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  129. taskStatus = -1,
  130. classIds = classes
  131. });
  132. });
  133. }
  134. if (addStudentsCls.IsNotEmpty())
  135. {
  136. addStudentsCls.ForEach(x => {
  137. stuActivities.Add(new StuActivity
  138. {
  139. pk = "Activity",
  140. id = vote.id,
  141. code = $"Activity-{x.code.Replace("Base-","")}-{x.id}",
  142. type = "Vote",
  143. name = vote.name,
  144. startTime = vote.startTime,
  145. endTime = vote.endTime,
  146. scode = vote.code,
  147. scope = vote.scope,
  148. school = vote.school,
  149. creatorId = vote.creatorId,
  150. subjects = new List<string> { "" },
  151. blob = null,
  152. owner = vote.owner,
  153. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  154. taskStatus = -1,
  155. classIds = classes
  156. });
  157. });
  158. }
  159. (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetStutmdidListids(client, _dingDing, vote.tchLists, vote.school,ps);
  160. (string standard, List<string> tmdids, string school, List<string> update, int statistics) list = (null, null, null, new List<string> { StatisticsService.TeacherVote }, 0);
  161. if (tchList.IsNotEmpty())
  162. {
  163. list.tmdids = tchList.Select(x => x.id).ToList();
  164. School school = null;
  165. if (!string.IsNullOrEmpty(vote.school))
  166. {
  167. school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(vote.school, new Azure.Cosmos.PartitionKey("Base"));
  168. list.school = school.id;
  169. list.standard = school.standard;
  170. }
  171. tchList.ForEach(x => {
  172. tchActivities.Add(new StuActivity
  173. {
  174. pk = "Activity",
  175. id = vote.id,
  176. code = $"Activity-{x.id}",
  177. type = "Vote",
  178. name = vote.name,
  179. startTime = vote.startTime,
  180. endTime = vote.endTime,
  181. scode = vote.code,
  182. scope = vote.scope,
  183. school = vote.school,
  184. creatorId = vote.creatorId,
  185. subjects = new List<string> { "" },
  186. blob = null,
  187. owner = vote.owner,
  188. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  189. taskStatus = -1,
  190. classIds = classes
  191. });
  192. });
  193. }
  194. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动,:教研组活动:" +
  195. // $"{tchActivities.ToJsonString()}\n", GroupNames.成都开发測試群組);
  196. await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, tchActivities);
  197. await StatisticsService.SendServiceBus(list, _configuration, _serviceBus);
  198. //向学生或醍摩豆账号发起通知
  199. #region
  200. //Notice notice = new Notice()
  201. //{
  202. // creation = vote.startTime,
  203. // expire = vote.endTime,
  204. // creatorId = vote.creatorId,
  205. // stuids = students,
  206. // tmdids = tmdids,
  207. // type = "notice",//问卷参加参加通知
  208. // priority = "normal",
  209. // msgId=vote.id,
  210. // school = vote.school,
  211. // scope = vote.scope,
  212. // //data = new { }.ToJsonString()
  213. // body = new Body { sid = vote.id, scode = vote.code, spk = vote.pk, biztype = "vote-join" }
  214. //};
  215. //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
  216. //messageBlob.ApplicationProperties.Add("name", "Notice");
  217. //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:NoticeTask"), messageBlob);
  218. #endregion
  219. var messageVoteEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
  220. messageVoteEnd.ApplicationProperties.Add("name", "Vote");
  221. if (voteRecords.Count > 0)
  222. {
  223. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  224. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
  225. voteRecords[0].sequenceNumber = end;
  226. await _azureStorage.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  227. }
  228. else
  229. {
  230. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
  231. ChangeRecord changeRecord = new ChangeRecord
  232. {
  233. RowKey = input.Id,
  234. PartitionKey = PartitionKey,
  235. sequenceNumber = end,
  236. msgId = messageVoteEnd.MessageId
  237. };
  238. await _azureStorage.Save<ChangeRecord>(changeRecord);
  239. }
  240. #if DEBUG
  241. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动{tdata.id}将于:{tdata.etime}完成并结算!", GroupNames.成都开发測試群組);
  242. #endif
  243. break;
  244. case "finish":
  245. #if DEBUG
  246. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动{tdata.id}开始结算{tdata.etime}!", GroupNames.成都开发測試群組);
  247. #endif
  248. //获取投票活动的所有投票记录
  249. var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Vote:Record:{vote.id}");
  250. //获取投票活动的选项及投票数
  251. var counts = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Vote:Count:{vote.id}");
  252. List<dynamic> countcds = new List<dynamic>();
  253. if (counts != null && counts.Length > 0)
  254. {
  255. foreach (var count in counts)
  256. {
  257. countcds.Add(new { code = count.Element.ToString(), count = (int)count.Score });
  258. }
  259. }
  260. List<Task<string>> tasks = new List<Task<string>>();
  261. List<VoteRecord> recordsBlob = new List<VoteRecord>();
  262. foreach (var rcd in records)
  263. {
  264. var value = rcd.Value.ToString().ToObject<VoteRecord>();
  265. recordsBlob.Add(value);
  266. }
  267. //分组每个人的
  268. var gp = recordsBlob.GroupBy(x => x.userid).Select(x => new { key = x.Key, list = x.ToList() });
  269. foreach (var g in gp)
  270. {
  271. tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, g.list.ToJsonString(), "vote", $"{vote.id}/urecord/{g.key}.json"));
  272. }
  273. //处理活动方的记录,
  274. string url = $"/vote/{vote.id}/record.json";
  275. tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, new { options = countcds, records = recordsBlob }.ToJsonString(), "vote", $"{vote.id}/record.json"));
  276. //处理投票者的记录
  277. if (string.IsNullOrEmpty(vote.recordUrl))
  278. {
  279. vote.recordUrl = url;
  280. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Vote>(vote, vote.id, new Azure.Cosmos.PartitionKey(vote.code));
  281. }
  282. else
  283. {
  284. //异动,且已经有结算记录则不必再继续。
  285. _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Record:{vote.id}");
  286. _azureRedis.GetRedisClient(8).KeyDelete($"Vote:Count:{vote.id}");
  287. break;
  288. }
  289. await Task.WhenAll(tasks);
  290. break;
  291. }
  292. }
  293. } catch (Exception ex) {
  294. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}投票活动异常{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  295. }
  296. }
  297. }
  298. }