TriggerVote.cs 24 KB

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