TriggerVote.cs 19 KB

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