TriggerVote.cs 21 KB

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