TriggerArt.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. using Azure.Messaging.ServiceBus;
  2. using HTEXLib.COMM.Helpers;
  3. using Microsoft.Extensions.Configuration;
  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.Models;
  13. using TEAMModelOS.SDK;
  14. using Azure.Cosmos;
  15. using TEAMModelOS.SDK.Models.Cosmos.Common;
  16. using Azure.Core;
  17. using TEAMModelOS.SDK.Models.Service;
  18. using Microsoft.AspNetCore.Http;
  19. using OpenXmlPowerTools;
  20. using DocumentFormat.OpenXml.Office2010.Excel;
  21. namespace TEAMModelOS.FunctionV4.CosmosDB
  22. {
  23. public class TriggerArt
  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 PartitionKey(tdata.code));
  33. ActivityList data = input.ToObject<ActivityList>();
  34. //删除blob 相关资料
  35. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, tdata.school, new List<string> { $"art/{tdata.id}" });
  36. await ActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, data);
  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. return;
  52. }
  53. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  54. var adid = tdata.id;
  55. var adcode = "";
  56. string blobcntr = null;
  57. if (tdata.scope.Equals("school"))
  58. {
  59. adcode = $"Activity-{tdata.school}";
  60. blobcntr = tdata.school;
  61. }
  62. else
  63. {
  64. adcode = $"Activity-{tdata.creatorId}";
  65. blobcntr = tdata.creatorId;
  66. }
  67. ArtEvaluation art = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ArtEvaluation>(tdata.id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
  68. if (art != null)
  69. {
  70. string PartitionKey = string.Format("{0}{1}{2}", art.code, "-", art.progress);
  71. List<ChangeRecord> voteRecords = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id }, { "PartitionKey", PartitionKey } });
  72. switch (art.progress)
  73. {
  74. case "pending":
  75. var messageVote = new ServiceBusMessage(new { tdata.id, progress = "going", code = tdata.code }.ToJsonString());
  76. messageVote.ApplicationProperties.Add("name", "Art");
  77. if (voteRecords.Count > 0)
  78. {
  79. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime));
  80. try
  81. {
  82. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
  83. }
  84. catch (Exception)
  85. {
  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. break;
  103. case "going":
  104. if (art.classes.Count > 0)
  105. {
  106. List<string> classes = ExamService.getClasses(art.classes, art.stuLists);
  107. (List<RMember> tmdIds, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, art.school, null);
  108. var addStudentsCls = tmdIds.FindAll(x => x.type == 2);
  109. var addTmdidsCls = tmdIds.FindAll(x => x.type == 1);
  110. List<string> tmds = new List<string>();
  111. if (addTmdidsCls.IsNotEmpty())
  112. {
  113. tmds.AddRange(addTmdidsCls.Select(x => x.id).ToList());
  114. }
  115. List<StuActivity> stuActivities = new List<StuActivity>();
  116. List<StuActivity> tmdActivities = new List<StuActivity>();
  117. List<StuActivity> tchActivities = new List<StuActivity>();
  118. List<string> sub = new();
  119. if (art.subjects.Count > 0)
  120. {
  121. foreach (var course in art.subjects)
  122. {
  123. sub.Add(course.id);
  124. }
  125. }
  126. if (tmds.IsNotEmpty())
  127. {
  128. tmds.ForEach(x =>
  129. {
  130. HashSet<string> classIds = new HashSet<string>();
  131. classLists.ForEach(z =>
  132. {
  133. z.members.ForEach(y =>
  134. {
  135. if (y.id.Equals(x) && y.type == 1)
  136. {
  137. classIds.Add(z.id);
  138. }
  139. });
  140. });
  141. tmdActivities.Add(new StuActivity
  142. {
  143. pk = "Activity",
  144. id = art.id,
  145. code = $"Activity-{x}",
  146. type = "Art",
  147. name = art.name,
  148. startTime = art.startTime,
  149. endTime = art.endTime,
  150. scode = art.code,
  151. scope = art.scope,
  152. school = art.school,
  153. creatorId = art.creatorId,
  154. subjects = sub,
  155. blob = null,
  156. owner = art.owner,
  157. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  158. ext = new Dictionary<string, JsonElement>() { { "subjects", art.subjects.ToJsonString().ToObject<JsonElement>() } },
  159. taskStatus = -1,
  160. classIds = classIds.ToList()
  161. });
  162. });
  163. }
  164. if (addStudentsCls.IsNotEmpty())
  165. {
  166. addStudentsCls.ForEach(x =>
  167. {
  168. HashSet<string> classIds = new HashSet<string>();
  169. classLists.ForEach(z =>
  170. {
  171. z.members.ForEach(y =>
  172. {
  173. if (y.id.Equals(x.id) && y.code.Equals(art.school) && y.type == 2)
  174. {
  175. classIds.Add(z.id);
  176. }
  177. });
  178. });
  179. stuActivities.Add(new StuActivity
  180. {
  181. pk = "Activity",
  182. id = art.id,
  183. code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
  184. type = "Atr",
  185. name = art.name,
  186. startTime = art.startTime,
  187. endTime = art.endTime,
  188. scode = art.code,
  189. scope = art.scope,
  190. school = art.school,
  191. creatorId = art.creatorId,
  192. subjects = sub,
  193. blob = null,
  194. owner = art.owner,
  195. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  196. ext = new Dictionary<string, JsonElement>() { { "subjects", art.subjects.ToJsonString().ToObject<JsonElement>() } },
  197. taskStatus = -1,
  198. classIds = classIds.ToList()
  199. });
  200. });
  201. }
  202. await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, tchActivities);
  203. //await StatisticsService.SendServiceBus(list, _configuration, _serviceBus, client)
  204. }
  205. var messageVoteEnd = new ServiceBusMessage(new { tdata.id, progress = "finish", tdata.code }.ToJsonString());
  206. messageVoteEnd.ApplicationProperties.Add("name", "Art");
  207. if (voteRecords.Count > 0)
  208. {
  209. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  210. try
  211. {
  212. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
  213. }
  214. catch (Exception)
  215. {
  216. }
  217. voteRecords[0].sequenceNumber = end;
  218. await table.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  219. }
  220. else
  221. {
  222. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  223. ChangeRecord changeRecord = new()
  224. {
  225. RowKey = tdata.id,
  226. PartitionKey = PartitionKey,
  227. sequenceNumber = end,
  228. msgId = messageVoteEnd.MessageId
  229. };
  230. await table.Save<ChangeRecord>(changeRecord);
  231. }
  232. break;
  233. case "finish":
  234. //判定是否是区级创建的活动内容
  235. if (art.lost.Count == 0 && art.pass == 0)
  236. {
  237. if (art.owner.Equals("area") && string.IsNullOrEmpty(art.pId))
  238. {
  239. List<(string id, string code, List<Tasks> settings)> artSchools = new();
  240. string ql = $"select c.id,c.school,c.settings,c.classes from c where c.pk = 'Art' and c.pId = '{art.id}'";
  241. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: ql))
  242. {
  243. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  244. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  245. {
  246. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  247. while (accounts.MoveNext())
  248. {
  249. JsonElement account = accounts.Current;
  250. List<Tasks> settings = account.GetProperty("settings").ToObject<List<Tasks>>();
  251. artSchools.Add((account.GetProperty("id").GetString(), account.GetProperty("school").GetString(), settings));
  252. }
  253. }
  254. }
  255. foreach (var (id, code, settings) in artSchools)
  256. {
  257. List<(string eId, string sId)> ids = new();
  258. var examIds = settings.SelectMany(s => s.task).Where(a => a.type == 1).Select(z => new { z.acId, z.subject }).ToList();
  259. examIds.ForEach(x =>
  260. {
  261. ids.Add((x.acId, x.subject));
  262. });
  263. List<(string code, string sub, List<string> stu)> stuInfo = await getLostAsync(ids, client, code);
  264. List<string> stus = new();
  265. foreach (var lost in stuInfo)
  266. {
  267. if (stus.Count == 0)
  268. {
  269. stus = stus.Union(lost.stu).ToList();
  270. }
  271. else {
  272. stus = stus.Intersect(lost.stu).ToList();
  273. }
  274. LostStudent lostStudent = new()
  275. {
  276. code = lost.code,
  277. subject = lost.sub,
  278. stu = lost.stu.Count
  279. };
  280. art.lost.Add(lostStudent);
  281. }
  282. art.miss.Add(stus.Count);
  283. }
  284. art.pass = 1;
  285. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ArtEvaluation>(art, art.id, new PartitionKey(art.code));
  286. }
  287. else
  288. {
  289. //获取当前艺术评价相关评测ID目前暂时排除区级发布的评测信息
  290. List<(string eId, string sId)> ids = new();
  291. var examId = art.settings.SelectMany(x => x.task).Where(c => c.type == 1).Select(z => new { z.acId, z.subject }).ToList();
  292. examId.ForEach(x =>
  293. {
  294. ids.Add((x.acId, x.subject));
  295. });
  296. List<(string code, string sub, List<string> stu)> stuInfo = await getLostAsync(ids, client, art.school);
  297. List<string> stus = new();
  298. foreach (var (code, sub, stu) in stuInfo)
  299. {
  300. if (stus.Count == 0)
  301. {
  302. stus = stus.Union(stu).ToList();
  303. }
  304. else
  305. {
  306. stus = stus.Intersect(stu).ToList();
  307. }
  308. LostStudent lostStudent = new()
  309. {
  310. code = code,
  311. subject = sub,
  312. stu = stu.Count
  313. };
  314. art.lost.Add(lostStudent);
  315. }
  316. art.miss.Add(stus.Count);
  317. //art.miss = stus.Count;
  318. art.pass = 1;
  319. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ArtEvaluation>(art, art.id, new PartitionKey(art.code));
  320. }
  321. }
  322. List<StudentArtResult> studentArtResults = new();
  323. string sql = $"SELECT value c FROM c where c.pk='ArtResult' ";
  324. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student)
  325. .GetItemQueryIterator<StudentArtResult>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"ArtResult-{art.id}") }))
  326. {
  327. studentArtResults.Add(item);
  328. }
  329. List<Task<ItemResponse<StudentArtResult>>> tasks = new List<Task<ItemResponse<StudentArtResult>>>();
  330. foreach (var rs in studentArtResults)
  331. {
  332. if (rs.totalScore == 0)
  333. {
  334. rs.totalScore = Math.Round(rs.subjectScores.Where(m => m.score >= 0).Sum(z => z.score), 2);
  335. tasks.Add(client.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync(rs, rs.id, new PartitionKey(rs.code)));
  336. }
  337. }
  338. if (tasks.Count > 0) {
  339. await Task.WhenAll(tasks);
  340. }
  341. break;
  342. }
  343. }
  344. }
  345. catch (CosmosException e)
  346. {
  347. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}", GroupNames.醍摩豆服務運維群組);
  348. }
  349. catch (Exception ex)
  350. {
  351. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}艺术评价异常{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  352. }
  353. }
  354. public static async Task<List<(string code, string subject, List<string> stus)>> getLostAsync(List<(string eId, string sId)> examIds, CosmosClient client, string code)
  355. {
  356. List<(string code, string sub, List<string> stu)> stuInfo = new();
  357. if (examIds.Any())
  358. {
  359. string examSql = $"select c.id,c.school,c.lostStu from c where c.id in ({string.Join(",", examIds.Select(o => $"'{o.eId}'"))})";
  360. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: examSql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Exam-{code}") }))
  361. {
  362. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  363. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  364. {
  365. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  366. while (accounts.MoveNext())
  367. {
  368. JsonElement account = accounts.Current;
  369. List<string> lostStu = account.GetProperty("lostStu").ToObject<List<string>>();
  370. string id = account.GetProperty("id").GetString();
  371. string sub = examIds.Where(c => c.eId.Equals(id)).FirstOrDefault().sId;
  372. stuInfo.Add((account.GetProperty("school").GetString(), sub, lostStu));
  373. }
  374. }
  375. }
  376. }
  377. return stuInfo;
  378. }
  379. }
  380. }