TriggerVote.cs 25 KB

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