TriggerExam.cs 58 KB

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