ExamController.cs 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836
  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. var record = await redisClient.HashGetAllAsync($"Exam:Scoring:{id}-{subjectId}");
  1455. foreach (var rcd in record)
  1456. {
  1457. var value = JsonDocument.Parse(rcd.Value.ToString());
  1458. value.RootElement.TryGetProperty("info", out JsonElement json);
  1459. List<tmdInfo> tmds = json.ToObject<List<tmdInfo>>();
  1460. foreach (tmdInfo tmd in tmds)
  1461. {
  1462. if (!string.IsNullOrEmpty(tmd.tmdId) && tmd.tmdId.Equals(tId.ToString()))
  1463. {
  1464. attr.Add(new { stuId = rcd.Name.ToString(), info = value });
  1465. break;
  1466. }
  1467. }
  1468. /* if (tId.ToString().Equals(tmdId.ToString()))
  1469. {
  1470. attr.Add(new { stuId = rcd.Name.ToString(), info = value });
  1471. }*/
  1472. }
  1473. int index = 0;
  1474. foreach (ExamSubject subject in info.subjects)
  1475. {
  1476. if (!subject.id.Equals(subjectId.ToString()))
  1477. {
  1478. index++;
  1479. }
  1480. else
  1481. {
  1482. break;
  1483. }
  1484. }
  1485. return Ok(new { attr, paper = info.papers[index].blob });
  1486. }
  1487. catch (Exception ex)
  1488. {
  1489. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1490. return BadRequest();
  1491. }
  1492. }
  1493. //批阅,给老师随机分配阅卷数据,以及查询改老师已有的阅卷数据
  1494. [ProducesDefaultResponseType]
  1495. //[AuthToken(Roles = "Student")]
  1496. [HttpPost("review")]
  1497. public async Task<IActionResult> Review(JsonElement requert)
  1498. {
  1499. //ResponseBuilder builder = ResponseBuilder.custom();
  1500. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1501. try
  1502. {
  1503. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1504. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1505. if (!requert.TryGetProperty("count", out JsonElement count)) return BadRequest();
  1506. if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  1507. var client = _azureCosmos.GetCosmosClient();
  1508. var redisClient = _azureRedis.GetRedisClient(8);
  1509. List<ExamClassResult> classResults = new();
  1510. List<dynamic> recs = new List<dynamic>();
  1511. List<dynamic> all = new List<dynamic>();
  1512. var record = await redisClient.HashGetAllAsync($"Exam:Scoring:{id}-{subjectId}");
  1513. foreach (var rcd in record)
  1514. {
  1515. var value = JsonDocument.Parse(rcd.Value.ToString());
  1516. value.RootElement.TryGetProperty("info", out JsonElement json);
  1517. List<tmdInfo> tmds = json.ToObject<List<tmdInfo>>();
  1518. foreach (tmdInfo tmd in tmds)
  1519. {
  1520. if (!string.IsNullOrEmpty(tmd.tmdId) && tmd.tmdId.Equals(tId.ToString()))
  1521. {
  1522. recs.Add(new { stuId = rcd.Name.ToString(), info = value });
  1523. break;
  1524. }
  1525. if (string.IsNullOrEmpty(tmd.tmdId))
  1526. {
  1527. all.Add(new { stuId = rcd.Name.ToString(), ans = value });
  1528. break;
  1529. }
  1530. }
  1531. /*if (tId.ToString().Equals(tmdId.ToString()))
  1532. {
  1533. recs.Add(new { stuId = rcd.Name.ToString(), ans = value });
  1534. }
  1535. if (string.IsNullOrEmpty(tmdId.ToString()))
  1536. {
  1537. all.Add(new { stuId = rcd.Name.ToString(), ans = value });
  1538. }*/
  1539. }
  1540. if (requert.TryGetProperty("stuId", out JsonElement stuId))
  1541. {
  1542. var stuAns = await redisClient.HashGetAsync($"Exam:Scoring:{id}-{subjectId}", stuId.ToString());
  1543. var value = JsonDocument.Parse(stuAns.ToString());
  1544. //保证此学生与该老师绑定
  1545. value.RootElement.TryGetProperty("ans", out JsonElement blob);
  1546. value.RootElement.TryGetProperty("score", out JsonElement sc);
  1547. value.RootElement.TryGetProperty("info", out JsonElement json);
  1548. List<tmdInfo> tmds = json.ToObject<List<tmdInfo>>();
  1549. foreach (tmdInfo tmd in tmds)
  1550. {
  1551. if (string.IsNullOrEmpty(tmd.tmdId))
  1552. {
  1553. tmd.tmdId = tId.ToString();
  1554. break;
  1555. }
  1556. }
  1557. await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", stuId.ToString(), new { info = tmds, ans = blob, score = sc }.ToJsonString());
  1558. return Ok(value);
  1559. }
  1560. else
  1561. {
  1562. if (recs.Count == count.GetInt32())
  1563. {
  1564. return Ok(new { msg = "分配人数已到上限" });
  1565. }
  1566. else
  1567. {
  1568. if (all.Count == 0)
  1569. {
  1570. return Ok(new { msg = "暂无可选学生" });
  1571. }
  1572. //随机选取一名学生打分
  1573. Random random = new Random();
  1574. int n = random.Next(all.Count);
  1575. dynamic item = all[n];
  1576. //序列化单个学生作答记录、得分情况、批注情况
  1577. var cs = JsonSerializer.Serialize(item);
  1578. var json = JsonDocument.Parse(cs);
  1579. json.RootElement.TryGetProperty("stuId", out JsonElement sId);
  1580. json.RootElement.TryGetProperty("ans", out JsonElement ans);
  1581. ans.TryGetProperty("score", out JsonElement sc);
  1582. ans.TryGetProperty("ans", out JsonElement blob);
  1583. ans.TryGetProperty("info", out JsonElement element);
  1584. List<tmdInfo> tmds = element.ToObject<List<tmdInfo>>();
  1585. foreach (tmdInfo tmd in tmds)
  1586. {
  1587. if (string.IsNullOrEmpty(tmd.tmdId))
  1588. {
  1589. tmd.tmdId = tId.ToString();
  1590. break;
  1591. }
  1592. }
  1593. //选取后,缓存池相应的减少,以便于分配给其他的老师
  1594. await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString(), new { info = tmds, ans = blob, score = sc }.ToJsonString());
  1595. return Ok(item);
  1596. }
  1597. }
  1598. //var json = JsonDocument.Parse(record);
  1599. /*ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new Azure.Cosmos.PartitionKey($"Exam-hbcn"));
  1600. if (info.scope.Equals("school"))
  1601. {
  1602. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1603. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1604. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  1605. {
  1606. classResults.Add(item);
  1607. }
  1608. }
  1609. else
  1610. {
  1611. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1612. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1613. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  1614. {
  1615. classResults.Add(item);
  1616. }
  1617. }
  1618. List<Task<bool>> tasks = new List<Task<bool>>();
  1619. foreach (ExamClassResult examClass in classResults)
  1620. {
  1621. foreach (string stuId in examClass.studentIds)
  1622. {
  1623. int index = examClass.studentIds.IndexOf(stuId);
  1624. 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()));
  1625. }
  1626. }
  1627. await Task.WhenAll(tasks);
  1628. return Ok();*/
  1629. //info = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  1630. }
  1631. catch (Exception ex)
  1632. {
  1633. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/review\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1634. return BadRequest();
  1635. }
  1636. }
  1637. //批阅 提交分数
  1638. [ProducesDefaultResponseType]
  1639. //[AuthToken(Roles = "Student")]
  1640. [HttpPost("sub-result")]
  1641. public async Task<IActionResult> SubResult(JsonElement requert)
  1642. {
  1643. //ResponseBuilder builder = ResponseBuilder.custom();
  1644. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1645. try
  1646. {
  1647. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1648. if (!requert.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
  1649. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1650. if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  1651. if (!requert.TryGetProperty("score", out JsonElement score)) return BadRequest();
  1652. if (!requert.TryGetProperty("count", out JsonElement count)) return BadRequest();
  1653. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1654. //if (!requert.TryGetProperty("mark", out JsonElement mark)) return BadRequest();
  1655. //requert.TryGetProperty("mark", out JsonElement mark);
  1656. var client = _azureCosmos.GetCosmosClient();
  1657. var redisClient = _azureRedis.GetRedisClient(8);
  1658. List<ExamClassResult> classResults = new();
  1659. List<dynamic> recs = new List<dynamic>();
  1660. var record = await redisClient.HashGetAllAsync($"Exam:Scoring:{id}-{subjectId}");
  1661. foreach (var rcd in record)
  1662. {
  1663. var values = JsonDocument.Parse(rcd.Value.ToString());
  1664. values.RootElement.TryGetProperty("info", out JsonElement json);
  1665. List<tmdInfo> tmdInfos = json.ToObject<List<tmdInfo>>();
  1666. foreach (tmdInfo tmd in tmdInfos)
  1667. {
  1668. if (!string.IsNullOrEmpty(tmd.tmdId) && tmd.tmdId.Equals(tId.ToString()))
  1669. {
  1670. recs.Add(new { stuId = rcd.Name.ToString(), info = values });
  1671. break;
  1672. }
  1673. }
  1674. /*if (tId.ToString().Equals(tmdId.ToString()))
  1675. {
  1676. recs.Add(new { stuId = rcd.Name.ToString(), ans = values });
  1677. }*/
  1678. }
  1679. var stuAns = await redisClient.HashGetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString());
  1680. var value = JsonDocument.Parse(stuAns.ToString());
  1681. value.RootElement.TryGetProperty("ans", out JsonElement blob);
  1682. value.RootElement.TryGetProperty("info", out JsonElement element);
  1683. List<tmdInfo> tmds = element.ToObject<List<tmdInfo>>();
  1684. StringBuilder builder = new StringBuilder();
  1685. if (requert.TryGetProperty("mark", out JsonElement mark))
  1686. {
  1687. //存放老师批注信息到blob
  1688. builder.Append(id).Append("/");
  1689. builder.Append(subjectId).Append("/");
  1690. builder.Append(sId).Append("mark").Append("/");
  1691. builder.Append("ans.json");
  1692. await _azureStorage.UploadFileByContainer(code.ToString(), mark.ToJsonString(), "exam", builder.ToString(), false);
  1693. foreach (tmdInfo tmd in tmds)
  1694. {
  1695. if (string.IsNullOrEmpty(tmd.tmdId))
  1696. {
  1697. tmd.tmdId = tId.ToString();
  1698. tmd.mark = builder.ToString();
  1699. break;
  1700. }
  1701. }
  1702. await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString(), new { info = tmds, ans = blob, score = score }.ToJsonString());
  1703. }
  1704. else
  1705. {
  1706. foreach (tmdInfo tmd in tmds)
  1707. {
  1708. if (string.IsNullOrEmpty(tmd.tmdId))
  1709. {
  1710. tmd.tmdId = tId.ToString();
  1711. break;
  1712. }
  1713. }
  1714. await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString(), new { info = tmds, ans = blob, score = score }.ToJsonString());
  1715. }
  1716. if (recs.Count == count.GetInt32())
  1717. {
  1718. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1719. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1720. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  1721. {
  1722. classResults.Add(item);
  1723. }
  1724. foreach (ExamClassResult exam in classResults)
  1725. {
  1726. foreach (dynamic re in recs)
  1727. {
  1728. var cs = JsonSerializer.Serialize(re);
  1729. var json = JsonDocument.Parse(cs);
  1730. json.RootElement.TryGetProperty("stuId", out JsonElement stuId);
  1731. json.RootElement.TryGetProperty("ans", out JsonElement ans);
  1732. ans.TryGetProperty("score", out JsonElement sc);
  1733. ans.TryGetProperty("mark", out JsonElement marks);
  1734. int index = exam.studentIds.IndexOf(stuId.ToString());
  1735. if (index != -1)
  1736. {
  1737. exam.studentScores[index] = sc.ToObject<List<double>>();
  1738. exam.mark[index] = marks.ToString();
  1739. }
  1740. }
  1741. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  1742. }
  1743. }
  1744. return Ok(new { code = 200 });
  1745. }
  1746. catch (Exception ex)
  1747. {
  1748. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/sub-result\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1749. return BadRequest();
  1750. }
  1751. }
  1752. }
  1753. }