ExamController.cs 175 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210
  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.DI;
  18. using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
  19. using TEAMModelOS.SDK.Extension;
  20. using TEAMModelOS.SDK.Helper.Common.StringHelper;
  21. using TEAMModelOS.SDK.Models.Cosmos.Common;
  22. using TEAMModelOS.SDK.Models.Table;
  23. using Azure.Messaging.ServiceBus;
  24. using Microsoft.Extensions.Configuration;
  25. using TEAMModelOS.Filter;
  26. using TEAMModelOS.SDK.Models.Service;
  27. using TEAMModelOS.SDK.Models.Cosmos;
  28. using HTEXLib.COMM.Helpers;
  29. using Microsoft.AspNetCore.Authorization;
  30. using System.Net.Http;
  31. namespace TEAMModelOS.Controllers
  32. {
  33. [ProducesResponseType(StatusCodes.Status200OK)]
  34. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  35. [Route("common/exam")]
  36. [ApiController]
  37. public class ExamController : ControllerBase
  38. {
  39. private readonly AzureCosmosFactory _azureCosmos;
  40. private readonly SnowflakeId _snowflakeId;
  41. private readonly AzureServiceBusFactory _serviceBus;
  42. private readonly DingDing _dingDing;
  43. private readonly Option _option;
  44. private readonly AzureStorageFactory _azureStorage;
  45. private readonly AzureRedisFactory _azureRedis;
  46. public IConfiguration _configuration { get; set; }
  47. private readonly NotificationService _notificationService;
  48. private readonly CoreAPIHttpService _coreAPIHttpService;
  49. public ExamController(CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
  50. IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, NotificationService notificationService, IConfiguration configuration)
  51. {
  52. _azureCosmos = azureCosmos;
  53. _serviceBus = serviceBus;
  54. _snowflakeId = snowflakeId;
  55. _dingDing = dingDing;
  56. _option = option?.Value;
  57. _azureStorage = azureStorage;
  58. _azureRedis = azureRedis;
  59. _configuration = configuration;
  60. _notificationService = notificationService;
  61. _coreAPIHttpService = coreAPIHttpService;
  62. }
  63. /// <summary>
  64. /// 保存考试信息
  65. /// </summary>
  66. /// <param name="request"></param>
  67. /// <returns></returns>
  68. [ProducesDefaultResponseType]
  69. [AuthToken(Roles = "teacher,admin")]
  70. [HttpPost("save")]
  71. [Authorize(Roles = "IES")]
  72. public async Task<IActionResult> Save(ExamInfo request)
  73. {
  74. try
  75. {
  76. //新增
  77. //string code = request.code;
  78. var client = _azureCosmos.GetCosmosClient();
  79. ExamInfo exam;
  80. string code = request.code;
  81. request.ttl = -1;
  82. request.code = "Exam-" + request.code;
  83. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  84. request.createTime = now;
  85. if (request.startTime <= 0)
  86. {
  87. request.startTime = now;
  88. }
  89. //查询所有学生名单
  90. /* List<string> sids = new List<string>();
  91. //List<Student> students = new List<Student>();
  92. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.id from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{request.school}") }))
  93. {
  94. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  95. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  96. {
  97. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  98. while (accounts.MoveNext())
  99. {
  100. JsonElement account = accounts.Current;
  101. sids.Add(account.GetProperty("id").GetString());
  102. }
  103. }
  104. }*/
  105. //int stuCount = 0;
  106. List<(string pId, List<string> gid)> ps = new();
  107. var group = request.groupLists;
  108. if (group.Count > 0)
  109. {
  110. foreach (var keys in group)
  111. {
  112. foreach (KeyValuePair<string, List<string>> pp in keys)
  113. {
  114. ps.Add((pp.Key, pp.Value));
  115. }
  116. }
  117. }
  118. List<string> classes = ExamService.getClasses(request.classes, request.stuLists);
  119. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, classes, request.school, ps);
  120. request.stuCount = tchList.Count;
  121. /*for (int i = 0; i < classes.Count; i++)
  122. {
  123. List<string> ids = new List<string>();
  124. //处理班级人数(公共部分的校本名单)
  125. //List<Student> students = new List<Student>();
  126. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.classId = '{classes[i]}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{request.school}") }))
  127. {
  128. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  129. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  130. {
  131. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  132. while (accounts.MoveNext())
  133. {
  134. JsonElement account = accounts.Current;
  135. ids.Add(account.GetProperty("id").GetString());
  136. }
  137. }
  138. }
  139. if (request.scope.Equals("private"))
  140. {
  141. //处理发布对象为自选名单(个人)
  142. List<GroupList> stuLists = new List<GroupList>();
  143. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: $"select value(c) from c where c.id = '{classes[i]}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
  144. {
  145. stuLists.Add(item);
  146. }
  147. }
  148. else
  149. {
  150. //request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  151. //发布对象为自选名单(校本)
  152. List<GroupList> stuLists = new List<GroupList>();
  153. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: $"select value(c) from c where c.id = '{classes[i]}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{request.school}") }))
  154. {
  155. stuLists.Add(item);
  156. }
  157. }
  158. stuCount += ids.Count;
  159. }*/
  160. if (string.IsNullOrEmpty(request.id))
  161. {
  162. request.id = Guid.NewGuid().ToString();
  163. if (request.startTime > now)
  164. {
  165. request.progress = "pending";
  166. }
  167. else
  168. {
  169. request.progress = "going";
  170. }
  171. var messageBlob = new ServiceBusMessage();
  172. if (request.scope.Equals("school"))
  173. {
  174. request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  175. messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "insert", root = $"exam/{request.id}", name = request.school }.ToJsonString());
  176. }
  177. else
  178. {
  179. request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
  180. messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "insert", root = $"exam/{request.id}", name = request.creatorId }.ToJsonString());
  181. }
  182. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  183. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  184. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  185. int n = 0;
  186. List<string> sheetIds = new List<string>();
  187. foreach (PaperSimple simple in request.papers)
  188. {
  189. simple.blob = $"/exam/{request.id}/paper/{request.subjects[n].id}";
  190. n++;
  191. simple.sheet = null;
  192. }
  193. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
  194. }
  195. else
  196. {
  197. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(request.id, new PartitionKey($"{request.code}"));
  198. //info.name = request.name;
  199. if (info.progress.Equals("going"))
  200. {
  201. //exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
  202. return Ok(new { v = "活动正在进行中,无法修改", code = 200 });
  203. }
  204. var messageBlob = new ServiceBusMessage();
  205. if (request.scope.Equals("school"))
  206. {
  207. request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  208. messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = $"exam/{request.id}", name = request.school }.ToJsonString());
  209. }
  210. else
  211. {
  212. request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
  213. messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = $"exam/{request.id}", name = request.creatorId }.ToJsonString());
  214. }
  215. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  216. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  217. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  218. request.progress = info.progress;
  219. int n = 0;
  220. foreach (PaperSimple simple in request.papers)
  221. {
  222. simple.blob = "/exam/" + request.id + "/paper/" + request.subjects[n].id;
  223. n++;
  224. }
  225. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
  226. }
  227. return Ok(new { exam });
  228. }
  229. catch (Exception ex)
  230. {
  231. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/save()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  232. return BadRequest();
  233. }
  234. }
  235. /// <summary>
  236. /// 保存考试信息
  237. /// </summary>
  238. /// <param name="request"></param>
  239. /// <returns></returns>
  240. [ProducesDefaultResponseType]
  241. [AuthToken(Roles = "teacher,admin")]
  242. [HttpPost("update-end-time")]
  243. [Authorize(Roles = "IES")]
  244. public async Task<IActionResult> updateTime(JsonElement request)
  245. {
  246. try
  247. {
  248. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  249. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  250. var client = _azureCosmos.GetCosmosClient();
  251. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Exam-{code}"));
  252. if (response.Status == 200)
  253. {
  254. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  255. ExamInfo exam = json.ToObject<ExamInfo>();
  256. if (request.TryGetProperty("time", out JsonElement time))
  257. {
  258. exam.endTime = time.GetInt64();
  259. }
  260. if (request.TryGetProperty("name", out JsonElement name))
  261. {
  262. exam.name = name.GetString();
  263. }
  264. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  265. }
  266. return Ok(new { code = 200 });
  267. }
  268. catch (Exception e)
  269. {
  270. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/update-end-time()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  271. return BadRequest();
  272. }
  273. }
  274. //TODO blob 批量删除
  275. /// <summary>
  276. /// 删除
  277. /// </summary>
  278. /// <param name="request"></param>
  279. /// <returns></returns>
  280. [ProducesDefaultResponseType]
  281. [AuthToken(Roles = "teacher,admin")]
  282. [HttpPost("delete")]
  283. [Authorize(Roles = "IES")]
  284. public async Task<IActionResult> Delete(JsonElement request)
  285. {
  286. /* ResponseBuilder builder = ResponseBuilder.custom();
  287. IdPk items = await _azureCosmos.DeleteAsync<ExamInfo>(request.id, request.pk);
  288. await _azureCosmos.DeleteAll<Paper>(new Dictionary<string, object>() { { "code", request.id } });
  289. return builder.Data(items).build();*/
  290. var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
  291. try
  292. {
  293. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  294. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  295. if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  296. var client = _azureCosmos.GetCosmosClient();
  297. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.GetString(), new PartitionKey($"Exam-{code}"));
  298. bool flag = false;
  299. //必须是本人或者这个学校的管理者才能删除
  300. if (exam.creatorId == userid)
  301. {
  302. flag = true;
  303. }
  304. else
  305. {
  306. if (exam.scope == "school" && exam.school.Equals(school))
  307. {
  308. flag = true;
  309. }
  310. }
  311. if (flag)
  312. {
  313. exam.status = 404;
  314. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  315. //string school_code = code.ToString().Substring(typeof(ExamClassResult).Name.Length + 1);
  316. //var response = await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
  317. //删除blob 相关资料
  318. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, code.ToString(), new List<string> { $"exam/{id}" });
  319. //通知评测删除信息
  320. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "delete", root = $"exam/{id}", name = $"{code}" }.ToJsonString());
  321. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  322. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  323. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  324. //删除阅卷配置
  325. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
  326. if (cresponse.Status == 200)
  327. {
  328. using var json = await JsonDocument.ParseAsync(cresponse.ContentStream);
  329. Correct correct = json.ToObject<Correct>();
  330. if (correct.subs.IsNotEmpty())
  331. {
  332. foreach (var sub in correct.subs)
  333. {
  334. //List<string> correctIds = new List<string>();
  335. if (sub.markers.IsNotEmpty())
  336. {
  337. foreach (var marker in sub.markers)
  338. {
  339. await ExamService.deleteAsync(client, id.GetString(), marker.id);
  340. }
  341. }
  342. if (sub.err.Count > 0)
  343. {
  344. foreach (var tId in sub.err)
  345. {
  346. await ExamService.deleteAsync(client, id.GetString(), tId);
  347. }
  348. }
  349. if (sub.arb.Count > 0)
  350. {
  351. foreach (var tId in sub.arb)
  352. {
  353. await ExamService.deleteAsync(client, id.GetString(), tId);
  354. }
  355. }
  356. }
  357. }
  358. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(id.GetString(), new PartitionKey($"Correct-{code}"));
  359. }
  360. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  361. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(queryText: $"select c.id from c where c.examId = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  362. {
  363. examClassResults.Add(item);
  364. }
  365. List<string> resultIds = new List<string>();
  366. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: $"select c.id from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamResult-{id}") }))
  367. {
  368. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  369. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  370. {
  371. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  372. while (accounts.MoveNext())
  373. {
  374. JsonElement account = accounts.Current;
  375. resultIds.Add(account.GetProperty("id").GetString());
  376. }
  377. }
  378. }
  379. foreach (ExamClassResult classResult in examClassResults)
  380. {
  381. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(classResult.id, new PartitionKey($"ExamClassResult-{code}"));
  382. }
  383. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemsStreamAsync(resultIds, $"ExamResult-{id}");
  384. /*foreach (ExamResult result in results)
  385. {
  386. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(result.id, new PartitionKey($"ExamResult-{id}"));
  387. }*/
  388. //await _azureCosmos.DeleteAll(examClassResults);
  389. }
  390. return Ok(new { id });
  391. }
  392. catch (Exception e)
  393. {
  394. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/delete()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  395. return BadRequest();
  396. }
  397. }
  398. /// <summary>
  399. /// 查询考试信息
  400. /// </summary>
  401. /// <param name="request"></param>
  402. /// <returns></returns>
  403. [ProducesDefaultResponseType]
  404. [Authorize(Roles = "IES")]
  405. [AuthToken(Roles = "teacher,admin")]
  406. [HttpPost("find")]
  407. public async Task<IActionResult> Find(JsonElement requert)
  408. {
  409. try
  410. {
  411. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  412. var client = _azureCosmos.GetCosmosClient();
  413. List<SchoolYear> years = await _azureStorage.FindListByDict<SchoolYear>(new Dictionary<string, object>() { { "RowKey", code }, { "PartitionKey", "Exam" } });
  414. int year = 0;
  415. if (years.Count > 0)
  416. {
  417. year = years[0].year;
  418. if (year == 1970)
  419. {
  420. long ct = 0;
  421. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: "SELECT top 1 c.createTime FROM c order by c.createTime ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{code}") }))
  422. {
  423. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  424. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  425. {
  426. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  427. while (accounts.MoveNext())
  428. {
  429. JsonElement account = accounts.Current;
  430. ct = account.GetProperty("createTime").GetInt64();
  431. }
  432. }
  433. }
  434. year = ct == 0 ? DateTimeOffset.UtcNow.Year : DateTimeOffset.FromUnixTimeMilliseconds(ct).Year;
  435. years[0].year = year;
  436. await _azureStorage.SaveOrUpdate<SchoolYear>(years[0]);
  437. }
  438. }
  439. else
  440. {
  441. long ct = 0;
  442. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: "SELECT top 1 c.createTime FROM c order by c.createTime ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{code}") }))
  443. {
  444. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  445. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  446. {
  447. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  448. while (accounts.MoveNext())
  449. {
  450. JsonElement account = accounts.Current;
  451. ct = account.GetProperty("createTime").GetInt64();
  452. }
  453. }
  454. }
  455. year = ct == 0 ? DateTimeOffset.UtcNow.Year : DateTimeOffset.FromUnixTimeMilliseconds(ct).Year;
  456. SchoolYear sy = new()
  457. {
  458. RowKey = code.ToString(),
  459. PartitionKey = "Exam",
  460. year = year
  461. };
  462. await _azureStorage.Save<SchoolYear>(sy);
  463. }
  464. 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.owner, c.scope,c.classes,c.sRate,c.lostStu,c.sStatus from c ";
  465. if (requert.TryGetProperty("classIds", out JsonElement classIds))
  466. {
  467. List<string> ids = classIds.ToObject<List<string>>();
  468. HashSet<string> strs = new HashSet<string>();
  469. if (ids.Count > 1)
  470. {
  471. foreach (string id in ids)
  472. {
  473. strs.Add($"array_contains(c.classes,'{id}')");
  474. }
  475. }
  476. else
  477. {
  478. string ssr = ids.Count > 0 ? ids[0] : "";
  479. strs.Add($"array_contains(c.classes,'{ssr}')");
  480. }
  481. string ss = string.Join(" or ", strs);
  482. 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.owner, c.scope,c.classes,c.sRate,c.lostStu,c.sStatus from c where ({ss})";
  483. };
  484. string continuationToken = string.Empty;
  485. string token = default;
  486. //是否需要进行分页查询,默认不分页
  487. bool iscontinuation = false;
  488. if (requert.TryGetProperty("token", out JsonElement token_1))
  489. {
  490. token = token_1.GetString();
  491. iscontinuation = true;
  492. };
  493. //默认不指定返回大小
  494. int? topcout = null;
  495. if (requert.TryGetProperty("count", out JsonElement jcount))
  496. {
  497. if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
  498. {
  499. topcout = data;
  500. }
  501. }
  502. List<ExamInfo> examInfo = new List<ExamInfo>();
  503. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: query, continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"Exam-{code}") }))
  504. {
  505. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  506. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  507. {
  508. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  509. {
  510. //obj.TryGetProperty("progress", out JsonElement progress);
  511. examInfo.Add(obj.ToObject<ExamInfo>());
  512. }
  513. }
  514. if (iscontinuation)
  515. {
  516. continuationToken = item.GetContinuationToken();
  517. break;
  518. }
  519. }
  520. //List<string> examIds = new List<string>();
  521. /* List<ExamResult> examResults = new List<ExamResult>();
  522. foreach (ExamInfo info in examInfos) {
  523. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamResult>(
  524. queryText: $"select value(c) from c where c.examId = '{info.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamResult-{info.id}") }))
  525. {
  526. examResults.Add(item);
  527. }
  528. }*/
  529. /* List<(string id, double scores)> listExamInfo = new List<(string id, double scores)>();
  530. foreach (ExamInfo info in examInfos)
  531. {
  532. //记录某次考试所有学生得分总分
  533. double score = 0;
  534. double allScore = 0;
  535. int stuCount = 0;
  536. foreach (ExamResult examResult in examResults) {
  537. if (info.id == examResult.examId) {
  538. foreach (List<double> sc in examResult.studentScores) {
  539. score += sc.Sum();
  540. }
  541. stuCount = examResult.studentIds.Count;
  542. }
  543. }
  544. double ascore = stuCount > 0 ? Math.Round(score * 0.1 / stuCount, 2) : 0;
  545. foreach (PaperSimple simple in info.papers) {
  546. allScore += simple.point.Sum();
  547. }
  548. listExamInfo.Add((info.id, (allScore> 0 ? ascore / allScore * 100: 0)));
  549. }
  550. var examInfo = examInfos.Select(o =>
  551. new
  552. {
  553. o.id,
  554. o.scope,
  555. o.stuCount,
  556. o.name,
  557. o.period,
  558. o.startTime,
  559. o.endTime,
  560. o.type,
  561. o.progress,
  562. o.examType,
  563. o.createTime,
  564. o.subjects,
  565. o.grades,
  566. o.classes,
  567. score = listExamInfo.FirstOrDefault(c => c.id == o.id).scores,
  568. }
  569. );*/
  570. return Ok(new { examInfo, token = continuationToken, year });
  571. }
  572. catch (Exception e)
  573. {
  574. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  575. return BadRequest();
  576. }
  577. }
  578. [ProducesDefaultResponseType]
  579. [Authorize(Roles = "IES")]
  580. [AuthToken(Roles = "teacher,admin")]
  581. [HttpPost("find-summary")]
  582. public async Task<IActionResult> FindSummary(JsonElement requert)
  583. {
  584. try
  585. {
  586. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  587. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  588. var client = _azureCosmos.GetCosmosClient();
  589. List<ExamInfo> examInfo = new List<ExamInfo>();
  590. //var query = $"select value(c) from c ";
  591. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c where c.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
  592. {
  593. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  594. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  595. {
  596. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  597. {
  598. //obj.TryGetProperty("progress", out JsonElement progress);
  599. examInfo.Add(obj.ToObject<ExamInfo>());
  600. }
  601. }
  602. }
  603. return Ok(new { examInfo });
  604. }
  605. catch (Exception e)
  606. {
  607. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/FindSummary()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  608. return BadRequest();
  609. }
  610. }
  611. /// <summary>
  612. /// 学生回答问题
  613. /// </summary>
  614. /// <param name="request"></param>
  615. /// <returns></returns>
  616. [ProducesDefaultResponseType]
  617. [Authorize(Roles = "IES")]
  618. [AuthToken(Roles = "student,teacher")]
  619. [HttpPost("upsert-record")]
  620. public async Task<IActionResult> upsertRecord(JsonElement request)
  621. {
  622. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  623. //学校编码
  624. //if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
  625. if (!request.TryGetProperty("answer", out JsonElement answer)) return BadRequest();
  626. //if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  627. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  628. if (!request.TryGetProperty("classIds", out JsonElement classId)) return BadRequest();
  629. if (!request.TryGetProperty("multipleRule", out JsonElement multipleRule)) return BadRequest();
  630. //if (!request.TryGetProperty("answers ", out JsonElement tandardAnswer)) return BadRequest();
  631. if (!request.TryGetProperty("paperId", out JsonElement paperId)) return BadRequest();
  632. //根据不同评测的类型返回对应的编码
  633. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  634. if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
  635. var (userId, _, _, school) = HttpContext.GetAuthTokenInfo();
  636. try
  637. {
  638. List<string> ids = new List<string>();
  639. ids = classId.ToObject<List<string>>();
  640. var client = _azureCosmos.GetCosmosClient();
  641. ExamInfo info = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.GetString(), new PartitionKey($"{scode}"));
  642. //确定当前学生所在班级且该班级参与该活动
  643. List<string> cIds = new();
  644. if (ids.Count == 0) return Ok(new { code = 1, msg = "未找到相关班级信息" });
  645. if (string.IsNullOrEmpty(userId)) return Ok(new { code = 1, msg = "当前用户信息未找到" });
  646. foreach (string cId in ids)
  647. {
  648. //List<string> stus = new List<string>();
  649. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(
  650. queryText: $"select c.classId as id from c where c.classId = '{cId}' and c.id = '{userId}'",
  651. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{info.school}") }))
  652. {
  653. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  654. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  655. {
  656. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  657. while (accounts.MoveNext())
  658. {
  659. JsonElement account = accounts.Current;
  660. cIds.Add(account.GetProperty("id").GetString());
  661. }
  662. break;
  663. }
  664. }
  665. if (info.scope.Equals("private"))
  666. {
  667. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(
  668. queryText: $"select c.id from c join A0 in c.members where c.id = '{cId}' and A0.id = '{userId}'",
  669. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
  670. {
  671. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  672. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  673. {
  674. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  675. while (accounts.MoveNext())
  676. {
  677. JsonElement account = accounts.Current;
  678. cIds.Add(account.GetProperty("id").GetString());
  679. }
  680. break;
  681. }
  682. }
  683. /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(
  684. queryText: $"select c.id from c where c.id = '{cId}' and array_contains(c.tmids,'{userId}') ",
  685. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
  686. {
  687. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  688. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  689. {
  690. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  691. while (accounts.MoveNext())
  692. {
  693. JsonElement account = accounts.Current;
  694. cIds.Add(account.GetProperty("id").GetString());
  695. }
  696. break;
  697. }
  698. }*/
  699. }
  700. else
  701. {
  702. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(
  703. queryText: $"select c.id from c join A0 in c.members where c.id = '{cId}' and A0.id = '{userId}'",
  704. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{info.school}") }))
  705. {
  706. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  707. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  708. {
  709. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  710. while (accounts.MoveNext())
  711. {
  712. JsonElement account = accounts.Current;
  713. cIds.Add(account.GetProperty("id").GetString());
  714. }
  715. break;
  716. }
  717. }
  718. }
  719. }
  720. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  721. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
  722. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id in ({string.Join(",", cIds.Select(o => $"'{o}'"))})",
  723. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  724. {
  725. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  726. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  727. {
  728. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  729. {
  730. examClassResults.Add(obj.ToObject<ExamClassResult>());
  731. }
  732. }
  733. }
  734. ExamClassResult classResult = new ExamClassResult();
  735. List<PaperSimple> standerAnswers = new List<PaperSimple>();
  736. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
  737. queryText: $"select A0.point,A0.answers from c join A0 in c.papers where c.id = '{id}'and A0.id = '{paperId}'",
  738. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  739. {
  740. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  741. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  742. {
  743. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  744. {
  745. standerAnswers.Add(obj.ToObject<PaperSimple>());
  746. }
  747. }
  748. }
  749. List<List<string>> ans = answer.ToObject<List<List<string>>>();
  750. List<List<string>> standard = new List<List<string>>();
  751. List<double> points = new List<double>();
  752. int rule = int.Parse(multipleRule.ToString());
  753. foreach (PaperSimple simple in standerAnswers)
  754. {
  755. standard = simple.answers;
  756. points = simple.point;
  757. }
  758. List<Task<string>> tasks = new List<Task<string>>();
  759. foreach (ExamClassResult result in examClassResults)
  760. {
  761. int index = result.studentIds.IndexOf(userId.ToString());
  762. //存放客观题作答详情
  763. if (result.ans.Count == 0)
  764. {
  765. foreach (string cc in result.studentIds)
  766. {
  767. List<List<string>> anc = new List<List<string>>();
  768. foreach (List<string> opc in standard)
  769. {
  770. anc.Add(new List<string>());
  771. }
  772. result.ans.Add(anc);
  773. }
  774. }
  775. //处理新增学生作答信息
  776. //List<List<string>> oq = new List<List<string>>();
  777. //classResult.studentAnswers[index] = ans;
  778. if (index == -1)
  779. {
  780. List<double> ansPoint = new List<double>();
  781. List<List<string>> anc = new List<List<string>>();
  782. List<List<Details>> mark = new List<List<Details>>();
  783. foreach (List<string> num in standard)
  784. {
  785. List<string> newAns = new List<string>();
  786. foreach (string san in num)
  787. {
  788. newAns.Add(san);
  789. }
  790. anc.Add(newAns);
  791. ansPoint.Add(-1);
  792. mark.Add(new List<Details>());
  793. }
  794. result.mark.Add(mark);
  795. result.ans.Add(anc);
  796. result.studentIds.Add(userId.ToString());
  797. result.studentScores.Add(ansPoint);
  798. result.studentAnswers.Add(new List<string>());
  799. result.sum.Add(0);
  800. }
  801. //int flagCount = 0;
  802. /*foreach (List<string> str in ans) {
  803. if (str.Count == 0) {
  804. flagCount++;
  805. }
  806. } */
  807. int newIndex = result.studentIds.IndexOf(userId.ToString());
  808. /* if (flagCount != standard.Count)
  809. {*/
  810. StringBuilder builder = new StringBuilder();
  811. builder.Append(result.examId).Append("/");
  812. builder.Append(result.subjectId).Append("/");
  813. builder.Append(userId).Append("/");
  814. builder.Append("ans.json");
  815. /*string FileName = result.examId + "/" + result.subjectId + "/" + studentId;
  816. string blob = FileName + "/" + "ans.json";*/
  817. tasks.Add(_azureStorage.UploadFileByContainer(code.ToString(), ans.ToJsonString(), "exam", builder.ToString(), false));
  818. result.studentAnswers[newIndex].Add(builder.ToString());
  819. //}
  820. //List<(int index ,string content, double count)> acount = new List<(int index,string content, double count)>();
  821. for (int i = 0; i < ans.Count; i++)
  822. {
  823. var ac = ans[i].Where(a => a.Trim().Length > 0).ToList().Count;
  824. var sc = standard[i].Count;
  825. //算分处理
  826. if (sc > 0)
  827. {
  828. result.ans[newIndex][i] = ans[i];
  829. if (ac == sc && sc == 1)
  830. {
  831. foreach (string right in ans[i])
  832. {
  833. if (standard[i].Contains(right))
  834. {
  835. result.studentScores[newIndex][i] = points[i];
  836. }
  837. else
  838. {
  839. result.studentScores[newIndex][i] = 0;
  840. }
  841. }
  842. }
  843. else
  844. {
  845. if (rule > 0)
  846. {
  847. int falseCount = 0;
  848. if (ac > 0)
  849. {
  850. foreach (string obj in ans[i])
  851. {
  852. if (!standard[i].Contains(obj))
  853. {
  854. falseCount++;
  855. }
  856. }
  857. switch (rule)
  858. {
  859. case 1:
  860. if (ac == sc)
  861. {
  862. if (falseCount == 0)
  863. {
  864. result.studentScores[newIndex][i] = points[i];
  865. }
  866. else
  867. {
  868. result.studentScores[newIndex][i] = 0;
  869. }
  870. }
  871. else
  872. {
  873. result.studentScores[newIndex][i] = 0;
  874. }
  875. break;
  876. case 2:
  877. if (falseCount > 0)
  878. {
  879. result.studentScores[newIndex][i] = 0;
  880. }
  881. else
  882. {
  883. if (ac == sc)
  884. {
  885. result.studentScores[newIndex][i] = points[i];
  886. }
  887. else
  888. {
  889. result.studentScores[newIndex][i] = points[i] / 2;
  890. }
  891. }
  892. break;
  893. case 3:
  894. if (falseCount > 0)
  895. {
  896. result.studentScores[newIndex][i] = 0;
  897. }
  898. else
  899. {
  900. if (ac == sc)
  901. {
  902. result.studentScores[newIndex][i] = points[i];
  903. }
  904. else
  905. {
  906. result.studentScores[newIndex][i] = System.Math.Round((double)ac / sc * points[i], 1);
  907. }
  908. }
  909. break;
  910. case 4:
  911. if (ac == sc)
  912. {
  913. result.studentScores[newIndex][i] = points[i];
  914. }
  915. else
  916. {
  917. double persent = (double)(sc - 2 * falseCount) / sc;
  918. if (persent <= 0)
  919. {
  920. result.studentScores[newIndex][i] = 0;
  921. }
  922. else
  923. {
  924. result.studentScores[newIndex][i] = System.Math.Round(persent * points[i], 1);
  925. }
  926. }
  927. break;
  928. }
  929. }
  930. else
  931. {
  932. result.studentScores[newIndex][i] = 0;
  933. }
  934. }
  935. }
  936. }
  937. }
  938. /*if (result.studentScores.Contains(-1)) {
  939. }*/
  940. bool flag = true;
  941. foreach (List<double> scores in result.studentScores)
  942. {
  943. foreach (double score in scores)
  944. {
  945. if (score == -1)
  946. {
  947. flag = false;
  948. break;
  949. }
  950. }
  951. }
  952. //bool isAns = true;
  953. bool isAns = result.studentScores[newIndex].Exists(s => s == -1);
  954. HttpContext.Items.TryGetValue("Scope", out object scope);
  955. if (flag)
  956. {
  957. result.progress = true;
  958. info.subjects.ForEach(s =>
  959. {
  960. if (s.id.Equals(subjectId.ToString()))
  961. {
  962. s.classCount += 1;
  963. }
  964. });
  965. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, id.ToString(), new PartitionKey($"{scode}"));
  966. }
  967. if (isAns)
  968. {
  969. if ($"{scope}".Equals(Constant.ScopeStudent))
  970. {
  971. StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
  972. activity.taskStatus = 1;
  973. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
  974. }
  975. if ($"{scope}".Equals(Constant.ScopeTmdUser))
  976. {
  977. StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
  978. activity.taskStatus = 1;
  979. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
  980. }
  981. if ($"{scope}".Equals(Constant.ScopeTeacher))
  982. {
  983. StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
  984. activity.taskStatus = 1;
  985. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
  986. }
  987. }
  988. else
  989. {
  990. if ($"{scope}".Equals(Constant.ScopeStudent))
  991. {
  992. StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
  993. activity.taskStatus = 0;
  994. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
  995. }
  996. if ($"{scope}".Equals(Constant.ScopeTmdUser))
  997. {
  998. StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
  999. activity.taskStatus = 0;
  1000. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
  1001. }
  1002. if ($"{scope}".Equals(Constant.ScopeTeacher))
  1003. {
  1004. StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
  1005. activity.taskStatus = 0;
  1006. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
  1007. }
  1008. }
  1009. result.sum[newIndex] = result.studentScores[newIndex].Sum();
  1010. classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  1011. }
  1012. await Task.WhenAll(tasks);
  1013. return Ok(new { classResult });
  1014. }
  1015. catch (Exception e)
  1016. {
  1017. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecord()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1018. return BadRequest();
  1019. }
  1020. }
  1021. [ProducesDefaultResponseType]
  1022. [Authorize(Roles = "IES")]
  1023. [AuthToken(Roles = "teacher,admin")]
  1024. [HttpPost("upsert-record-by-teacher")]
  1025. public async Task<IActionResult> upsertRecordByTeacher(JsonElement request)
  1026. {
  1027. //ResponseBuilder builder = ResponseBuilder.custom();
  1028. try
  1029. {
  1030. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1031. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1032. if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
  1033. if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  1034. //if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  1035. //此参数表明此次操作对象为个人还是校本的评测内容
  1036. if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
  1037. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1038. //要先处理状态,判断卷子是否存在,并判断卷子归属的考试是否允许再次提交
  1039. //List<ExamInfo> exams = await _azureCosmos.FindByDict<ExamInfo>(new Dictionary<string, object> { { "id", request.examCode } });
  1040. List<List<double>> ans = point.ToObject<List<List<double>>>();
  1041. List<stus> sIds = studentId.ToObject<List<stus>>();
  1042. var client = _azureCosmos.GetCosmosClient();
  1043. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  1044. if (request.TryGetProperty("classId", out JsonElement classId))
  1045. {
  1046. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  1047. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
  1048. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  1049. {
  1050. examClassResults.Add(item);
  1051. }
  1052. }
  1053. else
  1054. {
  1055. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  1056. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1057. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  1058. {
  1059. examClassResults.Add(item);
  1060. }
  1061. }
  1062. ExamClassResult classResult = new ExamClassResult();
  1063. List<Task<ItemResponse<StuActivity>>> tasks = new List<Task<ItemResponse<StuActivity>>>();
  1064. //ExamInfo classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
  1065. //ExamClassResult classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamClassResult>(id.ToString(), new PartitionKey($"{code}"));
  1066. /*foreach (double index in ans) {
  1067. classResult.studentScores.in
  1068. }*/
  1069. foreach (ExamClassResult result in examClassResults)
  1070. {
  1071. int index_sc = 0;
  1072. foreach (stus s in sIds)
  1073. {
  1074. int index = result.studentIds.IndexOf(s.id.ToString());
  1075. for (int i = 0; i < ans[index_sc].Count; i++)
  1076. {
  1077. result.studentScores[index][i] = ans[index_sc][i];
  1078. }
  1079. result.sum[index] = result.studentScores[index].Sum();
  1080. bool flag = result.studentScores[index].Exists(r => r == -1);
  1081. if (!flag)
  1082. {
  1083. if (s.type == 1)
  1084. {
  1085. try
  1086. {
  1087. StuActivity activity = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{s.id}"));
  1088. activity.sStatus = 1;
  1089. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
  1090. }
  1091. catch (Exception ex)
  1092. {
  1093. await _dingDing.SendBotMsg($"{_option.Location}\n{ex.Message}\n{ex.StackTrace}\n,id:{id},code:{s.id},school:{result?.school}", GroupNames.成都开发測試群組);
  1094. }
  1095. }
  1096. else
  1097. {
  1098. try
  1099. {
  1100. var response = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Activity-{result.school}-{s.id}"));
  1101. if (response.Status == 200)
  1102. {
  1103. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1104. StuActivity activity = json.ToObject<StuActivity>();
  1105. activity.sStatus = 1;
  1106. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
  1107. }else
  1108. {
  1109. List<string> scode = new();
  1110. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.shoolId from c where c.id = '{s.id}' and c.pk = 'Base'"))
  1111. {
  1112. using var stuJson = await JsonDocument.ParseAsync(item.ContentStream);
  1113. if (stuJson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1114. {
  1115. var accounts = stuJson.RootElement.GetProperty("Documents").EnumerateArray();
  1116. while (accounts.MoveNext())
  1117. {
  1118. JsonElement account = accounts.Current;
  1119. scode.Add(account.GetProperty("shoolId").GetString());
  1120. }
  1121. }
  1122. }
  1123. foreach (var sid in scode)
  1124. {
  1125. StuActivity activity = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{sid}-{s.id}"));
  1126. activity.sStatus = 1;
  1127. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
  1128. }
  1129. }
  1130. //StuActivity activity = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{result.school}-{s.id}"));
  1131. }
  1132. catch (Exception ex)
  1133. {
  1134. await _dingDing.SendBotMsg($"{_option.Location}\n{ex.Message}\n{ex.StackTrace}\n,id:{id},code:{s.id},school:{result?.school}", GroupNames.成都开发測試群組);
  1135. }
  1136. }
  1137. }
  1138. index_sc++;
  1139. }
  1140. if (!result.progress)
  1141. {
  1142. bool flag = true;
  1143. foreach (List<double> scores in result.studentScores)
  1144. {
  1145. foreach (double score in scores)
  1146. {
  1147. if (score == -1)
  1148. {
  1149. flag = false;
  1150. break;
  1151. }
  1152. }
  1153. }
  1154. if (flag)
  1155. {
  1156. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1157. result.progress = true;
  1158. exam.subjects.ForEach(s =>
  1159. {
  1160. if (s.id.Equals(subjectId.ToString()))
  1161. {
  1162. s.classCount += 1;
  1163. }
  1164. });
  1165. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
  1166. }
  1167. }
  1168. else
  1169. {
  1170. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1171. exam.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1172. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
  1173. }
  1174. classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  1175. await Task.WhenAll(tasks);
  1176. }
  1177. return Ok(new { classResult });
  1178. }
  1179. catch (Exception ex)
  1180. {
  1181. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecordByTeacher()\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  1182. return BadRequest();
  1183. }
  1184. /*if (exams.IsNotEmpty())
  1185. {
  1186. ExamInfo examInfo = exams[0];
  1187. //提交答案时间必须是状态已发布,且时间在起止时间内
  1188. if (examInfo.startTime <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && examInfo.status == 200 &&
  1189. examInfo.endTime >= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
  1190. {
  1191. return builder.Data(await _azureCosmos.SaveOrUpdate(request)).build();
  1192. }
  1193. else
  1194. {
  1195. return builder.Error(ResponseCode.FAILED, "请在作答时间段内提交答案!").build();
  1196. }
  1197. }
  1198. else
  1199. {
  1200. return builder.Error(ResponseCode.DATA_EXIST, "考试不存在!").build();
  1201. }*/
  1202. }
  1203. /// <summary>
  1204. /// 查询评测详细信息(教师或者学生通用)
  1205. /// </summary>
  1206. /// <param name="request"></param>
  1207. /// <returns></returns>
  1208. [ProducesDefaultResponseType]
  1209. [Authorize(Roles = "IES")]
  1210. [AuthToken(Roles = "teacher,admin")]
  1211. [HttpPost("find-summary-record")]
  1212. public async Task<IActionResult> findSummaryRecord(JsonElement requert)
  1213. {
  1214. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1215. try
  1216. {
  1217. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1218. //if (!requert.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
  1219. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1220. if (!requert.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
  1221. if (!requert.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  1222. // 如果只有学生id则返回学生参加过的考试 只返回相关摘要信息
  1223. var client = _azureCosmos.GetCosmosClient();
  1224. var (_, _, _, school) = HttpContext.GetAuthTokenInfo();
  1225. //string code = school_code.ToString().Substring(5);
  1226. //ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{school_code}"));
  1227. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  1228. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(queryText: $"select c.id,c.subjectId,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}'",
  1229. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school_code}") }))
  1230. {
  1231. examClassResults.Add(item);
  1232. }
  1233. List<string> ids = new();
  1234. foreach (ExamClassResult result in examClassResults)
  1235. {
  1236. ids.AddRange(result.studentIds);
  1237. }
  1238. ///获取真实的名称
  1239. List<ufo> ufos = new();
  1240. List<string> delIds = new();
  1241. if (ids.Count > 0)
  1242. {
  1243. List<string> sIds = new();
  1244. List<string> tIds = new();
  1245. List<ufo> students = new List<ufo>();
  1246. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))}) and c.pk = 'Base'"))
  1247. {
  1248. using var stuJson = await JsonDocument.ParseAsync(item.ContentStream);
  1249. if (stuJson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1250. {
  1251. var accounts = stuJson.RootElement.GetProperty("Documents").EnumerateArray();
  1252. while (accounts.MoveNext())
  1253. {
  1254. JsonElement account = accounts.Current;
  1255. ufo fo = new()
  1256. {
  1257. id = account.GetProperty("id").GetString(),
  1258. name = account.GetProperty("name").GetString(),
  1259. type = 2
  1260. };
  1261. students.Add(fo);
  1262. }
  1263. }
  1264. }
  1265. if (students.Count > 0)
  1266. {
  1267. ufos.AddRange(students);
  1268. foreach (ufo f in students)
  1269. {
  1270. sIds.Add(f.id);
  1271. }
  1272. if (ids.Count > sIds.Count)
  1273. {
  1274. tIds = ids.Except(sIds).ToList();
  1275. var content = new StringContent(tIds.ToJsonString(), Encoding.UTF8, "application/json");
  1276. string json = await _coreAPIHttpService.GetUserInfos(content);
  1277. if (!string.IsNullOrWhiteSpace(json))
  1278. {
  1279. try
  1280. {
  1281. List<ufo> tmdInfos = json.ToObject<List<ufo>>();
  1282. if (tmdInfos.IsNotEmpty())
  1283. {
  1284. foreach (ufo fo in tmdInfos)
  1285. {
  1286. fo.type = 1;
  1287. tIds.Add(fo.id);
  1288. }
  1289. ufos.AddRange(tmdInfos);
  1290. }
  1291. }
  1292. catch (Exception ex)
  1293. {
  1294. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.Get("Default").location}用户转换失败:{_coreAPIHttpService.options.Get("Default").url}{json}\n {ex.StackTrace}", GroupNames.成都开发測試群組);
  1295. }
  1296. }
  1297. }
  1298. delIds = ids.Except(sIds.Union(tIds)).ToList();
  1299. }
  1300. else
  1301. {
  1302. var content = new StringContent(ids.ToJsonString(), Encoding.UTF8, "application/json");
  1303. string json = await _coreAPIHttpService.GetUserInfos(content);
  1304. if (!string.IsNullOrWhiteSpace(json))
  1305. {
  1306. try
  1307. {
  1308. List<ufo> tmdInfos = json.ToObject<List<ufo>>();
  1309. if (tmdInfos.IsNotEmpty())
  1310. {
  1311. foreach (ufo fo in tmdInfos)
  1312. {
  1313. fo.type = 1;
  1314. tIds.Add(fo.id);
  1315. }
  1316. ufos.AddRange(tmdInfos);
  1317. delIds = ids.Except(tIds).ToList();
  1318. }
  1319. }
  1320. catch (Exception ex)
  1321. {
  1322. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.Get("Default").location}用户转换失败:{_coreAPIHttpService.options.Get("Default").url}{json}\n {ex.StackTrace}", GroupNames.成都开发測試群組);
  1323. }
  1324. }
  1325. }
  1326. }
  1327. /*if (StringHelper.getKeyCount(requert) == 1 && requert.TryGetProperty("code", out JsonElement code))
  1328. {
  1329. List<object> props = new List<object>();
  1330. await foreach (var item in client.GetContainer(Constant.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}") }))
  1331. {
  1332. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1333. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1334. {
  1335. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1336. {
  1337. props.Add(obj.ToObject<object>());
  1338. }
  1339. }
  1340. }
  1341. return Ok(new { props });
  1342. }
  1343. else
  1344. {
  1345. if (requert.TryGetProperty("examCode", out JsonElement _))
  1346. {
  1347. //List<string> props = new List<string> { "id", "code", "examCode", "status", "mark", "score" };
  1348. //List<ExamRecord> examRecords = await _azureCosmos.FindByDict<ExamRecord>(request, props);
  1349. //return builder.Data(examRecords).Extend(new Dictionary<string, object> { { "props", props } }).build();
  1350. List<object> props = new List<object>();
  1351. await foreach (var item in client.GetContainer(Constant.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}") }))
  1352. {
  1353. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1354. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1355. {
  1356. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1357. {
  1358. props.Add(obj.ToObject<object>());
  1359. }
  1360. }
  1361. }
  1362. return Ok(new { props });
  1363. }
  1364. }*/
  1365. return Ok(new { examClassResults, ufos, delIds });
  1366. }
  1367. catch (Exception ex)
  1368. {
  1369. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findSummaryRecord()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1370. return BadRequest();
  1371. }
  1372. }
  1373. //学生端查询评测列表
  1374. [ProducesDefaultResponseType]
  1375. [Authorize(Roles = "IES")]
  1376. [AuthToken(Roles = "student,teacher,admin")]
  1377. [HttpPost("find-summary-by-student")]
  1378. public async Task<IActionResult> findSummaryStudent(JsonElement requert)
  1379. {
  1380. //ResponseBuilder builder = ResponseBuilder.custom();
  1381. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1382. try
  1383. {
  1384. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1385. //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1386. if (!requert.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  1387. if (!requert.TryGetProperty("code", out JsonElement school)) return BadRequest();
  1388. if (!requert.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
  1389. var client = _azureCosmos.GetCosmosClient();
  1390. var query = $"select c.id,c.code,c.school,c.creatorId,c.progress,A0.id paperId,A0.code paperCode,A0.name paperName,A0.knowledge,A0.point,A0.field,A0.multipleRule,A0.scope,A0.blob,A0.time from c join A0 in c.papers where c.id ='{id}'";
  1391. List<PaperSimple> papers = new List<PaperSimple>();
  1392. List<object> subjects = new List<object>();
  1393. List<string> classIds = new List<string>();
  1394. //List<string> stus = new List<string>();
  1395. //存放当前学生所在班级ID或者名单ID
  1396. HashSet<string> resultIds = new HashSet<string>();
  1397. //List<string> ids = new List<string>();
  1398. //处理班级人数(公共部分的校本名单)
  1399. //List<Student> students = new List<Student>();
  1400. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select c.classId id from c where c.id = '{studentId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{school}") }))
  1401. {
  1402. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1403. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1404. {
  1405. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1406. while (accounts.MoveNext())
  1407. {
  1408. JsonElement account = accounts.Current;
  1409. resultIds.Add(account.GetProperty("id").GetString());
  1410. }
  1411. }
  1412. }
  1413. //获取自定义名单信息
  1414. List<GroupList> stuLists = new List<GroupList>();
  1415. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}'",
  1416. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
  1417. {
  1418. stuLists.Add(item);
  1419. }
  1420. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}'",
  1421. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  1422. {
  1423. stuLists.Add(item);
  1424. }
  1425. if (stuLists.Count > 0)
  1426. {
  1427. foreach (GroupList stuList in stuLists)
  1428. {
  1429. resultIds.Add(stuList.id);
  1430. }
  1431. }
  1432. var queryClassId = $"select c.classes id,c.stuLists stus from c where c.id ='{id}'";
  1433. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: queryClassId, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  1434. {
  1435. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1436. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1437. {
  1438. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1439. {
  1440. classIds.AddRange(obj.GetProperty("id").ToObject<List<string>>());
  1441. classIds.AddRange(obj.GetProperty("stus").ToObject<List<string>>());
  1442. //classIds = obj.ToObject<List<string>>();
  1443. }
  1444. }
  1445. }
  1446. //存放该学生所在班级参与当前评测的ID
  1447. List<string> infoIds = new List<string>();
  1448. foreach (string ids in resultIds)
  1449. {
  1450. if (classIds.Contains(ids))
  1451. {
  1452. infoIds.Add(ids);
  1453. }
  1454. }
  1455. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<PaperSimple>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  1456. {
  1457. papers.Add(item);
  1458. }
  1459. var querySubject = $"select A0.id,A0.name from c join A0 in c.subjects where c.id ='{id}'";
  1460. //List<object> props = new List<object>();
  1461. List<string> subId = new();
  1462. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: querySubject, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  1463. {
  1464. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1465. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1466. {
  1467. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1468. {
  1469. subjects.Add(obj.ToObject<object>());
  1470. subId.Add(obj.GetProperty("id").GetString());
  1471. }
  1472. }
  1473. }
  1474. var queryAnswers = $"select c.id,c.code,c.studentIds,c.subjectId,c.studentAnswers,c.studentScores,c.sum,c.mark,c.krate,c.frate from c where c.examId ='{id}' and array_contains(c.studentIds,'{studentId}') and c.pk = 'ExamClassResult' ";
  1475. List<ExamClassResult> answers = new List<ExamClassResult>();
  1476. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: queryAnswers,
  1477. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  1478. {
  1479. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1480. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1481. {
  1482. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1483. {
  1484. answers.Add(obj.ToObject<ExamClassResult>());
  1485. }
  1486. }
  1487. }
  1488. List<List<string>> stuAns = new();
  1489. List<List<double>> stuScore = new();
  1490. List<List<List<Details>>> mark = new();
  1491. List<List<double>> total = new();
  1492. List<double> average = new();
  1493. if (answers.Count > 0)
  1494. {
  1495. foreach (ExamClassResult result in answers)
  1496. {
  1497. List<double> sTotal = new();
  1498. int index = result.studentIds.IndexOf(studentId.ToString());
  1499. if (index == -1)
  1500. {
  1501. break;
  1502. }
  1503. stuAns.Add(result.studentAnswers[index]);
  1504. stuScore.Add(result.studentScores[index]);
  1505. mark.Add(result.mark[index]);
  1506. average.Add(result.average);
  1507. sTotal.Add(result.sum.Where(s => s <= 59).Count());
  1508. sTotal.Add(result.sum.Where(s => s > 59 && s <= 70).Count());
  1509. sTotal.Add(result.sum.Where(s => s > 70 && s <= 80).Count());
  1510. sTotal.Add(result.sum.Where(s => s > 80 && s <= 90).Count());
  1511. sTotal.Add(result.sum.Where(s => s > 90 && s <= 100).Count());
  1512. total.Add(sTotal);
  1513. }
  1514. }
  1515. List<(List<string> kn, List<double> kps, List<double> ckps)> know = new();
  1516. List<(List<int> fs, List<double> fps, List<double> cfps)> fp = new();
  1517. foreach (var s in stuTask(subId, papers, answers, studentId.GetString()))
  1518. {
  1519. know = s.know;
  1520. fp = s.filed;
  1521. }
  1522. if (papers.IsNotEmpty())
  1523. {
  1524. var knowledge = know.Select(k => new { k.kn, k.kps, k.ckps });
  1525. var filed = fp.Select(k => new { k.fs, k.fps, k.cfps });
  1526. //papers = papers
  1527. return Ok(new { papers, subjects, stuScore, stuAns, mark, total, claId = infoIds, knowledge, filed, average, status = 200 });
  1528. }
  1529. else
  1530. {
  1531. return Ok(new { papers, subjects, stuScore, stuAns, mark, total, claId = infoIds, status = 404 });
  1532. }
  1533. }
  1534. catch (Exception ex)
  1535. {
  1536. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-summary-by-student()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1537. return Ok(new { status = 400 });
  1538. }
  1539. }
  1540. private IEnumerable<(List<(List<string> kn, List<double> kps, List<double> ckps)> know, List<(List<int> fs, List<double> fps, List<double> cfps)> filed)> stuTask(List<string> subjectIds, List<PaperSimple> papers, List<ExamClassResult> answers, string stuId)
  1541. {
  1542. List<(List<string> kn, List<double> kps, List<double> ckps)> know = new List<(List<string> kn, List<double> kps, List<double> ckps)>();
  1543. List<(List<int> fs, List<double> fps, List<double> cfps)> filed = new List<(List<int> fs, List<double> fps, List<double> cfps)>();
  1544. int no = 0;
  1545. foreach (string sub in subjectIds)
  1546. {
  1547. List<double> kp = new();
  1548. List<double> fp = new();
  1549. List<double> ckp = new();
  1550. List<double> cfp = new();
  1551. List<int> fields = new() { 1, 2, 3, 4, 5, 6 };
  1552. //获取该试卷所有知识点和认知层次分布
  1553. List<List<string>> kones = papers[no].knowledge;
  1554. List<int> fs = papers[no].field;
  1555. List<double> point = papers[no].point;
  1556. //去重知识点
  1557. HashSet<string> knowles = new();
  1558. List<string> knowledges = new();
  1559. if (kones.Count > 0)
  1560. {
  1561. kones.ForEach(kno =>
  1562. {
  1563. kno.ForEach(k =>
  1564. {
  1565. knowles.Add(k);
  1566. });
  1567. });
  1568. }
  1569. foreach (string cla in knowles)
  1570. {
  1571. knowledges.Add(cla);
  1572. }
  1573. for (int k = 0; k < knowledges.Count; k++)
  1574. {
  1575. if (null == knowledges[k])
  1576. {
  1577. knowledges.Remove(knowledges[k]);
  1578. }
  1579. }
  1580. foreach (ExamClassResult result in answers)
  1581. {
  1582. if (result.subjectId.Equals(sub))
  1583. {
  1584. int index = result.studentIds.IndexOf(stuId.ToString());
  1585. //处理知识点
  1586. foreach (string k in knowledges)
  1587. {
  1588. //初始化单个知识点得分
  1589. double score = 0;
  1590. double allScore = 0;
  1591. int n = 0;
  1592. foreach (List<string> str in kones)
  1593. {
  1594. if (str.Contains(k))
  1595. {
  1596. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  1597. allScore += point.Count > 0 ? point[n] * itemPersent : 0;
  1598. if (result.studentScores.Count > 0)
  1599. {
  1600. if (result.studentScores[index].Count > 0)
  1601. {
  1602. score += result.studentScores[index][n] == -1 ? 0 : result.studentScores[index][n];
  1603. }
  1604. }
  1605. }
  1606. n++;
  1607. }
  1608. kp.Add(allScore > 0 ? Math.Round(score / allScore, 2) : 0);
  1609. }
  1610. //处理认知层次
  1611. foreach (int k in fields)
  1612. {
  1613. //初始化认知层次得分
  1614. double score = 0;
  1615. double allScore = 0;
  1616. int n = 0;
  1617. foreach (int str in fs)
  1618. {
  1619. if (str == k)
  1620. {
  1621. var itemPersent = 1;
  1622. allScore += point.Count > 0 ? point[n] * itemPersent : 0;
  1623. if (result.studentScores.Count > 0)
  1624. {
  1625. if (result.studentScores[index].Count > 0)
  1626. {
  1627. score += result.studentScores[index][n] == -1 ? 0 : result.studentScores[index][n];
  1628. }
  1629. }
  1630. }
  1631. n++;
  1632. }
  1633. fp.Add(allScore > 0 ? Math.Round(score / allScore, 2) : 0);
  1634. }
  1635. ckp = result.krate;
  1636. cfp = result.frate;
  1637. }
  1638. }
  1639. know.Add((knowledges, kp, ckp));
  1640. filed.Add((fields, fp, cfp));
  1641. no++;
  1642. }
  1643. yield return (know, filed);
  1644. }
  1645. //查询学生活动列表
  1646. [ProducesDefaultResponseType]
  1647. [Authorize(Roles = "IES")]
  1648. [AuthToken(Roles = "student")]
  1649. [HttpPost("find-all-by-student")]
  1650. public async Task<IActionResult> findAllStudent(JsonElement requert)
  1651. {
  1652. //ResponseBuilder builder = ResponseBuilder.custom();
  1653. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1654. try
  1655. {
  1656. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1657. if (!requert.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  1658. List<string> resultIds = new List<string>();
  1659. var client = _azureCosmos.GetCosmosClient();
  1660. //查询校本班级ID
  1661. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(
  1662. queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
  1663. {
  1664. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1665. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1666. {
  1667. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1668. while (accounts.MoveNext())
  1669. {
  1670. JsonElement account = accounts.Current;
  1671. resultIds.Add(account.GetProperty("id").GetString());
  1672. }
  1673. }
  1674. }
  1675. //查询私人班级ID
  1676. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(
  1677. queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
  1678. {
  1679. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1680. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1681. {
  1682. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1683. while (accounts.MoveNext())
  1684. {
  1685. JsonElement account = accounts.Current;
  1686. resultIds.Add(account.GetProperty("id").GetString());
  1687. }
  1688. }
  1689. }
  1690. //StringBuilder builder = new StringBuilder();
  1691. HashSet<string> strs = new HashSet<string>();
  1692. if (resultIds.Count > 1)
  1693. {
  1694. foreach (string str in resultIds)
  1695. {
  1696. strs.Add($"array_contains(c.classes,'{str}')");
  1697. //builder.Append($"array_contains(c.targetClassIds,'{str}')").Append("or");
  1698. }
  1699. //builder.ToString().Substring(0, builder.ToString().Length - 2);
  1700. }
  1701. else
  1702. {
  1703. string ssr = resultIds.Count > 0 ? resultIds[0] : "";
  1704. strs.Add($"array_contains(c.classes,'{ssr}')");
  1705. //builder.Append($" array_contains(c.targetClassIds,'{ssr}')");
  1706. }
  1707. string ss = string.Join(" or ", strs);
  1708. //if (!requert.TryGetProperty("school", out JsonElement school)) return BadRequest();
  1709. 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' ";
  1710. List<object> props = new List<object>();
  1711. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: query))
  1712. {
  1713. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1714. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1715. {
  1716. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1717. {
  1718. props.Add(obj.ToObject<object>());
  1719. }
  1720. }
  1721. }
  1722. 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'";
  1723. List<ExamClassResult> Classes = new List<ExamClassResult>();
  1724. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: queryClass))
  1725. {
  1726. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1727. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1728. {
  1729. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1730. {
  1731. Classes.Add(obj.ToObject<ExamClassResult>());
  1732. }
  1733. }
  1734. }
  1735. List<ExamClassResult> result = new List<ExamClassResult>();
  1736. foreach (ExamClassResult classResult in Classes)
  1737. {
  1738. int index = classResult.studentIds.IndexOf(studentId.ToString());
  1739. ExamClassResult result1 = new ExamClassResult();
  1740. result1.examId = classResult.examId;
  1741. result1.subjectId = classResult.subjectId;
  1742. result1.studentAnswers.Add(classResult.studentAnswers[index]);
  1743. result1.studentScores.Add(classResult.studentScores[index]);
  1744. result.Add(result1);
  1745. }
  1746. return Ok(new { props, result });
  1747. }
  1748. catch (Exception ex)
  1749. {
  1750. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1751. return BadRequest();
  1752. }
  1753. }
  1754. //查询学生活动列表
  1755. [ProducesDefaultResponseType]
  1756. [Authorize(Roles = "IES")]
  1757. [AuthToken(Roles = "student")]
  1758. [HttpPost("find-score-by-student")]
  1759. public async Task<IActionResult> findScoreByStudent(JsonElement requert)
  1760. {
  1761. //ResponseBuilder builder = ResponseBuilder.custom();
  1762. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1763. try
  1764. {
  1765. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1766. //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1767. var client = _azureCosmos.GetCosmosClient();
  1768. var query = $"select c.examId,c.subjectId,c.studentScores from c where array_contains(c.studentIds,'{id}') ";
  1769. List<object> props = new List<object>();
  1770. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: query))
  1771. {
  1772. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1773. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1774. {
  1775. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1776. {
  1777. props.Add(obj.ToObject<object>());
  1778. }
  1779. }
  1780. }
  1781. return Ok(props);
  1782. }
  1783. catch (Exception ex)
  1784. {
  1785. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1786. return BadRequest();
  1787. }
  1788. }
  1789. //查询学生活动列表
  1790. [ProducesDefaultResponseType]
  1791. [Authorize(Roles = "IES")]
  1792. [AuthToken(Roles = "teacher,admin")]
  1793. [HttpPost("finish")]
  1794. public async Task<IActionResult> finish(JsonElement requert)
  1795. {
  1796. //ResponseBuilder builder = ResponseBuilder.custom();
  1797. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1798. try
  1799. {
  1800. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1801. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1802. var client = _azureCosmos.GetCosmosClient();
  1803. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1804. info.progress = "finish";
  1805. info.endTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1806. List<ExamClassResult> classResults = new();
  1807. if (info.scope.Equals("school"))
  1808. {
  1809. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  1810. queryText: $"select value(c) from c where c.examId = '{id}'",
  1811. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  1812. {
  1813. classResults.Add(item);
  1814. }
  1815. }
  1816. else
  1817. {
  1818. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  1819. queryText: $"select value(c) from c where c.examId = '{id}'",
  1820. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  1821. {
  1822. classResults.Add(item);
  1823. }
  1824. }
  1825. foreach (ExamClassResult examClass in classResults)
  1826. {
  1827. examClass.progress = true;
  1828. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(examClass, examClass.id, new PartitionKey($"{examClass.code}"));
  1829. }
  1830. info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  1831. return Ok(info);
  1832. }
  1833. catch (Exception ex)
  1834. {
  1835. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/finish\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1836. return BadRequest();
  1837. }
  1838. }
  1839. /*//查询任务列表
  1840. [ProducesDefaultResponseType]
  1841. //[AuthToken(Roles = "Student")]
  1842. [HttpPost("scoring")]
  1843. public async Task<IActionResult> Scoring(JsonElement requert)
  1844. {
  1845. //ResponseBuilder builder = ResponseBuilder.custom();
  1846. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1847. try
  1848. {
  1849. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1850. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1851. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1852. var client = _azureCosmos.GetCosmosClient();
  1853. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1854. int index = 0;
  1855. foreach (ExamSubject subject in info.subjects) {
  1856. if (!subject.id.Equals(subjectId.ToString()))
  1857. {
  1858. index++;
  1859. }
  1860. else {
  1861. break;
  1862. }
  1863. }
  1864. List<string> stuAns = new();
  1865. Dictionary<string, List<List<double>>> keyValues = new();
  1866. List<ExamClassResult> classResults = new();
  1867. if (info.scope.Equals("school"))
  1868. {
  1869. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  1870. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1871. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  1872. {
  1873. classResults.Add(item);
  1874. }
  1875. }
  1876. else
  1877. {
  1878. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  1879. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1880. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  1881. {
  1882. classResults.Add(item);
  1883. }
  1884. }
  1885. List<List<double>> itemScore = new();
  1886. for (int i = 0; i < info.papers[index].point.Count; i++)
  1887. {
  1888. List<double> score = new();
  1889. foreach (ExamClassResult examClass in classResults)
  1890. {
  1891. foreach (List<double> sc in examClass.studentScores)
  1892. {
  1893. score.Add(sc[i]);
  1894. }
  1895. }
  1896. itemScore.Add(score);
  1897. }
  1898. foreach (ExamClassResult examClass in classResults)
  1899. {
  1900. foreach (List<string> ans in examClass.studentAnswers)
  1901. {
  1902. if (ans.Count > 0)
  1903. {
  1904. stuAns.Add(ans[0]);
  1905. }
  1906. else
  1907. {
  1908. stuAns.Add("");
  1909. }
  1910. }
  1911. }
  1912. //info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  1913. return Ok(new { score = itemScore , stuAns, paper = info.papers });
  1914. }
  1915. catch (Exception ex)
  1916. {
  1917. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1918. return BadRequest();
  1919. }
  1920. }*/
  1921. [ProducesDefaultResponseType]
  1922. [Authorize(Roles = "IES")]
  1923. [AuthToken(Roles = "teacher,admin")]
  1924. [HttpPost("scoring")]
  1925. public async Task<IActionResult> scoring(JsonElement requert)
  1926. {
  1927. //ResponseBuilder builder = ResponseBuilder.custom();
  1928. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1929. try
  1930. {
  1931. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1932. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1933. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1934. //if (!requert.TryGetProperty("type", out JsonElement type)) return BadRequest();
  1935. if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  1936. if (!requert.TryGetProperty("count", out JsonElement scount)) return BadRequest();
  1937. var client = _azureCosmos.GetCosmosClient();
  1938. //var redisClient = _azureRedis.GetRedisClient(8);
  1939. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1940. List<ExamClassResult> classResults = new();
  1941. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  1942. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  1943. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and array_contains(c.tIds,'{tId}') ",
  1944. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  1945. {
  1946. attr.Add(item);
  1947. }
  1948. List<SDK.Models.Cosmos.Common.Scoring> attrSc = new List<SDK.Models.Cosmos.Common.Scoring>();
  1949. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  1950. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1951. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  1952. {
  1953. attrSc.Add(item);
  1954. }
  1955. int index = 0;
  1956. foreach (ExamSubject subject in info.subjects)
  1957. {
  1958. if (!subject.id.Equals(subjectId.ToString()))
  1959. {
  1960. index++;
  1961. }
  1962. else
  1963. {
  1964. break;
  1965. }
  1966. }
  1967. List<dynamic> objs = new List<dynamic>();
  1968. List<dynamic> wobjs = new List<dynamic>();
  1969. /*if (type.GetInt32() != 1) {
  1970. return Ok(new { attr, paper = info.papers[index].blob });
  1971. }*/
  1972. //List<SDK.Models.Cosmos.Common.Scoring> errs = new();
  1973. //List<SDK.Models.Cosmos.Common.Scoring> arbs = new();
  1974. Correct correct = null;
  1975. var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
  1976. if (cResponse.Status == 200)
  1977. {
  1978. using var cJson = await JsonDocument.ParseAsync(cResponse.ContentStream);
  1979. correct = cJson.ToObject<Correct>();
  1980. }
  1981. int finishCount = 0;
  1982. foreach (SDK.Models.Cosmos.Common.Scoring ss in attrSc)
  1983. {
  1984. for (int i = 0; i < correct.num; i++)
  1985. {
  1986. List<double> tsc = new List<double>();
  1987. foreach (Item item in ss.items)
  1988. {
  1989. if (item.scores.Count > 0)
  1990. {
  1991. if (i >= item.scores.Count)
  1992. {
  1993. break;
  1994. }
  1995. else
  1996. {
  1997. tsc.Add(item.scores[i].sc);
  1998. }
  1999. }
  2000. }
  2001. bool flag = tsc.Exists(s => s == -1);
  2002. if (!flag && tsc.Count > 0)
  2003. {
  2004. finishCount++;
  2005. }
  2006. }
  2007. }
  2008. if (attr.Count > 0)
  2009. {
  2010. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  2011. {
  2012. //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});
  2013. List<dynamic> sc = new List<dynamic>();
  2014. List<dynamic> allSc = new List<dynamic>();
  2015. ss.qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
  2016. int indexScore = 0;
  2017. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code.GetString());
  2018. foreach (Item item in ss.items)
  2019. {
  2020. var count = item.scores.GroupBy(i => new { i.tmdId, i.sc }).Select(c => c.Key.sc).ToList();
  2021. allSc.Add(count.FirstOrDefault());
  2022. List<double> scc = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).ToList();
  2023. List<string> blob = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.mark).ToList();
  2024. //item.scores.Where(x => x.tmdId.Equals(tId.GetString())).SelectMany(p => p.sc, (p, d) => new { });
  2025. if (scc.Count > 0)
  2026. {
  2027. sc.Add(new { sc = scc.FirstOrDefault(), blob = blob.FirstOrDefault(), item.ssc });
  2028. }
  2029. else
  2030. {
  2031. ss.scores = scores;
  2032. sc.Add(new { sc = ss.scores[indexScore], blob = "", item.ssc });
  2033. }
  2034. indexScore++;
  2035. }
  2036. var obj = new { ss.id, ss.stuId, ss.examId, ss.subjectId, item = sc, ss.qs, blob = ansBlob, ss.tIds, scores = scores, ss.model, ss.mode };
  2037. objs.Add(obj);
  2038. }
  2039. }
  2040. else
  2041. {
  2042. if (requert.TryGetProperty("stuId", out JsonElement stuId))
  2043. {
  2044. objs = await Review(attrSc, id.GetString(), code.GetString(), subjectId.GetString(), scount.GetInt32(), tId.GetString(), stuId.GetString());
  2045. }
  2046. else
  2047. {
  2048. objs = await Review(attrSc, id.GetString(), code.GetString(), subjectId.GetString(), scount.GetInt32(), tId.GetString(), "");
  2049. }
  2050. }
  2051. var fp = attr.Count > 0 ? Math.Round(finishCount * 1.0 / (attrSc.Count * correct.num), 2) : 0;
  2052. return Ok(new { objs, paper = info.papers[index].blob, fp });
  2053. }
  2054. catch (Exception ex)
  2055. {
  2056. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  2057. return BadRequest();
  2058. }
  2059. }
  2060. //查找异常卷
  2061. [ProducesDefaultResponseType]
  2062. [Authorize(Roles = "IES")]
  2063. [AuthToken(Roles = "teacher,admin")]
  2064. [HttpPost("find-err")]
  2065. public async Task<IActionResult> findErr(JsonElement requert)
  2066. {
  2067. //ResponseBuilder builder = ResponseBuilder.custom();
  2068. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2069. try
  2070. {
  2071. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2072. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2073. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  2074. //if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  2075. var client = _azureCosmos.GetCosmosClient();
  2076. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
  2077. if (response.Status == 200)
  2078. {
  2079. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  2080. ExamInfo info = json.ToObject<ExamInfo>();
  2081. //ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  2082. List<ExamClassResult> classResults = new();
  2083. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  2084. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2085. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  2086. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2087. {
  2088. attr.Add(item);
  2089. }
  2090. int index = 0;
  2091. foreach (ExamSubject subject in info.subjects)
  2092. {
  2093. if (!subject.id.Equals(subjectId.ToString()))
  2094. {
  2095. index++;
  2096. }
  2097. else
  2098. {
  2099. break;
  2100. }
  2101. }
  2102. List<dynamic> objs = new List<dynamic>();
  2103. List<SDK.Models.Cosmos.Common.Scoring> errs = new();
  2104. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  2105. {
  2106. List<Qs> qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.err)).ToList();
  2107. if (qs.Count > 0)
  2108. {
  2109. ss.qs = qs;
  2110. errs.Add(ss);
  2111. }
  2112. }
  2113. return Ok(new { errs, paper = info.papers[index].blob });
  2114. }
  2115. else
  2116. {
  2117. return BadRequest();
  2118. }
  2119. }
  2120. catch (Exception ex)
  2121. {
  2122. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-err\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  2123. return BadRequest();
  2124. }
  2125. }
  2126. [ProducesDefaultResponseType]
  2127. [AuthToken(Roles = "teacher,admin")]
  2128. [HttpPost("find-arb")]
  2129. [Authorize(Roles = "IES")]
  2130. public async Task<IActionResult> findArb(JsonElement requert)
  2131. {
  2132. //ResponseBuilder builder = ResponseBuilder.custom();
  2133. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2134. try
  2135. {
  2136. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2137. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2138. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  2139. if (!requert.TryGetProperty("et", out JsonElement et)) return BadRequest();
  2140. //if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  2141. var client = _azureCosmos.GetCosmosClient();
  2142. long time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  2143. if (et.GetInt64() > time)
  2144. {
  2145. return Ok(new { msg = "还在进行中", code = 202 });
  2146. }
  2147. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  2148. List<ExamClassResult> classResults = new();
  2149. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  2150. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2151. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  2152. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2153. {
  2154. attr.Add(item);
  2155. }
  2156. int index = 0;
  2157. foreach (ExamSubject subject in info.subjects)
  2158. {
  2159. if (!subject.id.Equals(subjectId.ToString()))
  2160. {
  2161. index++;
  2162. }
  2163. else
  2164. {
  2165. break;
  2166. }
  2167. }
  2168. List<dynamic> objs = new List<dynamic>();
  2169. /*if (type.GetInt32() != 1) {
  2170. return Ok(new { attr, paper = info.papers[index].blob });
  2171. }*/
  2172. //List<SDK.Models.Cosmos.Common.Scoring> errs = new();
  2173. List<SDK.Models.Cosmos.Common.Scoring> arbs = new();
  2174. //List<(string id,List<double>)> osc = new List<(string id, List<double>)>();
  2175. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  2176. {
  2177. //List<double> original = new List<double>();
  2178. List<Item> arb = ss.items.Where(s => s.flag == false).ToList();
  2179. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code.GetString());
  2180. ss.blob = ansBlob;
  2181. ss.scores = scores;
  2182. if (arb.Count > 0)
  2183. {
  2184. ss.items = arb;
  2185. arbs.Add(ss);
  2186. }
  2187. }
  2188. return Ok(new { arbs = arbs.Select(a => new { a.items, a.blob, a.stuId, a.subjectId, a.id, a.scores }), paper = info.papers[index].blob });
  2189. }
  2190. catch (Exception ex)
  2191. {
  2192. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-arb\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  2193. return BadRequest();
  2194. }
  2195. }
  2196. //批阅,给老师随机分配阅卷数据,以及查询改老师已有的阅卷数据
  2197. private async Task<List<dynamic>> Review(List<SDK.Models.Cosmos.Common.Scoring> attr, string id, string code, string subjectId, int count, string tId, string stuId)
  2198. {
  2199. //ResponseBuilder builder = ResponseBuilder.custom();
  2200. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2201. try
  2202. {
  2203. var client = _azureCosmos.GetCosmosClient();
  2204. //var redisClient = _azureRedis.GetRedisClient(8);
  2205. List<ExamClassResult> classResults = new();
  2206. List<SDK.Models.Cosmos.Common.Scoring> recs = new();
  2207. List<SDK.Models.Cosmos.Common.Scoring> all = new();
  2208. //List<SDK.Models.Cosmos.Common.Scoring> attr = new();
  2209. /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2210. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' ",
  2211. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2212. {
  2213. attr.Add(item);
  2214. }*/
  2215. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  2216. {
  2217. if (scoring.tIds.Contains(tId.ToString()))
  2218. {
  2219. recs.Add(scoring);
  2220. }
  2221. else if (scoring.tIds.Count < scoring.count * scoring.model)
  2222. {
  2223. all.Add(scoring);
  2224. }
  2225. }
  2226. if (!string.IsNullOrEmpty(stuId))
  2227. {
  2228. List<SDK.Models.Cosmos.Common.Scoring> value = new();
  2229. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2230. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.stuId = '{stuId}' ",
  2231. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2232. {
  2233. value.Add(item);
  2234. }
  2235. if (value.Count > 0)
  2236. {
  2237. foreach (SDK.Models.Cosmos.Common.Scoring scoring in value)
  2238. {
  2239. if (scoring.tIds.Contains(tId.ToString()))
  2240. {
  2241. break;
  2242. }
  2243. else
  2244. {
  2245. scoring.tIds.Add(tId.ToString());
  2246. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
  2247. }
  2248. }
  2249. }
  2250. List<dynamic> objs = new List<dynamic>();
  2251. List<SDK.Models.Cosmos.Common.Scoring> val = new List<SDK.Models.Cosmos.Common.Scoring>();
  2252. foreach (SDK.Models.Cosmos.Common.Scoring ss in value)
  2253. {
  2254. //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 });
  2255. List<dynamic> sc = new List<dynamic>();
  2256. int indexScore = 0;
  2257. ss.qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
  2258. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code);
  2259. foreach (Item item in ss.items)
  2260. {
  2261. List<double> scc = item.scores.Where(x => x.tmdId.Equals(tId)).Select(c => c.sc).ToList();
  2262. //item.scores.Where(x => x.tmdId.Equals(tId.GetString())).SelectMany(p => p.sc, (p, d) => new { });
  2263. if (scc.Count > 0)
  2264. {
  2265. sc.Add(new { sc = scc.FirstOrDefault(), item.ssc });
  2266. }
  2267. else
  2268. {
  2269. ss.scores = scores;
  2270. sc.Add(new { sc = ss.scores[indexScore], item.ssc });
  2271. }
  2272. indexScore++;
  2273. }
  2274. var obj = new { ss.id, ss.stuId, ss.examId, ss.subjectId, item = sc, ss.qs, blob = ansBlob, ss.tIds, scores = scores, ss.model, ss.mode };
  2275. objs.Add(obj);
  2276. }
  2277. return objs;
  2278. }
  2279. else
  2280. {
  2281. List<SDK.Models.Cosmos.Common.Scoring> notYet = new();
  2282. notYet = all.Where(x => x.tIds.Count < x.count * x.model - 1).ToList();
  2283. List<dynamic> objs = new List<dynamic>();
  2284. for (int i = 0; i < count; i++)
  2285. {
  2286. Random random = new Random();
  2287. SDK.Models.Cosmos.Common.Scoring item = new();
  2288. if (notYet.Count > 0)
  2289. {
  2290. int index = random.Next(notYet.Count);
  2291. item = notYet[index];
  2292. notYet.RemoveAt(index);
  2293. }
  2294. else
  2295. {
  2296. int index = random.Next(all.Count);
  2297. item = all[index];
  2298. all.RemoveAt(index);
  2299. }
  2300. if (!item.tIds.Contains(tId.ToString()))
  2301. {
  2302. item.tIds.Add(tId.ToString());
  2303. }
  2304. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  2305. List<dynamic> sc = new List<dynamic>();
  2306. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, item.stuId, item.examId, item.subjectId, code);
  2307. int indexScore = 0;
  2308. item.qs = item.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
  2309. foreach (Item its in item.items)
  2310. {
  2311. List<double> ssc = its.scores.Where(x => x.tmdId.Equals(tId)).Select(c => c.sc).ToList();
  2312. if (ssc.Count > 0)
  2313. {
  2314. sc.Add(new { sc = ssc.FirstOrDefault(), its.ssc });
  2315. }
  2316. else
  2317. {
  2318. item.scores = scores;
  2319. sc.Add(new { sc = item.scores[indexScore], its.ssc });
  2320. }
  2321. indexScore++;
  2322. }
  2323. var obj = new { item.id, item.stuId, item.examId, item.subjectId, item = sc, item.qs, blob = ansBlob, item.tIds, scores = scores, item.model, item.mode };
  2324. objs.Add(obj);
  2325. }
  2326. return objs;
  2327. /*if (recs.Count == count.GetInt32())
  2328. {
  2329. return Ok(new { msg = "分配人数已到上限" });
  2330. }
  2331. else
  2332. {
  2333. if (all.Count == 0)
  2334. {
  2335. return Ok(new { msg = "暂无可选学生" });
  2336. }
  2337. //随机选取一名学生打分
  2338. Random random = new Random();
  2339. SDK.Models.Cosmos.Common.Scoring item = new();
  2340. List<SDK.Models.Cosmos.Common.Scoring> notYet = new();
  2341. notYet = all.Where(x => x.tIds.Count < x.count * x.model - 1).ToList();
  2342. if (notYet.Count > 0)
  2343. {
  2344. item = notYet[random.Next(notYet.Count)];
  2345. }
  2346. else
  2347. {
  2348. item = all[random.Next(all.Count)];
  2349. }
  2350. if (!item.tIds.Contains(tId.ToString()))
  2351. {
  2352. item.tIds.Add(tId.ToString());
  2353. }
  2354. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  2355. List<dynamic> sc = new List<dynamic>();
  2356. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, item.stuId, item.examId, item.subjectId, code.GetString());
  2357. int indexScore = 0;
  2358. foreach (Item its in item.items)
  2359. {
  2360. List<double> ssc = its.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).ToList();
  2361. if (ssc.Count > 0)
  2362. {
  2363. sc.Add(new { sc = ssc.FirstOrDefault(), its.ssc });
  2364. }
  2365. else
  2366. {
  2367. item.scores = scores;
  2368. sc.Add(new { sc = item.scores[indexScore], its.ssc });
  2369. }
  2370. indexScore++;
  2371. }
  2372. var obj = new { item.id, item.stuId, item.examId, item.subjectId, item = sc, item.qs, blob = ansBlob, item.tIds, scores = scores, item.model, item.mode };
  2373. return Ok(obj);
  2374. }*/
  2375. }
  2376. }
  2377. catch (Exception ex)
  2378. {
  2379. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/review\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2380. return new List<dynamic>() { new { code = 404, msg = "分配任务异常" } };
  2381. }
  2382. }
  2383. //批阅 提交分数
  2384. [ProducesDefaultResponseType]
  2385. [AuthToken(Roles = "teacher,admin")]
  2386. [HttpPost("sub-result")]
  2387. [Authorize(Roles = "IES")]
  2388. public async Task<IActionResult> SubResult(JsonElement requert)
  2389. {
  2390. //ResponseBuilder builder = ResponseBuilder.custom();
  2391. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2392. try
  2393. {
  2394. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2395. if (!requert.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
  2396. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  2397. if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  2398. if (!requert.TryGetProperty("score", out JsonElement score)) return BadRequest();
  2399. if (!requert.TryGetProperty("count", out JsonElement count)) return BadRequest();
  2400. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2401. requert.TryGetProperty("mark", out JsonElement mark);
  2402. var client = _azureCosmos.GetCosmosClient();
  2403. var (userid, name, _, school) = HttpContext.GetAuthTokenInfo();
  2404. //取得学校基本信息
  2405. var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school.ToString(), new PartitionKey("Base"));
  2406. string schname = string.Empty;
  2407. if (schresponse.Status == 200)
  2408. {
  2409. using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
  2410. schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
  2411. schname = jsonschname.ToString();
  2412. }
  2413. List<ExamClassResult> classResults = new();
  2414. List<SDK.Models.Cosmos.Common.Scoring> attr = new();
  2415. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2416. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.stuId = '{sId}' and array_contains(c.tIds,'{tId}') ",
  2417. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2418. {
  2419. attr.Add(item);
  2420. }
  2421. List<double> ssc = score.ToObject<List<double>>();
  2422. List<string> marks = mark.ToObject<List<string>>();
  2423. StringBuilder builder = new();
  2424. if (attr.Count > 0)
  2425. {
  2426. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  2427. {
  2428. int itemIndex = 0;
  2429. //int tIdIndex = scoring.tIds.IndexOf(tId.GetString());
  2430. if (requert.TryGetProperty("qu", out JsonElement qu))
  2431. {
  2432. List<int> nos = qu.ToObject<List<int>>();
  2433. foreach (int number in nos)
  2434. {
  2435. List<Info> items = scoring.items[number].scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  2436. if (items.Count > 0)
  2437. {
  2438. foreach (Info info in items)
  2439. {
  2440. info.sc = ssc[number];
  2441. info.mark = marks.Count > 0 ? marks[number] : "";
  2442. }
  2443. }
  2444. else
  2445. {
  2446. Info info = new();
  2447. info.sc = ssc[number];
  2448. info.tmdId = tId.GetString();
  2449. info.mark = marks.Count > 0 ? marks[number] : "";
  2450. info.index = number;
  2451. scoring.items[number].scores.Add(info);
  2452. }
  2453. }
  2454. }
  2455. else
  2456. {
  2457. foreach (Item item in scoring.items)
  2458. {
  2459. List<Info> items = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  2460. if (items.Count > 0)
  2461. {
  2462. foreach (Info info in items)
  2463. {
  2464. info.sc = ssc[itemIndex];
  2465. info.mark = marks.Count > 0 ? marks[itemIndex] : "";
  2466. }
  2467. }
  2468. else
  2469. {
  2470. if (ssc[itemIndex] >= 0)
  2471. {
  2472. Info info = new();
  2473. info.sc = ssc[itemIndex];
  2474. info.tmdId = tId.GetString();
  2475. info.mark = marks.Count > 0 ? marks[itemIndex] : "";
  2476. info.index = itemIndex;
  2477. item.scores.Add(info);
  2478. }
  2479. }
  2480. itemIndex++;
  2481. }
  2482. }
  2483. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
  2484. }
  2485. }
  2486. else
  2487. {
  2488. return BadRequest();
  2489. }
  2490. Correct correct = null;
  2491. var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
  2492. if (cResponse.Status == 200)
  2493. {
  2494. using var cJson = await JsonDocument.ParseAsync(cResponse.ContentStream);
  2495. correct = cJson.ToObject<Correct>();
  2496. }
  2497. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  2498. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  2499. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  2500. {
  2501. classResults.Add(item);
  2502. }
  2503. bool isFinish = false;
  2504. int scount = attr.Select(a => a.items[0].scores).ToList().Count;
  2505. foreach (SDK.Models.Cosmos.Common.Scoring sc in attr)
  2506. {
  2507. foreach (var item in sc.items)
  2508. {
  2509. if (item.scores.Count == 0)
  2510. {
  2511. isFinish = false;
  2512. break;
  2513. }
  2514. else
  2515. {
  2516. if (item.scores.Count != correct.num)
  2517. {
  2518. isFinish = false;
  2519. break;
  2520. }
  2521. else
  2522. {
  2523. isFinish = true;
  2524. }
  2525. }
  2526. }
  2527. }
  2528. if (isFinish)
  2529. {
  2530. foreach (ExamClassResult exam in classResults)
  2531. {
  2532. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  2533. {
  2534. int index = exam.studentIds.IndexOf(scoring.stuId);
  2535. if (index != -1)
  2536. {
  2537. int itemIndex = 0;
  2538. foreach (Item item in scoring.items)
  2539. {
  2540. var ace = item.scores.Where(x => string.IsNullOrEmpty(x.tmdId)).ToList();
  2541. if (ace.Count > 0)
  2542. {
  2543. return Ok(new { code = 1, msg = "用户信息未找到" });
  2544. }
  2545. //判定是否仲裁卷
  2546. if (!item.flag)
  2547. {
  2548. item.isArb = 0;
  2549. string bizcode = "scoring-arb";
  2550. List<string> ids = new List<string>();
  2551. foreach (CorSub sub in correct.subs)
  2552. {
  2553. ids = sub.arb;
  2554. }
  2555. //request.subs.Select(r => r.markers).ToList();
  2556. Notification notification = new Notification
  2557. {
  2558. hubName = "hita",
  2559. type = "msg",
  2560. from = $"ies5:{_option.Location}:private",
  2561. to = ids,
  2562. label = $"{bizcode}_school",
  2563. body = new { location = _option.Location, biz = bizcode, tmdid = userid, tmdname = name.ToString(), schoolcode = school, schoolname = $"{schname}", examname = correct.name, status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  2564. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  2565. };
  2566. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  2567. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  2568. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  2569. var location = _option.Location;
  2570. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);
  2571. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
  2572. return Ok(new { msg = "需要仲裁", code = 2 });
  2573. }
  2574. if (item.scores.Count > 0)
  2575. {
  2576. double sc = item.scores.Select(x => x.sc).ToList().Aggregate((i, j) => (i + j) / item.scores.Count);
  2577. scoring.scores[itemIndex] = sc;
  2578. }
  2579. string tmdId = tId.GetString();
  2580. //定位老师是几阅
  2581. int indexOfSc = 0;
  2582. foreach (Info info in item.scores)
  2583. {
  2584. if (info.tmdId.Equals(tmdId))
  2585. {
  2586. break;
  2587. }
  2588. else
  2589. {
  2590. indexOfSc++;
  2591. }
  2592. }
  2593. //判定是否已经存在对应的批注信息
  2594. bool flag = exam.mark[index][itemIndex].Exists(x => x.tmdId.Equals(tmdId));
  2595. if (flag)
  2596. {
  2597. //重复打分更新部分值
  2598. exam.mark[index][itemIndex].Where(x => x.tmdId.Equals(tmdId)).ToList().ForEach(score =>
  2599. {
  2600. score.sc = item.scores[indexOfSc].sc;
  2601. score.mark = item.scores[indexOfSc].mark;
  2602. });
  2603. }
  2604. else
  2605. {
  2606. Details dt = new()
  2607. {
  2608. index = item.scores[indexOfSc].index,
  2609. sc = item.scores[indexOfSc].sc,
  2610. tmdId = item.scores[indexOfSc].tmdId,
  2611. mark = item.scores[indexOfSc].mark,
  2612. identity = item.scores[indexOfSc].identity
  2613. };
  2614. exam.mark[index][itemIndex].Add(dt);
  2615. }
  2616. itemIndex++;
  2617. }
  2618. exam.studentScores[index] = scoring.scores;
  2619. exam.sum[index] = exam.studentScores[index].Sum();
  2620. }
  2621. }
  2622. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  2623. }
  2624. }
  2625. return Ok(new { code = 200 });
  2626. }
  2627. catch (Exception ex)
  2628. {
  2629. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/sub-result\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2630. return BadRequest();
  2631. }
  2632. }
  2633. //查询阅卷类型数据
  2634. [ProducesDefaultResponseType]
  2635. [Authorize(Roles = "IES")]
  2636. [AuthToken(Roles = "teacher,admin")]
  2637. [HttpPost("find-scoring")]
  2638. public async Task<IActionResult> findScoring(JsonElement requert)
  2639. {
  2640. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2641. if (!requert.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
  2642. if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  2643. if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  2644. if (!requert.TryGetProperty("type", out JsonElement type)) return BadRequest();
  2645. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2646. var client = _azureCosmos.GetCosmosClient();
  2647. List<SDK.Models.Cosmos.Common.Scoring> attr = new();
  2648. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2649. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.stuId = '{sId}' and c.type = '{type}' and array_contains(c.tIds,'{tId}') ",
  2650. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2651. {
  2652. attr.Add(item);
  2653. }
  2654. return Ok(attr);
  2655. }
  2656. //申报异常卷内容
  2657. [ProducesDefaultResponseType]
  2658. [AuthToken(Roles = "teacher,admin")]
  2659. [HttpPost("save-err")]
  2660. [Authorize(Roles = "IES")]
  2661. public async Task<IActionResult> saveErr(JsonElement requert)
  2662. {
  2663. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2664. if (!requert.TryGetProperty("err", out JsonElement err)) return BadRequest();
  2665. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2666. if (!requert.TryGetProperty("index", out JsonElement index)) return BadRequest();
  2667. if (!requert.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
  2668. var client = _azureCosmos.GetCosmosClient();
  2669. var (userid, name, _, school) = HttpContext.GetAuthTokenInfo();
  2670. //取得学校基本信息
  2671. var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school.ToString(), new PartitionKey("Base"));
  2672. string schname = string.Empty;
  2673. if (schresponse.Status == 200)
  2674. {
  2675. using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
  2676. schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
  2677. schname = jsonschname.ToString();
  2678. }
  2679. SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
  2680. if (null != scoring)
  2681. {
  2682. Correct correct = null;
  2683. var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(scoring.examId, new PartitionKey($"Correct-{code}"));
  2684. if (cResponse.Status == 200)
  2685. {
  2686. using var cJson = await JsonDocument.ParseAsync(cResponse.ContentStream);
  2687. correct = cJson.ToObject<Correct>();
  2688. }
  2689. if (string.IsNullOrEmpty(scoring.qs[index.GetInt32()].tId))
  2690. {
  2691. scoring.qs[index.GetInt32()].err = err.GetString();
  2692. scoring.qs[index.GetInt32()].tId = tId.GetString();
  2693. scoring.qs[index.GetInt32()].index = index.GetInt32();
  2694. }
  2695. else
  2696. {
  2697. return Ok(new { msg = "改题已经被申报", code = 404 });
  2698. }
  2699. string bizcode = "scoring-err";
  2700. List<string> ids = new List<string>();
  2701. foreach (CorSub sub in correct.subs)
  2702. {
  2703. ids = sub.err;
  2704. }
  2705. //request.subs.Select(r => r.markers).ToList();
  2706. Notification notification = new Notification
  2707. {
  2708. hubName = "hita",
  2709. type = "msg",
  2710. from = $"ies5:{_option.Location}:private",
  2711. to = ids,
  2712. label = $"{bizcode}_school",
  2713. body = new { location = _option.Location, biz = bizcode, tmdid = userid, tmdname = name.ToString(), schoolcode = school, schoolname = $"{schname}", examname = correct.name, status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  2714. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  2715. };
  2716. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  2717. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  2718. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  2719. var location = _option.Location;
  2720. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);
  2721. /* scoring.type = 2;
  2722. scoring.err = err.GetString();*/
  2723. }
  2724. else
  2725. {
  2726. return Ok(new { code = 404 });
  2727. }
  2728. var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
  2729. return Ok(new { sc });
  2730. }
  2731. //处理异常卷内容
  2732. [ProducesDefaultResponseType]
  2733. [Authorize(Roles = "IES")]
  2734. [AuthToken(Roles = "teacher,admin")]
  2735. [HttpPost("fd-err")]
  2736. public async Task<IActionResult> fdErr(JsonElement requert)
  2737. {
  2738. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2739. if (!requert.TryGetProperty("improve", out JsonElement improve)) return BadRequest();
  2740. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2741. if (!requert.TryGetProperty("index", out JsonElement index)) return BadRequest();
  2742. //if (!requert.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
  2743. var client = _azureCosmos.GetCosmosClient();
  2744. SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
  2745. if (null != scoring)
  2746. {
  2747. if (string.IsNullOrEmpty(scoring.qs[index.GetInt32()].improve))
  2748. {
  2749. scoring.qs[index.GetInt32()].improve = improve.GetString();
  2750. //scoring.qs[index.GetInt32()].tId = tId.GetString();
  2751. //scoring.qs[index.GetInt32()].index = index.GetInt32();
  2752. }
  2753. else
  2754. {
  2755. return Ok(new { msg = "改题已经被处理", code = 404 });
  2756. }
  2757. /* scoring.type = 2;
  2758. scoring.err = err.GetString();*/
  2759. }
  2760. else
  2761. {
  2762. return Ok(new { code = 404 });
  2763. }
  2764. var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
  2765. return Ok(new { sc });
  2766. }
  2767. //处理仲裁卷内容
  2768. [ProducesDefaultResponseType]
  2769. [AuthToken(Roles = "teacher,admin")]
  2770. [HttpPost("save-arb")]
  2771. [Authorize(Roles = "IES")]
  2772. public async Task<IActionResult> saveArb(JsonElement requert)
  2773. {
  2774. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2775. if (!requert.TryGetProperty("score", out JsonElement score)) return BadRequest();
  2776. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2777. if (!requert.TryGetProperty("index", out JsonElement indexScore)) return BadRequest();
  2778. var client = _azureCosmos.GetCosmosClient();
  2779. //List<double> scs = score.ToObject<List<double>>();
  2780. List<ExamClassResult> classResults = new();
  2781. int sin = indexScore.GetInt32();
  2782. SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
  2783. if (null != scoring)
  2784. {
  2785. scoring.scores[sin] = score.GetDouble();
  2786. scoring.items[sin].isArb = 1;
  2787. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  2788. queryText: $"select value(c) from c where c.examId = '{scoring.examId}' and c.subjectId = '{scoring.subjectId}'",
  2789. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  2790. {
  2791. classResults.Add(item);
  2792. }
  2793. foreach (ExamClassResult exam in classResults)
  2794. {
  2795. int index = exam.studentIds.IndexOf(scoring.stuId);
  2796. if (index != -1)
  2797. {
  2798. exam.studentScores[index][sin] = score.GetDouble();
  2799. //exam.mark[index] = scoring.marks;
  2800. }
  2801. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  2802. }
  2803. }
  2804. else
  2805. {
  2806. return Ok(new { code = 404 });
  2807. }
  2808. var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
  2809. return Ok(new { sc });
  2810. }
  2811. //阅卷信息统计
  2812. [ProducesDefaultResponseType]
  2813. [Authorize(Roles = "IES")]
  2814. [AuthToken(Roles = "teacher,admin")]
  2815. [HttpPost("analysis-scoring")]
  2816. public async Task<IActionResult> Analysis(JsonElement requert)
  2817. {
  2818. try
  2819. {
  2820. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2821. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2822. //if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  2823. //if (!requert.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  2824. var client = _azureCosmos.GetCosmosClient();
  2825. var queryTeacher = $"select c.id,c.name from c ";
  2826. //List<object> props = new List<object>();
  2827. List<(string id, string name)> tInfos = new();
  2828. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryTeacher, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  2829. {
  2830. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  2831. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2832. {
  2833. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2834. {
  2835. tInfos.Add((obj.GetProperty("id").GetString(), obj.GetProperty("name").GetString()));
  2836. }
  2837. }
  2838. }
  2839. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
  2840. if (response.Status == 200)
  2841. {
  2842. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  2843. ExamInfo info = json.ToObject<ExamInfo>();
  2844. List<ExamClassResult> classResults = new();
  2845. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  2846. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2847. queryText: $"select value(c) from c where c.examId = '{id}' ",
  2848. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2849. {
  2850. attr.Add(item);
  2851. }
  2852. List<SDK.Models.Cosmos.Common.Scoring> errs = new();
  2853. List<(string subjectId, int count)> ps = new List<(string subjectId, int count)>();
  2854. List<(string subjectId, int count)> tps = new List<(string subjectId, int count)>();
  2855. List<(string subjectId, int count)> arbs = new List<(string subjectId, int count)>();
  2856. List<(string subjectId, int count)> tarbs = new List<(string subjectId, int count)>();
  2857. List<(string subjectId, int count)> cs = new List<(string subjectId, int count)>();
  2858. foreach (ExamSubject subject in info.subjects)
  2859. {
  2860. int qsCount = 0;
  2861. int tqsCount = 0;
  2862. int arbCount = 0;
  2863. int tarbCount = 0;
  2864. int csCount = 0;
  2865. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  2866. {
  2867. if (subject.id.Equals(ss.subjectId))
  2868. {
  2869. List<Qs> qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.err)).ToList();
  2870. if (qs.Count > 0)
  2871. {
  2872. qsCount++;
  2873. }
  2874. List<Qs> tqs = ss.qs.Where(s => !string.IsNullOrEmpty(s.improve)).ToList();
  2875. if (tqs.Count > 0)
  2876. {
  2877. tqsCount++;
  2878. }
  2879. List<Item> arb = ss.items.Where(s => s.flag == false).ToList();
  2880. if (arb.Count > 0)
  2881. {
  2882. arbCount++;
  2883. }
  2884. List<Item> tarb = ss.items.Where(s => s.isArb == 1 && s.flag == false).ToList();
  2885. if (tarb.Count > 0)
  2886. {
  2887. tarbCount++;
  2888. }
  2889. bool flag = ss.scores.Exists(s => s == -1);
  2890. if (!flag) csCount++;
  2891. }
  2892. }
  2893. ps.Add((subject.id, qsCount));
  2894. tps.Add((subject.id, tqsCount));
  2895. arbs.Add((subject.id, arbCount));
  2896. tarbs.Add((subject.id, tarbCount));
  2897. cs.Add((subject.id, csCount));
  2898. }
  2899. //阅卷老师
  2900. List<object> teachers = new();
  2901. Correct correct = null;
  2902. List<(string sub, List<string> ids)> errIds = new();
  2903. List<(string sub, List<string> ids)> arbIds = new();
  2904. var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
  2905. if (cResponse.Status == 200)
  2906. {
  2907. using var cJson = await JsonDocument.ParseAsync(cResponse.ContentStream);
  2908. correct = cJson.ToObject<Correct>();
  2909. foreach (CorSub corSub in correct.subs)
  2910. {
  2911. List<string> eName = new();
  2912. List<string> aName = new();
  2913. foreach (string s in corSub.err)
  2914. {
  2915. eName.Add(tInfos.Where(t => t.id.Equals(s)).Select(s => s.name).First());
  2916. }
  2917. foreach (string s in corSub.arb)
  2918. {
  2919. aName.Add(tInfos.Where(t => t.id.Equals(s)).Select(s => s.name).First());
  2920. }
  2921. errIds.Add((corSub.id, eName));
  2922. arbIds.Add((corSub.id, aName));
  2923. foreach (CorTmd corTmd in corSub.markers)
  2924. {
  2925. int qus = 0;
  2926. int quf = 0;
  2927. int tArbs = 0;
  2928. int fArbs = 0;
  2929. int sCount = 0;
  2930. int fCount = 0;
  2931. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  2932. {
  2933. if (ss.subjectId.Equals(corSub.id))
  2934. {
  2935. foreach (Qs qs in ss.qs)
  2936. {
  2937. if (!string.IsNullOrEmpty(qs.err) && qs.tId.Equals(corTmd.id))
  2938. {
  2939. qus++;
  2940. }
  2941. if (!string.IsNullOrEmpty(qs.improve) && qs.tId.Equals(corTmd.id))
  2942. {
  2943. quf++;
  2944. }
  2945. }
  2946. List<double> sigles = new();
  2947. foreach (Item item in ss.items)
  2948. {
  2949. if (item.scores.Exists(sc => sc.tmdId.Equals(corTmd.id)) && item.isArb == 1)
  2950. {
  2951. tArbs++;
  2952. }
  2953. if (item.flag == true && item.isArb == 1)
  2954. {
  2955. fArbs++;
  2956. }
  2957. var tsc = item.scores.Where(t => t.tmdId.Equals(corTmd.id)).Select(s => s.sc).ToList();
  2958. sigles.AddRange(tsc);
  2959. }
  2960. bool flag = sigles.Exists(s => s == -1);
  2961. if (!flag && sigles.Count == ss.items.Count)
  2962. {
  2963. fCount++;
  2964. }
  2965. sCount = corTmd.count;
  2966. }
  2967. }
  2968. var obj = new
  2969. {
  2970. sId = corSub.id,
  2971. sName = corSub.name,
  2972. name = corTmd.name,
  2973. qus,
  2974. quf,
  2975. tArbs,
  2976. fArbs,
  2977. fCount,
  2978. sCount,
  2979. };
  2980. teachers.Add(obj);
  2981. }
  2982. }
  2983. }
  2984. var sc = info.subjects.Select(s => new
  2985. {
  2986. s.name,
  2987. count = info.stuCount,
  2988. num = info.stuCount * correct.num,
  2989. tqs = tps.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
  2990. qs = ps.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
  2991. errName = errIds.Where(q => q.sub.Equals(s.id)).Select(c => c.ids).FirstOrDefault(),
  2992. tarbs = tarbs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
  2993. arbs = arbs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
  2994. arbName = arbIds.Where(q => q.sub.Equals(s.id)).Select(c => c.ids).FirstOrDefault(),
  2995. cs = cs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First()
  2996. }); ;
  2997. return Ok(new { sc, teachers });
  2998. }
  2999. else
  3000. {
  3001. return BadRequest();
  3002. }
  3003. }
  3004. catch (Exception ex)
  3005. {
  3006. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/analysis-scoring\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  3007. return BadRequest();
  3008. }
  3009. }
  3010. /*private async Task deleteAsync(CosmosClient client, string id, string tId)
  3011. {
  3012. List<string> correctIds = new List<string>();
  3013. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.cid = '{id}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CorrectTask-{tId}") }))
  3014. {
  3015. using var jsonTask = await JsonDocument.ParseAsync(item.ContentStream);
  3016. if (jsonTask.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3017. {
  3018. var accounts = jsonTask.RootElement.GetProperty("Documents").EnumerateArray();
  3019. while (accounts.MoveNext())
  3020. {
  3021. JsonElement account = accounts.Current;
  3022. correctIds.Add(account.GetProperty("id").GetString());
  3023. }
  3024. }
  3025. }
  3026. if (correctIds.Count > 0)
  3027. {
  3028. await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsStreamAsync(correctIds, $"CorrectTask-{tId}");
  3029. }
  3030. }*/
  3031. private async Task<(string blob, List<double>)> getMoreStuInfo(CosmosClient client, string stuId, string examId, string subjectId, string code)
  3032. {
  3033. var queryClass = $"select c.studentAnswers,c.studentIds,c.studentScores from c where array_contains(c.studentIds,'{stuId}') and c.examId = '{examId}' and c.subjectId = '{subjectId}'";
  3034. List<List<string>> ans = new List<List<string>>();
  3035. List<string> ids = new List<string>();
  3036. List<List<double>> scs = new List<List<double>>();
  3037. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  3038. {
  3039. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  3040. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3041. {
  3042. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  3043. while (accounts.MoveNext())
  3044. {
  3045. JsonElement account = accounts.Current;
  3046. ans = account.GetProperty("studentAnswers").ToObject<List<List<string>>>();
  3047. ids = account.GetProperty("studentIds").ToObject<List<string>>();
  3048. scs = account.GetProperty("studentScores").ToObject<List<List<double>>>();
  3049. }
  3050. }
  3051. }
  3052. int num = ids.IndexOf(stuId);
  3053. string ansBlob = "";
  3054. List<double> scores = new List<double>();
  3055. if (num >= 0)
  3056. {
  3057. if (ans[num].Count > 0)
  3058. {
  3059. ansBlob = ans[num].First();
  3060. }
  3061. scores = scs[num];
  3062. }
  3063. return (ansBlob, scores);
  3064. }
  3065. }
  3066. public class stus
  3067. {
  3068. public string id { get; set; }
  3069. public int type { get; set; }
  3070. }
  3071. public class ufo
  3072. {
  3073. public string id { get; set; }
  3074. public string name { get; set; }
  3075. public int type { get; set; }
  3076. }
  3077. }