TriggerArt.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. using DocumentFormat.OpenXml.Office2016.Excel;
  22. using static TEAMModelOS.SDK.Models.Cosmos.Student.StudentAnalysis;
  23. using HTEXLib.Helpers.ShapeHelpers;
  24. using DocumentFormat.OpenXml.Spreadsheet;
  25. namespace TEAMModelOS.FunctionV4.CosmosDB
  26. {
  27. public class TriggerArt
  28. {
  29. public static async Task Trigger(CoreAPIHttpService _coreAPIHttpService, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  30. CosmosClient client, JsonElement input, TriggerData tdata, AzureRedisFactory _azureRedis, IConfiguration _configuration, HttpTrigger _httpTrigger)
  31. {
  32. try
  33. {
  34. if ((tdata.status != null && tdata.status.Value == 404))
  35. {
  36. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(tdata.id, new PartitionKey(tdata.code));
  37. ActivityList data = input.ToObject<ActivityList>();
  38. //删除blob 相关资料
  39. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, tdata.school, new List<string> { $"art/{tdata.id}" });
  40. await ActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, data);
  41. var table_cancel = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  42. List<ChangeRecord> records = await table_cancel.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id } });
  43. foreach (var record in records)
  44. {
  45. try
  46. {
  47. await table_cancel.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  48. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  49. }
  50. catch (Exception)
  51. {
  52. continue;
  53. }
  54. }
  55. return;
  56. }
  57. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  58. var adid = tdata.id;
  59. var adcode = "";
  60. string blobcntr = null;
  61. if (tdata.scope.Equals("school"))
  62. {
  63. adcode = $"Activity-{tdata.school}";
  64. blobcntr = tdata.school;
  65. }
  66. else
  67. {
  68. adcode = $"Activity-{tdata.creatorId}";
  69. blobcntr = tdata.creatorId;
  70. }
  71. ArtEvaluation art = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ArtEvaluation>(tdata.id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
  72. if (art != null)
  73. {
  74. string PartitionKey = string.Format("{0}{1}{2}", art.code, "-", art.progress);
  75. List<ChangeRecord> voteRecords = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id }, { "PartitionKey", PartitionKey } });
  76. switch (art.progress)
  77. {
  78. case "pending":
  79. var messageVote = new ServiceBusMessage(new { tdata.id, progress = "going", code = tdata.code }.ToJsonString());
  80. messageVote.ApplicationProperties.Add("name", "Art");
  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. {
  86. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
  87. }
  88. catch (Exception)
  89. {
  90. }
  91. voteRecords[0].sequenceNumber = start;
  92. await table.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  93. }
  94. else
  95. {
  96. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime));
  97. ChangeRecord changeRecord = new ChangeRecord
  98. {
  99. RowKey = tdata.id,
  100. PartitionKey = PartitionKey,
  101. sequenceNumber = start,
  102. msgId = messageVote.MessageId
  103. };
  104. await table.Save<ChangeRecord>(changeRecord);
  105. }
  106. break;
  107. case "going":
  108. if (art.classes.Count > 0)
  109. {
  110. List<string> classes = ExamService.getClasses(art.classes, art.stuLists);
  111. (List<RMember> tmdIds, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, art.school, null);
  112. var addStudentsCls = tmdIds.FindAll(x => x.type == 2);
  113. var addTmdidsCls = tmdIds.FindAll(x => x.type == 1);
  114. List<string> tmds = new List<string>();
  115. if (addTmdidsCls.IsNotEmpty())
  116. {
  117. tmds.AddRange(addTmdidsCls.Select(x => x.id).ToList());
  118. }
  119. List<StuActivity> stuActivities = new List<StuActivity>();
  120. List<StuActivity> tmdActivities = new List<StuActivity>();
  121. List<StuActivity> tchActivities = new List<StuActivity>();
  122. List<string> sub = new();
  123. if (art.subjects.Count > 0)
  124. {
  125. foreach (var course in art.subjects)
  126. {
  127. sub.Add(course.id);
  128. }
  129. }
  130. if (tmds.IsNotEmpty())
  131. {
  132. tmds.ForEach(x =>
  133. {
  134. HashSet<string> classIds = new HashSet<string>();
  135. classLists.ForEach(z =>
  136. {
  137. z.members.ForEach(y =>
  138. {
  139. if (y.id.Equals(x) && y.type == 1)
  140. {
  141. classIds.Add(z.id);
  142. }
  143. });
  144. });
  145. tmdActivities.Add(new StuActivity
  146. {
  147. pk = "Activity",
  148. id = art.id,
  149. code = $"Activity-{x}",
  150. type = "Art",
  151. name = art.name,
  152. startTime = art.startTime,
  153. endTime = art.endTime,
  154. scode = art.code,
  155. scope = art.scope,
  156. school = art.school,
  157. creatorId = art.creatorId,
  158. subjects = sub,
  159. blob = null,
  160. owner = art.owner,
  161. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  162. ext = new Dictionary<string, JsonElement>() { { "subjects", art.subjects.ToJsonString().ToObject<JsonElement>() } },
  163. taskStatus = -1,
  164. classIds = classIds.ToList()
  165. });
  166. });
  167. }
  168. if (addStudentsCls.IsNotEmpty())
  169. {
  170. addStudentsCls.ForEach(x =>
  171. {
  172. HashSet<string> classIds = new HashSet<string>();
  173. classLists.ForEach(z =>
  174. {
  175. z.members.ForEach(y =>
  176. {
  177. if (y.id.Equals(x.id) && y.code.Equals(art.school) && y.type == 2)
  178. {
  179. classIds.Add(z.id);
  180. }
  181. });
  182. });
  183. stuActivities.Add(new StuActivity
  184. {
  185. pk = "Activity",
  186. id = art.id,
  187. code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
  188. type = "Atr",
  189. name = art.name,
  190. startTime = art.startTime,
  191. endTime = art.endTime,
  192. scode = art.code,
  193. scope = art.scope,
  194. school = art.school,
  195. creatorId = art.creatorId,
  196. subjects = sub,
  197. blob = null,
  198. owner = art.owner,
  199. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  200. ext = new Dictionary<string, JsonElement>() { { "subjects", art.subjects.ToJsonString().ToObject<JsonElement>() } },
  201. taskStatus = -1,
  202. classIds = classIds.ToList()
  203. });
  204. });
  205. }
  206. await ActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, tchActivities);
  207. //await StatisticsService.SendServiceBus(list, _configuration, _serviceBus, client)
  208. }
  209. var messageVoteEnd = new ServiceBusMessage(new { tdata.id, progress = "finish", tdata.code }.ToJsonString());
  210. messageVoteEnd.ApplicationProperties.Add("name", "Art");
  211. if (voteRecords.Count > 0)
  212. {
  213. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  214. try
  215. {
  216. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
  217. }
  218. catch (Exception)
  219. {
  220. }
  221. voteRecords[0].sequenceNumber = end;
  222. await table.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  223. }
  224. else
  225. {
  226. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  227. ChangeRecord changeRecord = new()
  228. {
  229. RowKey = tdata.id,
  230. PartitionKey = PartitionKey,
  231. sequenceNumber = end,
  232. msgId = messageVoteEnd.MessageId
  233. };
  234. await table.Save<ChangeRecord>(changeRecord);
  235. }
  236. break;
  237. case "finish":
  238. //判定是否是区级创建的活动内容
  239. /* if (art.lost.Count == 0 && art.pass == 0)
  240. {
  241. if (art.owner.Equals("area") && string.IsNullOrEmpty(art.pId))
  242. {
  243. *//* List<(string id, string code, List<Tasks> settings)> artSchools = new();
  244. string ql = $"select c.id,c.school,c.settings,c.classes from c where c.pk = 'Art' and c.pId = '{art.id}'";
  245. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: ql))
  246. {
  247. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  248. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  249. {
  250. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  251. while (accounts.MoveNext())
  252. {
  253. JsonElement account = accounts.Current;
  254. List<Tasks> settings = account.GetProperty("settings").ToObject<List<Tasks>>();
  255. artSchools.Add((account.GetProperty("id").GetString(), account.GetProperty("school").GetString(), settings));
  256. }
  257. }
  258. }
  259. foreach (var (id, code, settings) in artSchools)
  260. {
  261. List<(string eId, string sId)> ids = new();
  262. var examIds = settings.SelectMany(s => s.task).Where(a => a.type == 1).Select(z => new { z.acId, z.subject }).ToList();
  263. examIds.ForEach(x =>
  264. {
  265. ids.Add((x.acId, x.subject));
  266. });
  267. List<(string code, string sub, List<string> stu)> stuInfo = await getLostAsync(ids, client, code);
  268. List<string> stus = new();
  269. foreach (var lost in stuInfo)
  270. {
  271. if (stus.Count == 0)
  272. {
  273. stus = stus.Union(lost.stu).ToList();
  274. }
  275. else {
  276. stus = stus.Intersect(lost.stu).ToList();
  277. }
  278. LostStudent lostStudent = new()
  279. {
  280. code = lost.code,
  281. subject = lost.sub,
  282. stu = lost.stu.Count
  283. };
  284. art.lost.Add(lostStudent);
  285. }
  286. art.miss.Add(stus.Count);
  287. }
  288. art.pass = 1;
  289. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ArtEvaluation>(art, art.id, new PartitionKey(art.code));*//*
  290. }
  291. else
  292. {
  293. //获取当前艺术评价相关评测ID目前暂时排除区级发布的评测信息
  294. *//*List<(string eId, string sId)> ids = new();
  295. var examId = art.settings.SelectMany(x => x.task).Where(c => c.type == 1).Select(z => new { z.acId, z.subject }).ToList();
  296. examId.ForEach(x =>
  297. {
  298. ids.Add((x.acId, x.subject));
  299. });
  300. List<(string code, string sub, List<string> stu)> stuInfo = await getLostAsync(ids, client, art.school);
  301. List<string> stus = new();
  302. foreach (var (code, sub, stu) in stuInfo)
  303. {
  304. if (stus.Count == 0)
  305. {
  306. stus = stus.Union(stu).ToList();
  307. }
  308. else
  309. {
  310. stus = stus.Intersect(stu).ToList();
  311. }
  312. LostStudent lostStudent = new()
  313. {
  314. code = code,
  315. subject = sub,
  316. stu = stu.Count
  317. };
  318. art.lost.Add(lostStudent);
  319. }
  320. art.miss.Add(stus.Count);
  321. //art.miss = stus.Count;
  322. art.pass = 1;
  323. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ArtEvaluation>(art, art.id, new PartitionKey(art.code));*//*
  324. }
  325. }*/
  326. List<StudentArtResult> studentArtResults = new();
  327. string sql = $"SELECT value c FROM c where c.pk='ArtResult' ";
  328. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student)
  329. .GetItemQueryIterator<StudentArtResult>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"ArtResult-{art.id}") }))
  330. {
  331. studentArtResults.Add(item);
  332. }
  333. //根据学校编码去获取区级ID
  334. School scInfo = new();
  335. //School scInfo = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{art.school}", partitionKey: new Azure.Cosmos.PartitionKey("Base"));
  336. var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{art.school}", partitionKey: new Azure.Cosmos.PartitionKey("Base"));
  337. if (response.Status == 200)
  338. {
  339. using var cJson = await JsonDocument.ParseAsync(response.ContentStream);
  340. scInfo = cJson.ToObject<School>();
  341. }
  342. ArtSetting setting = new();
  343. try
  344. {
  345. var artResponse = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{scInfo.areaId}", partitionKey: new Azure.Cosmos.PartitionKey("ArtSetting"));
  346. if (response.Status == 200)
  347. {
  348. using var json = await JsonDocument.ParseAsync(artResponse.ContentStream);
  349. setting = json.ToObject<ArtSetting>();
  350. }
  351. }
  352. catch (Exception e)
  353. {
  354. }
  355. List<Task<ItemResponse<StudentArtResult>>> tasks = new List<Task<ItemResponse<StudentArtResult>>>();
  356. //新增数据推送 obj => Portrait
  357. Portrait portrait = new()
  358. {
  359. schoolCode = art.school,
  360. periodId = art.period.id,
  361. subjectId = "subject_art"
  362. };
  363. var period = scInfo.period.Where(x => x.id.Equals(art.period.id)).FirstOrDefault();
  364. //获取学期信息
  365. var (currSemester, studyYear, date, nextSemester) = SchoolService.GetSemester(period, art.startTime);
  366. //总分的占比情况
  367. foreach (var rs in studentArtResults)
  368. {
  369. foreach (var res in rs.results) {
  370. if (res.quotaId.Equals("quota_21") && res.score > -1 && res.score < 95) {
  371. /*res.score *= 1.5;
  372. if (res.score >= 95) {
  373. res.score = new Random().Next(90, 99);
  374. }*/
  375. res.score = Math.Round(res.score);
  376. }
  377. }
  378. //if (rs.totalScore == 0)
  379. //{
  380. foreach (var sc in rs.subjectScores)
  381. {
  382. //if (sc.score == 0)
  383. //{
  384. /* var subjectMore = rs.results.GroupBy(x => x.subjectId).Select(c => new { subject = c.Key, list = c.ToList().Select(m => new { m.quotaId,m.score}) });
  385. var totalScore = subjectMore.Select(x => new {
  386. x.subject,
  387. quotaScroe = x.list.Select(c => new {
  388. c.quotaId,
  389. c.score
  390. }),
  391. });*/
  392. var quotaPercent = setting.quotas.Select(x => new
  393. {
  394. x.id,
  395. x.percent,
  396. score = x.children.Select(c => new
  397. {
  398. real = rs.results.Where(r => r.quotaId.Equals(c.id) && r.subjectId.Equals(sc.subjectId) && r.score > -1).FirstOrDefault()?.score * c.percent * 0.01,
  399. score = c.children.Select(s => new
  400. {
  401. real = rs.results.Where(r => r.quotaId.Equals(s.id) && r.subjectId.Equals(sc.subjectId) && r.score > -1).FirstOrDefault()?.score * s.percent * 0.01
  402. }).Sum(n => n.real) * c.percent * 0.01
  403. }).Sum(n => n.real + n.score) * x.percent * 0.01
  404. });
  405. double realScore = Math.Round((double)quotaPercent.Sum(c => c.score),2);
  406. sc.score = realScore;
  407. //}
  408. }
  409. rs.totalScore = Math.Round(rs.subjectScores.Where(m => m.score >= 0).Sum(z => z.score),2);
  410. tasks.Add(client.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync(rs, rs.id, new PartitionKey(rs.code)));
  411. PortraitStudent student = new()
  412. {
  413. studentId = rs.studentId,
  414. name = rs.studentName,
  415. classId = rs.classIds[0]
  416. };
  417. SemesterData semesterData = new()
  418. {
  419. examName = art.name,
  420. examId = art.id,
  421. examDate = art.startTime,
  422. examType = "",
  423. year = studyYear,
  424. semesterId = currSemester.id,
  425. totalScore = 200,
  426. sumScore = rs.totalScore,
  427. excellenceRate = 0,
  428. passRate = 0,
  429. };
  430. int index = 0;
  431. foreach (var sj in art.subjects)
  432. {
  433. ItemScore item = new()
  434. {
  435. name = sj.name,
  436. score = rs.subjectScores.Where(x => x.subjectId.Equals(sj.id)).FirstOrDefault().score,
  437. time = art.startTime,
  438. totalScore = 100,
  439. type = sj.id
  440. };
  441. index++;
  442. semesterData.itemScore.Add(item);
  443. }
  444. student.semesterData.Add(semesterData);
  445. portrait.students.Add(student);
  446. //}
  447. }
  448. if (tasks.Count > 0)
  449. {
  450. await Task.WhenAll(tasks);
  451. }
  452. //获取学生信息
  453. //(List<RMember> rmembers, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, art.classes, art.school);
  454. /* foreach (var member in studentArtResults)
  455. {
  456. }*/
  457. string location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  458. var responseData = await _httpTrigger.RequestHttpTrigger(portrait.ToJson(), location, "upsert-student-portrait");
  459. break;
  460. }
  461. }
  462. }
  463. catch (CosmosException e)
  464. {
  465. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.Status}", GroupNames.醍摩豆服務運維群組);
  466. }
  467. catch (Exception ex)
  468. {
  469. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}艺术评价异常{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  470. }
  471. }
  472. }
  473. }