TriggerExam.cs 57 KB

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