TriggerExam.cs 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. using Azure.Cosmos;
  2. using Azure.Messaging.ServiceBus;
  3. using Microsoft.Azure.Documents;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.Json;
  9. using System.Threading.Tasks;
  10. using TEAMModelOS.SDK.DI;
  11. using TEAMModelOS.SDK.Extension;
  12. using TEAMModelOS.SDK;
  13. using TEAMModelOS.SDK.Models;
  14. using TEAMModelOS.SDK.Models.Cosmos;
  15. using TEAMModelOS.SDK.Models.Cosmos.Common;
  16. using TEAMModelOS.SDK.Models.Service;
  17. using HTEXLib.COMM.Helpers;
  18. namespace TEAMModelFunction
  19. {
  20. public class TriggerExam
  21. {
  22. public static async void Trigger(AzureCosmosFactory _azureCosmos, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
  23. CosmosClient client, Document input, string code, long stime, long etime, string school)
  24. {
  25. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(input.Id, new Azure.Cosmos.PartitionKey($"{code}"));
  26. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  27. List<ExamSubject> examSubjects = new List<ExamSubject>();
  28. try
  29. {
  30. if (info.scope.Equals("teacher", StringComparison.OrdinalIgnoreCase) || info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  31. {
  32. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{info.creatorId}") }))
  33. {
  34. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  35. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  36. {
  37. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  38. {
  39. examClassResults.Add(obj.ToObject<ExamClassResult>());
  40. }
  41. }
  42. }
  43. }
  44. else
  45. {
  46. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{school}") }))
  47. {
  48. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  49. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  50. {
  51. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  52. {
  53. examClassResults.Add(obj.ToObject<ExamClassResult>());
  54. }
  55. }
  56. }
  57. }
  58. List<ChangeRecord> records = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", info.progress } });
  59. //处理科目信息
  60. List<string> sub = new List<string>();
  61. foreach (ExamSubject subject in info.subjects)
  62. {
  63. sub.Add(subject.id);
  64. }
  65. //ChangeRecord record = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ChangeRecord>(input.Id, new Azure.Cosmos.PartitionKey($"{info.progress}"));
  66. switch (info.progress)
  67. {
  68. case "pending":
  69. var message = new ServiceBusMessage(new { id = input.Id, progress = "going", code = code }.ToJsonString());
  70. message.ApplicationProperties.Add("name", "Exam");
  71. if (records.Count > 0)
  72. {
  73. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
  74. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  75. records[0].sequenceNumber = start;
  76. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  77. //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  78. }
  79. else
  80. {
  81. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(stime));
  82. ChangeRecord changeRecord = new ChangeRecord
  83. {
  84. RowKey = input.Id,
  85. PartitionKey = "pending",
  86. sequenceNumber = start,
  87. msgId = message.MessageId
  88. };
  89. await _azureStorage.Save<ChangeRecord>(changeRecord);
  90. //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  91. }
  92. break;
  93. case "going":
  94. List<string> classes = ExamService.getClasses(info.classes,info.stuLists);
  95. (List<TmdInfo> tmdids, List<StuInfo> studentss,List<ClassListInfo> classLists) = await TriggerStuActivity.GetStuList(client, _dingDing, classes, info.school);
  96. List<StuActivity> stuActivities = new List<StuActivity>();
  97. List<StuActivity> tmdActivities = new List<StuActivity>();
  98. try
  99. {
  100. if (tmdids.IsNotEmpty())
  101. {
  102. tmdids.ForEach(x =>
  103. {
  104. tmdActivities.Add(new StuActivity
  105. {
  106. pk = "Activity",
  107. id = info.id,
  108. code = $"Activity-{x.id}",
  109. type = "Exam",
  110. name = info.name,
  111. startTime = info.startTime,
  112. endTime = info.endTime,
  113. scode = info.code,
  114. scope = info.scope,
  115. school = info.school,
  116. creatorId = info.creatorId,
  117. subjects = sub,
  118. blob = null,
  119. owner = info.owner,
  120. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  121. taskStatus = -1,
  122. classIds = classes
  123. });;
  124. });
  125. }
  126. if (studentss.IsNotEmpty())
  127. {
  128. studentss.ForEach(x =>
  129. {
  130. stuActivities.Add(new StuActivity
  131. {
  132. pk = "Activity",
  133. id = info.id,
  134. code = $"Activity-{x.code.Replace("Base-", "")}-{x.id}",
  135. type = "Exam",
  136. name = info.name,
  137. startTime = info.startTime,
  138. endTime = info.endTime,
  139. scode = info.code,
  140. scope = info.scope,
  141. school = info.school,
  142. creatorId = info.creatorId,
  143. subjects = sub,
  144. blob = null,
  145. owner = info.owner,
  146. classIds = classes,
  147. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  148. taskStatus = -1
  149. });
  150. });
  151. }
  152. await TriggerStuActivity.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities);
  153. //向学生或醍摩豆账号发起通知
  154. #region
  155. //Notice notice = new Notice()
  156. //{
  157. // msgId = info.id,
  158. // creation = info.startTime,
  159. // expire = info.endTime,
  160. // creatorId = info.creatorId,
  161. // stuids = studentss,
  162. // tmdids = tmdids,
  163. // type = "notice",//评测参加通知
  164. // priority = "normal",
  165. // school = info.school,
  166. // scope = info.scope,
  167. // //data = new { }.ToJsonString()
  168. // body = new Body { sid = info.id, scode = info.code, spk = info.pk, biztype = "exam-join" }
  169. //};
  170. //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
  171. //messageBlob.ApplicationProperties.Add("name", "Notice");
  172. //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageBlob);
  173. #endregion
  174. if (examClassResults.Count == 0)
  175. {
  176. foreach (string cla in classes)
  177. {
  178. int m = 0;
  179. foreach (ExamSubject subject in info.subjects)
  180. {
  181. string classCode = "";
  182. if (string.IsNullOrEmpty(info.school) || !info.scope.Equals("school", StringComparison.OrdinalIgnoreCase))
  183. {
  184. classCode = "ExamClassResult-" + info.creatorId;
  185. }
  186. else
  187. {
  188. classCode = "ExamClassResult-" + info.school;
  189. }
  190. ExamClassResult result = new ExamClassResult
  191. {
  192. code = classCode,
  193. examId = info.id,
  194. id = Guid.NewGuid().ToString(),
  195. subjectId = subject.id,
  196. year = info.year,
  197. scope = info.scope
  198. };
  199. result.info.id = cla;
  200. List<string> ans = new List<string>();
  201. List<List<string>> anses = new List<List<string>>();
  202. List<List<Details>> marks = new List<List<Details>>();
  203. List<double> ansPoint = new List<double>();
  204. List<string> ids = new List<string>();
  205. foreach (double p in info.papers[m].point)
  206. {
  207. //Details details = new Details();
  208. //ans.Add(new List<string>());
  209. anses.Add(new List<string>());
  210. marks.Add(new List<Details>());
  211. ansPoint.Add(-1);
  212. }
  213. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"Class-{info.school}"));
  214. if (sresponse.Status == 200)
  215. {
  216. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  217. Class classroom = json.ToObject<Class>();
  218. School sc = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(info.school, new Azure.Cosmos.PartitionKey("Base"));
  219. foreach (Period period in sc.period)
  220. {
  221. if (period.id.Equals(classroom.periodId))
  222. {
  223. foreach (Semester semester in period.semesters)
  224. {
  225. if (semester.start == 1)
  226. {
  227. int year = DateTimeOffset.UtcNow.Year;
  228. int month = DateTimeOffset.UtcNow.Month;
  229. int day = DateTimeOffset.UtcNow.Day;
  230. int time = month > semester.month ? 0 : 1;
  231. int eyear = year - time;
  232. result.gradeId = (eyear - classroom.year).ToString();
  233. }
  234. }
  235. }
  236. }
  237. //result.info.id = classroom.id;
  238. result.info.name = classroom.name;
  239. //result.gradeId = classroom.year.ToString();
  240. //处理班级人数
  241. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.classId = '{classroom.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{info.school}") }))
  242. {
  243. using var json_stu = await JsonDocument.ParseAsync(item.ContentStream);
  244. if (json_stu.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  245. {
  246. var accounts = json_stu.RootElement.GetProperty("Documents").EnumerateArray();
  247. while (accounts.MoveNext())
  248. {
  249. JsonElement account = accounts.Current;
  250. ids.Add(account.GetProperty("id").GetString());
  251. }
  252. }
  253. }
  254. }
  255. if (info.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  256. {
  257. var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"StuList"));
  258. if (stuResponse.Status == 200)
  259. {
  260. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  261. StuList stuList = json.ToObject<StuList>();
  262. //result.info.id = stuList.id;
  263. result.info.name = stuList.name;
  264. //处理发布对象为自选名单(个人)
  265. foreach (Students stus in stuList.students)
  266. {
  267. if (!ids.Contains(stus.id))
  268. {
  269. ids.Add(stus.id);
  270. }
  271. }
  272. if (stuList.tmids.Count > 0)
  273. {
  274. foreach (string tid in stuList.tmids)
  275. {
  276. ids.Add(tid);
  277. }
  278. }
  279. }
  280. }
  281. else
  282. {
  283. var stuResponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(cla, new Azure.Cosmos.PartitionKey($"StuList-{info.school}"));
  284. if (stuResponse.Status == 200)
  285. {
  286. using var json = await JsonDocument.ParseAsync(stuResponse.ContentStream);
  287. StuList stuList = json.ToObject<StuList>();
  288. //result.info.id = stuList.id;
  289. result.info.name = stuList.name;
  290. //处理发布对象为自选名单(校本)
  291. foreach (Students stus in stuList.students)
  292. {
  293. if (!ids.Contains(stus.id))
  294. {
  295. ids.Add(stus.id);
  296. }
  297. }
  298. }
  299. }
  300. foreach (string stu in ids)
  301. {
  302. result.mark.Add(marks);
  303. result.studentIds.Add(stu);
  304. result.studentAnswers.Add(ans);
  305. result.studentScores.Add(ansPoint);
  306. result.ans.Add(anses);
  307. result.sum.Add(0);
  308. }
  309. //result.progress = info.progress;
  310. result.school = info.school;
  311. m++;
  312. await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(result, new Azure.Cosmos.PartitionKey($"{result.code}"));
  313. }
  314. }
  315. // 发送信息通知
  316. var messageEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = code }.ToJsonString());
  317. messageEnd.ApplicationProperties.Add("name", "Exam");
  318. if (records.Count > 0)
  319. {
  320. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  321. await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), records[0].sequenceNumber);
  322. records[0].sequenceNumber = end;
  323. await _azureStorage.SaveOrUpdate<ChangeRecord>(records[0]);
  324. //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(record, record.id, new Azure.Cosmos.PartitionKey($"{record.code}"));
  325. }
  326. else
  327. {
  328. long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageEnd, DateTimeOffset.FromUnixTimeMilliseconds(etime));
  329. ChangeRecord changeRecord = new ChangeRecord
  330. {
  331. RowKey = input.Id,
  332. PartitionKey = "going",
  333. sequenceNumber = end,
  334. msgId = messageEnd.MessageId
  335. };
  336. await _azureStorage.Save<ChangeRecord>(changeRecord);
  337. //await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(changeRecord, new Azure.Cosmos.PartitionKey($"{changeRecord.code}"));
  338. }
  339. }
  340. else
  341. {
  342. //处理单科结算时科目与试卷信息匹配的问题
  343. int gno = 0;
  344. foreach (ExamSubject subject in info.subjects)
  345. {
  346. if (subject.classCount == classes.Count)
  347. {
  348. await createClassResultAsync(info, examClassResults, subject, gno, _azureCosmos, _dingDing, _azureStorage);
  349. }
  350. gno++;
  351. }
  352. }
  353. }
  354. catch (Exception e)
  355. {
  356. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测going状态异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
  357. }
  358. break;
  359. case "finish":
  360. int fno = 0;
  361. try
  362. {
  363. foreach (ExamSubject subject in info.subjects)
  364. {
  365. await createClassResultAsync(info, examClassResults, subject, fno, _azureCosmos, _dingDing, _azureStorage);
  366. fno++;
  367. }
  368. //计算单次考试简易统计信息
  369. List<ExamResult> examResults = new List<ExamResult>();
  370. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamResult>(
  371. queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}") }))
  372. {
  373. examResults.Add(item);
  374. }
  375. List<Task<ItemResponse<ExamClassResult>>> tasks = new List<Task<ItemResponse<ExamClassResult>>>();
  376. //结算单科单班的标准差和平均分
  377. foreach (ExamClassResult classResult in examClassResults)
  378. {
  379. //标记单科单班总得分
  380. double subScore = 0;
  381. //标准差
  382. double sPowSum = 0;
  383. var scount = classResult.studentIds.Count;
  384. foreach (List<double> sc in classResult.studentScores)
  385. {
  386. List<double> newSc = new List<double>();
  387. foreach (double ssc in sc)
  388. {
  389. if (ssc == -1)
  390. {
  391. newSc.Add(0);
  392. }
  393. else
  394. {
  395. newSc.Add(ssc);
  396. }
  397. }
  398. subScore += newSc.Sum();
  399. }
  400. foreach (string sid in classResult.studentIds)
  401. {
  402. double ssc = classResult.studentScores[classResult.studentIds.IndexOf(sid)].Sum();
  403. sPowSum += Math.Pow(ssc - scount > 0 ? Math.Round(subScore * 1.0 / scount, 2) : 0, 2);
  404. }
  405. classResult.standard = Math.Round(scount > 0 ? Math.Pow(sPowSum / scount, 0.5) : 0, 2);
  406. classResult.average = scount > 0 ? Math.Round(subScore / scount, 2) : 0;
  407. classResult.progress = true;
  408. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}")));
  409. }
  410. await Task.WhenAll(tasks);
  411. //记录某次考试所有学生得分总分
  412. double score = 0;
  413. double allScore = 0;
  414. int stuCount = 0;
  415. //标准差
  416. double powSum = 0;
  417. List<string> losStu = new List<string>();
  418. //先与第一个值取并集
  419. if (examResults.Count > 0)
  420. {
  421. losStu = losStu.Union(examResults[0].lostStus).ToList();
  422. foreach (ExamResult examResult in examResults)
  423. {
  424. if (info.id == examResult.examId)
  425. {
  426. foreach (List<double> sc in examResult.studentScores)
  427. {
  428. score += sc.Sum();
  429. }
  430. stuCount = examResult.studentIds.Count;
  431. }
  432. //powSum += Math.Pow(score - examResult.studentIds.Count > 0 ? Math.Round(score * 1.0 / examResult.studentIds.Count, 2) : 0, 2);
  433. //取交集
  434. losStu = losStu.Intersect(examResult.lostStus).ToList();
  435. }
  436. }
  437. double NewsRateScore = stuCount > 0 ? Math.Round(score * 1.0 / stuCount, 2) : 0;
  438. foreach (PaperSimple simple in info.papers)
  439. {
  440. allScore += simple.point.Sum();
  441. }
  442. //计算全科标准差
  443. foreach (string id in examResults[0].studentIds)
  444. {
  445. double sc = 0;
  446. foreach (ExamResult result in examResults)
  447. {
  448. sc += result.studentScores[result.studentIds.IndexOf(id)].Sum();
  449. }
  450. powSum += Math.Pow(sc - NewsRateScore, 2);
  451. }
  452. info.standard = Math.Round(examResults[0].studentIds.Count > 0 ? Math.Pow(powSum / examResults[0].studentIds.Count, 0.5) : 0, 2);
  453. double NewsRate = allScore > 0 ? Math.Round(NewsRateScore / allScore * 100, 2) : 0;
  454. info.lostStu = losStu;
  455. /*//补充历史数据的容器名称
  456. if (string.IsNullOrEmpty(info.cn)) {
  457. if (info.scope.Equals("school"))
  458. {
  459. info.cn = info.school;
  460. }
  461. else {
  462. info.cn = info.creatorId;
  463. }
  464. }*/
  465. //判断均分是否发生变化,便于实时的更新评测基本信息
  466. if (info.sRate != NewsRate || info.average != NewsRateScore)
  467. {
  468. info.sRate = NewsRate;
  469. info.average = NewsRateScore;
  470. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(info, info.id, new Azure.Cosmos.PartitionKey(info.code));
  471. }
  472. }
  473. catch (Exception e)
  474. {
  475. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测finish状态异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
  476. }
  477. break;
  478. }
  479. }
  480. catch (Exception e)
  481. {
  482. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测结算异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
  483. }
  484. }
  485. //处理全部学生选题计数
  486. public static async Task examRecordCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, ExamResult result, List<ExamClassResult> classResults, AzureCosmosFactory _azureCosmos)
  487. {
  488. try
  489. {
  490. List<double> scores = new List<double>();
  491. foreach (List<double> sc in result.studentScores)
  492. {
  493. scores.Add(sc.Sum());
  494. }
  495. //确定高分组 最低分数
  496. scores.Sort((s1, s2) => { return s2.CompareTo(s1); });
  497. double rhwCount = Math.Floor(scores.Count * 0.27);
  498. double rhw = rhwCount > 0 ? scores[int.Parse(rhwCount.ToString("0"))] : 0;
  499. //确定低分组 最高分数
  500. //scores.Sort((s1, s2) => { return s1.CompareTo(s2); });
  501. double rhlCount = Math.Ceiling(scores.Count * 0.73);
  502. double rhl = rhlCount > 0 ? scores[int.Parse(rhlCount.ToString("0"))-1] : 0;
  503. //存放高分组学生ID
  504. List<string> phId = new List<string>();
  505. List<string> plId = new List<string>();
  506. List<List<List<string>>> opth = new List<List<List<string>>>();
  507. List<List<List<string>>> optl = new List<List<List<string>>>();
  508. await knowledgeCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
  509. await fieldCount(info, subject, _dingDing, no, classResults, rhwCount, rhw, rhlCount, rhl, _azureCosmos);
  510. int PHCount = 0;
  511. int PLCount = 0;
  512. foreach (ExamClassResult classResult in classResults)
  513. {
  514. if (classResult.subjectId.Equals(subject.id))
  515. {
  516. foreach (string id in classResult.studentIds)
  517. {
  518. int index = classResult.studentIds.IndexOf(id);
  519. if (classResult.studentScores.Count > 0)
  520. {
  521. if (classResult.studentScores[index].Sum() >= rhw && PHCount < rhwCount)
  522. {
  523. if (classResult.ans.Count > 0)
  524. {
  525. opth.Add(classResult.ans[index]);
  526. PHCount++;
  527. continue;
  528. }
  529. }
  530. if (classResult.studentScores[index].Sum() <= rhl && PLCount < (scores.Count - rhlCount))
  531. {
  532. if (classResult.ans.Count > 0)
  533. {
  534. optl.Add(classResult.ans[index]);
  535. PLCount++;
  536. continue;
  537. }
  538. }
  539. }
  540. }
  541. }
  542. }
  543. result.phc = getMore(info, no, opth);
  544. result.plc = getMore(info, no, optl);
  545. }
  546. catch (Exception ex)
  547. {
  548. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测作答记录结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  549. }
  550. }
  551. public static async Task knowledgeCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
  552. double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
  553. {
  554. try
  555. {
  556. int phcount = 0;
  557. int plcount = 0;
  558. //存放并去重知识点
  559. HashSet<string> kname = new HashSet<string>();
  560. if (info.papers[no].knowledge.Count > 0)
  561. {
  562. info.papers[no].knowledge.ForEach(kno =>
  563. {
  564. kno.ForEach(k =>
  565. {
  566. kname.Add(k);
  567. });
  568. });
  569. List<string> knowledgeName = new List<string>();
  570. foreach (string cla in kname)
  571. {
  572. knowledgeName.Add(cla);
  573. }
  574. for (int k = 0; k < knowledgeName.Count; k++)
  575. {
  576. if (null == knowledgeName[k])
  577. {
  578. knowledgeName.Remove(knowledgeName[k]);
  579. }
  580. }
  581. foreach (ExamClassResult classResult in classResults)
  582. {
  583. if (classResult.subjectId.Equals(subject.id))
  584. {
  585. //List<int> phc = new List<int>();
  586. List<int> ph = new List<int>();
  587. List<int> pl = new List<int>();
  588. List<int> pc = new List<int>();
  589. List<double> persent = new List<double>();
  590. for (int i = 0; i < knowledgeName.Count; i++)
  591. {
  592. //初始化单个知识点得分
  593. double score = 0;
  594. double allScore = 0;
  595. int n = 0;
  596. int phCount = 0;
  597. int plCount = 0;
  598. int pCount = 0;
  599. foreach (List<string> str in info.papers[no].knowledge)
  600. {
  601. if (str.Contains(knowledgeName[i]))
  602. {
  603. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  604. allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
  605. foreach (string id in classResult.studentIds)
  606. {
  607. int index = classResult.studentIds.IndexOf(id);
  608. if (classResult.studentScores.Count > 0)
  609. {
  610. if (classResult.studentScores[index].Count > 0)
  611. {
  612. score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n];
  613. if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
  614. {
  615. if (classResult.studentScores[index][n] <= 0)
  616. {
  617. phCount++;
  618. }
  619. phcount++;
  620. continue;
  621. }
  622. if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
  623. {
  624. if (classResult.studentScores[index][n] <= 0)
  625. {
  626. plCount++;
  627. }
  628. plcount++;
  629. continue;
  630. }
  631. if (classResult.studentScores[index][n] <= 0)
  632. {
  633. pCount++;
  634. }
  635. }
  636. }
  637. }
  638. }
  639. n++;
  640. }
  641. pc.Add(pCount);
  642. ph.Add(phCount);
  643. pl.Add(plCount);
  644. double per = classResult.studentIds.Count > 0 ? Math.Round(score / classResult.studentIds.Count, 2) : 0;
  645. persent.Add(allScore > 0 ? per / allScore : 0);
  646. }
  647. classResult.phc = ph;
  648. classResult.plc = pl;
  649. classResult.pc = pc;
  650. classResult.krate = persent;
  651. }
  652. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
  653. }
  654. }
  655. }
  656. catch (Exception ex)
  657. {
  658. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测知识点结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  659. }
  660. }
  661. public static async Task fieldCount(ExamInfo info, ExamSubject subject, DingDing _dingDing, int no, List<ExamClassResult> classResults,
  662. double rhwCount, double rhw, double rhlCount, double rhl, AzureCosmosFactory _azureCosmos)
  663. {
  664. try
  665. {
  666. int phcount = 0;
  667. int plcount = 0;
  668. //存放并去重知识点
  669. List<int> knowledgeName = new List<int>();
  670. knowledgeName.Add(1);
  671. knowledgeName.Add(2);
  672. knowledgeName.Add(3);
  673. knowledgeName.Add(4);
  674. knowledgeName.Add(5);
  675. knowledgeName.Add(6);
  676. foreach (ExamClassResult classResult in classResults)
  677. {
  678. if (classResult.subjectId.Equals(subject.id))
  679. {
  680. //List<int> phc = new List<int>();
  681. List<int> ph = new List<int>();
  682. List<int> pl = new List<int>();
  683. List<int> pc = new List<int>();
  684. List<double> persent = new List<double>();
  685. for (int i = 0; i < knowledgeName.Count; i++)
  686. {
  687. //初始化单个知识点得分
  688. double score = 0;
  689. double allScore = 0;
  690. int n = 0;
  691. int phCount = 0;
  692. int plCount = 0;
  693. int pCount = 0;
  694. if (info.papers[no].field.Count > 0)
  695. {
  696. foreach (int str in info.papers[no].field)
  697. {
  698. if (str == knowledgeName[i])
  699. {
  700. var itemPersent = 1;
  701. allScore += info.papers[no].point.Count > 0 ? info.papers[no].point[n] * itemPersent : 0;
  702. foreach (string id in classResult.studentIds)
  703. {
  704. int index = classResult.studentIds.IndexOf(id);
  705. if (classResult.studentScores.Count > 0)
  706. {
  707. if (classResult.studentScores[index].Count > 0)
  708. {
  709. score += classResult.studentScores[index][n] == -1 ? 0 : classResult.studentScores[index][n];
  710. if (classResult.studentScores[index].Sum() >= rhw && phcount < rhwCount)
  711. {
  712. if (classResult.studentScores[index][n] <= 0)
  713. {
  714. phCount++;
  715. }
  716. phcount++;
  717. continue;
  718. }
  719. if (classResult.studentScores[index].Sum() <= rhl && plcount < (info.stuCount - rhlCount))
  720. {
  721. if (classResult.studentScores[index][n] <= 0)
  722. {
  723. plCount++;
  724. }
  725. plcount++;
  726. continue;
  727. }
  728. if (classResult.studentScores[index][n] <= 0)
  729. {
  730. pCount++;
  731. }
  732. }
  733. }
  734. }
  735. }
  736. n++;
  737. }
  738. pc.Add(pCount);
  739. ph.Add(phCount);
  740. pl.Add(plCount);
  741. double per = classResult.studentIds.Count > 0 ? Math.Round(score / classResult.studentIds.Count, 2) : 0;
  742. persent.Add(allScore > 0 ? per / allScore : 0);
  743. }
  744. }
  745. classResult.fphc = ph;
  746. classResult.fplc = pl;
  747. classResult.fpc = pc;
  748. classResult.frate = persent;
  749. }
  750. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(classResult, classResult.id, new Azure.Cosmos.PartitionKey($"{classResult.code}"));
  751. }
  752. }
  753. catch (Exception ex)
  754. {
  755. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-{info.id}-评测认知层次结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  756. }
  757. }
  758. //处理选题计数
  759. public static List<Dictionary<string, int>> getMore(ExamInfo info, int no, List<List<List<string>>> list)
  760. {
  761. List<Dictionary<string, int>> recorde = new List<Dictionary<string, int>>();
  762. try
  763. {
  764. for (int i = 0; i < info.papers[no].answers.Count; i++)
  765. {
  766. if (info.papers[no].answers[i].Count <= 0)
  767. {
  768. recorde.Add(new Dictionary<string, int>());
  769. continue;
  770. }
  771. Dictionary<string, int> optCount = new Dictionary<string, int>();
  772. foreach (List<List<string>> stu in list)
  773. {
  774. if (stu.Count == info.papers[no].answers.Count)
  775. {
  776. var item = stu[i];
  777. foreach (string opt in item)
  778. {
  779. if (optCount.ContainsKey(opt))
  780. {
  781. optCount[opt] = optCount[opt] + 1;
  782. }
  783. else
  784. {
  785. optCount[opt] = 1;
  786. }
  787. }
  788. }
  789. }
  790. recorde.Add(optCount);
  791. }
  792. return recorde;
  793. }
  794. catch (Exception)
  795. {
  796. return recorde;
  797. }
  798. }
  799. public static async Task createClassResultAsync(ExamInfo info, List<ExamClassResult> examClassResults, ExamSubject subject, int no, AzureCosmosFactory _azureCosmos, DingDing _dingDing, AzureStorageFactory _azureStorage)
  800. {
  801. //保证试卷信息与科目信息同步
  802. ExamResult result = new ExamResult();
  803. //人数总和
  804. int Count = 0;
  805. int m = 0;
  806. double score = 0;
  807. //标准差
  808. double powSum = 0;
  809. double allScore = info.papers[no].point.Sum();
  810. List<ClassRange> classRanges = new List<ClassRange>();
  811. List<string> lostStu = new List<string>();
  812. List<double> csRate = new List<double>();
  813. List<List<List<string>>> opt = new List<List<List<string>>>();
  814. foreach (ExamClassResult classResult in examClassResults)
  815. {
  816. double classSrate = 0;
  817. if (classResult.subjectId.Equals(subject.id))
  818. {
  819. foreach (List<List<string>> op in classResult.ans)
  820. {
  821. opt.Add(op);
  822. }
  823. //记录缺考学生索引位置
  824. int index = 0;
  825. foreach (List<double> scores in classResult.studentScores)
  826. {
  827. List<double> newScores = new List<double>();
  828. int count = 0;
  829. foreach (double sc in scores)
  830. {
  831. newScores.Add(sc > -1 ? sc : 0);
  832. if (sc == -1)
  833. {
  834. count++;
  835. }
  836. }
  837. if (count == scores.Count)
  838. {
  839. lostStu.Add(classResult.studentIds[index]);
  840. //mcount++;
  841. }
  842. classSrate += newScores.Sum();
  843. score += newScores.Sum();
  844. result.studentScores.Add(newScores);
  845. index++;
  846. }
  847. //处理班级信息
  848. ClassRange range = new ClassRange();
  849. range.id = classResult.info.id;
  850. range.name = classResult.info.name;
  851. range.gradeId = classResult.gradeId;
  852. List<int> ran = new List<int>();
  853. int stuCount = classResult.studentIds.Count;
  854. Count += stuCount;
  855. if (m == 0)
  856. {
  857. ran.Add(0);
  858. ran.Add(stuCount - 1);
  859. }
  860. else
  861. {
  862. ran.Add(Count - stuCount);
  863. ran.Add(Count - 1);
  864. }
  865. m++;
  866. range.range = ran;
  867. classRanges.Add(range);
  868. //处理学生ID
  869. foreach (string id in classResult.studentIds)
  870. {
  871. result.studentIds.Add(id);
  872. }
  873. if (allScore > 0)
  874. {
  875. csRate.Add(classResult.studentIds.Count > 0 ? Math.Round(classSrate * 1.0 / classResult.studentIds.Count, 2) : 0 / allScore);
  876. }
  877. else
  878. {
  879. csRate.Add(0);
  880. }
  881. //powSum += Math.Pow(classSrate - result.average, 2);
  882. //处理选项计数内容
  883. }
  884. }
  885. await examRecordCount(info, subject, _dingDing, no, result, examClassResults, _azureCosmos);
  886. result.record = getMore(info, no, opt);
  887. result.average = result.studentIds.Count > 0 ? Math.Round(score * 1.0 / result.studentIds.Count, 2) : 0;
  888. foreach (ExamClassResult classResult in examClassResults)
  889. {
  890. //double classSrate = 0;
  891. if (classResult.subjectId.Equals(subject.id))
  892. {
  893. foreach (string id in classResult.studentIds)
  894. {
  895. double sc = classResult.studentScores[classResult.studentIds.IndexOf(id)].Sum();
  896. powSum += Math.Pow(sc - result.average, 2);
  897. }
  898. }
  899. }
  900. result.standard = Math.Round(result.studentIds.Count > 0 ? Math.Pow(powSum / result.studentIds.Count, 0.5) : 0, 2);
  901. result.csRate = csRate;
  902. result.lostStus = lostStu;
  903. result.sRate = allScore > 0 ? Math.Round(result.average / allScore * 100, 2) : 0;
  904. result.classes = classRanges;
  905. result.code = "ExamResult-" + info.id;
  906. result.school = info.school;
  907. result.id = subject.id;
  908. result.examId = info.id;
  909. result.subjectId = subject.id;
  910. result.year = info.year;
  911. result.paper = info.papers[no];
  912. //result.point = info.papers[j].point;
  913. result.scope = info.scope;
  914. result.name = info.name;
  915. result.time = info.startTime;
  916. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(result, new Azure.Cosmos.PartitionKey($"ExamResult-{info.id}"));
  917. }
  918. }
  919. }