TriggerExam.cs 57 KB

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