TriggerVote.cs 21 KB

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