TriggerVote.cs 24 KB

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