ExamController.cs 202 KB

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