TriggerExam.cs 61 KB

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