ExamService.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. using Azure.Cosmos;
  2. using DocumentFormat.OpenXml.Drawing.Charts;
  3. using DocumentFormat.OpenXml.Office2010.Excel;
  4. using HTEXLib.Helpers.ShapeHelpers;
  5. using MathNet.Numerics.Distributions;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.AspNetCore.Mvc;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Text.Json;
  13. using System.Threading.Tasks;
  14. using TEAMModelOS.SDK.DI;
  15. using TEAMModelOS.SDK.Extension;
  16. namespace TEAMModelOS.SDK.Models.Service
  17. {
  18. public static class ExamService
  19. {
  20. public static List<string> getClasses(List<string> cla, List<string> stus)
  21. {
  22. List<string> classes = new List<string>();
  23. try
  24. {
  25. if (cla.Count > 0)
  26. {
  27. foreach (string cl in cla)
  28. {
  29. classes.Add(cl);
  30. }
  31. }
  32. if (stus.Count > 0)
  33. {
  34. foreach (string stu in stus)
  35. {
  36. classes.Add(stu);
  37. }
  38. }
  39. return classes;
  40. }
  41. catch (Exception)
  42. {
  43. return classes;
  44. }
  45. }
  46. public static async Task deleteAsync(CosmosClient client, string id, string tId)
  47. {
  48. List<string> correctIds = new List<string>();
  49. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.cid = '{id}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CorrectTask-{tId}") }))
  50. {
  51. using var jsonTask = await JsonDocument.ParseAsync(item.ContentStream);
  52. if (jsonTask.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  53. {
  54. var accounts = jsonTask.RootElement.GetProperty("Documents").EnumerateArray();
  55. while (accounts.MoveNext())
  56. {
  57. JsonElement account = accounts.Current;
  58. correctIds.Add(account.GetProperty("id").GetString());
  59. }
  60. }
  61. }
  62. if (correctIds.Count > 0)
  63. {
  64. await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsStreamAsync(correctIds, $"CorrectTask-{tId}");
  65. }
  66. }
  67. public static async Task<List<(string name, List<(string classId, double average)> classMore, double total,List<(string studentId, double scores, string classId)>students )>> getGradeScore(CoreAPIHttpService _coreAPIHttpService, DingDing _dingDing, CosmosClient client, List<string> classIds, string periodId, string schooCode,List<string> examType, long stime, long etime)
  68. {
  69. List<(string name, List<(string classId,double average)> classMore, double total, List<(string studentId, double scores, string classId)> stus)> grades = new();
  70. //List<(string grade, double score)> grades = new();
  71. try
  72. {
  73. //获取该年级所有班级ID
  74. /*List<string> classIds = new();
  75. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.year = {gradeId} and c.pk = 'Class' and c.periodId = '{periodId}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schooCode}") }))
  76. {
  77. using var jsonTask = await JsonDocument.ParseAsync(item.ContentStream);
  78. if (jsonTask.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  79. {
  80. var accounts = jsonTask.RootElement.GetProperty("Documents").EnumerateArray();
  81. while (accounts.MoveNext())
  82. {
  83. JsonElement account = accounts.Current;
  84. classIds.Add(account.GetProperty("id").GetString());
  85. }
  86. }
  87. }*/
  88. if (classIds.Count == 0)
  89. {
  90. return grades;
  91. }
  92. else
  93. {
  94. //获取该学期内学校发生的所有评测活动(不包含个人评测活动)
  95. List<ExamInfo> exams = new();
  96. /* School sc = new();
  97. var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(schooCode.ToString(), new PartitionKey($"Base"));
  98. if (response.Status == 200)
  99. {
  100. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  101. sc = json.ToObject<School>();
  102. }*/
  103. StringBuilder stringBuilder = new($"select value(c) from c where c.startTime >= {stime} and c.startTime < {etime} and c.progress = 'finish' and c.period.id = '{periodId}'");
  104. if (examType.Any()) {
  105. stringBuilder.Append($" and c.examType.name in ({string.Join(",", examType.Select(o => $"'{o}'"))}) ");
  106. }
  107. stringBuilder.Append(" order by c.createTime desc");
  108. //var gradeNames = sc.period.Where(x => x.id.Equals(periodId.ToString()))?.FirstOrDefault().grades;
  109. //var index = gradeNames.IndexOf(gradeName.ToString());
  110. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamInfo>(
  111. queryText: stringBuilder.ToString(),
  112. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{schooCode}") }))
  113. {
  114. exams.Add(item);
  115. }
  116. List<ExamInfo> newExams = new();
  117. //exams = exams.Where(x => x.period.id.Equals(periodId)).ToList();
  118. foreach (ExamInfo info in exams)
  119. {
  120. bool flag = true;
  121. foreach (string id in classIds)
  122. {
  123. if (!info.classes.Contains(id))
  124. {
  125. flag = false;
  126. }
  127. }
  128. if (flag) {
  129. newExams.Add(info);
  130. }
  131. }
  132. if (newExams.Count > 3) {
  133. newExams = newExams.Take(3).ToList();
  134. }
  135. List<string> examIds = newExams.Select(x => x.id).ToList();
  136. if (examIds.Count > 0) {
  137. List<ExamClassResult> classResults = new();
  138. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  139. queryText: $"select value(c) from c where c.examId in ({string.Join(",", examIds.Select(x => $"'{x}'"))})",
  140. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{schooCode}") }))
  141. {
  142. classResults.Add(item);
  143. }
  144. (List<RMember> rmembers, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classIds, schooCode);
  145. foreach (ExamInfo info in newExams)
  146. {
  147. double totalScore = info.papers.SelectMany(x => x.point).Sum();
  148. var classResult = classResults.Where(x => x.examId.Equals(info.id)).ToList();
  149. var classScores = classResult.GroupBy(x => x.info.id).Select(c => new { classId = c.Key, average = Math.Round(c.ToList().Sum(z => z.average) / info.subjects.Count / totalScore,2) }).ToList();
  150. List<(string className, double average)> classMore = new();
  151. foreach (var cs in classScores)
  152. {
  153. classMore.Add((cs.classId, cs.average));
  154. }
  155. var gradeScores = Math.Round(info.average / totalScore,2);
  156. List<(string sname, double scores, string classId)> stus = new();
  157. foreach (RMember member in rmembers)
  158. {
  159. double scroe = 0;
  160. foreach (ExamClassResult result in classResult)
  161. {
  162. if (result.studentIds.Contains(member.id))
  163. {
  164. int index = result.studentIds.IndexOf(member.id);
  165. scroe += result.sum[index];
  166. }
  167. }
  168. var persent = Math.Round(scroe * 1.0 / totalScore, 2);
  169. stus.Add((member.id, persent, member.classId));
  170. }
  171. grades.Add((info.name, classMore, gradeScores, stus));
  172. }
  173. }
  174. }
  175. }
  176. catch (Exception e)
  177. {
  178. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ExamService-getGradeScore()\n{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
  179. }
  180. return grades;
  181. }
  182. public static async Task<string> saveMoreAsync(CosmosClient client, DingDing _dingDing, ExamLite trExam)
  183. {
  184. try
  185. {
  186. trExam.ttl = -1;
  187. trExam.code = "ExamLite-" + trExam.school;
  188. trExam.scope = "school";
  189. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  190. trExam.createTime = now;
  191. if (trExam.publish == 1)
  192. {
  193. trExam.progress = "pending";
  194. }
  195. else
  196. {
  197. if (trExam.startTime > now)
  198. {
  199. trExam.progress = "pending";
  200. }
  201. else
  202. {
  203. trExam.progress = "going";
  204. }
  205. }
  206. if (string.IsNullOrEmpty(trExam.id))
  207. {
  208. trExam.id = Guid.NewGuid().ToString();
  209. await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(trExam, new PartitionKey($"{trExam.code}"));
  210. }
  211. else
  212. {
  213. await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync(trExam, new PartitionKey($"{trExam.code}"));
  214. }
  215. return trExam.id;
  216. }
  217. catch (Exception e)
  218. {
  219. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ExamService-saveMore\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  220. return "";
  221. }
  222. }
  223. public static async Task<(List<ExamInfo> datas, string continuationToken)> FindExam(JsonElement request, string id, string school, AzureCosmosFactory _azureCosmos)
  224. {
  225. List<ExamInfo> examInfo = new();
  226. try
  227. {
  228. var client = _azureCosmos.GetCosmosClient();
  229. string sub = string.Empty;
  230. string subject = string.Empty;
  231. /* if (request.TryGetProperty("subjectId", out JsonElement subjectId) && !string.IsNullOrWhiteSpace($"{subjectId}"))
  232. {
  233. sub = $" join A0 in c.subjects ";
  234. subject = $" and A0.id = '{subjectId}'";
  235. }*/
  236. StringBuilder stringBuilder = new($"select c.id,c.name,c.code,c.period,c.startTime,c.endTime,c.stuCount,c.type,c.progress,c.examType,c.createTime,c.source, c.subjects, c.grades,c.owner, c.scope,c.classes, c.stuLists, c.sRate,c.lostStu,c.sStatus,c.qamode,c.school,c.cloudas from c where (c.status<>404 or IS_DEFINED(c.status) = false) and c.pk = 'Exam'");
  237. //开始时间,
  238. if (request.TryGetProperty("stime", out JsonElement stime))
  239. {
  240. if (long.TryParse($"{stime}", out long data))
  241. {
  242. stringBuilder.Append($" and c.startTime >= {data} ");
  243. };
  244. };
  245. //默认当前时间
  246. var etimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  247. stringBuilder.Append($" and c.startTime <= {etimestamp} ");
  248. /*if (request.TryGetProperty("etime", out JsonElement etime))
  249. {
  250. if (long.TryParse($"{etime}", out long data))
  251. {
  252. stringBuilder.Append($" and c.createTime <= {data} ");
  253. };
  254. };*/
  255. string periodId = string.Empty;
  256. if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
  257. {
  258. stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
  259. }
  260. if (request.TryGetProperty("owner", out JsonElement owner) && !string.IsNullOrWhiteSpace($"{owner}"))
  261. {
  262. stringBuilder.Append($" and c.owner = '{owner}' ");
  263. }
  264. if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
  265. {
  266. stringBuilder.Append($" and c.source = '{source}' ");
  267. }
  268. if (request.TryGetProperty("type", out JsonElement type))
  269. {
  270. if (!type.ValueKind.Equals(JsonValueKind.Undefined) && !type.ValueKind.Equals(JsonValueKind.Null) && type.ValueKind.Equals(JsonValueKind.String))
  271. {
  272. stringBuilder.Append($" and c.pk = '{type}' ");
  273. }
  274. }
  275. stringBuilder.Append("order by c.createTime desc");
  276. //string token = null;
  277. string token = default;
  278. //默认不指定返回大小
  279. int? topcout = null;
  280. if (request.TryGetProperty("count", out JsonElement jcount))
  281. {
  282. if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
  283. {
  284. topcout = data;
  285. }
  286. }
  287. //是否需要进行分页查询,默认不分页
  288. bool iscontinuation = false;
  289. if (topcout != null && topcout.Value > 0)
  290. {
  291. iscontinuation = true;
  292. }
  293. //如果指定了返回大小
  294. if (request.TryGetProperty("continuationToken", out JsonElement token_1))
  295. {
  296. if (!token_1.ValueKind.Equals(JsonValueKind.Null) && token_1.ValueKind.Equals(JsonValueKind.String))
  297. {
  298. token = token_1.GetString();
  299. }
  300. }
  301. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout }))
  302. {
  303. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  304. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  305. {
  306. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  307. {
  308. examInfo.Add(obj.ToObject<ExamInfo>());
  309. }
  310. }
  311. if (iscontinuation)
  312. {
  313. token = item.GetContinuationToken();
  314. break;
  315. }
  316. }
  317. return (examInfo, token);
  318. }
  319. catch (Exception e)
  320. {
  321. return (examInfo,"500");
  322. }
  323. }
  324. /*
  325. public static async Task<string> getKnowledges(List<string> knowledges,List<ExamClassResult> answers ,string sub,List<List<string>> kones,List<double> point) {
  326. foreach (string k in knowledges)
  327. {
  328. double score = 0;
  329. double allScore = 0;
  330. int n = 0;
  331. int count = 0;
  332. foreach (ExamClassResult result in answers)
  333. {
  334. if (result.subjectId.Equals(sub))
  335. {
  336. foreach (List<string> str in kones)
  337. {
  338. if (str.Contains(k))
  339. {
  340. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  341. allScore += point.Count > 0 ? point[n] * itemPersent : 0;
  342. if (result.studentScores.Count > 0)
  343. {
  344. score += result.studentScores.Sum(r => r.Sum()) * itemPersent;
  345. }
  346. }
  347. n++;
  348. }
  349. count += result.studentIds.Count;
  350. }
  351. }
  352. double per = count > 0 ? Math.Round(score / count, 2) : 0;
  353. }
  354. }*/
  355. }
  356. }