TriggerArt.cs 60 KB

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