ExamController.cs 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  1. using Azure.Cosmos;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Dynamic;
  8. using System.IdentityModel.Tokens.Jwt;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Text.Json;
  13. using System.Threading.Tasks;
  14. using TEAMModelOS.Models;
  15. using TEAMModelOS.SDK.Models;
  16. using TEAMModelOS.SDK;
  17. using TEAMModelOS.SDK.Context.Constant.Common;
  18. using TEAMModelOS.SDK.DI;
  19. using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
  20. using TEAMModelOS.SDK.Extension;
  21. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  22. using TEAMModelOS.SDK.Helper.Common.StringHelper;
  23. using TEAMModelOS.SDK.Models.Cosmos.Common;
  24. namespace TEAMModelOS.Controllers
  25. {
  26. [ProducesResponseType(StatusCodes.Status200OK)]
  27. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  28. //[Authorize(Roles = "IES5")
  29. [Route("common/exam")]
  30. [ApiController]
  31. public class ExamController : ControllerBase
  32. {
  33. private readonly AzureCosmosFactory _azureCosmos;
  34. private readonly SnowflakeId _snowflakeId;
  35. private readonly AzureServiceBusFactory _serviceBus;
  36. private readonly DingDing _dingDing;
  37. private readonly Option _option;
  38. private readonly AzureStorageFactory _azureStorage;
  39. public ExamController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage)
  40. {
  41. _azureCosmos = azureCosmos;
  42. _serviceBus = serviceBus;
  43. _snowflakeId = snowflakeId;
  44. _dingDing = dingDing;
  45. _option = option?.Value;
  46. _azureStorage = azureStorage;
  47. }
  48. /// <summary>
  49. /// 保存考试信息
  50. /// </summary>
  51. /// <param name="request"></param>
  52. /// <returns></returns>
  53. [ProducesDefaultResponseType]
  54. //[AuthToken(Roles = "Teacher")]
  55. [HttpPost("save")]
  56. public async Task<IActionResult> Save(ExamInfo request)
  57. {
  58. try
  59. {
  60. //新增
  61. //string code = request.code;
  62. var client = _azureCosmos.GetCosmosClient();
  63. ExamInfo exam;
  64. string code = request.code;
  65. request.code = "Exam-" + request.code;
  66. request.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  67. int stuCount = 0;
  68. for (int i = 0; i < request.classes.Count; i++)
  69. {
  70. List<string> ids = new List<string>();
  71. //处理班级人数(公共部分的校本名单)
  72. //List<Student> students = new List<Student>();
  73. await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.classId = '{request.classes[i]}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{request.school}") }))
  74. {
  75. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  76. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  77. {
  78. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  79. while (accounts.MoveNext())
  80. {
  81. JsonElement account = accounts.Current;
  82. ids.Add(account.GetProperty("id").GetString());
  83. }
  84. }
  85. }
  86. if (request.scope.Equals("private"))
  87. {
  88. //处理发布对象为自选名单(个人)
  89. List<StuList> stuLists = new List<StuList>();
  90. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<StuList>(queryText: $"select value(c) from c where c.id = '{request.classes[i]}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
  91. {
  92. stuLists.Add(item);
  93. }
  94. if (stuLists.Count > 0) {
  95. foreach (StuList stuList in stuLists) {
  96. foreach (Students students in stuList.students) {
  97. if (students.code.Contains(code))
  98. {
  99. if (!ids.Contains(students.id))
  100. {
  101. ids.Add(students.id);
  102. }
  103. }
  104. else {
  105. ids.Add(students.id);
  106. }
  107. }
  108. if (stuList.tmids.Count > 0) {
  109. foreach (string tid in stuList.tmids) {
  110. ids.Add(tid);
  111. }
  112. }
  113. }
  114. }
  115. }
  116. else
  117. {
  118. //发布对象为自选名单(校本)
  119. List<StuList> stuLists = new List<StuList>();
  120. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<StuList>(queryText: $"select value(c) from c where c.id = '{request.classes[i]}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{request.school}") }))
  121. {
  122. stuLists.Add(item);
  123. }
  124. if (stuLists.Count > 0)
  125. {
  126. foreach (StuList stuList in stuLists)
  127. {
  128. foreach (Students students in stuList.students)
  129. {
  130. if (students.code.Contains(code))
  131. {
  132. if (!ids.Contains(students.id))
  133. {
  134. ids.Add(students.id);
  135. }
  136. }
  137. else
  138. {
  139. ids.Add(students.id);
  140. }
  141. }
  142. }
  143. }
  144. }
  145. stuCount += ids.Count;
  146. }
  147. request.stuCount = stuCount;
  148. if (string.IsNullOrEmpty(request.id))
  149. {
  150. request.id = Guid.NewGuid().ToString();
  151. request.progress = "pending";
  152. int n = 0;
  153. foreach (PaperSimple simple in request.papers) {
  154. simple.blob = "/exam/" + request.id + "/paper/" + request.subjects[n].id;
  155. n++;
  156. }
  157. //request.papers
  158. /*long SequenceNumber = await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.startTime);
  159. request.sequenceNumber = SequenceNumber;*/
  160. exam = await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
  161. //await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.startTime);
  162. //request.sequenceNumber = SequenceNumber;
  163. }
  164. else
  165. {
  166. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(request.id, new PartitionKey($"{request.code}"));
  167. if (info.progress.Equals("going"))
  168. {
  169. return Ok(new { v = "活动正在进行中" });
  170. }
  171. request.progress = info.progress;
  172. int n = 0;
  173. foreach (PaperSimple simple in request.papers)
  174. {
  175. simple.blob = "/exam/" + request.id + "/paper/" + request.subjects[n].id;
  176. n++;
  177. }
  178. /* await _serviceBus.GetServiceBusClient().cancelMessage(Constants.TopicName, info.sequenceNumber);
  179. long SequenceNumber = await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.startTime);
  180. request.sequenceNumber = SequenceNumber;*/
  181. exam = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
  182. //await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.startTime);
  183. }
  184. //Survey homeWork = await _azureCosmos.SaveOrUpdate<Survey>(request.survey);
  185. //设定结束时间
  186. //string msgEndId = _snowflakeId.NextId() + "";
  187. //await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.endTime);
  188. return Ok(new { exam });
  189. }
  190. catch (Exception ex)
  191. {
  192. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/save()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  193. return BadRequest();
  194. }
  195. }
  196. //TODO blob 批量删除
  197. /// <summary>
  198. /// 删除
  199. /// </summary>
  200. /// <param name="request"></param>
  201. /// <returns></returns>
  202. [ProducesDefaultResponseType]
  203. //[AuthToken(Roles = "Teacher")]
  204. [HttpPost("delete")]
  205. public async Task<IActionResult> Delete(JsonElement request)
  206. {
  207. /* ResponseBuilder builder = ResponseBuilder.custom();
  208. IdPk items = await _azureCosmos.DeleteAsync<ExamInfo>(request.id, request.pk);
  209. await _azureCosmos.DeleteAll<Paper>(new Dictionary<string, object>() { { "code", request.id } });
  210. return builder.Data(items).build();*/
  211. try
  212. {
  213. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  214. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  215. if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  216. var client = _azureCosmos.GetCosmosClient();
  217. //string school_code = code.ToString().Substring(typeof(ExamClassResult).Name.Length + 1);
  218. var response = await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
  219. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  220. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(queryText: $"select c.id from c where c.examId = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  221. {
  222. examClassResults.Add(item);
  223. }
  224. List<string> resultIds = new List<string>();
  225. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select c.id from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamResult-{id}") }))
  226. {
  227. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  228. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  229. {
  230. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  231. while (accounts.MoveNext())
  232. {
  233. JsonElement account = accounts.Current;
  234. resultIds.Add(account.GetProperty("id").GetString());
  235. }
  236. }
  237. }
  238. foreach (ExamClassResult classResult in examClassResults)
  239. {
  240. await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(classResult.id, new PartitionKey($"ExamClassResult-{code}"));
  241. }
  242. await client.GetContainer("TEAMModelOS", "Common").DeleteItemsStreamAsync(resultIds, $"ExamResult-{id}");
  243. /*foreach (ExamResult result in results)
  244. {
  245. await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(result.id, new PartitionKey($"ExamResult-{id}"));
  246. }*/
  247. //await _azureCosmos.DeleteAll(examClassResults);
  248. return Ok(new { id });
  249. }
  250. catch (Exception e)
  251. {
  252. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/delete()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  253. return BadRequest();
  254. }
  255. }
  256. /// <summary>
  257. /// 查询考试信息
  258. /// </summary>
  259. /// <param name="request"></param>
  260. /// <returns></returns>
  261. [ProducesDefaultResponseType]
  262. //[AuthToken(Roles = "Teacher")]
  263. [HttpPost("find")]
  264. public async Task<IActionResult> Find(JsonElement requert)
  265. {
  266. try
  267. {
  268. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  269. var query = $"select c.id,c.name,c.code,c.period,c.startTime,c.endTime,c.stuCount,c.type,c.progress,c.examType,c.createTime, c.subjects, c.grades, c.scope,c.classes from c ";
  270. if (requert.TryGetProperty("classIds", out JsonElement classIds)) {
  271. List<string> ids = classIds.ToObject<List<string>>();
  272. HashSet<string> strs = new HashSet<string>();
  273. if (ids.Count > 1)
  274. {
  275. foreach (string id in ids) {
  276. strs.Add($"array_contains(c.classes,'{id}')");
  277. }
  278. }
  279. else
  280. {
  281. string ssr = ids.Count > 0 ? ids[0] : "";
  282. strs.Add($"array_contains(c.classes,'{ssr}')");
  283. }
  284. string ss = string.Join(" or ", strs);
  285. query = $"select c.id,c.name,c.code,c.period,c.startTime,c.endTime,c.stuCount,c.type,c.progress,c.examType,c.createTime, c.subjects, c.grades, c.scope,c.classes from c where ({ss})";
  286. };
  287. var client = _azureCosmos.GetCosmosClient();
  288. List<ExamInfo> examInfo = new List<ExamInfo>();
  289. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{code}") }))
  290. {
  291. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  292. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  293. {
  294. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  295. {
  296. //obj.TryGetProperty("progress", out JsonElement progress);
  297. examInfo.Add(obj.ToObject<ExamInfo>());
  298. }
  299. }
  300. }
  301. //List<string> examIds = new List<string>();
  302. /* List<ExamResult> examResults = new List<ExamResult>();
  303. foreach (ExamInfo info in examInfos) {
  304. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamResult>(
  305. queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamResult-{info.id}") }))
  306. {
  307. examResults.Add(item);
  308. }
  309. }*/
  310. /* List<(string id, double scores)> listExamInfo = new List<(string id, double scores)>();
  311. foreach (ExamInfo info in examInfos)
  312. {
  313. //记录某次考试所有学生得分总分
  314. double score = 0;
  315. double allScore = 0;
  316. int stuCount = 0;
  317. foreach (ExamResult examResult in examResults) {
  318. if (info.id == examResult.examId) {
  319. foreach (List<double> sc in examResult.studentScores) {
  320. score += sc.Sum();
  321. }
  322. stuCount = examResult.studentIds.Count;
  323. }
  324. }
  325. double ascore = stuCount > 0 ? Math.Round(score * 0.1 / stuCount, 2) : 0;
  326. foreach (PaperSimple simple in info.papers) {
  327. allScore += simple.point.Sum();
  328. }
  329. listExamInfo.Add((info.id, (allScore> 0 ? ascore / allScore * 100: 0)));
  330. }
  331. var examInfo = examInfos.Select(o =>
  332. new
  333. {
  334. o.id,
  335. o.scope,
  336. o.stuCount,
  337. o.name,
  338. o.period,
  339. o.startTime,
  340. o.endTime,
  341. o.type,
  342. o.progress,
  343. o.examType,
  344. o.createTime,
  345. o.subjects,
  346. o.grades,
  347. o.classes,
  348. score = listExamInfo.FirstOrDefault(c => c.id == o.id).scores,
  349. }
  350. );*/
  351. return Ok(new { examInfo });
  352. }
  353. catch (Exception e)
  354. {
  355. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  356. return BadRequest();
  357. }
  358. }
  359. [ProducesDefaultResponseType]
  360. //[AuthToken(Roles = "Teacher")]
  361. [HttpPost("find-summary")]
  362. public async Task<IActionResult> FindSummary(JsonElement requert)
  363. {
  364. try
  365. {
  366. //ResponseBuilder builder = ResponseBuilder.custom();
  367. //if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
  368. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  369. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  370. //if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  371. //var jwt = new JwtSecurityToken(id_token.GetString());
  372. //if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
  373. //var id = jwt.Payload.Sub;
  374. var client = _azureCosmos.GetCosmosClient();
  375. List<ExamInfo> examInfo = new List<ExamInfo>();
  376. //var query = $"select value(c) from c ";
  377. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
  378. {
  379. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  380. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  381. {
  382. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  383. {
  384. //obj.TryGetProperty("progress", out JsonElement progress);
  385. examInfo.Add(obj.ToObject<ExamInfo>());
  386. }
  387. }
  388. }
  389. return Ok(new { examInfo });
  390. }
  391. catch (Exception e)
  392. {
  393. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/FindSummary()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  394. return BadRequest();
  395. }
  396. }
  397. /// <summary>
  398. /// 学生回答问题
  399. /// </summary>
  400. /// <param name="request"></param>
  401. /// <returns></returns>
  402. [ProducesDefaultResponseType]
  403. //[AuthToken(Roles = "Teacher")]
  404. [HttpPost("upsert-record")]
  405. public async Task<IActionResult> upsertRecord(JsonElement request)
  406. {
  407. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  408. //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  409. if (!request.TryGetProperty("answer", out JsonElement answer)) return BadRequest();
  410. if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  411. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  412. if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  413. if (!request.TryGetProperty("multipleRule", out JsonElement multipleRule)) return BadRequest();
  414. //if (!request.TryGetProperty("answers ", out JsonElement tandardAnswer)) return BadRequest();
  415. if (!request.TryGetProperty("paperId", out JsonElement paperId)) return BadRequest();
  416. //根据不同评测的类型返回对应的编码
  417. if (!request.TryGetProperty("code", out JsonElement school)) return BadRequest();
  418. if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
  419. try
  420. {
  421. List<string> ids = new List<string>();
  422. ids = classId.ToObject<List<string>>();
  423. var client = _azureCosmos.GetCosmosClient();
  424. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  425. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
  426. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id in ({string.Join(",", ids.Select(o => $"'{o}'"))})",
  427. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  428. {
  429. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  430. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  431. {
  432. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  433. {
  434. examClassResults.Add(obj.ToObject<ExamClassResult>());
  435. }
  436. }
  437. }
  438. ExamClassResult classResult = new ExamClassResult() ;
  439. List<PaperSimple> standerAnswers = new List<PaperSimple>();
  440. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
  441. queryText: $"select A0.point,A0.answers from c join A0 in c.papers where c.id = '{id}'and A0.id = '{paperId}'",
  442. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  443. {
  444. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  445. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  446. {
  447. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  448. {
  449. standerAnswers.Add(obj.ToObject<PaperSimple>());
  450. }
  451. }
  452. }
  453. List<List<string>> ans = answer.ToObject<List<List<string>>>();
  454. List<List<string>> standard = new List<List<string>>();
  455. List<double> points = new List<double>();
  456. int rule = int.Parse(multipleRule.ToString());
  457. foreach (PaperSimple simple in standerAnswers) {
  458. standard = simple.answers;
  459. points = simple.point;
  460. }
  461. List<Task<string>> tasks = new List<Task<string>>();
  462. foreach (ExamClassResult result in examClassResults) {
  463. int index = result.studentIds.IndexOf(studentId.ToString());
  464. //classResult.studentAnswers[index] = ans;
  465. if (index == -1)
  466. {
  467. List<double> ansPoint = new List<double>();
  468. foreach (List<string> num in standard)
  469. {
  470. //ans.Add(new List<string>());
  471. ansPoint.Add(-1);
  472. }
  473. result.studentIds.Add(studentId.ToString());
  474. result.studentScores.Add(ansPoint);
  475. result.studentAnswers.Add(new List<string>());
  476. result.sum.Add(0);
  477. }
  478. //int flagCount = 0;
  479. /*foreach (List<string> str in ans) {
  480. if (str.Count == 0) {
  481. flagCount++;
  482. }
  483. } */
  484. int newIndex = result.studentIds.IndexOf(studentId.ToString());
  485. /* if (flagCount != standard.Count)
  486. {*/
  487. StringBuilder builder = new StringBuilder();
  488. builder.Append(result.examId).Append("/");
  489. builder.Append(result.subjectId).Append("/");
  490. builder.Append(studentId).Append("/");
  491. builder.Append("ans.json");
  492. /*string FileName = result.examId + "/" + result.subjectId + "/" + studentId;
  493. string blob = FileName + "/" + "ans.json";*/
  494. tasks.Add(_azureStorage.UploadFileByContainer(school.ToString(), ans.ToJsonString(), "exam", builder.ToString(), false));
  495. result.studentAnswers[newIndex].Add(builder.ToString());
  496. //}
  497. for (int i = 0; i < ans.Count; i++)
  498. {
  499. //result.studentAnswers[index][i] = ans[i];
  500. //算分处理
  501. if (standard[i].Count > 0)
  502. {
  503. if (ans[i].Count == standard[i].Count && standard[i].Count == 1)
  504. {
  505. foreach (string right in ans[i])
  506. {
  507. if (standard[i].Contains(right))
  508. {
  509. result.studentScores[newIndex][i] = points[i];
  510. }
  511. else
  512. {
  513. result.studentScores[newIndex][i] = 0;
  514. }
  515. }
  516. }
  517. else
  518. {
  519. if (rule > 0)
  520. {
  521. int falseCount = 0;
  522. if (ans[i].Count > 0)
  523. {
  524. foreach (string obj in ans[i])
  525. {
  526. if (!standard[i].Contains(obj))
  527. {
  528. falseCount++;
  529. }
  530. }
  531. switch (rule)
  532. {
  533. case 1:
  534. if (ans[i].Count == standard[i].Count)
  535. {
  536. if (falseCount == 0)
  537. {
  538. result.studentScores[newIndex][i] = points[i];
  539. }
  540. else
  541. {
  542. result.studentScores[newIndex][i] = 0;
  543. }
  544. }
  545. else
  546. {
  547. result.studentScores[newIndex][i] = 0;
  548. }
  549. break;
  550. case 2:
  551. if (falseCount > 0)
  552. {
  553. result.studentScores[newIndex][i] = 0;
  554. }
  555. else
  556. {
  557. if (ans[i].Count == standard[i].Count)
  558. {
  559. result.studentScores[newIndex][i] = points[i];
  560. }
  561. else
  562. {
  563. result.studentScores[newIndex][i] = points[i] / 2;
  564. }
  565. }
  566. break;
  567. case 3:
  568. if (falseCount > 0)
  569. {
  570. result.studentScores[newIndex][i] = 0;
  571. }
  572. else
  573. {
  574. if (ans[i].Count == standard[i].Count)
  575. {
  576. result.studentScores[newIndex][i] = points[i];
  577. }
  578. else
  579. {
  580. result.studentScores[newIndex][i] = System.Math.Round((double)ans[i].Count / standard[i].Count * points[i], 1);
  581. }
  582. }
  583. break;
  584. case 4:
  585. if (ans[i].Count == standard[i].Count)
  586. {
  587. result.studentScores[newIndex][i] = points[i];
  588. }
  589. else
  590. {
  591. double persent = (double)(standard[i].Count - 2 * falseCount) / standard[i].Count;
  592. if (persent <= 0)
  593. {
  594. result.studentScores[newIndex][i] = 0;
  595. }
  596. else
  597. {
  598. result.studentScores[newIndex][i] = System.Math.Round(persent * points[i], 1);
  599. }
  600. }
  601. break;
  602. }
  603. }
  604. else {
  605. result.studentScores[newIndex][i] = 0;
  606. }
  607. }
  608. }
  609. }
  610. }
  611. /*if (result.studentScores.Contains(-1)) {
  612. }*/
  613. bool flag = true;
  614. foreach (List<double> scores in result.studentScores)
  615. {
  616. foreach (double score in scores)
  617. {
  618. if (score == -1)
  619. {
  620. flag = false;
  621. break;
  622. }
  623. }
  624. }
  625. if (flag)
  626. {
  627. ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{scode}"));
  628. result.progress = true;
  629. exam.subjects.ForEach(s =>
  630. {
  631. if (s.id.Equals(subjectId.ToString()))
  632. {
  633. s.classCount += 1;
  634. }
  635. });
  636. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{scode}"));
  637. }
  638. result.sum[newIndex] = result.studentScores[newIndex].Sum();
  639. classResult = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  640. }
  641. await Task.WhenAll(tasks);
  642. return Ok(new { classResult });
  643. }
  644. catch (Exception e)
  645. {
  646. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecord()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  647. return BadRequest();
  648. }
  649. }
  650. [ProducesDefaultResponseType]
  651. //[AuthToken(Roles = "Teacher")]
  652. [HttpPost("upsert-record-by-teacher")]
  653. public async Task<IActionResult> upsertRecordByTeacher(JsonElement request)
  654. {
  655. //ResponseBuilder builder = ResponseBuilder.custom();
  656. try
  657. {
  658. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  659. //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  660. if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
  661. if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  662. if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  663. //此参数表明此次操作对象为个人还是校本的评测内容
  664. if (!request.TryGetProperty("code", out JsonElement school)) return BadRequest();
  665. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  666. //要先处理状态,判断卷子是否存在,并判断卷子归属的考试是否允许再次提交
  667. //List<ExamInfo> exams = await _azureCosmos.FindByDict<ExamInfo>(new Dictionary<string, object> { { "id", request.examCode } });
  668. List<double> ans = point.ToObject<List<double>>();
  669. var client = _azureCosmos.GetCosmosClient();
  670. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  671. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
  672. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
  673. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  674. {
  675. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  676. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  677. {
  678. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  679. {
  680. examClassResults.Add(obj.ToObject<ExamClassResult>());
  681. }
  682. }
  683. }
  684. ExamClassResult classResult = new ExamClassResult();
  685. //ExamInfo classResult = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
  686. //ExamClassResult classResult = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamClassResult>(id.ToString(), new PartitionKey($"{code}"));
  687. /*foreach (double index in ans) {
  688. classResult.studentScores.in
  689. }*/
  690. foreach (ExamClassResult result in examClassResults) {
  691. int index = result.studentIds.IndexOf(studentId.ToString());
  692. for (int i = 0; i < ans.Count; i++)
  693. {
  694. result.studentScores[index][i] = ans[i];
  695. }
  696. if (!result.progress)
  697. {
  698. bool flag = true;
  699. foreach (List<double> scores in result.studentScores)
  700. {
  701. foreach (double score in scores)
  702. {
  703. if (score == -1)
  704. {
  705. flag = false;
  706. break;
  707. }
  708. }
  709. }
  710. if (flag)
  711. {
  712. ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{school}"));
  713. result.progress = true;
  714. exam.subjects.ForEach(s =>
  715. {
  716. if (s.id.Equals(subjectId.ToString()))
  717. {
  718. s.classCount += 1;
  719. }
  720. });
  721. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{school}"));
  722. }
  723. }
  724. else
  725. {
  726. ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{school}"));
  727. exam.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  728. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{school}"));
  729. }
  730. result.sum[index] = result.studentScores[index].Sum();
  731. classResult = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  732. }
  733. return Ok(new { classResult });
  734. }
  735. catch (Exception ex)
  736. {
  737. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecordByTeacher()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  738. return BadRequest();
  739. }
  740. /*if (exams.IsNotEmpty())
  741. {
  742. ExamInfo examInfo = exams[0];
  743. //提交答案时间必须是状态已发布,且时间在起止时间内
  744. if (examInfo.startTime <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && examInfo.status == 200 &&
  745. examInfo.endTime >= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
  746. {
  747. return builder.Data(await _azureCosmos.SaveOrUpdate(request)).build();
  748. }
  749. else
  750. {
  751. return builder.Error(ResponseCode.FAILED, "请在作答时间段内提交答案!").build();
  752. }
  753. }
  754. else
  755. {
  756. return builder.Error(ResponseCode.DATA_EXIST, "考试不存在!").build();
  757. }*/
  758. }
  759. /// <summary>
  760. /// 查询评测详细信息(教师或者学生通用)
  761. /// </summary>
  762. /// <param name="request"></param>
  763. /// <returns></returns>
  764. [ProducesDefaultResponseType]
  765. //[AuthToken(Roles = "Teacher")]
  766. [HttpPost("find-summary-record")]
  767. public async Task<IActionResult> findSummaryRecord(JsonElement requert)
  768. {
  769. //var (id, school) = HttpContext.GetAuthTokenInfo();
  770. try
  771. {
  772. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  773. //if (!requert.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
  774. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  775. if (!requert.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
  776. if (!requert.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  777. // 如果只有学生id则返回学生参加过的考试 只返回相关摘要信息
  778. var client = _azureCosmos.GetCosmosClient();
  779. //string code = school_code.ToString().Substring(5);
  780. //ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{school_code}"));
  781. List<object> examClassResults = new List<object>();
  782. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select c.id, c.code,c.info,c.studentIds,c.studentAnswers,c.studentScores from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
  783. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school_code}") }))
  784. {
  785. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  786. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  787. {
  788. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  789. {
  790. examClassResults.Add(obj.ToObject<object>());
  791. }
  792. }
  793. }
  794. /*if (StringHelper.getKeyCount(requert) == 1 && requert.TryGetProperty("code", out JsonElement code))
  795. {
  796. List<object> props = new List<object>();
  797. await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: $"select c.id, c.code, c.examCode, c.status ,c.mark, c.score from c where c.id = {id}", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamRecord-{school_code}") }))
  798. {
  799. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  800. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  801. {
  802. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  803. {
  804. props.Add(obj.ToObject<object>());
  805. }
  806. }
  807. }
  808. return Ok(new { props });
  809. }
  810. else
  811. {
  812. if (requert.TryGetProperty("examCode", out JsonElement _))
  813. {
  814. //List<string> props = new List<string> { "id", "code", "examCode", "status", "mark", "score" };
  815. //List<ExamRecord> examRecords = await _azureCosmos.FindByDict<ExamRecord>(request, props);
  816. //return builder.Data(examRecords).Extend(new Dictionary<string, object> { { "props", props } }).build();
  817. List<object> props = new List<object>();
  818. await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: $"select c.id, c.code, c.examCode, c.status ,c.mark, c.score from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamRecord-{school_code}") }))
  819. {
  820. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  821. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  822. {
  823. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  824. {
  825. props.Add(obj.ToObject<object>());
  826. }
  827. }
  828. }
  829. return Ok(new { props });
  830. }
  831. }*/
  832. return Ok(new { examClassResults });
  833. }
  834. catch (Exception ex)
  835. {
  836. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findSummaryRecord()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  837. return BadRequest();
  838. }
  839. }
  840. //学生端查询评测列表
  841. [ProducesDefaultResponseType]
  842. //[AuthToken(Roles = "Student")]
  843. [HttpPost("find-summary-by-student")]
  844. public async Task<IActionResult> findSummaryStudent(JsonElement requert)
  845. {
  846. //ResponseBuilder builder = ResponseBuilder.custom();
  847. //var (id, school) = HttpContext.GetAuthTokenInfo();
  848. try
  849. {
  850. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  851. //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  852. if (!requert.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  853. if (!requert.TryGetProperty("code", out JsonElement school)) return BadRequest();
  854. if(!requert.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
  855. var client = _azureCosmos.GetCosmosClient();
  856. var query = $"select c.id,c.code,c.progress,A0.id paperId,A0.code paperCode,A0.name paperName,A0.multipleRule,A0.scope,A0.blob from c join A0 in c.papers where c.id ='{id}'";
  857. List<object> papers = new List<object>();
  858. List<object> subjects = new List<object>();
  859. List<string> classIds = new List<string>();
  860. //存放当前学生所在班级ID或者名单ID
  861. HashSet<string> resultIds = new HashSet<string>();
  862. //List<string> ids = new List<string>();
  863. //处理班级人数(公共部分的校本名单)
  864. //List<Student> students = new List<Student>();
  865. await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: $"select c.classId id from c where c.id = '{studentId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{school}") }))
  866. {
  867. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  868. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  869. {
  870. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  871. while (accounts.MoveNext())
  872. {
  873. JsonElement account = accounts.Current;
  874. resultIds.Add(account.GetProperty("id").GetString());
  875. }
  876. }
  877. }
  878. //获取自定义名单信息
  879. List<StuList> stuLists = new List<StuList>();
  880. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<StuList>(queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}'" ,
  881. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
  882. {
  883. stuLists.Add(item);
  884. }
  885. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<StuList>(queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}'",
  886. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{school}") }))
  887. {
  888. stuLists.Add(item);
  889. }
  890. if (stuLists.Count > 0)
  891. {
  892. foreach (StuList stuList in stuLists)
  893. {
  894. resultIds.Add(stuList.id);
  895. }
  896. }
  897. var queryClassId = $"select c.classes id from c where c.id ='{id}'";
  898. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: queryClassId, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  899. {
  900. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  901. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  902. {
  903. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  904. {
  905. classIds = obj.GetProperty("id").ToObject<List<string>>();
  906. //classIds = obj.ToObject<List<string>>();
  907. }
  908. }
  909. }
  910. //存放该学生所在班级参与当前评测的ID
  911. List<string> infoIds = new List<string>();
  912. foreach (string ids in resultIds)
  913. {
  914. if (classIds.Contains(ids))
  915. {
  916. infoIds.Add(ids);
  917. }
  918. }
  919. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  920. {
  921. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  922. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  923. {
  924. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  925. {
  926. papers.Add(obj.ToObject<object>());
  927. }
  928. }
  929. }
  930. var querySubject = $"select A0.id,A0.name from c join A0 in c.subjects where c.id ='{id}'";
  931. //List<object> props = new List<object>();
  932. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: querySubject, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  933. {
  934. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  935. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  936. {
  937. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  938. {
  939. subjects.Add(obj.ToObject<object>());
  940. }
  941. }
  942. }
  943. var queryAnswers = $"select c.id,c.code,c.studentIds,c.subjectId,c.studentAnswers,c.studentScores,c.sum from c where c.examId ='{id}' and array_contains(c.studentIds,'{studentId}') and c.pk = 'ExamClassResult' ";
  944. List<ExamClassResult> answers = new List<ExamClassResult>();
  945. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: queryAnswers,
  946. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  947. {
  948. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  949. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  950. {
  951. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  952. {
  953. answers.Add(obj.ToObject<ExamClassResult>());
  954. }
  955. }
  956. }
  957. List<List<string>> stuAns = new List<List<string>>();
  958. List<List<double>> stuScore = new List<List<double>>();
  959. List<double> total = new List<double>();
  960. if (answers.Count > 0)
  961. {
  962. foreach (ExamClassResult result in answers) {
  963. int index = result.studentIds.IndexOf(studentId.ToString());
  964. if (index == -1)
  965. {
  966. break;
  967. }
  968. stuAns.Add(result.studentAnswers[index]);
  969. stuScore.Add(result.studentScores[index]);
  970. total.Add(result.sum.Where(s => s <= 59).Count());
  971. total.Add(result.sum.Where(s => s > 59 && s <= 70 ).Count());
  972. total.Add(result.sum.Where(s => s > 70 && s <= 80).Count());
  973. total.Add(result.sum.Where(s => s > 80 && s <= 90).Count());
  974. total.Add(result.sum.Where(s => s > 90 && s <= 100).Count());
  975. }
  976. }
  977. return Ok(new { papers, subjects,stuScore, stuAns, total,claId = infoIds });
  978. }
  979. catch (Exception ex)
  980. {
  981. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-summary-by-student()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  982. return BadRequest();
  983. }
  984. }
  985. //查询学生活动列表
  986. [ProducesDefaultResponseType]
  987. //[AuthToken(Roles = "Student")]
  988. [HttpPost("find-all-by-student")]
  989. public async Task<IActionResult> findAllStudent(JsonElement requert)
  990. {
  991. //ResponseBuilder builder = ResponseBuilder.custom();
  992. //var (id, school) = HttpContext.GetAuthTokenInfo();
  993. try
  994. {
  995. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  996. if (!requert.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  997. List<string> resultIds = new List<string>();
  998. var client = _azureCosmos.GetCosmosClient();
  999. //查询校本班级ID
  1000. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(
  1001. queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
  1002. {
  1003. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1004. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1005. {
  1006. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1007. while (accounts.MoveNext())
  1008. {
  1009. JsonElement account = accounts.Current;
  1010. resultIds.Add(account.GetProperty("id").GetString());
  1011. }
  1012. }
  1013. }
  1014. //查询私人班级ID
  1015. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(
  1016. queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
  1017. {
  1018. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1019. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1020. {
  1021. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1022. while (accounts.MoveNext())
  1023. {
  1024. JsonElement account = accounts.Current;
  1025. resultIds.Add(account.GetProperty("id").GetString());
  1026. }
  1027. }
  1028. }
  1029. //StringBuilder builder = new StringBuilder();
  1030. HashSet<string> strs = new HashSet<string>();
  1031. if (resultIds.Count > 1)
  1032. {
  1033. foreach (string str in resultIds)
  1034. {
  1035. strs.Add($"array_contains(c.classes,'{str}')");
  1036. //builder.Append($"array_contains(c.targetClassIds,'{str}')").Append("or");
  1037. }
  1038. //builder.ToString().Substring(0, builder.ToString().Length - 2);
  1039. }
  1040. else {
  1041. string ssr = resultIds.Count > 0 ? resultIds[0] : "";
  1042. strs.Add($"array_contains(c.classes,'{ssr}')");
  1043. //builder.Append($" array_contains(c.targetClassIds,'{ssr}')");
  1044. }
  1045. string ss = string.Join(" or ", strs);
  1046. //if (!requert.TryGetProperty("school", out JsonElement school)) return BadRequest();
  1047. var query = $"select c.id,c.code,c.name,c.startTime,c.endTime,c.type,c.progress,c.school,c.scope from c where ({ss}) and c.progress != 'pending' ";
  1048. List<object> props = new List<object>();
  1049. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query))
  1050. {
  1051. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1052. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1053. {
  1054. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1055. {
  1056. props.Add(obj.ToObject<object>());
  1057. }
  1058. }
  1059. }
  1060. var queryClass = $"select c.examId,c.subjectId,c.studentIds,c.studentAnswers,c.studentScores from c where array_contains(c.studentIds,'{studentId}') and c.pk = 'ExamClassResult'";
  1061. List<ExamClassResult> Classes = new List<ExamClassResult>();
  1062. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: queryClass))
  1063. {
  1064. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1065. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1066. {
  1067. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1068. {
  1069. Classes.Add(obj.ToObject<ExamClassResult>());
  1070. }
  1071. }
  1072. }
  1073. List<ExamClassResult> result = new List<ExamClassResult>();
  1074. foreach (ExamClassResult classResult in Classes) {
  1075. int index = classResult.studentIds.IndexOf(studentId.ToString());
  1076. ExamClassResult result1 = new ExamClassResult();
  1077. result1.examId = classResult.examId;
  1078. result1.subjectId = classResult.subjectId;
  1079. result1.studentAnswers.Add(classResult.studentAnswers[index]);
  1080. result1.studentScores.Add(classResult.studentScores[index]);
  1081. result.Add(result1);
  1082. }
  1083. return Ok(new {props, result });
  1084. }
  1085. catch (Exception ex)
  1086. {
  1087. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1088. return BadRequest();
  1089. }
  1090. }
  1091. //查询学生活动列表
  1092. [ProducesDefaultResponseType]
  1093. //[AuthToken(Roles = "Student")]
  1094. [HttpPost("find-score-by-student")]
  1095. public async Task<IActionResult> findScoreByStudent(JsonElement requert)
  1096. {
  1097. //ResponseBuilder builder = ResponseBuilder.custom();
  1098. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1099. try
  1100. {
  1101. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1102. //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1103. var client = _azureCosmos.GetCosmosClient();
  1104. var query = $"select c.examId,c.subjectId,c.studentScores from c where array_contains(c.studentIds,'{id}') ";
  1105. List<object> props = new List<object>();
  1106. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query))
  1107. {
  1108. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1109. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1110. {
  1111. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1112. {
  1113. props.Add(obj.ToObject<object>());
  1114. }
  1115. }
  1116. }
  1117. return Ok(props);
  1118. }
  1119. catch (Exception ex)
  1120. {
  1121. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1122. return BadRequest();
  1123. }
  1124. }
  1125. //查询学生活动列表
  1126. [ProducesDefaultResponseType]
  1127. //[AuthToken(Roles = "Student")]
  1128. [HttpPost("finish")]
  1129. public async Task<IActionResult> finish(JsonElement requert)
  1130. {
  1131. //ResponseBuilder builder = ResponseBuilder.custom();
  1132. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1133. try
  1134. {
  1135. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1136. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1137. var client = _azureCosmos.GetCosmosClient();
  1138. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1139. info.progress = "finish";
  1140. info = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  1141. return Ok(info);
  1142. }
  1143. catch (Exception ex)
  1144. {
  1145. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/finish\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1146. return BadRequest();
  1147. }
  1148. }
  1149. }
  1150. }