TriggerExam.cs 54 KB

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