TriggerVote.cs 19 KB

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