TriggerVote.cs 22 KB

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