TriggerExam.cs 57 KB

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