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