ExamService.cs 19 KB

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