TriggerArt.cs 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. using Azure.Messaging.ServiceBus;
  2. using Microsoft.Extensions.Configuration;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.Json;
  8. using System.Threading.Tasks;
  9. using TEAMModelOS.SDK.DI;
  10. using TEAMModelOS.SDK.Extension;
  11. using TEAMModelOS.SDK.Models;
  12. using TEAMModelOS.SDK;
  13. using Microsoft.Azure.Cosmos;
  14. using TEAMModelOS.SDK.Models.Cosmos.Common;
  15. using TEAMModelOS.Function;
  16. namespace TEAMModelOS.CosmosDBTriggers
  17. {
  18. public class TriggerArt
  19. {
  20. public static async Task Trigger(CoreAPIHttpService _coreAPIHttpService, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  21. CosmosClient client, JsonElement input, TriggerData tdata, AzureRedisFactory _azureRedis, IConfiguration _configuration, HttpTrigger _httpTrigger)
  22. {
  23. try
  24. {
  25. if ((tdata.status != null && tdata.status.Value == 404))
  26. {
  27. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(tdata.id, new PartitionKey(tdata.code));
  28. ActivityList data = input.ToObject<ActivityList>();
  29. //删除blob 相关资料
  30. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, tdata.school, new List<string> { $"art/{tdata.id}" });
  31. // await IESActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, data);
  32. var table_cancel = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  33. List<ChangeRecord> records = await table_cancel.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id } });
  34. foreach (var record in records)
  35. {
  36. try
  37. {
  38. await table_cancel.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  39. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  40. }
  41. catch (Exception)
  42. {
  43. continue;
  44. }
  45. }
  46. return;
  47. }
  48. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  49. var adid = tdata.id;
  50. var adcode = "";
  51. string blobcntr = null;
  52. if (tdata.scope.Equals("school"))
  53. {
  54. adcode = $"Activity-{tdata.school}";
  55. blobcntr = tdata.school;
  56. }
  57. else
  58. {
  59. adcode = $"Activity-{tdata.creatorId}";
  60. blobcntr = tdata.creatorId;
  61. }
  62. ArtEvaluation art = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ArtEvaluation>(tdata.id, new PartitionKey($"{tdata.code}"));
  63. if (art != null)
  64. {
  65. string PartitionKey = string.Format("{0}{1}{2}", art.code, "-", art.progress);
  66. List<ChangeRecord> voteRecords = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", tdata.id }, { "PartitionKey", PartitionKey } });
  67. switch (art.progress)
  68. {
  69. case "pending":
  70. var messageVote = new ServiceBusMessage(new { tdata.id, progress = "going", code = tdata.code }.ToJsonString());
  71. messageVote.ApplicationProperties.Add("name", "Art");
  72. if (voteRecords.Count > 0)
  73. {
  74. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime));
  75. try
  76. {
  77. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
  78. }
  79. catch (Exception)
  80. {
  81. }
  82. voteRecords[0].sequenceNumber = start;
  83. await table.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  84. }
  85. else
  86. {
  87. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVote, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime));
  88. ChangeRecord changeRecord = new ChangeRecord
  89. {
  90. RowKey = tdata.id,
  91. PartitionKey = PartitionKey,
  92. sequenceNumber = start,
  93. msgId = messageVote.MessageId
  94. };
  95. await table.Save<ChangeRecord>(changeRecord);
  96. }
  97. break;
  98. case "going":
  99. /*
  100. if (art.classes.Count > 0)
  101. {
  102. List<string> classes = ExamService.getClasses(art.classes, art.stuLists);
  103. (List<RMember> tmdIds, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, art.school, null);
  104. var addStudentsCls = tmdIds.FindAll(x => x.type == 2);
  105. var addTmdidsCls = tmdIds.FindAll(x => x.type == 1);
  106. List<string> tmds = new List<string>();
  107. if (addTmdidsCls.IsNotEmpty())
  108. {
  109. tmds.AddRange(addTmdidsCls.Select(x => x.id).ToList());
  110. }
  111. List<StuActivity> stuActivities = new List<StuActivity>();
  112. List<StuActivity> tmdActivities = new List<StuActivity>();
  113. List<StuActivity> tchActivities = new List<StuActivity>();
  114. List<string> sub = new();
  115. if (art.subjects.Count > 0)
  116. {
  117. foreach (var course in art.subjects)
  118. {
  119. sub.Add(course.id);
  120. }
  121. }
  122. if (tmds.IsNotEmpty())
  123. {
  124. tmds.ForEach(x =>
  125. {
  126. HashSet<string> classIds = new HashSet<string>();
  127. classLists.ForEach(z =>
  128. {
  129. z.members.ForEach(y =>
  130. {
  131. if (y.id.Equals(x) && y.type == 1)
  132. {
  133. classIds.Add(z.id);
  134. }
  135. });
  136. });
  137. tmdActivities.Add(new StuActivity
  138. {
  139. pk = "Activity",
  140. id = art.id,
  141. code = $"Activity-{x}",
  142. type = "Art",
  143. name = art.name,
  144. startTime = art.startTime,
  145. endTime = art.endTime,
  146. scode = art.code,
  147. scope = art.scope,
  148. school = art.school,
  149. creatorId = art.creatorId,
  150. subjects = sub,
  151. blob = null,
  152. owner = art.owner,
  153. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  154. ext = new Dictionary<string, JsonElement>() { { "subjects", art.subjects.ToJsonString().ToObject<JsonElement>() } },
  155. taskStatus = -1,
  156. classIds = classIds.ToList()
  157. });
  158. });
  159. }
  160. if (addStudentsCls.IsNotEmpty())
  161. {
  162. addStudentsCls.ForEach(x =>
  163. {
  164. HashSet<string> classIds = new HashSet<string>();
  165. classLists.ForEach(z =>
  166. {
  167. z.members.ForEach(y =>
  168. {
  169. if (y.id.Equals(x.id) && y.code.Equals(art.school) && y.type == 2)
  170. {
  171. classIds.Add(z.id);
  172. }
  173. });
  174. });
  175. stuActivities.Add(new StuActivity
  176. {
  177. pk = "Activity",
  178. id = art.id,
  179. code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
  180. type = "Art",
  181. name = art.name,
  182. startTime = art.startTime,
  183. endTime = art.endTime,
  184. scode = art.code,
  185. scope = art.scope,
  186. school = art.school,
  187. creatorId = art.creatorId,
  188. subjects = sub,
  189. blob = null,
  190. owner = art.owner,
  191. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  192. ext = new Dictionary<string, JsonElement>() { { "subjects", art.subjects.ToJsonString().ToObject<JsonElement>() } },
  193. taskStatus = -1,
  194. classIds = classIds.ToList()
  195. });
  196. });
  197. }
  198. await IESActivityService.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities, tchActivities);
  199. }*/
  200. try
  201. {
  202. var messageVoteEnd = new ServiceBusMessage(new { tdata.id, progress = "finish", tdata.code }.ToJsonString());
  203. messageVoteEnd.ApplicationProperties.Add("name", "Art");
  204. if (voteRecords.Count > 0)
  205. {
  206. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  207. try
  208. {
  209. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), voteRecords[0].sequenceNumber);
  210. }
  211. catch (Exception)
  212. {
  213. }
  214. voteRecords[0].sequenceNumber = end;
  215. await table.SaveOrUpdate<ChangeRecord>(voteRecords[0]);
  216. }
  217. else
  218. {
  219. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageVoteEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime));
  220. ChangeRecord changeRecord = new()
  221. {
  222. RowKey = tdata.id,
  223. PartitionKey = PartitionKey,
  224. sequenceNumber = end,
  225. msgId = messageVoteEnd.MessageId
  226. };
  227. await table.Save<ChangeRecord>(changeRecord);
  228. }
  229. }
  230. catch (Exception e)
  231. {
  232. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-艺术评测going{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  233. }
  234. finally {
  235. string pkey = string.Format("{0}{1}{2}", art.code, "-", "pending");
  236. await table.DeleteSingle<ChangeRecord>(pkey, tdata.id);
  237. }
  238. break;
  239. case "finish":
  240. //判定是否是区级创建的活动内容
  241. /* if (art.lost.Count == 0 && art.pass == 0)
  242. {
  243. if (art.owner.Equals("area") && string.IsNullOrEmpty(art.pId))
  244. {
  245. *//* List<(string id, string code, List<Tasks> settings)> artSchools = new();
  246. string ql = $"select c.id,c.school,c.settings,c.classes from c where c.pk = 'Art' and c.pId = '{art.id}'";
  247. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIteratorSql(queryText: ql))
  248. {
  249. using var json = await JsonDocument.ParseAsync(item.Content);
  250. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  251. {
  252. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  253. while (accounts.MoveNext())
  254. {
  255. JsonElement account = accounts.Current;
  256. List<Tasks> settings = account.GetProperty("settings").ToObject<List<Tasks>>();
  257. artSchools.Add((account.GetProperty("id").GetString(), account.GetProperty("school").GetString(), settings));
  258. }
  259. }
  260. }
  261. foreach (var (id, code, settings) in artSchools)
  262. {
  263. List<(string eId, string sId)> ids = new();
  264. var examIds = settings.SelectMany(s => s.task).Where(a => a.type == 1).Select(z => new { z.acId, z.subject }).ToList();
  265. examIds.ForEach(x =>
  266. {
  267. ids.Add((x.acId, x.subject));
  268. });
  269. List<(string code, string sub, List<string> stu)> stuInfo = await getLostAsync(ids, client, code);
  270. List<string> stus = new();
  271. foreach (var lost in stuInfo)
  272. {
  273. if (stus.Count == 0)
  274. {
  275. stus = stus.Union(lost.stu).ToList();
  276. }
  277. else {
  278. stus = stus.Intersect(lost.stu).ToList();
  279. }
  280. LostStudent lostStudent = new()
  281. {
  282. code = lost.code,
  283. subject = lost.sub,
  284. stu = lost.stu.Count
  285. };
  286. art.lost.Add(lostStudent);
  287. }
  288. art.miss.Add(stus.Count);
  289. }
  290. art.pass = 1;
  291. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ArtEvaluation>(art, art.id, new PartitionKey(art.code));*//*
  292. }
  293. else
  294. {
  295. //获取当前艺术评价相关评测ID目前暂时排除区级发布的评测信息
  296. *//*List<(string eId, string sId)> ids = new();
  297. var examId = art.settings.SelectMany(x => x.task).Where(c => c.type == 1).Select(z => new { z.acId, z.subject }).ToList();
  298. examId.ForEach(x =>
  299. {
  300. ids.Add((x.acId, x.subject));
  301. });
  302. List<(string code, string sub, List<string> stu)> stuInfo = await getLostAsync(ids, client, art.school);
  303. List<string> stus = new();
  304. foreach (var (code, sub, stu) in stuInfo)
  305. {
  306. if (stus.Count == 0)
  307. {
  308. stus = stus.Union(stu).ToList();
  309. }
  310. else
  311. {
  312. stus = stus.Intersect(stu).ToList();
  313. }
  314. LostStudent lostStudent = new()
  315. {
  316. code = code,
  317. subject = sub,
  318. stu = stu.Count
  319. };
  320. art.lost.Add(lostStudent);
  321. }
  322. art.miss.Add(stus.Count);
  323. //art.miss = stus.Count;
  324. art.pass = 1;
  325. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ArtEvaluation>(art, art.id, new PartitionKey(art.code));*//*
  326. }
  327. }*/
  328. //根据学校编码去获取区级ID
  329. try {
  330. School scInfo = new();
  331. //School scInfo = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{art.school}", partitionKey: new PartitionKey("Base"));
  332. var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{art.school}", partitionKey: new PartitionKey("Base"));
  333. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  334. {
  335. using var cJson = await JsonDocument.ParseAsync(response.Content);
  336. scInfo = cJson.ToObject<School>();
  337. }
  338. ArtSetting setting = new();
  339. try
  340. {
  341. var artResponse = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{scInfo.areaId}", partitionKey: new PartitionKey("ArtSetting"));
  342. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  343. {
  344. using var json = await JsonDocument.ParseAsync(artResponse.Content);
  345. setting = json.ToObject<ArtSetting>();
  346. }
  347. }
  348. catch (Exception e)
  349. {
  350. }
  351. if (art.classes.Any())
  352. {
  353. //获取该艺术评测的评测Id
  354. List<(string id, string subjectId)> ids = new();
  355. List<ExamClassResult> examClassResults = new();
  356. var examId = art.settings.SelectMany(x => x.task).Where(c => c.type == 1).Select(z => new { z.acId, z.subject }).ToList();
  357. examId.ForEach(x =>
  358. {
  359. ids.Add((x.acId, x.subject));
  360. });
  361. List<string> results = new();
  362. results = ids.Select(x => x.id).ToList();
  363. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: $"select value(c) from c where c.examId in ({string.Join(",", results.Select(x => $"'{x}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{art.school}") }))
  364. {
  365. using var json = await JsonDocument.ParseAsync(item.Content);
  366. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  367. {
  368. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  369. {
  370. examClassResults.Add(obj.ToObject<ExamClassResult>());
  371. }
  372. }
  373. }
  374. //获取该艺术评测下面的评测活动
  375. List<ExamInfo> exams = new();
  376. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryIteratorSql<ExamInfo>(queryText: $"select value(c) from c where c.pk = 'Exam' and c.id in ({string.Join(",", results.Select(o => $"'{o}'"))})"))
  377. {
  378. exams.Add(item);
  379. }
  380. var sta = examClassResults.SelectMany(x => x.status).ToList();
  381. var ansCount = sta.Where(x => x == 0).ToList();
  382. var persent = ansCount.Count * 1.0 / sta.Count * 100;
  383. var period = scInfo.period.Where(x => x.id.Equals(art.period.id))?.FirstOrDefault();
  384. List<StudentArtResult> studentArtResults = new();
  385. string sql = $"SELECT value c FROM c where c.pk='ArtResult' ";
  386. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student)
  387. .GetItemQueryIteratorSql<StudentArtResult>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"ArtResult-{art.id}") }))
  388. {
  389. studentArtResults.Add(item);
  390. }
  391. List<Task<ItemResponse<StudentArtResult>>> tasks = new List<Task<ItemResponse<StudentArtResult>>>();
  392. //新增数据推送 obj => Portrait
  393. Portrait portrait = new()
  394. {
  395. schoolCode = art.school,
  396. periodId = art.period?.id,
  397. subjectId = "subject_art"
  398. };
  399. //var period = scInfo.period.Where(x => x.id.Equals(art.period.id)).FirstOrDefault();
  400. List<(string ptype, string subId, List<(string name, List<string> kno)> knos)> knoledge = new();
  401. //List<string> subs = new List<string> { "subject_painting", "subject_music" };
  402. if (exams.Count == 0) return;
  403. foreach (var ss in art.subjects)
  404. {
  405. if (string.IsNullOrEmpty(exams[0].papers[0].periodId))
  406. {
  407. knoledge.Add(await getKnowledge("university", "hbcn", client, ss.id, "be32942d-97a9-52ba-45d6-2e5b722583f5"));
  408. }
  409. else
  410. {
  411. knoledge.Add(await getKnowledge(art.periodType, exams.Where(c => c.subjects[0].id.Equals(ss.id))?.FirstOrDefault().papers[0].code, client, ss.id, exams.Where(c => c.subjects[0].id.Equals(ss.id))?.FirstOrDefault().papers[0].periodId));
  412. }
  413. }
  414. List<(string name, double score, double aver, string subject)> blockScore = new();
  415. List<(List<(string name, double score, double point, string subject)> studentScore, string stuId)> studentScores = new();
  416. foreach (var exam in exams)
  417. {
  418. HashSet<string> knowledge = new HashSet<string>();
  419. List<double> point = new List<double>();
  420. List<List<double>> result = new List<List<double>>();
  421. List<ClassRange> classes = new List<ClassRange>();
  422. //求单个知识点所占分数
  423. List<string> per = new List<string>();
  424. if (exam.papers[0].knowledge != null && exam.papers[0].knowledge.Count > 0)
  425. {
  426. exam.papers[0].knowledge.ForEach(k =>
  427. {
  428. k.ForEach(e =>
  429. {
  430. knowledge.Add(e);
  431. });
  432. });
  433. }
  434. point = exam.papers[0].point;
  435. List<string> knowledgeName = new List<string>();
  436. foreach (string cla in knowledge)
  437. {
  438. knowledgeName.Add(cla);
  439. }
  440. for (int k = 0; k < knowledgeName.Count; k++)
  441. {
  442. if (null == knowledgeName[k])
  443. {
  444. knowledgeName.Remove(knowledgeName[k]);
  445. }
  446. }
  447. List<double> Score = new List<double>();
  448. //List<(string name, double score, string subject)> pointScore = new();
  449. List<string> stus = examClassResults.Where(c => c.examId.Equals(exam.id)).SelectMany(z => z.studentIds).ToList();
  450. List<List<double>> stuScores = examClassResults.Where(c => c.examId.Equals(exam.id)).SelectMany(z => z.studentScores).ToList();
  451. foreach (string id in stus)
  452. {
  453. //double scores = 0;
  454. List<(string name, double score, double point, string subject)> studentScore = new();
  455. for (int k = 0; k < knowledgeName.Count; k++)
  456. {
  457. int n = 0;
  458. double OnePoint = 0;
  459. double scores = 0;
  460. exam.papers[0].knowledge.ForEach(kno =>
  461. {
  462. if (kno.Contains(knowledgeName[k]))
  463. {
  464. var itemPersent = kno.Count > 0 ? 1 / Convert.ToDouble(kno.Count) : 0;
  465. OnePoint += point[n] * itemPersent;
  466. int index = stus.IndexOf(id);
  467. if (stuScores[index][n] > 0)
  468. {
  469. scores += stuScores[index][n] * itemPersent;
  470. }
  471. }
  472. n++;
  473. });
  474. studentScore.Add((knowledgeName[k], Math.Round(scores, 2), OnePoint, exam.subjects[0].id));
  475. }
  476. studentScores.Add((studentScore, id));
  477. }
  478. for (int k = 0; k < knowledgeName.Count; k++)
  479. {
  480. double OnePoint = 0;
  481. int n = 0;
  482. double scores = 0;
  483. exam.papers[0].knowledge.ForEach(kno =>
  484. {
  485. if (kno.Contains(knowledgeName[k]))
  486. {
  487. var itemPersent = kno.Count > 0 ? 1 / Convert.ToDouble(kno.Count) : 0;
  488. OnePoint += point[n] * itemPersent;
  489. foreach (string id in stus)
  490. {
  491. int index = stus.IndexOf(id);
  492. if (stuScores[index][n] > 0)
  493. {
  494. scores += stuScores[index][n] * itemPersent;
  495. }
  496. }
  497. }
  498. n++;
  499. });
  500. double sc = stus.Count > 0 ? Math.Round(scores * 1.0 / stus.Count, 2) : 0;
  501. blockScore.Add((knowledgeName[k], OnePoint, sc, exam.subjects[0].id));
  502. //blockScore.AddRange(pointScore);
  503. }
  504. }
  505. var bls = blockScore.GroupBy(x => x.subject).Select(v => new
  506. {
  507. subjectId = v.Key,
  508. knoScore = v.ToList().GroupBy(k => k.name).Select(z => new
  509. {
  510. knoName = z.Key,
  511. score = z.ToList().Sum(j => j.score),
  512. aver = z.ToList().Sum(j => j.aver)
  513. })
  514. });
  515. //List<(string subId,List<(string name, List<string> kno)>)> subjectKnow = knoledge.Select(x => new { x.subId, x.knos }).ToList();
  516. //var subjectKnow;
  517. var subjectKnow = string.IsNullOrEmpty(exams[0].papers[0].periodId) ? knoledge.Select(x => new { x.subId, x.knos }).ToList() : knoledge.Where(c => c.ptype.Equals(art.periodType)).Select(x => new { x.subId, x.knos }).ToList();
  518. /*if (string.IsNullOrEmpty(exams[0].papers[0].periodId))
  519. {
  520. var subjectKnow = knoledge.Select(x => new { x.subId, x.knos }).ToList();
  521. }
  522. else {
  523. var subjectKnow = knoledge.Where(c => c.ptype.Equals(art.periodType)).Select(x => new { x.subId, x.knos }).ToList();
  524. }*/
  525. List<(string subjectId, List<(string name, double score, double persent, double aver, List<string> dim)> bks)> bs = new();
  526. List<(string subjectId, List<(string stuId, List<(string name, double score, double point, List<string> dim)> values)> stuBks)> sbs = new();
  527. List<(string name, double score, double av, string sId)> stuBlockScore = new();
  528. foreach (var bb in subjectKnow)
  529. {
  530. var kno1 = bls.Where(c => c.subjectId.Equals(bb.subId)).SelectMany(x => x.knoScore).ToList();
  531. var stuInfo = studentScores.Select(c => new
  532. {
  533. c.stuId,
  534. subInfo = c.studentScore.Where(x => x.subject.Equals(bb.subId)).ToList()
  535. }).Where(z => z.subInfo.Count > 0).ToList();
  536. //var kno2 = dimensions.Where(c => c.subjectBind.Equals(bb.subId)).Select(x => new { x.dimension,x.blocks}).ToList();
  537. List<(string name, double score, double aver)> blockScores = new();
  538. foreach (var k2 in bb.knos)
  539. {
  540. double bsc = 0;
  541. double avs = 0;
  542. foreach (var k3 in kno1)
  543. {
  544. if (null != k2.kno && k2.kno.Contains(k3.knoName))
  545. {
  546. bsc += k3.score;
  547. avs += k3.aver;
  548. }
  549. }
  550. foreach (var stu in stuInfo)
  551. {
  552. double realScore = 0;
  553. double realPoint = 0;
  554. foreach (var subScore in stu.subInfo)
  555. {
  556. if (null != k2.kno && k2.kno.Contains(subScore.name))
  557. {
  558. realScore = subScore.score;
  559. realPoint = subScore.point;
  560. }
  561. }
  562. stuBlockScore.Add((k2.name, realScore, realPoint, stu.stuId));
  563. }
  564. blockScores.Add((k2.name, bsc, avs));
  565. }
  566. var stuBlock = stuBlockScore.GroupBy(x => (x.sId)).Select(c => new
  567. {
  568. stuId = c.Key,
  569. block = c.ToList().GroupBy(b => b.name).Select(q => new
  570. {
  571. name = q.Key,
  572. score = q.ToList().Sum(q => q.score),
  573. point = q.ToList().Sum(q => q.av),
  574. dimension = setting.dimensions.Where(s => s.blocks.Contains(q.Key)).Select(x => x.dimension).ToList()
  575. })
  576. }).ToList();
  577. var blk = blockScores.Select(x => new
  578. {
  579. x.name,
  580. x.score,
  581. persent = Math.Round(x.aver > 0 ? x.aver / x.score : 0, 2),
  582. x.aver,
  583. dimension = setting.dimensions.Where(s => s.blocks.Contains(x.name)).Select(x => x.dimension)
  584. });
  585. List<(string name, double score, double persent, double aver, List<string> dim)> bks = new();
  586. List<(string stuId, List<(string name, double score, double point, List<string> dim)> values)> stuBks = new();
  587. foreach (var bk in blk)
  588. {
  589. bks.Add((bk.name, bk.score, bk.persent, bk.aver, bk.dimension.ToList()));
  590. }
  591. foreach (var stuBlk in stuBlock)
  592. {
  593. List<(string name, double score, double point, List<string> dim)> values = new();
  594. foreach (var lk in stuBlk.block)
  595. {
  596. values.Add((lk.name, lk.score, lk.point, lk.dimension));
  597. }
  598. stuBks.Add((stuBlk.stuId, values));
  599. }
  600. bs.Add((bb.subId, bks));
  601. sbs.Add((bb.subId, stuBks));
  602. }
  603. var blocks = bs.Select(x => new
  604. {
  605. x.subjectId,
  606. dim = x.bks.Select(z => new
  607. {
  608. z.name,
  609. z.score,
  610. z.persent,
  611. z.aver,
  612. z.dim
  613. })
  614. });
  615. var stuBlocks = sbs.Select(x => new {
  616. x.subjectId,
  617. dim = x.stuBks.Select(z => new {
  618. z.stuId,
  619. blk = z.values.Select(c => new {
  620. c.name,
  621. c.score,
  622. c.point,
  623. c.dim
  624. })
  625. })
  626. });
  627. //获取维度得分率
  628. var dim = setting.dimensions.GroupBy(a => a.subjectBind).Select(x => new
  629. {
  630. x.Key,
  631. dim = x.ToList().Select(c => new
  632. {
  633. c.dimension,
  634. persent = Math.Round(c.blocks.Select(z => new
  635. {
  636. persent = Math.Round(bs.Where(z => z.subjectId.Equals(x.Key)).SelectMany(k => k.bks).Where(q => q.name.Equals(z)).Sum(h => h.score) > 0 ?
  637. bs.Where(z => z.subjectId.Equals(x.Key)).SelectMany(k => k.bks).Where(q => q.name.Equals(z)).Sum(h => h.aver) /
  638. bs.Where(z => z.subjectId.Equals(x.Key)).SelectMany(k => k.bks).Where(q => q.name.Equals(z)).Sum(h => h.score) : 0, 2)
  639. }).Sum(o => o.persent) / c.blocks.Count, 2)
  640. })
  641. });
  642. //获取学期信息
  643. var (currSemester, studyYear, currSemesterDate, date, nextSemester) = SchoolService.GetSemester(period, art.startTime);
  644. //总分的占比情况
  645. foreach (var rs in studentArtResults)
  646. {
  647. foreach (var res in rs.results)
  648. {
  649. if (res.quotaId.Equals("quota_21") && res.score > -1 && res.score < 95)
  650. {
  651. /*res.score *= 1.5;
  652. if (res.score >= 95) {
  653. res.score = new Random().Next(90, 99);
  654. }*/
  655. //res.score = Math.Round(res.score);
  656. }
  657. }
  658. //if (rs.totalScore == 0)
  659. //{
  660. foreach (var sc in rs.subjectScores)
  661. {
  662. //if (sc.score == 0)
  663. //{
  664. /* var subjectMore = rs.results.GroupBy(x => x.subjectId).Select(c => new { subject = c.Key, list = c.ToList().Select(m => new { m.quotaId,m.score}) });
  665. var totalScore = subjectMore.Select(x => new {
  666. x.subject,
  667. quotaScroe = x.list.Select(c => new {
  668. c.quotaId,
  669. c.score
  670. }),
  671. });*/
  672. var quotaPercent = setting.quotas.Select(x => new
  673. {
  674. x.id,
  675. x.percent,
  676. score = x.children.Select(c => new
  677. {
  678. real = rs.results.Where(r => r.quotaId.Equals(c.id) && r.subjectId.Equals(sc.subjectId) && r.score > -1).FirstOrDefault()?.score * c.percent * 0.01,
  679. score = c.children.Select(s => new
  680. {
  681. real = rs.results.Where(r => r.quotaId.Equals(s.id) && r.subjectId.Equals(sc.subjectId) && r.score > -1).FirstOrDefault()?.score * s.percent * 0.01
  682. }).Sum(n => n.real) * c.percent * 0.01
  683. }).Sum(n => n.real + n.score) * x.percent * 0.01
  684. });
  685. double realScore = Math.Round((double)quotaPercent.Sum(c => c.score), 2);
  686. sc.score = realScore;
  687. //}
  688. }
  689. rs.totalScore = Math.Round(rs.subjectScores.Where(m => m.score >= 0).Sum(z => z.score), 2);
  690. tasks.Add(client.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync(rs, rs.id, new PartitionKey(rs.code)));
  691. PortraitStudent student = new()
  692. {
  693. studentId = rs.studentId,
  694. name = rs.studentName,
  695. classId = rs.classIds[0]
  696. };
  697. SemesterData semesterData = new()
  698. {
  699. examName = art.name,
  700. examId = art.id,
  701. examDate = art.startTime,
  702. examType = "",
  703. year = studyYear,
  704. semesterId = currSemester.id,
  705. totalScore = 200,
  706. sumScore = rs.totalScore,
  707. excellenceRate = 0,
  708. passRate = 0,
  709. };
  710. int index = 0;
  711. foreach (var sj in art.subjects)
  712. {
  713. ItemScore item = new()
  714. {
  715. name = sj.name,
  716. score = rs.subjectScores.Where(x => x.subjectId.Equals(sj.id)).FirstOrDefault().score,
  717. time = art.startTime,
  718. totalScore = 100,
  719. id = sj.id,
  720. type = sj.id,
  721. block = stuBlocks.Where(c => c.subjectId.Equals(sj.id)).SelectMany(x => x.dim).Where(z => z.stuId.Equals(rs.studentId))?.FirstOrDefault().blk,
  722. kno = studentScores.Where(c => c.stuId.Equals(rs.studentId)).SelectMany(c => c.studentScore).Where(
  723. p => p.subject.Equals(sj.id)).Select(z => new
  724. {
  725. z.name,
  726. z.score,
  727. z.point,
  728. block = subjectKnow.Where(v => v.subId.Equals(sj.id)).SelectMany(k => k.knos).Where(c => null != c.kno && c.kno.Contains(z.name)).Select(x => x.name)
  729. }),
  730. dim = dim.Where(c => c.Key.Equals(sj.id))?.FirstOrDefault().dim
  731. };
  732. index++;
  733. semesterData.itemScore.Add(item);
  734. }
  735. student.semesterData.Add(semesterData);
  736. portrait.students.Add(student);
  737. //}
  738. }
  739. if (tasks.Count > 0)
  740. {
  741. await Task.WhenAll(tasks);
  742. }
  743. //获取学生信息
  744. //(List<RMember> rmembers, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, art.classes, art.school);
  745. /* foreach (var member in studentArtResults)
  746. {
  747. }*/
  748. if (null != period && persent >= 60)
  749. {
  750. string location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
  751. var responseData = await _httpTrigger.RequestHttpTrigger(portrait, location, "upsert-student-portrait");
  752. }
  753. }
  754. } catch (Exception e) {
  755. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-艺术评测finish{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  756. }
  757. finally
  758. {
  759. string pk = string.Format("{0}{1}{2}", art.code, "-", "going");
  760. await table.DeleteSingle<ChangeRecord>(pk, tdata.id);
  761. }
  762. break;
  763. }
  764. }
  765. }
  766. catch (CosmosException e)
  767. {
  768. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}", GroupNames.醍摩豆服務運維群組);
  769. }
  770. catch (Exception ex)
  771. {
  772. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}艺术评价异常{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  773. }
  774. }
  775. private static async Task<(string key, string subId, List<(string name, List<string> kno)>)> getKnowledge(string key, string school, CosmosClient client, string subjectBid, string pId)
  776. {
  777. try
  778. {
  779. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school, new PartitionKey($"Base"));
  780. string subjectId = string.Empty;
  781. List<Knowledge> knowledges = new();
  782. List<(string name, List<string> kno)> blocks = new();
  783. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  784. {
  785. using var json = await JsonDocument.ParseAsync(response.Content);
  786. School sc = json.ToObject<School>();
  787. var subjects = sc.period.Where(p => p.id.Equals(pId)).Select(x => x.subjects);
  788. foreach (var sj in subjects)
  789. {
  790. foreach (var s in sj)
  791. {
  792. if (!string.IsNullOrWhiteSpace(s.bindId) && s.bindId.Equals(subjectBid))
  793. {
  794. subjectId = s.id;
  795. }
  796. }
  797. }
  798. string code = $"Knowledge-{school}-{subjectId}";
  799. StringBuilder sql = new StringBuilder($"select value(c) from c");
  800. if (!string.IsNullOrWhiteSpace(pId))
  801. {
  802. sql.Append($" where c.periodId = '{pId}'");
  803. }
  804. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<Knowledge>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
  805. {
  806. knowledges.Add(item);
  807. }
  808. }
  809. foreach (var know in knowledges)
  810. {
  811. foreach (var block in know.blocks)
  812. {
  813. blocks.Add((block.name, block.points));
  814. }
  815. }
  816. return (key, subjectBid, blocks);
  817. }
  818. catch (Exception e)
  819. {
  820. return (null, null, null);
  821. }
  822. }
  823. }
  824. }