ExamController.cs 181 KB

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