TriggerArt.cs 59 KB

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