TriggerVote.cs 25 KB

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