ExamController.cs 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768
  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. using TEAMModelOS.SDK.Models.Table;
  25. using Azure.Messaging.ServiceBus;
  26. using Microsoft.Extensions.Configuration;
  27. using TEAMModelOS.Filter;
  28. namespace TEAMModelOS.Controllers
  29. {
  30. [ProducesResponseType(StatusCodes.Status200OK)]
  31. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  32. //[Authorize(Roles = "IES5")
  33. [Route("common/exam")]
  34. [ApiController]
  35. public class ExamController : ControllerBase
  36. {
  37. private readonly AzureCosmosFactory _azureCosmos;
  38. private readonly SnowflakeId _snowflakeId;
  39. private readonly AzureServiceBusFactory _serviceBus;
  40. private readonly DingDing _dingDing;
  41. private readonly Option _option;
  42. private readonly AzureStorageFactory _azureStorage;
  43. private readonly AzureRedisFactory _azureRedis;
  44. public IConfiguration _configuration { get; set; }
  45. public ExamController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
  46. IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration)
  47. {
  48. _azureCosmos = azureCosmos;
  49. _serviceBus = serviceBus;
  50. _snowflakeId = snowflakeId;
  51. _dingDing = dingDing;
  52. _option = option?.Value;
  53. _azureStorage = azureStorage;
  54. _azureRedis = azureRedis;
  55. _configuration = configuration;
  56. }
  57. /// <summary>
  58. /// 保存考试信息
  59. /// </summary>
  60. /// <param name="request"></param>
  61. /// <returns></returns>
  62. [ProducesDefaultResponseType]
  63. [AuthToken(Roles = "Teacher")]
  64. [HttpPost("save")]
  65. public async Task<IActionResult> Save(ExamInfo request)
  66. {
  67. try
  68. {
  69. //新增
  70. //string code = request.code;
  71. var client = _azureCosmos.GetCosmosClient();
  72. ExamInfo exam;
  73. string code = request.code;
  74. request.ttl = -1;
  75. request.code = "Exam-" + request.code;
  76. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  77. request.createTime = now;
  78. if (request.startTime <= 0)
  79. {
  80. request.startTime = now;
  81. }
  82. int stuCount = 0;
  83. for (int i = 0; i < request.classes.Count; i++)
  84. {
  85. List<string> ids = new List<string>();
  86. //处理班级人数(公共部分的校本名单)
  87. //List<Student> students = new List<Student>();
  88. 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}") }))
  89. {
  90. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  91. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  92. {
  93. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  94. while (accounts.MoveNext())
  95. {
  96. JsonElement account = accounts.Current;
  97. ids.Add(account.GetProperty("id").GetString());
  98. }
  99. }
  100. }
  101. if (request.scope.Equals("private"))
  102. {
  103. //处理发布对象为自选名单(个人)
  104. List<StuList> stuLists = new List<StuList>();
  105. 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") }))
  106. {
  107. stuLists.Add(item);
  108. }
  109. if (stuLists.Count > 0)
  110. {
  111. foreach (StuList stuList in stuLists)
  112. {
  113. foreach (Students students in stuList.students)
  114. {
  115. if (students.code.Contains(code))
  116. {
  117. if (!ids.Contains(students.id))
  118. {
  119. ids.Add(students.id);
  120. }
  121. }
  122. else
  123. {
  124. ids.Add(students.id);
  125. }
  126. }
  127. if (stuList.tmids.Count > 0)
  128. {
  129. foreach (string tid in stuList.tmids)
  130. {
  131. ids.Add(tid);
  132. }
  133. }
  134. }
  135. }
  136. }
  137. else
  138. {
  139. //request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  140. //发布对象为自选名单(校本)
  141. List<StuList> stuLists = new List<StuList>();
  142. 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}") }))
  143. {
  144. stuLists.Add(item);
  145. }
  146. if (stuLists.Count > 0)
  147. {
  148. foreach (StuList stuList in stuLists)
  149. {
  150. foreach (Students students in stuList.students)
  151. {
  152. if (students.code.Contains(code))
  153. {
  154. if (!ids.Contains(students.id))
  155. {
  156. ids.Add(students.id);
  157. }
  158. }
  159. else
  160. {
  161. ids.Add(students.id);
  162. }
  163. }
  164. }
  165. }
  166. }
  167. stuCount += ids.Count;
  168. }
  169. request.stuCount = stuCount;
  170. if (string.IsNullOrEmpty(request.id))
  171. {
  172. request.id = Guid.NewGuid().ToString();
  173. if (request.startTime > now)
  174. {
  175. request.progress = "pending";
  176. }
  177. else
  178. {
  179. request.progress = "going";
  180. }
  181. var messageBlob = new ServiceBusMessage();
  182. if (request.scope.Equals("school"))
  183. {
  184. request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  185. messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "insert", root = $"exam/{request.id}", name = request.school }.ToJsonString());
  186. }
  187. else
  188. {
  189. request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
  190. messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "insert", root = $"exam/{request.id}", name = request.creatorId }.ToJsonString());
  191. }
  192. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  193. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  194. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  195. int n = 0;
  196. foreach (PaperSimple simple in request.papers)
  197. {
  198. simple.blob = "/exam/" + request.id + "/paper/" + request.subjects[n].id;
  199. n++;
  200. }
  201. //request.papers
  202. /*long SequenceNumber = await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.startTime);
  203. request.sequenceNumber = SequenceNumber;*/
  204. //await _azureStorage.GetBlobContainerClient("hbcn").GetBlobsCatalogSize($"exam/{request.id}");
  205. exam = await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
  206. //await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.startTime);
  207. //request.sequenceNumber = SequenceNumber;
  208. }
  209. else
  210. {
  211. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(request.id, new PartitionKey($"{request.code}"));
  212. if (info.progress.Equals("going"))
  213. {
  214. return Ok(new { v = "活动正在进行中" });
  215. }
  216. var messageBlob = new ServiceBusMessage();
  217. if (request.scope.Equals("school"))
  218. {
  219. request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  220. messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = $"exam/{request.id}", name = request.school }.ToJsonString());
  221. }
  222. else
  223. {
  224. request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
  225. messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = $"exam/{request.id}", name = request.creatorId }.ToJsonString());
  226. }
  227. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  228. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  229. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  230. request.progress = info.progress;
  231. int n = 0;
  232. foreach (PaperSimple simple in request.papers)
  233. {
  234. simple.blob = "/exam/" + request.id + "/paper/" + request.subjects[n].id;
  235. n++;
  236. }
  237. /* await _serviceBus.GetServiceBusClient().cancelMessage(Constants.TopicName, info.sequenceNumber);
  238. long SequenceNumber = await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.startTime);
  239. request.sequenceNumber = SequenceNumber;*/
  240. exam = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
  241. //await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.startTime);
  242. }
  243. //Survey homeWork = await _azureCosmos.SaveOrUpdate<Survey>(request.survey);
  244. //设定结束时间
  245. //string msgEndId = _snowflakeId.NextId() + "";
  246. //await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.endTime);
  247. return Ok(new { exam });
  248. }
  249. catch (Exception ex)
  250. {
  251. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/save()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  252. return BadRequest();
  253. }
  254. }
  255. //TODO blob 批量删除
  256. /// <summary>
  257. /// 删除
  258. /// </summary>
  259. /// <param name="request"></param>
  260. /// <returns></returns>
  261. [ProducesDefaultResponseType]
  262. //[AuthToken(Roles = "Teacher")]
  263. [HttpPost("delete")]
  264. public async Task<IActionResult> Delete(JsonElement request)
  265. {
  266. /* ResponseBuilder builder = ResponseBuilder.custom();
  267. IdPk items = await _azureCosmos.DeleteAsync<ExamInfo>(request.id, request.pk);
  268. await _azureCosmos.DeleteAll<Paper>(new Dictionary<string, object>() { { "code", request.id } });
  269. return builder.Data(items).build();*/
  270. try
  271. {
  272. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  273. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  274. if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  275. var client = _azureCosmos.GetCosmosClient();
  276. //string school_code = code.ToString().Substring(typeof(ExamClassResult).Name.Length + 1);
  277. var response = await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
  278. //删除blob 相关资料
  279. await _azureStorage.GetBlobServiceClient().DelectBlobs(code.ToString(), $"exam/{id}");
  280. //通知评测删除信息
  281. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "delete", root = $"exam/{id}", name = $"{code}" }.ToJsonString());
  282. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  283. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  284. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  285. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  286. 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}") }))
  287. {
  288. examClassResults.Add(item);
  289. }
  290. List<string> resultIds = new List<string>();
  291. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select c.id from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamResult-{id}") }))
  292. {
  293. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  294. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  295. {
  296. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  297. while (accounts.MoveNext())
  298. {
  299. JsonElement account = accounts.Current;
  300. resultIds.Add(account.GetProperty("id").GetString());
  301. }
  302. }
  303. }
  304. foreach (ExamClassResult classResult in examClassResults)
  305. {
  306. await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(classResult.id, new PartitionKey($"ExamClassResult-{code}"));
  307. }
  308. await client.GetContainer("TEAMModelOS", "Common").DeleteItemsStreamAsync(resultIds, $"ExamResult-{id}");
  309. /*foreach (ExamResult result in results)
  310. {
  311. await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(result.id, new PartitionKey($"ExamResult-{id}"));
  312. }*/
  313. //await _azureCosmos.DeleteAll(examClassResults);
  314. return Ok(new { id });
  315. }
  316. catch (Exception e)
  317. {
  318. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/delete()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  319. return BadRequest();
  320. }
  321. }
  322. /// <summary>
  323. /// 查询考试信息
  324. /// </summary>
  325. /// <param name="request"></param>
  326. /// <returns></returns>
  327. [ProducesDefaultResponseType]
  328. //[AuthToken(Roles = "Teacher")]
  329. [HttpPost("find")]
  330. public async Task<IActionResult> Find(JsonElement requert)
  331. {
  332. try
  333. {
  334. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  335. var client = _azureCosmos.GetCosmosClient();
  336. List<SchoolYear> years = await _azureStorage.FindListByDict<SchoolYear>(new Dictionary<string, object>() { { "RowKey", code }, { "PartitionKey", "Exam" } });
  337. int year = 0;
  338. if (years.Count > 0)
  339. {
  340. year = years[0].year;
  341. }
  342. else
  343. {
  344. long ct = 0;
  345. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: "SELECT top 1 c.createTime FROM c order by c.createTime ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{code}") }))
  346. {
  347. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  348. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  349. {
  350. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  351. while (accounts.MoveNext())
  352. {
  353. JsonElement account = accounts.Current;
  354. ct = account.GetProperty("createTime").GetInt64();
  355. }
  356. }
  357. }
  358. year = DateTimeOffset.FromUnixTimeMilliseconds(ct).Year;
  359. SchoolYear sy = new()
  360. {
  361. RowKey = code.ToString(),
  362. PartitionKey = "Exam",
  363. year = year
  364. };
  365. await _azureStorage.Save<SchoolYear>(sy);
  366. }
  367. 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.source, c.subjects, c.grades, c.scope,c.classes,c.sRate,c.lostStu from c ";
  368. if (requert.TryGetProperty("classIds", out JsonElement classIds))
  369. {
  370. List<string> ids = classIds.ToObject<List<string>>();
  371. HashSet<string> strs = new HashSet<string>();
  372. if (ids.Count > 1)
  373. {
  374. foreach (string id in ids)
  375. {
  376. strs.Add($"array_contains(c.classes,'{id}')");
  377. }
  378. }
  379. else
  380. {
  381. string ssr = ids.Count > 0 ? ids[0] : "";
  382. strs.Add($"array_contains(c.classes,'{ssr}')");
  383. }
  384. string ss = string.Join(" or ", strs);
  385. 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.source,c.subjects, c.grades, c.scope,c.classes,c.sRate,c.lostStu from c where ({ss})";
  386. };
  387. string continuationToken = string.Empty;
  388. string token = default;
  389. //是否需要进行分页查询,默认不分页
  390. bool iscontinuation = false;
  391. if (requert.TryGetProperty("token", out JsonElement token_1))
  392. {
  393. token = token_1.GetString();
  394. iscontinuation = true;
  395. };
  396. //默认不指定返回大小
  397. int? topcout = null;
  398. if (requert.TryGetProperty("count", out JsonElement jcount))
  399. {
  400. if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
  401. {
  402. topcout = data;
  403. }
  404. }
  405. List<ExamInfo> examInfo = new List<ExamInfo>();
  406. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"Exam-{code}") }))
  407. {
  408. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  409. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  410. {
  411. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  412. {
  413. //obj.TryGetProperty("progress", out JsonElement progress);
  414. examInfo.Add(obj.ToObject<ExamInfo>());
  415. }
  416. }
  417. if (iscontinuation)
  418. {
  419. continuationToken = item.GetContinuationToken();
  420. break;
  421. }
  422. }
  423. //List<string> examIds = new List<string>();
  424. /* List<ExamResult> examResults = new List<ExamResult>();
  425. foreach (ExamInfo info in examInfos) {
  426. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamResult>(
  427. queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamResult-{info.id}") }))
  428. {
  429. examResults.Add(item);
  430. }
  431. }*/
  432. /* List<(string id, double scores)> listExamInfo = new List<(string id, double scores)>();
  433. foreach (ExamInfo info in examInfos)
  434. {
  435. //记录某次考试所有学生得分总分
  436. double score = 0;
  437. double allScore = 0;
  438. int stuCount = 0;
  439. foreach (ExamResult examResult in examResults) {
  440. if (info.id == examResult.examId) {
  441. foreach (List<double> sc in examResult.studentScores) {
  442. score += sc.Sum();
  443. }
  444. stuCount = examResult.studentIds.Count;
  445. }
  446. }
  447. double ascore = stuCount > 0 ? Math.Round(score * 0.1 / stuCount, 2) : 0;
  448. foreach (PaperSimple simple in info.papers) {
  449. allScore += simple.point.Sum();
  450. }
  451. listExamInfo.Add((info.id, (allScore> 0 ? ascore / allScore * 100: 0)));
  452. }
  453. var examInfo = examInfos.Select(o =>
  454. new
  455. {
  456. o.id,
  457. o.scope,
  458. o.stuCount,
  459. o.name,
  460. o.period,
  461. o.startTime,
  462. o.endTime,
  463. o.type,
  464. o.progress,
  465. o.examType,
  466. o.createTime,
  467. o.subjects,
  468. o.grades,
  469. o.classes,
  470. score = listExamInfo.FirstOrDefault(c => c.id == o.id).scores,
  471. }
  472. );*/
  473. return Ok(new { examInfo, token = continuationToken, year });
  474. }
  475. catch (Exception e)
  476. {
  477. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  478. return BadRequest();
  479. }
  480. }
  481. [ProducesDefaultResponseType]
  482. //[AuthToken(Roles = "Teacher")]
  483. [HttpPost("find-summary")]
  484. public async Task<IActionResult> FindSummary(JsonElement requert)
  485. {
  486. try
  487. {
  488. //ResponseBuilder builder = ResponseBuilder.custom();
  489. //if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
  490. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  491. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  492. //if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  493. //var jwt = new JwtSecurityToken(id_token.GetString());
  494. //if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
  495. //var id = jwt.Payload.Sub;
  496. var client = _azureCosmos.GetCosmosClient();
  497. List<ExamInfo> examInfo = new List<ExamInfo>();
  498. //var query = $"select value(c) from c ";
  499. 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}") }))
  500. {
  501. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  502. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  503. {
  504. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  505. {
  506. //obj.TryGetProperty("progress", out JsonElement progress);
  507. examInfo.Add(obj.ToObject<ExamInfo>());
  508. }
  509. }
  510. }
  511. return Ok(new { examInfo });
  512. }
  513. catch (Exception e)
  514. {
  515. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/FindSummary()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  516. return BadRequest();
  517. }
  518. }
  519. /// <summary>
  520. /// 学生回答问题
  521. /// </summary>
  522. /// <param name="request"></param>
  523. /// <returns></returns>
  524. [ProducesDefaultResponseType]
  525. //[AuthToken(Roles = "Teacher")]
  526. [HttpPost("upsert-record")]
  527. public async Task<IActionResult> upsertRecord(JsonElement request)
  528. {
  529. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  530. //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  531. if (!request.TryGetProperty("answer", out JsonElement answer)) return BadRequest();
  532. if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  533. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  534. if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  535. if (!request.TryGetProperty("multipleRule", out JsonElement multipleRule)) return BadRequest();
  536. //if (!request.TryGetProperty("answers ", out JsonElement tandardAnswer)) return BadRequest();
  537. if (!request.TryGetProperty("paperId", out JsonElement paperId)) return BadRequest();
  538. //根据不同评测的类型返回对应的编码
  539. if (!request.TryGetProperty("code", out JsonElement school)) return BadRequest();
  540. if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
  541. try
  542. {
  543. List<string> ids = new List<string>();
  544. ids = classId.ToObject<List<string>>();
  545. var client = _azureCosmos.GetCosmosClient();
  546. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  547. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
  548. 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}'"))})",
  549. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  550. {
  551. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  552. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  553. {
  554. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  555. {
  556. examClassResults.Add(obj.ToObject<ExamClassResult>());
  557. }
  558. }
  559. }
  560. ExamClassResult classResult = new ExamClassResult();
  561. List<PaperSimple> standerAnswers = new List<PaperSimple>();
  562. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
  563. queryText: $"select A0.point,A0.answers from c join A0 in c.papers where c.id = '{id}'and A0.id = '{paperId}'",
  564. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  565. {
  566. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  567. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  568. {
  569. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  570. {
  571. standerAnswers.Add(obj.ToObject<PaperSimple>());
  572. }
  573. }
  574. }
  575. List<List<string>> ans = answer.ToObject<List<List<string>>>();
  576. List<List<string>> standard = new List<List<string>>();
  577. List<double> points = new List<double>();
  578. int rule = int.Parse(multipleRule.ToString());
  579. foreach (PaperSimple simple in standerAnswers)
  580. {
  581. standard = simple.answers;
  582. points = simple.point;
  583. }
  584. List<Task<string>> tasks = new List<Task<string>>();
  585. foreach (ExamClassResult result in examClassResults)
  586. {
  587. int index = result.studentIds.IndexOf(studentId.ToString());
  588. //存放客观题作答详情
  589. if (result.ans.Count == 0)
  590. {
  591. foreach (string cc in result.studentIds)
  592. {
  593. List<List<string>> anc = new List<List<string>>();
  594. foreach (List<string> opc in standard)
  595. {
  596. anc.Add(new List<string>());
  597. }
  598. result.ans.Add(anc);
  599. }
  600. }
  601. //List<List<string>> oq = new List<List<string>>();
  602. //classResult.studentAnswers[index] = ans;
  603. if (index == -1)
  604. {
  605. List<double> ansPoint = new List<double>();
  606. foreach (List<string> num in standard)
  607. {
  608. //ans.Add(new List<string>());
  609. ansPoint.Add(-1);
  610. }
  611. result.studentIds.Add(studentId.ToString());
  612. result.studentScores.Add(ansPoint);
  613. result.studentAnswers.Add(new List<string>());
  614. result.sum.Add(0);
  615. }
  616. //int flagCount = 0;
  617. /*foreach (List<string> str in ans) {
  618. if (str.Count == 0) {
  619. flagCount++;
  620. }
  621. } */
  622. int newIndex = result.studentIds.IndexOf(studentId.ToString());
  623. /* if (flagCount != standard.Count)
  624. {*/
  625. StringBuilder builder = new StringBuilder();
  626. builder.Append(result.examId).Append("/");
  627. builder.Append(result.subjectId).Append("/");
  628. builder.Append(studentId).Append("/");
  629. builder.Append("ans.json");
  630. /*string FileName = result.examId + "/" + result.subjectId + "/" + studentId;
  631. string blob = FileName + "/" + "ans.json";*/
  632. tasks.Add(_azureStorage.UploadFileByContainer(school.ToString(), ans.ToJsonString(), "exam", builder.ToString(), false));
  633. result.studentAnswers[newIndex].Add(builder.ToString());
  634. //}
  635. //List<(int index ,string content, double count)> acount = new List<(int index,string content, double count)>();
  636. for (int i = 0; i < ans.Count; i++)
  637. {
  638. //List<string> op = new List<string>();
  639. var ac = ans[i].Count;
  640. var sc = standard[i].Count;
  641. //记录次数
  642. int n = 0;
  643. //result.studentAnswers[index][i] = ans[i];
  644. //算分处理
  645. if (sc > 0)
  646. {
  647. result.ans[index][i] = ans[i];
  648. if (ac == sc && sc == 1)
  649. {
  650. foreach (string right in ans[i])
  651. {
  652. if (standard[i].Contains(right))
  653. {
  654. result.studentScores[newIndex][i] = points[i];
  655. }
  656. else
  657. {
  658. result.studentScores[newIndex][i] = 0;
  659. }
  660. }
  661. }
  662. else
  663. {
  664. if (rule > 0)
  665. {
  666. int falseCount = 0;
  667. if (ac > 0)
  668. {
  669. foreach (string obj in ans[i])
  670. {
  671. if (!standard[i].Contains(obj))
  672. {
  673. falseCount++;
  674. }
  675. }
  676. switch (rule)
  677. {
  678. case 1:
  679. if (ac == sc)
  680. {
  681. if (falseCount == 0)
  682. {
  683. result.studentScores[newIndex][i] = points[i];
  684. }
  685. else
  686. {
  687. result.studentScores[newIndex][i] = 0;
  688. }
  689. }
  690. else
  691. {
  692. result.studentScores[newIndex][i] = 0;
  693. }
  694. break;
  695. case 2:
  696. if (falseCount > 0)
  697. {
  698. result.studentScores[newIndex][i] = 0;
  699. }
  700. else
  701. {
  702. if (ac == sc)
  703. {
  704. result.studentScores[newIndex][i] = points[i];
  705. }
  706. else
  707. {
  708. result.studentScores[newIndex][i] = points[i] / 2;
  709. }
  710. }
  711. break;
  712. case 3:
  713. if (falseCount > 0)
  714. {
  715. result.studentScores[newIndex][i] = 0;
  716. }
  717. else
  718. {
  719. if (ac == sc)
  720. {
  721. result.studentScores[newIndex][i] = points[i];
  722. }
  723. else
  724. {
  725. result.studentScores[newIndex][i] = System.Math.Round((double)ac / sc * points[i], 1);
  726. }
  727. }
  728. break;
  729. case 4:
  730. if (ac == sc)
  731. {
  732. result.studentScores[newIndex][i] = points[i];
  733. }
  734. else
  735. {
  736. double persent = (double)(sc - 2 * falseCount) / sc;
  737. if (persent <= 0)
  738. {
  739. result.studentScores[newIndex][i] = 0;
  740. }
  741. else
  742. {
  743. result.studentScores[newIndex][i] = System.Math.Round(persent * points[i], 1);
  744. }
  745. }
  746. break;
  747. }
  748. }
  749. else
  750. {
  751. result.studentScores[newIndex][i] = 0;
  752. }
  753. }
  754. }
  755. }
  756. }
  757. /*if (result.studentScores.Contains(-1)) {
  758. }*/
  759. bool flag = true;
  760. foreach (List<double> scores in result.studentScores)
  761. {
  762. foreach (double score in scores)
  763. {
  764. if (score == -1)
  765. {
  766. flag = false;
  767. break;
  768. }
  769. }
  770. }
  771. if (flag)
  772. {
  773. ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{scode}"));
  774. result.progress = true;
  775. /*//标记单科单班总得分
  776. double score = 0;
  777. //标准差
  778. double powSum = 0;
  779. var scount = result.studentIds.Count;
  780. foreach (List<double> sc in result.studentScores) {
  781. score += sc.Sum();
  782. }
  783. foreach (string sid in result.studentIds) {
  784. double ssc = result.studentScores[result.studentIds.IndexOf(sid)].Sum();
  785. powSum += Math.Pow(ssc - scount > 0 ? Math.Round(score * 1.0 / scount, 2) : 0, 2);
  786. }
  787. result.standard = Math.Round(scount > 0 ? Math.Pow(powSum / scount, 0.5) : 0, 2);
  788. result.average = scount > 0 ? Math.Round(score / scount, 2) : 0;*/
  789. exam.subjects.ForEach(s =>
  790. {
  791. if (s.id.Equals(subjectId.ToString()))
  792. {
  793. s.classCount += 1;
  794. }
  795. });
  796. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{scode}"));
  797. }
  798. result.sum[newIndex] = result.studentScores[newIndex].Sum();
  799. classResult = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  800. }
  801. await Task.WhenAll(tasks);
  802. return Ok(new { classResult });
  803. }
  804. catch (Exception e)
  805. {
  806. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecord()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  807. return BadRequest();
  808. }
  809. }
  810. [ProducesDefaultResponseType]
  811. //[AuthToken(Roles = "Teacher")]
  812. [HttpPost("upsert-record-by-teacher")]
  813. public async Task<IActionResult> upsertRecordByTeacher(JsonElement request)
  814. {
  815. //ResponseBuilder builder = ResponseBuilder.custom();
  816. try
  817. {
  818. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  819. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  820. if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
  821. if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  822. //if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  823. //此参数表明此次操作对象为个人还是校本的评测内容
  824. if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
  825. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  826. //要先处理状态,判断卷子是否存在,并判断卷子归属的考试是否允许再次提交
  827. //List<ExamInfo> exams = await _azureCosmos.FindByDict<ExamInfo>(new Dictionary<string, object> { { "id", request.examCode } });
  828. List<double> ans = point.ToObject<List<double>>();
  829. var client = _azureCosmos.GetCosmosClient();
  830. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  831. if (request.TryGetProperty("classId", out JsonElement classId))
  832. {
  833. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  834. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
  835. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  836. {
  837. examClassResults.Add(item);
  838. }
  839. }
  840. else
  841. {
  842. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  843. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and array_contains(c.studentIds,'{studentId}')",
  844. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  845. {
  846. examClassResults.Add(item);
  847. }
  848. }
  849. ExamClassResult classResult = new ExamClassResult();
  850. //ExamInfo classResult = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
  851. //ExamClassResult classResult = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamClassResult>(id.ToString(), new PartitionKey($"{code}"));
  852. /*foreach (double index in ans) {
  853. classResult.studentScores.in
  854. }*/
  855. foreach (ExamClassResult result in examClassResults)
  856. {
  857. int index = result.studentIds.IndexOf(studentId.ToString());
  858. for (int i = 0; i < ans.Count; i++)
  859. {
  860. result.studentScores[index][i] = ans[i];
  861. }
  862. if (!result.progress)
  863. {
  864. bool flag = true;
  865. foreach (List<double> scores in result.studentScores)
  866. {
  867. foreach (double score in scores)
  868. {
  869. if (score == -1)
  870. {
  871. flag = false;
  872. break;
  873. }
  874. }
  875. }
  876. if (flag)
  877. {
  878. ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  879. result.progress = true;
  880. exam.subjects.ForEach(s =>
  881. {
  882. if (s.id.Equals(subjectId.ToString()))
  883. {
  884. s.classCount += 1;
  885. }
  886. });
  887. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
  888. }
  889. }
  890. else
  891. {
  892. ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  893. exam.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  894. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
  895. }
  896. result.sum[index] = result.studentScores[index].Sum();
  897. classResult = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  898. }
  899. return Ok(new { classResult });
  900. }
  901. catch (Exception ex)
  902. {
  903. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecordByTeacher()\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  904. return BadRequest();
  905. }
  906. /*if (exams.IsNotEmpty())
  907. {
  908. ExamInfo examInfo = exams[0];
  909. //提交答案时间必须是状态已发布,且时间在起止时间内
  910. if (examInfo.startTime <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && examInfo.status == 200 &&
  911. examInfo.endTime >= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
  912. {
  913. return builder.Data(await _azureCosmos.SaveOrUpdate(request)).build();
  914. }
  915. else
  916. {
  917. return builder.Error(ResponseCode.FAILED, "请在作答时间段内提交答案!").build();
  918. }
  919. }
  920. else
  921. {
  922. return builder.Error(ResponseCode.DATA_EXIST, "考试不存在!").build();
  923. }*/
  924. }
  925. /// <summary>
  926. /// 查询评测详细信息(教师或者学生通用)
  927. /// </summary>
  928. /// <param name="request"></param>
  929. /// <returns></returns>
  930. [ProducesDefaultResponseType]
  931. //[AuthToken(Roles = "Teacher")]
  932. [HttpPost("find-summary-record")]
  933. public async Task<IActionResult> findSummaryRecord(JsonElement requert)
  934. {
  935. //var (id, school) = HttpContext.GetAuthTokenInfo();
  936. try
  937. {
  938. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  939. //if (!requert.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
  940. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  941. if (!requert.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
  942. if (!requert.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  943. // 如果只有学生id则返回学生参加过的考试 只返回相关摘要信息
  944. var client = _azureCosmos.GetCosmosClient();
  945. //string code = school_code.ToString().Substring(5);
  946. //ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{school_code}"));
  947. List<object> examClassResults = new List<object>();
  948. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select c.id, c.code,c.info,c.studentIds,c.studentAnswers,c.studentScores,c.mark from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
  949. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school_code}") }))
  950. {
  951. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  952. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  953. {
  954. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  955. {
  956. examClassResults.Add(obj.ToObject<object>());
  957. }
  958. }
  959. }
  960. /*if (StringHelper.getKeyCount(requert) == 1 && requert.TryGetProperty("code", out JsonElement code))
  961. {
  962. List<object> props = new List<object>();
  963. 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}") }))
  964. {
  965. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  966. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  967. {
  968. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  969. {
  970. props.Add(obj.ToObject<object>());
  971. }
  972. }
  973. }
  974. return Ok(new { props });
  975. }
  976. else
  977. {
  978. if (requert.TryGetProperty("examCode", out JsonElement _))
  979. {
  980. //List<string> props = new List<string> { "id", "code", "examCode", "status", "mark", "score" };
  981. //List<ExamRecord> examRecords = await _azureCosmos.FindByDict<ExamRecord>(request, props);
  982. //return builder.Data(examRecords).Extend(new Dictionary<string, object> { { "props", props } }).build();
  983. List<object> props = new List<object>();
  984. 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}") }))
  985. {
  986. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  987. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  988. {
  989. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  990. {
  991. props.Add(obj.ToObject<object>());
  992. }
  993. }
  994. }
  995. return Ok(new { props });
  996. }
  997. }*/
  998. return Ok(new { examClassResults });
  999. }
  1000. catch (Exception ex)
  1001. {
  1002. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findSummaryRecord()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1003. return BadRequest();
  1004. }
  1005. }
  1006. //学生端查询评测列表
  1007. [ProducesDefaultResponseType]
  1008. //[AuthToken(Roles = "Student")]
  1009. [HttpPost("find-summary-by-student")]
  1010. public async Task<IActionResult> findSummaryStudent(JsonElement requert)
  1011. {
  1012. //ResponseBuilder builder = ResponseBuilder.custom();
  1013. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1014. try
  1015. {
  1016. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1017. //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1018. if (!requert.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  1019. if (!requert.TryGetProperty("code", out JsonElement school)) return BadRequest();
  1020. if (!requert.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
  1021. var client = _azureCosmos.GetCosmosClient();
  1022. var query = $"select c.id,c.code,c.school,c.creatorId,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}'";
  1023. List<object> papers = new List<object>();
  1024. List<object> subjects = new List<object>();
  1025. List<string> classIds = new List<string>();
  1026. //存放当前学生所在班级ID或者名单ID
  1027. HashSet<string> resultIds = new HashSet<string>();
  1028. //List<string> ids = new List<string>();
  1029. //处理班级人数(公共部分的校本名单)
  1030. //List<Student> students = new List<Student>();
  1031. 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}") }))
  1032. {
  1033. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1034. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1035. {
  1036. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1037. while (accounts.MoveNext())
  1038. {
  1039. JsonElement account = accounts.Current;
  1040. resultIds.Add(account.GetProperty("id").GetString());
  1041. }
  1042. }
  1043. }
  1044. //获取自定义名单信息
  1045. List<StuList> stuLists = new List<StuList>();
  1046. 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}'",
  1047. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
  1048. {
  1049. stuLists.Add(item);
  1050. }
  1051. 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}'",
  1052. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{school}") }))
  1053. {
  1054. stuLists.Add(item);
  1055. }
  1056. if (stuLists.Count > 0)
  1057. {
  1058. foreach (StuList stuList in stuLists)
  1059. {
  1060. resultIds.Add(stuList.id);
  1061. }
  1062. }
  1063. var queryClassId = $"select c.classes id from c where c.id ='{id}'";
  1064. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: queryClassId, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  1065. {
  1066. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1067. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1068. {
  1069. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1070. {
  1071. classIds = obj.GetProperty("id").ToObject<List<string>>();
  1072. //classIds = obj.ToObject<List<string>>();
  1073. }
  1074. }
  1075. }
  1076. //存放该学生所在班级参与当前评测的ID
  1077. List<string> infoIds = new List<string>();
  1078. foreach (string ids in resultIds)
  1079. {
  1080. if (classIds.Contains(ids))
  1081. {
  1082. infoIds.Add(ids);
  1083. }
  1084. }
  1085. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  1086. {
  1087. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1088. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1089. {
  1090. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1091. {
  1092. papers.Add(obj.ToObject<object>());
  1093. }
  1094. }
  1095. }
  1096. var querySubject = $"select A0.id,A0.name from c join A0 in c.subjects where c.id ='{id}'";
  1097. //List<object> props = new List<object>();
  1098. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: querySubject, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  1099. {
  1100. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1101. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1102. {
  1103. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1104. {
  1105. subjects.Add(obj.ToObject<object>());
  1106. }
  1107. }
  1108. }
  1109. var queryAnswers = $"select c.id,c.code,c.studentIds,c.subjectId,c.studentAnswers,c.studentScores,c.sum,c.mark from c where c.examId ='{id}' and array_contains(c.studentIds,'{studentId}') and c.pk = 'ExamClassResult' ";
  1110. List<ExamClassResult> answers = new List<ExamClassResult>();
  1111. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: queryAnswers,
  1112. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  1113. {
  1114. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1115. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1116. {
  1117. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1118. {
  1119. answers.Add(obj.ToObject<ExamClassResult>());
  1120. }
  1121. }
  1122. }
  1123. List<List<string>> stuAns = new List<List<string>>();
  1124. List<List<double>> stuScore = new List<List<double>>();
  1125. List<string> mark = new List<string>();
  1126. List<double> total = new List<double>();
  1127. if (answers.Count > 0)
  1128. {
  1129. foreach (ExamClassResult result in answers)
  1130. {
  1131. int index = result.studentIds.IndexOf(studentId.ToString());
  1132. if (index == -1)
  1133. {
  1134. break;
  1135. }
  1136. stuAns.Add(result.studentAnswers[index]);
  1137. stuScore.Add(result.studentScores[index]);
  1138. if (result.mark.Count > 0)
  1139. {
  1140. mark.Add(result.mark[index]);
  1141. }
  1142. total.Add(result.sum.Where(s => s <= 59).Count());
  1143. total.Add(result.sum.Where(s => s > 59 && s <= 70).Count());
  1144. total.Add(result.sum.Where(s => s > 70 && s <= 80).Count());
  1145. total.Add(result.sum.Where(s => s > 80 && s <= 90).Count());
  1146. total.Add(result.sum.Where(s => s > 90 && s <= 100).Count());
  1147. }
  1148. }
  1149. if (papers.IsNotEmpty())
  1150. {
  1151. return Ok(new { papers, subjects, stuScore, stuAns, mark, total, claId = infoIds, status = 200 });
  1152. }
  1153. else {
  1154. return Ok(new { papers, subjects, stuScore, stuAns, mark, total, claId = infoIds,status=404 });
  1155. }
  1156. }
  1157. catch (Exception ex)
  1158. {
  1159. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-summary-by-student()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1160. return Ok(new { status = 400 });
  1161. }
  1162. }
  1163. //查询学生活动列表
  1164. [ProducesDefaultResponseType]
  1165. //[AuthToken(Roles = "Student")]
  1166. [HttpPost("find-all-by-student")]
  1167. public async Task<IActionResult> findAllStudent(JsonElement requert)
  1168. {
  1169. //ResponseBuilder builder = ResponseBuilder.custom();
  1170. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1171. try
  1172. {
  1173. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1174. if (!requert.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  1175. List<string> resultIds = new List<string>();
  1176. var client = _azureCosmos.GetCosmosClient();
  1177. //查询校本班级ID
  1178. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(
  1179. queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
  1180. {
  1181. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1182. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1183. {
  1184. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1185. while (accounts.MoveNext())
  1186. {
  1187. JsonElement account = accounts.Current;
  1188. resultIds.Add(account.GetProperty("id").GetString());
  1189. }
  1190. }
  1191. }
  1192. //查询私人班级ID
  1193. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(
  1194. queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
  1195. {
  1196. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1197. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1198. {
  1199. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1200. while (accounts.MoveNext())
  1201. {
  1202. JsonElement account = accounts.Current;
  1203. resultIds.Add(account.GetProperty("id").GetString());
  1204. }
  1205. }
  1206. }
  1207. //StringBuilder builder = new StringBuilder();
  1208. HashSet<string> strs = new HashSet<string>();
  1209. if (resultIds.Count > 1)
  1210. {
  1211. foreach (string str in resultIds)
  1212. {
  1213. strs.Add($"array_contains(c.classes,'{str}')");
  1214. //builder.Append($"array_contains(c.targetClassIds,'{str}')").Append("or");
  1215. }
  1216. //builder.ToString().Substring(0, builder.ToString().Length - 2);
  1217. }
  1218. else
  1219. {
  1220. string ssr = resultIds.Count > 0 ? resultIds[0] : "";
  1221. strs.Add($"array_contains(c.classes,'{ssr}')");
  1222. //builder.Append($" array_contains(c.targetClassIds,'{ssr}')");
  1223. }
  1224. string ss = string.Join(" or ", strs);
  1225. //if (!requert.TryGetProperty("school", out JsonElement school)) return BadRequest();
  1226. 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' ";
  1227. List<object> props = new List<object>();
  1228. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query))
  1229. {
  1230. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1231. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1232. {
  1233. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1234. {
  1235. props.Add(obj.ToObject<object>());
  1236. }
  1237. }
  1238. }
  1239. 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'";
  1240. List<ExamClassResult> Classes = new List<ExamClassResult>();
  1241. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: queryClass))
  1242. {
  1243. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1244. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1245. {
  1246. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1247. {
  1248. Classes.Add(obj.ToObject<ExamClassResult>());
  1249. }
  1250. }
  1251. }
  1252. List<ExamClassResult> result = new List<ExamClassResult>();
  1253. foreach (ExamClassResult classResult in Classes)
  1254. {
  1255. int index = classResult.studentIds.IndexOf(studentId.ToString());
  1256. ExamClassResult result1 = new ExamClassResult();
  1257. result1.examId = classResult.examId;
  1258. result1.subjectId = classResult.subjectId;
  1259. result1.studentAnswers.Add(classResult.studentAnswers[index]);
  1260. result1.studentScores.Add(classResult.studentScores[index]);
  1261. result.Add(result1);
  1262. }
  1263. return Ok(new { props, result });
  1264. }
  1265. catch (Exception ex)
  1266. {
  1267. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1268. return BadRequest();
  1269. }
  1270. }
  1271. //查询学生活动列表
  1272. [ProducesDefaultResponseType]
  1273. //[AuthToken(Roles = "Student")]
  1274. [HttpPost("find-score-by-student")]
  1275. public async Task<IActionResult> findScoreByStudent(JsonElement requert)
  1276. {
  1277. //ResponseBuilder builder = ResponseBuilder.custom();
  1278. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1279. try
  1280. {
  1281. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1282. //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1283. var client = _azureCosmos.GetCosmosClient();
  1284. var query = $"select c.examId,c.subjectId,c.studentScores from c where array_contains(c.studentIds,'{id}') ";
  1285. List<object> props = new List<object>();
  1286. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query))
  1287. {
  1288. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1289. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1290. {
  1291. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1292. {
  1293. props.Add(obj.ToObject<object>());
  1294. }
  1295. }
  1296. }
  1297. return Ok(props);
  1298. }
  1299. catch (Exception ex)
  1300. {
  1301. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1302. return BadRequest();
  1303. }
  1304. }
  1305. //查询学生活动列表
  1306. [ProducesDefaultResponseType]
  1307. //[AuthToken(Roles = "Student")]
  1308. [HttpPost("finish")]
  1309. public async Task<IActionResult> finish(JsonElement requert)
  1310. {
  1311. //ResponseBuilder builder = ResponseBuilder.custom();
  1312. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1313. try
  1314. {
  1315. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1316. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1317. var client = _azureCosmos.GetCosmosClient();
  1318. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1319. info.progress = "finish";
  1320. info.endTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1321. List<ExamClassResult> classResults = new();
  1322. if (info.scope.Equals("school"))
  1323. {
  1324. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1325. queryText: $"select value(c) from c where c.examId = '{id}'",
  1326. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  1327. {
  1328. classResults.Add(item);
  1329. }
  1330. }
  1331. else
  1332. {
  1333. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1334. queryText: $"select value(c) from c where c.examId = '{id}'",
  1335. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  1336. {
  1337. classResults.Add(item);
  1338. }
  1339. }
  1340. foreach (ExamClassResult examClass in classResults)
  1341. {
  1342. examClass.progress = true;
  1343. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(examClass, examClass.id, new PartitionKey($"{examClass.code}"));
  1344. }
  1345. info = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  1346. return Ok(info);
  1347. }
  1348. catch (Exception ex)
  1349. {
  1350. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/finish\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1351. return BadRequest();
  1352. }
  1353. }
  1354. /*//查询任务列表
  1355. [ProducesDefaultResponseType]
  1356. //[AuthToken(Roles = "Student")]
  1357. [HttpPost("scoring")]
  1358. public async Task<IActionResult> Scoring(JsonElement requert)
  1359. {
  1360. //ResponseBuilder builder = ResponseBuilder.custom();
  1361. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1362. try
  1363. {
  1364. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1365. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1366. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1367. var client = _azureCosmos.GetCosmosClient();
  1368. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1369. int index = 0;
  1370. foreach (ExamSubject subject in info.subjects) {
  1371. if (!subject.id.Equals(subjectId.ToString()))
  1372. {
  1373. index++;
  1374. }
  1375. else {
  1376. break;
  1377. }
  1378. }
  1379. List<string> stuAns = new();
  1380. Dictionary<string, List<List<double>>> keyValues = new();
  1381. List<ExamClassResult> classResults = new();
  1382. if (info.scope.Equals("school"))
  1383. {
  1384. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1385. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1386. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  1387. {
  1388. classResults.Add(item);
  1389. }
  1390. }
  1391. else
  1392. {
  1393. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1394. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1395. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  1396. {
  1397. classResults.Add(item);
  1398. }
  1399. }
  1400. List<List<double>> itemScore = new();
  1401. for (int i = 0; i < info.papers[index].point.Count; i++)
  1402. {
  1403. List<double> score = new();
  1404. foreach (ExamClassResult examClass in classResults)
  1405. {
  1406. foreach (List<double> sc in examClass.studentScores)
  1407. {
  1408. score.Add(sc[i]);
  1409. }
  1410. }
  1411. itemScore.Add(score);
  1412. }
  1413. foreach (ExamClassResult examClass in classResults)
  1414. {
  1415. foreach (List<string> ans in examClass.studentAnswers)
  1416. {
  1417. if (ans.Count > 0)
  1418. {
  1419. stuAns.Add(ans[0]);
  1420. }
  1421. else
  1422. {
  1423. stuAns.Add("");
  1424. }
  1425. }
  1426. }
  1427. //info = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  1428. return Ok(new { score = itemScore , stuAns, paper = info.papers });
  1429. }
  1430. catch (Exception ex)
  1431. {
  1432. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1433. return BadRequest();
  1434. }
  1435. }*/
  1436. [ProducesDefaultResponseType]
  1437. //[AuthToken(Roles = "Student")]
  1438. [HttpPost("scoring")]
  1439. public async Task<IActionResult> scoring(JsonElement requert)
  1440. {
  1441. //ResponseBuilder builder = ResponseBuilder.custom();
  1442. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1443. try
  1444. {
  1445. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1446. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1447. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1448. if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  1449. var client = _azureCosmos.GetCosmosClient();
  1450. var redisClient = _azureRedis.GetRedisClient(8);
  1451. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1452. List<ExamClassResult> classResults = new();
  1453. List<dynamic> attr = new List<dynamic>();
  1454. //List<dynamic> all = new List<dynamic>();
  1455. var record = await redisClient.HashGetAllAsync($"Exam:Scoring:{id}-{subjectId}");
  1456. foreach (var rcd in record)
  1457. {
  1458. var value = JsonDocument.Parse(rcd.Value.ToString());
  1459. value.RootElement.TryGetProperty("tmdId", out JsonElement tmdId);
  1460. if (tId.ToString().Equals(tmdId.ToString()))
  1461. {
  1462. attr.Add(new { stuId = rcd.Name.ToString(), info = value });
  1463. }
  1464. }
  1465. int index = 0;
  1466. foreach (ExamSubject subject in info.subjects)
  1467. {
  1468. if (!subject.id.Equals(subjectId.ToString()))
  1469. {
  1470. index++;
  1471. }
  1472. else
  1473. {
  1474. break;
  1475. }
  1476. }
  1477. return Ok(new { attr, paper = info.papers[index].blob });
  1478. }
  1479. catch (Exception ex)
  1480. {
  1481. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1482. return BadRequest();
  1483. }
  1484. }
  1485. //批阅,给老师随机分配阅卷数据,以及查询改老师已有的阅卷数据
  1486. [ProducesDefaultResponseType]
  1487. //[AuthToken(Roles = "Student")]
  1488. [HttpPost("review")]
  1489. public async Task<IActionResult> Review(JsonElement requert)
  1490. {
  1491. //ResponseBuilder builder = ResponseBuilder.custom();
  1492. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1493. try
  1494. {
  1495. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1496. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1497. if (!requert.TryGetProperty("count", out JsonElement count)) return BadRequest();
  1498. if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  1499. var client = _azureCosmos.GetCosmosClient();
  1500. var redisClient = _azureRedis.GetRedisClient(8);
  1501. List<ExamClassResult> classResults = new();
  1502. List<dynamic> recs = new List<dynamic>();
  1503. List<dynamic> all = new List<dynamic>();
  1504. var record = await redisClient.HashGetAllAsync($"Exam:Scoring:{id}-{subjectId}");
  1505. foreach (var rcd in record)
  1506. {
  1507. var value = JsonDocument.Parse(rcd.Value.ToString());
  1508. value.RootElement.TryGetProperty("tmdId", out JsonElement tmdId);
  1509. if (tId.ToString().Equals(tmdId.ToString()))
  1510. {
  1511. recs.Add(new { stuId = rcd.Name.ToString(), ans = value });
  1512. }
  1513. if (string.IsNullOrEmpty(tmdId.ToString()))
  1514. {
  1515. all.Add(new { stuId = rcd.Name.ToString(), ans = value });
  1516. }
  1517. }
  1518. if (requert.TryGetProperty("stuId", out JsonElement stuId))
  1519. {
  1520. var stuAns = await redisClient.HashGetAsync($"Exam:Scoring:{id}-{subjectId}", stuId.ToString());
  1521. var value = JsonDocument.Parse(stuAns.ToString());
  1522. //保证此学生与该老师绑定
  1523. value.RootElement.TryGetProperty("ans", out JsonElement blob);
  1524. value.RootElement.TryGetProperty("score", out JsonElement sc);
  1525. await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", stuId.ToString(), new { ans = blob, score = sc, tmdId = tId }.ToJsonString());
  1526. return Ok(value);
  1527. }
  1528. else
  1529. {
  1530. if (recs.Count == count.GetInt32())
  1531. {
  1532. return Ok(new { msg = "分配人数已到上限" });
  1533. }
  1534. else
  1535. {
  1536. if (all.Count == 0)
  1537. {
  1538. return Ok(new { msg = "暂无可选学生" });
  1539. }
  1540. //随机选取一名学生打分
  1541. Random random = new Random();
  1542. int n = random.Next(all.Count);
  1543. dynamic item = all[n];
  1544. //序列化单个学生作答记录、得分情况、批注情况
  1545. var cs = JsonSerializer.Serialize(item);
  1546. var json = JsonDocument.Parse(cs);
  1547. json.RootElement.TryGetProperty("stuId", out JsonElement sId);
  1548. json.RootElement.TryGetProperty("ans", out JsonElement ans);
  1549. ans.TryGetProperty("score", out JsonElement sc);
  1550. ans.TryGetProperty("ans", out JsonElement blob);
  1551. //选取后,缓存池相应的减少,以便于分配给其他的老师
  1552. await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString(), new { ans = blob, score = sc, tmdId = tId }.ToJsonString());
  1553. return Ok(item);
  1554. }
  1555. }
  1556. //var json = JsonDocument.Parse(record);
  1557. /*ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new Azure.Cosmos.PartitionKey($"Exam-hbcn"));
  1558. if (info.scope.Equals("school"))
  1559. {
  1560. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1561. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1562. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  1563. {
  1564. classResults.Add(item);
  1565. }
  1566. }
  1567. else
  1568. {
  1569. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1570. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1571. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  1572. {
  1573. classResults.Add(item);
  1574. }
  1575. }
  1576. List<Task<bool>> tasks = new List<Task<bool>>();
  1577. foreach (ExamClassResult examClass in classResults)
  1578. {
  1579. foreach (string stuId in examClass.studentIds)
  1580. {
  1581. int index = examClass.studentIds.IndexOf(stuId);
  1582. tasks.Add(redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", stuId, new { ans = examClass.studentAnswers[index].Count > 0 ? examClass.studentAnswers[index][0] : "", score = examClass.studentScores[index] }.ToJsonString()));
  1583. }
  1584. }
  1585. await Task.WhenAll(tasks);
  1586. return Ok();*/
  1587. //info = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  1588. }
  1589. catch (Exception ex)
  1590. {
  1591. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/review\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1592. return BadRequest();
  1593. }
  1594. }
  1595. //批阅 提交分数
  1596. [ProducesDefaultResponseType]
  1597. //[AuthToken(Roles = "Student")]
  1598. [HttpPost("sub-result")]
  1599. public async Task<IActionResult> SubResult(JsonElement requert)
  1600. {
  1601. //ResponseBuilder builder = ResponseBuilder.custom();
  1602. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1603. try
  1604. {
  1605. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1606. if (!requert.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
  1607. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1608. if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  1609. if (!requert.TryGetProperty("score", out JsonElement score)) return BadRequest();
  1610. if (!requert.TryGetProperty("count", out JsonElement count)) return BadRequest();
  1611. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1612. //if (!requert.TryGetProperty("mark", out JsonElement mark)) return BadRequest();
  1613. //requert.TryGetProperty("mark", out JsonElement mark);
  1614. var client = _azureCosmos.GetCosmosClient();
  1615. var redisClient = _azureRedis.GetRedisClient(8);
  1616. List<ExamClassResult> classResults = new();
  1617. List<dynamic> recs = new List<dynamic>();
  1618. var record = await redisClient.HashGetAllAsync($"Exam:Scoring:{id}-{subjectId}");
  1619. foreach (var rcd in record)
  1620. {
  1621. var values = JsonDocument.Parse(rcd.Value.ToString());
  1622. values.RootElement.TryGetProperty("tmdId", out JsonElement tmdId);
  1623. if (tId.ToString().Equals(tmdId.ToString()))
  1624. {
  1625. recs.Add(new { stuId = rcd.Name.ToString(), ans = values });
  1626. }
  1627. }
  1628. var stuAns = await redisClient.HashGetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString());
  1629. var value = JsonDocument.Parse(stuAns.ToString());
  1630. value.RootElement.TryGetProperty("ans", out JsonElement blob);
  1631. value.RootElement.TryGetProperty("mark", out JsonElement element);
  1632. StringBuilder builder = new StringBuilder();
  1633. if (requert.TryGetProperty("mark", out JsonElement mark))
  1634. {
  1635. //存放老师批注信息到blob
  1636. builder.Append(id).Append("/");
  1637. builder.Append(subjectId).Append("/");
  1638. builder.Append(sId).Append("mark").Append("/");
  1639. builder.Append("ans.json");
  1640. await _azureStorage.UploadFileByContainer(code.ToString(), mark.ToJsonString(), "exam", builder.ToString(), false);
  1641. await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString(), new { ans = blob, score = score, tmdId = tId, mark = builder.ToString() }.ToJsonString());
  1642. }
  1643. else {
  1644. await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString(), new { ans = blob, score = score, tmdId = tId, mark = element }.ToJsonString());
  1645. }
  1646. if (recs.Count == count.GetInt32())
  1647. {
  1648. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1649. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1650. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  1651. {
  1652. classResults.Add(item);
  1653. }
  1654. foreach (ExamClassResult exam in classResults)
  1655. {
  1656. foreach (dynamic re in recs)
  1657. {
  1658. var cs = JsonSerializer.Serialize(re);
  1659. var json = JsonDocument.Parse(cs);
  1660. json.RootElement.TryGetProperty("stuId", out JsonElement stuId);
  1661. json.RootElement.TryGetProperty("ans", out JsonElement ans);
  1662. ans.TryGetProperty("score", out JsonElement sc);
  1663. ans.TryGetProperty("mark", out JsonElement marks);
  1664. int index = exam.studentIds.IndexOf(stuId.ToString());
  1665. if (index != -1)
  1666. {
  1667. exam.studentScores[index] = sc.ToObject<List<double>>();
  1668. exam.mark[index] = marks.ToString();
  1669. }
  1670. }
  1671. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  1672. }
  1673. }
  1674. return Ok(new { code = 200 });
  1675. }
  1676. catch (Exception ex)
  1677. {
  1678. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/sub-result\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1679. return BadRequest();
  1680. }
  1681. }
  1682. }
  1683. }