ExamController.cs 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058
  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,admin")]
  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<List<string>> mark = new List<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. {
  1155. return Ok(new { papers, subjects, stuScore, stuAns, mark, total, claId = infoIds, status = 404 });
  1156. }
  1157. }
  1158. catch (Exception ex)
  1159. {
  1160. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-summary-by-student()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1161. return Ok(new { status = 400 });
  1162. }
  1163. }
  1164. //查询学生活动列表
  1165. [ProducesDefaultResponseType]
  1166. //[AuthToken(Roles = "Student")]
  1167. [HttpPost("find-all-by-student")]
  1168. public async Task<IActionResult> findAllStudent(JsonElement requert)
  1169. {
  1170. //ResponseBuilder builder = ResponseBuilder.custom();
  1171. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1172. try
  1173. {
  1174. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1175. if (!requert.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  1176. List<string> resultIds = new List<string>();
  1177. var client = _azureCosmos.GetCosmosClient();
  1178. //查询校本班级ID
  1179. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(
  1180. queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
  1181. {
  1182. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1183. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1184. {
  1185. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1186. while (accounts.MoveNext())
  1187. {
  1188. JsonElement account = accounts.Current;
  1189. resultIds.Add(account.GetProperty("id").GetString());
  1190. }
  1191. }
  1192. }
  1193. //查询私人班级ID
  1194. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(
  1195. queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
  1196. {
  1197. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1198. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1199. {
  1200. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1201. while (accounts.MoveNext())
  1202. {
  1203. JsonElement account = accounts.Current;
  1204. resultIds.Add(account.GetProperty("id").GetString());
  1205. }
  1206. }
  1207. }
  1208. //StringBuilder builder = new StringBuilder();
  1209. HashSet<string> strs = new HashSet<string>();
  1210. if (resultIds.Count > 1)
  1211. {
  1212. foreach (string str in resultIds)
  1213. {
  1214. strs.Add($"array_contains(c.classes,'{str}')");
  1215. //builder.Append($"array_contains(c.targetClassIds,'{str}')").Append("or");
  1216. }
  1217. //builder.ToString().Substring(0, builder.ToString().Length - 2);
  1218. }
  1219. else
  1220. {
  1221. string ssr = resultIds.Count > 0 ? resultIds[0] : "";
  1222. strs.Add($"array_contains(c.classes,'{ssr}')");
  1223. //builder.Append($" array_contains(c.targetClassIds,'{ssr}')");
  1224. }
  1225. string ss = string.Join(" or ", strs);
  1226. //if (!requert.TryGetProperty("school", out JsonElement school)) return BadRequest();
  1227. 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' ";
  1228. List<object> props = new List<object>();
  1229. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query))
  1230. {
  1231. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1232. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1233. {
  1234. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1235. {
  1236. props.Add(obj.ToObject<object>());
  1237. }
  1238. }
  1239. }
  1240. 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'";
  1241. List<ExamClassResult> Classes = new List<ExamClassResult>();
  1242. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: queryClass))
  1243. {
  1244. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1245. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1246. {
  1247. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1248. {
  1249. Classes.Add(obj.ToObject<ExamClassResult>());
  1250. }
  1251. }
  1252. }
  1253. List<ExamClassResult> result = new List<ExamClassResult>();
  1254. foreach (ExamClassResult classResult in Classes)
  1255. {
  1256. int index = classResult.studentIds.IndexOf(studentId.ToString());
  1257. ExamClassResult result1 = new ExamClassResult();
  1258. result1.examId = classResult.examId;
  1259. result1.subjectId = classResult.subjectId;
  1260. result1.studentAnswers.Add(classResult.studentAnswers[index]);
  1261. result1.studentScores.Add(classResult.studentScores[index]);
  1262. result.Add(result1);
  1263. }
  1264. return Ok(new { props, result });
  1265. }
  1266. catch (Exception ex)
  1267. {
  1268. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1269. return BadRequest();
  1270. }
  1271. }
  1272. //查询学生活动列表
  1273. [ProducesDefaultResponseType]
  1274. //[AuthToken(Roles = "Student")]
  1275. [HttpPost("find-score-by-student")]
  1276. public async Task<IActionResult> findScoreByStudent(JsonElement requert)
  1277. {
  1278. //ResponseBuilder builder = ResponseBuilder.custom();
  1279. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1280. try
  1281. {
  1282. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1283. //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1284. var client = _azureCosmos.GetCosmosClient();
  1285. var query = $"select c.examId,c.subjectId,c.studentScores from c where array_contains(c.studentIds,'{id}') ";
  1286. List<object> props = new List<object>();
  1287. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query))
  1288. {
  1289. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1290. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1291. {
  1292. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1293. {
  1294. props.Add(obj.ToObject<object>());
  1295. }
  1296. }
  1297. }
  1298. return Ok(props);
  1299. }
  1300. catch (Exception ex)
  1301. {
  1302. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1303. return BadRequest();
  1304. }
  1305. }
  1306. //查询学生活动列表
  1307. [ProducesDefaultResponseType]
  1308. //[AuthToken(Roles = "Student")]
  1309. [HttpPost("finish")]
  1310. public async Task<IActionResult> finish(JsonElement requert)
  1311. {
  1312. //ResponseBuilder builder = ResponseBuilder.custom();
  1313. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1314. try
  1315. {
  1316. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1317. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1318. var client = _azureCosmos.GetCosmosClient();
  1319. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1320. info.progress = "finish";
  1321. info.endTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1322. List<ExamClassResult> classResults = new();
  1323. if (info.scope.Equals("school"))
  1324. {
  1325. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1326. queryText: $"select value(c) from c where c.examId = '{id}'",
  1327. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  1328. {
  1329. classResults.Add(item);
  1330. }
  1331. }
  1332. else
  1333. {
  1334. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1335. queryText: $"select value(c) from c where c.examId = '{id}'",
  1336. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  1337. {
  1338. classResults.Add(item);
  1339. }
  1340. }
  1341. foreach (ExamClassResult examClass in classResults)
  1342. {
  1343. examClass.progress = true;
  1344. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(examClass, examClass.id, new PartitionKey($"{examClass.code}"));
  1345. }
  1346. info = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  1347. return Ok(info);
  1348. }
  1349. catch (Exception ex)
  1350. {
  1351. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/finish\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1352. return BadRequest();
  1353. }
  1354. }
  1355. /*//查询任务列表
  1356. [ProducesDefaultResponseType]
  1357. //[AuthToken(Roles = "Student")]
  1358. [HttpPost("scoring")]
  1359. public async Task<IActionResult> Scoring(JsonElement requert)
  1360. {
  1361. //ResponseBuilder builder = ResponseBuilder.custom();
  1362. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1363. try
  1364. {
  1365. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1366. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1367. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1368. var client = _azureCosmos.GetCosmosClient();
  1369. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1370. int index = 0;
  1371. foreach (ExamSubject subject in info.subjects) {
  1372. if (!subject.id.Equals(subjectId.ToString()))
  1373. {
  1374. index++;
  1375. }
  1376. else {
  1377. break;
  1378. }
  1379. }
  1380. List<string> stuAns = new();
  1381. Dictionary<string, List<List<double>>> keyValues = new();
  1382. List<ExamClassResult> classResults = new();
  1383. if (info.scope.Equals("school"))
  1384. {
  1385. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1386. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1387. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  1388. {
  1389. classResults.Add(item);
  1390. }
  1391. }
  1392. else
  1393. {
  1394. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1395. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1396. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  1397. {
  1398. classResults.Add(item);
  1399. }
  1400. }
  1401. List<List<double>> itemScore = new();
  1402. for (int i = 0; i < info.papers[index].point.Count; i++)
  1403. {
  1404. List<double> score = new();
  1405. foreach (ExamClassResult examClass in classResults)
  1406. {
  1407. foreach (List<double> sc in examClass.studentScores)
  1408. {
  1409. score.Add(sc[i]);
  1410. }
  1411. }
  1412. itemScore.Add(score);
  1413. }
  1414. foreach (ExamClassResult examClass in classResults)
  1415. {
  1416. foreach (List<string> ans in examClass.studentAnswers)
  1417. {
  1418. if (ans.Count > 0)
  1419. {
  1420. stuAns.Add(ans[0]);
  1421. }
  1422. else
  1423. {
  1424. stuAns.Add("");
  1425. }
  1426. }
  1427. }
  1428. //info = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  1429. return Ok(new { score = itemScore , stuAns, paper = info.papers });
  1430. }
  1431. catch (Exception ex)
  1432. {
  1433. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1434. return BadRequest();
  1435. }
  1436. }*/
  1437. [ProducesDefaultResponseType]
  1438. //[AuthToken(Roles = "Student")]
  1439. [HttpPost("scoring")]
  1440. public async Task<IActionResult> scoring(JsonElement requert)
  1441. {
  1442. //ResponseBuilder builder = ResponseBuilder.custom();
  1443. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1444. try
  1445. {
  1446. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1447. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1448. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1449. if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  1450. var client = _azureCosmos.GetCosmosClient();
  1451. var redisClient = _azureRedis.GetRedisClient(8);
  1452. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1453. List<ExamClassResult> classResults = new();
  1454. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  1455. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  1456. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and array_contains(c.tIds,'{tId}') ",
  1457. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  1458. {
  1459. attr.Add(item);
  1460. }
  1461. /*var record = await redisClient.HashGetAllAsync($"Exam:Scoring:{id}-{subjectId}");
  1462. foreach (var rcd in record)
  1463. {
  1464. var value = JsonDocument.Parse(rcd.Value.ToString());
  1465. value.RootElement.TryGetProperty("info", out JsonElement json);
  1466. List<tmdInfo> tmds = json.ToObject<List<tmdInfo>>();
  1467. foreach (tmdInfo tmd in tmds)
  1468. {
  1469. if (!string.IsNullOrEmpty(tmd.tmdId) && tmd.tmdId.Equals(tId.ToString()))
  1470. {
  1471. attr.Add(new { stuId = rcd.Name.ToString(), info = value });
  1472. break;
  1473. }
  1474. }
  1475. *//* if (tId.ToString().Equals(tmdId.ToString()))
  1476. {
  1477. attr.Add(new { stuId = rcd.Name.ToString(), info = value });
  1478. }*//*
  1479. }*/
  1480. int index = 0;
  1481. foreach (ExamSubject subject in info.subjects)
  1482. {
  1483. if (!subject.id.Equals(subjectId.ToString()))
  1484. {
  1485. index++;
  1486. }
  1487. else
  1488. {
  1489. break;
  1490. }
  1491. }
  1492. List<dynamic> objs = new List<dynamic>();
  1493. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  1494. {
  1495. //var obj = new { stuId = ss.stuId, examId = ss.examId, subjectId = ss.subjectId, };
  1496. //ss.items.Add(ss.items.Where(x => x.scores.))
  1497. //var scc = ss.items.SelectMany(p => p.scores, (p, d) => new { p.ssc, d.sc, d.tmdId }).Where(x => x.tmdId.Equals(tId.GetString())).Select(m => new { m.sc ,m.ssc});
  1498. List<dynamic> sc = new List<dynamic>();
  1499. foreach (Item item in ss.items)
  1500. {
  1501. List<double> scc = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).ToList();
  1502. //item.scores.Where(x => x.tmdId.Equals(tId.GetString())).SelectMany(p => p.sc, (p, d) => new { });
  1503. if (scc.Count > 0)
  1504. {
  1505. sc.Add(new { sc = scc.FirstOrDefault(), item.ssc });
  1506. }
  1507. else
  1508. {
  1509. sc.Add(new { sc = -1, item.ssc });
  1510. }
  1511. //sc.Add(item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).FirstOrDefault());
  1512. //item.scores = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  1513. }
  1514. var obj = new { ss.stuId, ss.examId, ss.subjectId, item = sc, ss.blob, ss.tIds, ss.marks, ss.scores, ss.model, ss.mode };
  1515. objs.Add(obj);
  1516. }
  1517. return Ok(new { objs, paper = info.papers[index].blob });
  1518. }
  1519. catch (Exception ex)
  1520. {
  1521. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1522. return BadRequest();
  1523. }
  1524. }
  1525. //批阅,给老师随机分配阅卷数据,以及查询改老师已有的阅卷数据
  1526. [ProducesDefaultResponseType]
  1527. //[AuthToken(Roles = "Student")]
  1528. [HttpPost("review")]
  1529. public async Task<IActionResult> Review(JsonElement requert)
  1530. {
  1531. //ResponseBuilder builder = ResponseBuilder.custom();
  1532. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1533. try
  1534. {
  1535. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1536. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1537. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1538. if (!requert.TryGetProperty("count", out JsonElement count)) return BadRequest();
  1539. if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  1540. var client = _azureCosmos.GetCosmosClient();
  1541. //var redisClient = _azureRedis.GetRedisClient(8);
  1542. List<ExamClassResult> classResults = new();
  1543. List<SDK.Models.Cosmos.Common.Scoring> recs = new();
  1544. List<SDK.Models.Cosmos.Common.Scoring> all = new();
  1545. List<SDK.Models.Cosmos.Common.Scoring> attr = new();
  1546. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  1547. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' ",
  1548. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  1549. {
  1550. attr.Add(item);
  1551. }
  1552. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  1553. {
  1554. if (scoring.tIds.Contains(tId.ToString()))
  1555. {
  1556. recs.Add(scoring);
  1557. }
  1558. else if (scoring.tIds.Count < scoring.marks.Count * scoring.model)
  1559. {
  1560. all.Add(scoring);
  1561. }
  1562. }
  1563. /*var record = await redisClient.HashGetAllAsync($"Exam:Scoring:{id}-{subjectId}");
  1564. foreach (var rcd in record)
  1565. {
  1566. var value = JsonDocument.Parse(rcd.Value.ToString());
  1567. value.RootElement.TryGetProperty("info", out JsonElement json);
  1568. List<tmdInfo> tmds = json.ToObject<List<tmdInfo>>();
  1569. foreach (tmdInfo tmd in tmds)
  1570. {
  1571. if (!string.IsNullOrEmpty(tmd.tmdId) && tmd.tmdId.Equals(tId.ToString()))
  1572. {
  1573. recs.Add(new { stuId = rcd.Name.ToString(), info = value });
  1574. break;
  1575. }
  1576. if (string.IsNullOrEmpty(tmd.tmdId))
  1577. {
  1578. all.Add(new { stuId = rcd.Name.ToString(), ans = value });
  1579. break;
  1580. }
  1581. }
  1582. *//*if (tId.ToString().Equals(tmdId.ToString()))
  1583. {
  1584. recs.Add(new { stuId = rcd.Name.ToString(), ans = value });
  1585. }
  1586. if (string.IsNullOrEmpty(tmdId.ToString()))
  1587. {
  1588. all.Add(new { stuId = rcd.Name.ToString(), ans = value });
  1589. }*//*
  1590. }*/
  1591. if (requert.TryGetProperty("stuId", out JsonElement stuId))
  1592. {
  1593. List<SDK.Models.Cosmos.Common.Scoring> value = new();
  1594. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  1595. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.stuId = '{stuId}' ",
  1596. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  1597. {
  1598. value.Add(item);
  1599. }
  1600. if (value.Count > 0)
  1601. {
  1602. foreach (SDK.Models.Cosmos.Common.Scoring scoring in value)
  1603. {
  1604. if (scoring.tIds.Contains(tId.ToString()))
  1605. {
  1606. break;
  1607. }
  1608. else
  1609. {
  1610. scoring.tIds.Add(tId.ToString());
  1611. await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
  1612. }
  1613. }
  1614. }
  1615. /*var stuAns = await redisClient.HashGetAsync($"Exam:Scoring:{id}-{subjectId}", stuId.ToString());
  1616. var value = JsonDocument.Parse(stuAns.ToString());
  1617. //保证此学生与该老师绑定
  1618. value.RootElement.TryGetProperty("ans", out JsonElement blob);
  1619. value.RootElement.TryGetProperty("score", out JsonElement sc);
  1620. value.RootElement.TryGetProperty("info", out JsonElement json);
  1621. List<tmdInfo> tmds = json.ToObject<List<tmdInfo>>();
  1622. foreach (tmdInfo tmd in tmds)
  1623. {
  1624. if (string.IsNullOrEmpty(tmd.tmdId))
  1625. {
  1626. tmd.tmdId = tId.ToString();
  1627. break;
  1628. }
  1629. }
  1630. await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", stuId.ToString(), new { info = tmds, ans = blob, score = sc }.ToJsonString());*/
  1631. //var its = value.Where(x => x.items.s)
  1632. List<dynamic> objs = new List<dynamic>();
  1633. List<SDK.Models.Cosmos.Common.Scoring> val = new List<SDK.Models.Cosmos.Common.Scoring>();
  1634. foreach (SDK.Models.Cosmos.Common.Scoring ss in value)
  1635. {
  1636. //var scc = ss.items.SelectMany(p => p.scores, (p, d) => new { p.ssc, d.sc, d.tmdId }).Where(x => x.tmdId.Equals(tId.GetString())).Select(m => new { m.sc, m.ssc });
  1637. List<dynamic> sc = new List<dynamic>();
  1638. foreach (Item item in ss.items)
  1639. {
  1640. List<double> scc = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).ToList();
  1641. //item.scores.Where(x => x.tmdId.Equals(tId.GetString())).SelectMany(p => p.sc, (p, d) => new { });
  1642. if (scc.Count > 0)
  1643. {
  1644. sc.Add(new { sc = scc.FirstOrDefault(),item.ssc});
  1645. }
  1646. else
  1647. {
  1648. sc.Add(new { sc = -1 ,item.ssc});
  1649. }
  1650. //sc.Add(item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).FirstOrDefault());
  1651. //item.scores = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  1652. }
  1653. var obj = new { ss.stuId, ss.examId, ss.subjectId, item = sc, ss.blob, ss.tIds, ss.marks, ss.scores, ss.model, ss.mode };
  1654. objs.Add(obj);
  1655. }
  1656. return Ok(objs);
  1657. }
  1658. else
  1659. {
  1660. if (recs.Count == count.GetInt32())
  1661. {
  1662. return Ok(new { msg = "分配人数已到上限" });
  1663. }
  1664. else
  1665. {
  1666. if (all.Count == 0)
  1667. {
  1668. return Ok(new { msg = "暂无可选学生" });
  1669. }
  1670. //随机选取一名学生打分
  1671. Random random = new Random();
  1672. SDK.Models.Cosmos.Common.Scoring item = new();
  1673. List<SDK.Models.Cosmos.Common.Scoring> notYet = new();
  1674. notYet = all.Where(x => x.tIds.Count < x.marks.Count * x.model - 1).ToList();
  1675. if (notYet.Count > 0)
  1676. {
  1677. item = notYet[random.Next(notYet.Count)];
  1678. }
  1679. else
  1680. {
  1681. item = all[random.Next(all.Count)];
  1682. }
  1683. if (!item.tIds.Contains(tId.ToString()))
  1684. {
  1685. item.tIds.Add(tId.ToString());
  1686. }
  1687. await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  1688. //序列化单个学生作答记录、得分情况、批注情况
  1689. /*var cs = JsonSerializer.Serialize(item);
  1690. var json = JsonDocument.Parse(cs);
  1691. json.RootElement.TryGetProperty("stuId", out JsonElement sId);
  1692. json.RootElement.TryGetProperty("ans", out JsonElement ans);
  1693. ans.TryGetProperty("score", out JsonElement sc);
  1694. ans.TryGetProperty("ans", out JsonElement blob);
  1695. ans.TryGetProperty("info", out JsonElement element);
  1696. List<tmdInfo> tmds = element.ToObject<List<tmdInfo>>();
  1697. foreach (tmdInfo tmd in tmds)
  1698. {
  1699. if (string.IsNullOrEmpty(tmd.tmdId))
  1700. {
  1701. tmd.tmdId = tId.ToString();
  1702. break;
  1703. }
  1704. }*/
  1705. //选取后,缓存池相应的减少,以便于分配给其他的老师
  1706. //await redisClient.HashSetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString(), new { info = tmds, ans = blob, score = sc }.ToJsonString());
  1707. //ss.items.Add(ss.items.Where(x => x.scores.))
  1708. /*foreach (Item its in item.items)
  1709. {
  1710. its.scores = its.scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  1711. }*/
  1712. //List<double> sc = new List<double>();
  1713. var scc = item.items.SelectMany(p => p.scores, (p, d) => new { p.ssc, d.sc, d.tmdId }).Where(x => x.tmdId.Equals(tId.GetString())).Select(m => new { m.sc, m.ssc });
  1714. var obj = new { item.stuId, item.examId, item.subjectId, item = scc, item.blob, item.tIds, item.marks, item.scores, item.model, item.mode };
  1715. return Ok(obj);
  1716. }
  1717. }
  1718. //var json = JsonDocument.Parse(record);
  1719. /*ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new Azure.Cosmos.PartitionKey($"Exam-hbcn"));
  1720. if (info.scope.Equals("school"))
  1721. {
  1722. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1723. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1724. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  1725. {
  1726. classResults.Add(item);
  1727. }
  1728. }
  1729. else
  1730. {
  1731. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1732. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1733. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  1734. {
  1735. classResults.Add(item);
  1736. }
  1737. }
  1738. List<Task<bool>> tasks = new List<Task<bool>>();
  1739. foreach (ExamClassResult examClass in classResults)
  1740. {
  1741. foreach (string stuId in examClass.studentIds)
  1742. {
  1743. int index = examClass.studentIds.IndexOf(stuId);
  1744. 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()));
  1745. }
  1746. }
  1747. await Task.WhenAll(tasks);
  1748. return Ok();*/
  1749. //info = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  1750. }
  1751. catch (Exception ex)
  1752. {
  1753. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/review\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1754. return BadRequest();
  1755. }
  1756. }
  1757. //批阅 提交分数
  1758. [ProducesDefaultResponseType]
  1759. //[AuthToken(Roles = "Student")]
  1760. [HttpPost("sub-result")]
  1761. public async Task<IActionResult> SubResult(JsonElement requert)
  1762. {
  1763. //ResponseBuilder builder = ResponseBuilder.custom();
  1764. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1765. try
  1766. {
  1767. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1768. if (!requert.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
  1769. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1770. if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  1771. if (!requert.TryGetProperty("score", out JsonElement score)) return BadRequest();
  1772. if (!requert.TryGetProperty("count", out JsonElement count)) return BadRequest();
  1773. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1774. //if (!requert.TryGetProperty("mark", out JsonElement mark)) return BadRequest();
  1775. //requert.TryGetProperty("mark", out JsonElement mark);
  1776. var client = _azureCosmos.GetCosmosClient();
  1777. var redisClient = _azureRedis.GetRedisClient(8);
  1778. List<ExamClassResult> classResults = new();
  1779. List<SDK.Models.Cosmos.Common.Scoring> attr = new();
  1780. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  1781. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.stuId = '{sId}' and array_contains(c.tIds,'{tId}') ",
  1782. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  1783. {
  1784. attr.Add(item);
  1785. }
  1786. /*List<dynamic> recs = new List<dynamic>();
  1787. var record = await redisClient.HashGetAllAsync($"Exam:Scoring:{id}-{subjectId}");
  1788. foreach (var rcd in record)
  1789. {
  1790. var values = JsonDocument.Parse(rcd.Value.ToString());
  1791. values.RootElement.TryGetProperty("info", out JsonElement json);
  1792. List<tmdInfo> tmdInfos = json.ToObject<List<tmdInfo>>();
  1793. foreach (tmdInfo tmd in tmdInfos)
  1794. {
  1795. if (!string.IsNullOrEmpty(tmd.tmdId) && tmd.tmdId.Equals(tId.ToString()))
  1796. {
  1797. recs.Add(new { stuId = rcd.Name.ToString(), info = values });
  1798. break;
  1799. }
  1800. }
  1801. *//*if (tId.ToString().Equals(tmdId.ToString()))
  1802. {
  1803. recs.Add(new { stuId = rcd.Name.ToString(), ans = values });
  1804. }*//*
  1805. }*/
  1806. /*var stuAns = await redisClient.HashGetAsync($"Exam:Scoring:{id}-{subjectId}", sId.ToString());
  1807. var value = JsonDocument.Parse(stuAns.ToString());
  1808. value.RootElement.TryGetProperty("ans", out JsonElement blob);
  1809. value.RootElement.TryGetProperty("info", out JsonElement element);
  1810. List<tmdInfo> tmds = element.ToObject<List<tmdInfo>>();*/
  1811. List<double> ssc = score.ToObject<List<double>>();
  1812. StringBuilder builder = new();
  1813. if (requert.TryGetProperty("mark", out JsonElement mark))
  1814. {
  1815. //存放老师批注信息到blob
  1816. builder.Append(id).Append('/');
  1817. builder.Append(subjectId).Append('/');
  1818. builder.Append(sId).Append("mark").Append('/');
  1819. builder.Append("ans.json");
  1820. await _azureStorage.UploadFileByContainer(code.ToString(), mark.ToJsonString(), "exam", builder.ToString(), false);
  1821. if (attr.Count > 0)
  1822. {
  1823. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  1824. {
  1825. foreach (Item item in scoring.items)
  1826. {
  1827. bool flag = false;
  1828. int index = 0;
  1829. if (item.scores.Count > 0)
  1830. {
  1831. foreach (Info info in item.scores)
  1832. {
  1833. if (!info.tmdId.Equals(tId.GetString()))
  1834. {
  1835. index++;
  1836. }
  1837. else
  1838. {
  1839. scoring.marks[index] = builder.ToString();
  1840. flag = true;
  1841. break;
  1842. }
  1843. }
  1844. }
  1845. if (flag)
  1846. {
  1847. break;
  1848. }
  1849. //List<Info> info = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  1850. }
  1851. /* int index = scoring.tIds.IndexOf(tId.GetString());
  1852. if (index != -1)
  1853. {
  1854. scoring.marks[index] = builder.ToString();
  1855. }*/
  1856. }
  1857. }
  1858. }
  1859. if (attr.Count > 0)
  1860. {
  1861. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  1862. {
  1863. int itemIndex = 0;
  1864. //int tIdIndex = scoring.tIds.IndexOf(tId.GetString());
  1865. if (requert.TryGetProperty("qu", out JsonElement qu))
  1866. {
  1867. List<int> nos = qu.ToObject<List<int>>();
  1868. foreach (int number in nos)
  1869. {
  1870. List<Info> items = scoring.items[number].scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  1871. if (items.Count > 0)
  1872. {
  1873. foreach (Info info in items)
  1874. {
  1875. info.sc = ssc[number];
  1876. }
  1877. }
  1878. else
  1879. {
  1880. Info info = new();
  1881. info.sc = ssc[number];
  1882. info.tmdId = tId.GetString();
  1883. info.index = number;
  1884. scoring.items[number].scores.Add(info);
  1885. }
  1886. }
  1887. }
  1888. else
  1889. {
  1890. foreach (Item item in scoring.items)
  1891. {
  1892. List<Info> items = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  1893. if (items.Count > 0)
  1894. {
  1895. foreach (Info info in items)
  1896. {
  1897. info.sc = ssc[itemIndex];
  1898. }
  1899. }
  1900. else
  1901. {
  1902. Info info = new();
  1903. info.sc = ssc[itemIndex];
  1904. info.tmdId = tId.GetString();
  1905. info.index = itemIndex;
  1906. item.scores.Add(info);
  1907. }
  1908. itemIndex++;
  1909. }
  1910. }
  1911. await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
  1912. }
  1913. }
  1914. //判定阅卷结算的条件
  1915. if (attr.Count == count.GetInt32())
  1916. {
  1917. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
  1918. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1919. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  1920. {
  1921. classResults.Add(item);
  1922. }
  1923. foreach (ExamClassResult exam in classResults)
  1924. {
  1925. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  1926. {
  1927. int index = exam.studentIds.IndexOf(scoring.stuId);
  1928. //均分
  1929. int n = 0;
  1930. foreach (Item item in scoring.items)
  1931. {
  1932. var ace = item.scores.Where(x => string.IsNullOrEmpty(x.tmdId)).ToList();
  1933. if (ace.Count > 0)
  1934. {
  1935. return Ok(new { code = 200 });
  1936. }
  1937. //判定是否仲裁卷
  1938. if (!item.flag)
  1939. {
  1940. return Ok(new { msg = "试题分数差异过大" });
  1941. }
  1942. double sc = item.scores.Select(x => x.sc).ToList().Aggregate((i, j) => (i + j) / item.scores.Count);
  1943. scoring.scores[n] = sc;
  1944. n++;
  1945. }
  1946. if (index != -1)
  1947. {
  1948. exam.studentScores[index] = scoring.scores;
  1949. exam.mark[index] = scoring.marks;
  1950. }
  1951. }
  1952. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  1953. }
  1954. }
  1955. return Ok(new { code = 200 });
  1956. }
  1957. catch (Exception ex)
  1958. {
  1959. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/sub-result\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1960. return BadRequest();
  1961. }
  1962. }
  1963. //阅卷信息统计
  1964. [ProducesDefaultResponseType]
  1965. //[AuthToken(Roles = "Student")]
  1966. [HttpPost("analysis-scoring")]
  1967. public async Task<IActionResult> Analysis(JsonElement requert)
  1968. {
  1969. return null;
  1970. }
  1971. }
  1972. }