TriggerExam.cs 59 KB

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