TriggerVote.cs 24 KB

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