ExamController.cs 235 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370
  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 Microsoft.AspNetCore.Hosting;
  27. using static TEAMModelOS.SDK.SchoolService;
  28. using Azure.Core;
  29. using DocumentFormat.OpenXml.Spreadsheet;
  30. using DocumentFormat.OpenXml.Wordprocessing;
  31. using Item = TEAMModelOS.SDK.Models.Cosmos.Common.Item;
  32. using DocumentFormat.OpenXml.Office2016.Excel;
  33. using OpenXmlPowerTools;
  34. using TEAMModelOS.SDK.Services;
  35. using TEAMModelOS.SDK.Models.Service.BI;
  36. using MathNet.Numerics.RootFinding;
  37. using TEAMModelOS.SDK.Models.Cosmos.Student;
  38. using DocumentFormat.OpenXml.Drawing.Charts;
  39. using ClouDASLibx;
  40. using HTEXLib.Helpers.ShapeHelpers;
  41. using Microsoft.Extensions.Hosting;
  42. using System.Configuration;
  43. using DocumentFormat.OpenXml.Presentation;
  44. using static SKIT.FlurlHttpClient.Wechat.TenpayV3.Models.CreateApplyForSubjectApplymentRequest.Types;
  45. using TEAMModelOS.Controllers.Core;
  46. using Azure.Storage.Blobs.Models;
  47. using Top.Api;
  48. using Newtonsoft.Json.Linq;
  49. using System.IO;
  50. using DocumentFormat.OpenXml.Office2010.Excel;
  51. namespace TEAMModelOS.Controllers
  52. {
  53. [ProducesResponseType(StatusCodes.Status200OK)]
  54. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  55. [Route("common/exam")]
  56. [ApiController]
  57. public class ExamController : ControllerBase
  58. {
  59. private readonly AzureCosmosFactory _azureCosmos;
  60. private readonly SnowflakeId _snowflakeId;
  61. private readonly AzureServiceBusFactory _serviceBus;
  62. private readonly DingDing _dingDing;
  63. private readonly Option _option;
  64. private readonly AzureStorageFactory _azureStorage;
  65. private readonly AzureRedisFactory _azureRedis;
  66. public IConfiguration _configuration { get; set; }
  67. private readonly CoreAPIHttpService _coreAPIHttpService;
  68. private readonly IWebHostEnvironment _environment;
  69. public ExamController(IWebHostEnvironment environment, CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
  70. IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration)
  71. {
  72. _azureCosmos = azureCosmos;
  73. _serviceBus = serviceBus;
  74. _snowflakeId = snowflakeId;
  75. _dingDing = dingDing;
  76. _option = option?.Value;
  77. _azureStorage = azureStorage;
  78. _azureRedis = azureRedis;
  79. _configuration = configuration;
  80. _coreAPIHttpService = coreAPIHttpService;
  81. _environment = environment;
  82. }
  83. /// <summary>
  84. /// 保存考试信息
  85. /// </summary>
  86. /// <param name="request"></param>
  87. /// <returns></returns>
  88. [ProducesDefaultResponseType]
  89. [AuthToken(Roles = "teacher,admin")]
  90. [HttpPost("save")]
  91. [Authorize(Roles = "IES")]
  92. public async Task<IActionResult> Save(ExamInfo request)
  93. {
  94. try
  95. {
  96. //新增
  97. //string code = request.code;
  98. var client = _azureCosmos.GetCosmosClient();
  99. ExamInfo exam;
  100. string code = request.code;
  101. request.ttl = -1;
  102. request.code = "Exam-" + request.code;
  103. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  104. request.createTime = now;
  105. if (request.startTime <= 0)
  106. {
  107. request.startTime = now;
  108. }
  109. //查询所有学生名单
  110. /* List<string> sids = new List<string>();
  111. //List<Student> students = new List<Student>();
  112. 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}") }))
  113. {
  114. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  115. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  116. {
  117. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  118. while (accounts.MoveNext())
  119. {
  120. JsonElement account = accounts.Current;
  121. sids.Add(account.GetProperty("id").GetString());
  122. }
  123. }
  124. }*/
  125. //int stuCount = 0;
  126. List<(string pId, List<string> gid)> ps = new();
  127. var group = request.groupLists;
  128. if (group.Count > 0)
  129. {
  130. foreach (var keys in group)
  131. {
  132. foreach (KeyValuePair<string, List<string>> pp in keys)
  133. {
  134. ps.Add((pp.Key, pp.Value));
  135. }
  136. }
  137. }
  138. List<string> classes = ExamService.getClasses(request.classes, request.stuLists);
  139. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, request.school, ps);
  140. request.stuCount = tchList.Count;
  141. /*for (int i = 0; i < classes.Count; i++)
  142. {
  143. List<string> ids = new List<string>();
  144. //处理班级人数(公共部分的校本名单)
  145. //List<Student> students = new List<Student>();
  146. 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}") }))
  147. {
  148. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  149. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  150. {
  151. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  152. while (accounts.MoveNext())
  153. {
  154. JsonElement account = accounts.Current;
  155. ids.Add(account.GetProperty("id").GetString());
  156. }
  157. }
  158. }
  159. if (request.scope.Equals("private"))
  160. {
  161. //处理发布对象为自选名单(个人)
  162. List<GroupList> stuLists = new List<GroupList>();
  163. 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") }))
  164. {
  165. stuLists.Add(item);
  166. }
  167. }
  168. else
  169. {
  170. //request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  171. //发布对象为自选名单(校本)
  172. List<GroupList> stuLists = new List<GroupList>();
  173. 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}") }))
  174. {
  175. stuLists.Add(item);
  176. }
  177. }
  178. stuCount += ids.Count;
  179. }*/
  180. if (string.IsNullOrEmpty(request.id))
  181. {
  182. request.id = Guid.NewGuid().ToString();
  183. if (request.startTime > now)
  184. {
  185. request.progress = "pending";
  186. }
  187. else
  188. {
  189. request.progress = "going";
  190. }
  191. var messageBlob = new ServiceBusMessage();
  192. if (request.scope.Equals("school"))
  193. {
  194. request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  195. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.school }, _serviceBus, _configuration, _azureRedis);
  196. }
  197. else
  198. {
  199. request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
  200. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.creatorId }, _serviceBus, _configuration, _azureRedis);
  201. }
  202. int n = 0;
  203. List<string> sheetIds = new List<string>();
  204. foreach (PaperSimple simple in request.papers)
  205. {
  206. simple.blob = $"/exam/{request.id}/paper/{request.subjects[n].id}";
  207. n++;
  208. simple.sheet = null;
  209. }
  210. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
  211. await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
  212. //await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate { client = "web", count = 1, id = request.id, key = "exam-submit", name = request.name, scope = request.scope, target = "hbcn/tmdid" });
  213. }
  214. else
  215. {
  216. var response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
  217. if (response.Status == 200)
  218. {
  219. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  220. ExamInfo info = json.ToObject<ExamInfo>();
  221. if (info.progress.Equals("going"))
  222. {
  223. //exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
  224. return Ok(new { v = "活动正在进行中,无法修改", code = 200 });
  225. }
  226. var messageBlob = new ServiceBusMessage();
  227. if (request.scope.Equals("school"))
  228. {
  229. request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  230. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = request.school }, _serviceBus, _configuration, _azureRedis);
  231. }
  232. else
  233. {
  234. request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
  235. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = request.creatorId }, _serviceBus, _configuration, _azureRedis);
  236. }
  237. request.progress = info.progress;
  238. int n = 0;
  239. foreach (PaperSimple simple in request.papers)
  240. {
  241. simple.blob = "/exam/" + request.id + "/paper/" + request.subjects[n].id;
  242. n++;
  243. }
  244. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
  245. }
  246. else
  247. {
  248. if (request.startTime > now)
  249. {
  250. request.progress = "pending";
  251. }
  252. else
  253. {
  254. request.progress = "going";
  255. }
  256. var messageBlob = new ServiceBusMessage();
  257. if (request.scope.Equals("school"))
  258. {
  259. request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
  260. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.school }, _serviceBus, _configuration, _azureRedis);
  261. }
  262. else
  263. {
  264. request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
  265. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.creatorId }, _serviceBus, _configuration, _azureRedis);
  266. }
  267. int n = 0;
  268. List<string> sheetIds = new List<string>();
  269. foreach (PaperSimple simple in request.papers)
  270. {
  271. if (!string.IsNullOrEmpty(simple.subjectId))
  272. {
  273. simple.blob = $"/exam/{request.id}/paper/{simple.subjectId}/{simple.id}";
  274. }
  275. else
  276. {
  277. simple.blob = $"/exam/{request.id}/paper/{request.subjects[n].id}";
  278. n++;
  279. }
  280. simple.sheet = null;
  281. }
  282. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
  283. await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
  284. }
  285. }
  286. return Ok(new { exam });
  287. }
  288. catch (Exception ex)
  289. {
  290. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/save()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  291. return BadRequest();
  292. }
  293. }
  294. /* [ProducesDefaultResponseType]
  295. //[AuthToken(Roles = "teacher,admin")]
  296. [HttpPost("read-score")]
  297. // [Authorize(Roles = "IES")]
  298. public async Task<IActionResult> getAverage(JsonElement request) {
  299. var client = _azureCosmos.GetCosmosClient();
  300. var grades = ExamService.getGradeScore(_coreAPIHttpService,_dingDing,client,2021,"二年级", "463db08d-cbe7-48a0-a81a-fc39b3c1fep1","hbcn", 1688349974000, 1693706774000);
  301. return Ok(grades);
  302. }*/
  303. /// <summary>
  304. /// 保存考试信息
  305. /// </summary>
  306. /// <param name="request"></param>
  307. /// <returns></returns>
  308. [ProducesDefaultResponseType]
  309. [AuthToken(Roles = "teacher,admin")]
  310. [HttpPost("update-end-time")]
  311. [Authorize(Roles = "IES")]
  312. public async Task<IActionResult> updateTime(JsonElement request)
  313. {
  314. try
  315. {
  316. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  317. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  318. var client = _azureCosmos.GetCosmosClient();
  319. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Exam-{code}"));
  320. if (response.Status == 200)
  321. {
  322. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  323. ExamInfo exam = json.ToObject<ExamInfo>();
  324. if (request.TryGetProperty("time", out JsonElement time))
  325. {
  326. exam.endTime = time.GetInt64();
  327. }
  328. if (request.TryGetProperty("name", out JsonElement name))
  329. {
  330. exam.name = name.GetString();
  331. }
  332. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  333. }
  334. return Ok(new { code = 200 });
  335. }
  336. catch (Exception e)
  337. {
  338. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/update-end-time()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  339. return BadRequest();
  340. }
  341. }
  342. //TODO blob 批量删除
  343. /// <summary>
  344. /// 删除
  345. /// </summary>
  346. /// <param name="request"></param>
  347. /// <returns></returns>
  348. [ProducesDefaultResponseType]
  349. [AuthToken(Roles = "teacher,admin")]
  350. [HttpPost("delete")]
  351. [Authorize(Roles = "IES")]
  352. public async Task<IActionResult> Delete(JsonElement request)
  353. {
  354. /* ResponseBuilder builder = ResponseBuilder.custom();
  355. IdPk items = await _azureCosmos.DeleteAsync<ExamInfo>(request.id, request.pk);
  356. await _azureCosmos.DeleteAll<Paper>(new Dictionary<string, object>() { { "code", request.id } });
  357. return builder.Data(items).build();*/
  358. var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
  359. try
  360. {
  361. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  362. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  363. if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  364. var client = _azureCosmos.GetCosmosClient();
  365. ExamInfo exam;
  366. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Exam-{code}"));
  367. if (response.Status == 200)
  368. {
  369. using var jsonExam = await JsonDocument.ParseAsync(response.ContentStream);
  370. exam = jsonExam.ToObject<ExamInfo>();
  371. bool flag = false;
  372. //必须是本人或者这个学校的管理者才能删除
  373. if (exam.creatorId == userid)
  374. {
  375. flag = true;
  376. }
  377. else
  378. {
  379. if (exam.scope == "school" && exam.school.Equals(school))
  380. {
  381. flag = true;
  382. }
  383. }
  384. if (flag)
  385. {
  386. exam.status = 404;
  387. exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  388. //string school_code = code.ToString().Substring(typeof(ExamClassResult).Name.Length + 1);
  389. //var response = await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
  390. //删除blob 相关资料
  391. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, code.ToString(), new List<string> { $"exam/{id}" });
  392. //通知评测删除信息
  393. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "delete", root = $"exam", name = $"{code}" }, _serviceBus, _configuration, _azureRedis);
  394. //删除阅卷配置
  395. var cresponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
  396. if (cresponse.Status == 200)
  397. {
  398. using var json = await JsonDocument.ParseAsync(cresponse.ContentStream);
  399. Correct correct = json.ToObject<Correct>();
  400. if (correct.subs.IsNotEmpty())
  401. {
  402. foreach (var sub in correct.subs)
  403. {
  404. //List<string> correctIds = new List<string>();
  405. if (sub.markers.IsNotEmpty())
  406. {
  407. foreach (var marker in sub.markers)
  408. {
  409. await ExamService.deleteAsync(client, id.GetString(), marker.id);
  410. }
  411. }
  412. if (sub.err.Count > 0)
  413. {
  414. foreach (var tId in sub.err)
  415. {
  416. await ExamService.deleteAsync(client, id.GetString(), tId);
  417. }
  418. }
  419. if (sub.arb.Count > 0)
  420. {
  421. foreach (var tId in sub.arb)
  422. {
  423. await ExamService.deleteAsync(client, id.GetString(), tId);
  424. }
  425. }
  426. }
  427. }
  428. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(id.GetString(), new PartitionKey($"Correct-{code}"));
  429. }
  430. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  431. 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}") }))
  432. {
  433. examClassResults.Add(item);
  434. }
  435. List<string> resultIds = new List<string>();
  436. 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}") }))
  437. {
  438. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  439. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  440. {
  441. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  442. while (accounts.MoveNext())
  443. {
  444. JsonElement account = accounts.Current;
  445. resultIds.Add(account.GetProperty("id").GetString());
  446. }
  447. }
  448. }
  449. foreach (ExamClassResult classResult in examClassResults)
  450. {
  451. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(classResult.id, new PartitionKey($"ExamClassResult-{code}"));
  452. }
  453. await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemsStreamAsync(resultIds, $"ExamResult-{id}");
  454. }
  455. return Ok(new { id });
  456. }
  457. else
  458. {
  459. return NotFound(new { msg = "未找到对应内容" });
  460. }
  461. }
  462. catch (Exception e)
  463. {
  464. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/delete()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  465. return BadRequest();
  466. }
  467. }
  468. /// <summary>
  469. /// 查询考试信息
  470. /// </summary>
  471. /// <param name="request"></param>
  472. /// <returns></returns>
  473. [ProducesDefaultResponseType]
  474. [Authorize(Roles = "IES")]
  475. [AuthToken(Roles = "teacher,admin")]
  476. [HttpPost("find")]
  477. public async Task<IActionResult> Find(JsonElement request)
  478. {
  479. try
  480. {
  481. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  482. //if (request.TryGetProperty("period", out JsonElement period)) return BadRequest();
  483. var client = _azureCosmos.GetCosmosClient();
  484. //if (!request.TryGetProperty("userId", out JsonElement userId)) return BadRequest();
  485. //if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
  486. var (userId, _, _, school) = HttpContext.GetAuthTokenInfo();
  487. 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,c.cloudas from c where (c.status<>404 or IS_DEFINED(c.status) = false) and c.pk = 'Exam'");
  488. /*if (request.TryGetProperty("classIds", out JsonElement classIds))
  489. {
  490. List<string> ids = classIds.ToObject<List<string>>();
  491. HashSet<string> strs = new HashSet<string>();
  492. if (ids.Count > 1)
  493. {
  494. foreach (string id in ids)
  495. {
  496. strs.Add($"array_contains(c.classes,'{id}')");
  497. }
  498. }
  499. else
  500. {
  501. string ssr = ids.Count > 0 ? ids[0] : "";
  502. strs.Add($"array_contains(c.classes,'{ssr}')");
  503. }
  504. string ss = string.Join(" or ", strs);
  505. stringBuilder.Append($" and {ss}");
  506. };*/
  507. //开始时间,
  508. if (request.TryGetProperty("stime", out JsonElement stime))
  509. {
  510. if (long.TryParse($"{stime}", out long data))
  511. {
  512. stringBuilder.Append($" and c.createTime >= {data} ");
  513. };
  514. };
  515. //默认当前时间
  516. if (request.TryGetProperty("etime", out JsonElement etime))
  517. {
  518. if (long.TryParse($"{etime}", out long data))
  519. {
  520. stringBuilder.Append($" and c.createTime <= {data} ");
  521. };
  522. };
  523. string periodId = string.Empty;
  524. if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
  525. {
  526. stringBuilder.Append($" and (c.period.id = '{period}' or c.period.id = null)");
  527. periodId = period.GetString();
  528. }
  529. if (request.TryGetProperty("opt", out JsonElement opt))
  530. {
  531. if (opt.GetString().Equals("private"))
  532. {
  533. //针对于个人活动获取教师 任教或者助教大名单
  534. var groupList = await GroupListService.GetTeacherTeachGroupList(_coreAPIHttpService, client, _dingDing, userId, school, periodId);
  535. List<string> ids = new();
  536. foreach (var groups in groupList) {
  537. foreach (var gp in groups.groups) {
  538. ids.Add(gp.id);
  539. }
  540. }
  541. HashSet<string> strs = new HashSet<string>();
  542. if (ids.Count > 1)
  543. {
  544. foreach (string id in ids)
  545. {
  546. strs.Add($" array_contains(c.stuLists,'{id}') or array_contains(c.classes,'{id}')");
  547. }
  548. }
  549. else
  550. {
  551. string ssr = ids.Count > 0 ? ids[0] : "";
  552. strs.Add($" array_contains(c.stuLists,'{ssr}') or array_contains(c.classes,'{ssr}') ");
  553. }
  554. string ss = string.Join(" or ", strs);
  555. stringBuilder.Append($" and ({ss})");
  556. stringBuilder.Append($" and c.owner = 'teacher'");
  557. }
  558. else {
  559. stringBuilder.Append($" and c.code = 'Exam-{code}' ");
  560. }
  561. };
  562. if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
  563. {
  564. stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
  565. }
  566. if (request.TryGetProperty("progress", out JsonElement progress) && !string.IsNullOrWhiteSpace($"{progress}"))
  567. {
  568. stringBuilder.Append($" and c.progress = '{progress}' ");
  569. }
  570. if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
  571. {
  572. stringBuilder.Append($" and c.source = '{source}' ");
  573. }
  574. stringBuilder.Append("order by c.createTime desc");
  575. //string token = null;
  576. string token = default;
  577. //默认不指定返回大小
  578. int? topcout = null;
  579. if (request.TryGetProperty("count", out JsonElement jcount))
  580. {
  581. if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
  582. {
  583. topcout = data;
  584. }
  585. }
  586. //是否需要进行分页查询,默认不分页
  587. bool iscontinuation = false;
  588. if (topcout != null && topcout.Value > 0)
  589. {
  590. iscontinuation = true;
  591. }
  592. //如果指定了返回大小
  593. if (request.TryGetProperty("token", out JsonElement token_1))
  594. {
  595. if (!token_1.ValueKind.Equals(JsonValueKind.Null) && token_1.ValueKind.Equals(JsonValueKind.String))
  596. {
  597. token = token_1.GetString();
  598. }
  599. }
  600. List<ExamInfo> examInfo = new List<ExamInfo>();
  601. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout }))
  602. {
  603. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  604. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  605. {
  606. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  607. {
  608. //obj.TryGetProperty("progress", out JsonElement progress);
  609. examInfo.Add(obj.ToObject<ExamInfo>());
  610. }
  611. }
  612. if (iscontinuation)
  613. {
  614. token = item.GetContinuationToken();
  615. break;
  616. }
  617. }
  618. return Ok(new { examInfo, token = token });
  619. }
  620. catch (Exception e)
  621. {
  622. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  623. return BadRequest();
  624. }
  625. }
  626. [ProducesDefaultResponseType]
  627. [AuthToken(Roles = "teacher,admin,student")]
  628. #if !DEBUG
  629. [Authorize(Roles = "IES")]
  630. #endif
  631. [HttpPost("find-by-analysis")]
  632. public async Task<IActionResult> FindByAnalysis(JsonElement request)
  633. {
  634. try
  635. {
  636. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  637. var client = _azureCosmos.GetCosmosClient();
  638. var table = _azureStorage.GetCloudTableClient().GetTableReference("SchoolYear");
  639. List<SchoolYear> years = await table.FindListByDict<SchoolYear>(new Dictionary<string, object>() { { "RowKey", code }, { "PartitionKey", "Exam" } });
  640. int year = 0;
  641. if (years.Count > 0)
  642. {
  643. year = years[0].year;
  644. if (year == 1970)
  645. {
  646. long ct = 0;
  647. 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}") }))
  648. {
  649. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  650. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  651. {
  652. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  653. while (accounts.MoveNext())
  654. {
  655. JsonElement account = accounts.Current;
  656. ct = account.GetProperty("createTime").GetInt64();
  657. }
  658. }
  659. }
  660. year = ct == 0 ? DateTimeOffset.UtcNow.Year : DateTimeOffset.FromUnixTimeMilliseconds(ct).Year;
  661. years[0].year = year;
  662. await table.SaveOrUpdate<SchoolYear>(years[0]);
  663. }
  664. }
  665. else
  666. {
  667. long ct = 0;
  668. 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}") }))
  669. {
  670. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  671. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  672. {
  673. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  674. while (accounts.MoveNext())
  675. {
  676. JsonElement account = accounts.Current;
  677. ct = account.GetProperty("createTime").GetInt64();
  678. }
  679. }
  680. }
  681. year = ct == 0 ? DateTimeOffset.UtcNow.Year : DateTimeOffset.FromUnixTimeMilliseconds(ct).Year;
  682. SchoolYear sy = new()
  683. {
  684. RowKey = code.ToString(),
  685. PartitionKey = "Exam",
  686. year = year
  687. };
  688. await table.Save<SchoolYear>(sy);
  689. }
  690. string sub = string.Empty;
  691. string subject = string.Empty;
  692. if (request.TryGetProperty("subjectId", out JsonElement subjectId) && !string.IsNullOrWhiteSpace($"{subjectId}"))
  693. {
  694. sub = $" join A0 in c.subjects ";
  695. subject = $" and A0.id = '{subjectId}'";
  696. }
  697. string grade = string.Empty;
  698. string grades = string.Empty;
  699. if (request.TryGetProperty("grades", out JsonElement gs) && !string.IsNullOrWhiteSpace($"{gs}"))
  700. {
  701. grade = $" join A1 in c.grades ";
  702. grades = $" and A1.id = '{gs}'";
  703. }
  704. 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,c.creatorId from c {sub} {grade}" +
  705. $"where (c.status<>404 or IS_DEFINED(c.status) = false) and c.scope = 'school' and c.qamode <> 2 and c.school = '{code}' and c.pk = 'Exam' {subject} {grades}");
  706. if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
  707. {
  708. stringBuilder.Append($" and c.period.id = '{period}' ");
  709. }
  710. if (request.TryGetProperty("owner", out JsonElement owner) && !string.IsNullOrWhiteSpace($"{owner}"))
  711. {
  712. stringBuilder.Append($" and c.owner= '{owner}' ");
  713. }
  714. if (request.TryGetProperty("year", out JsonElement yy) && !string.IsNullOrWhiteSpace($"{yy}"))
  715. {
  716. int end = yy.GetInt32() + 1;
  717. long stime = DateTimeOffset.Parse($"{yy.GetInt32()}-1-1").ToUnixTimeMilliseconds();
  718. long etime = DateTimeOffset.Parse($"{end}-1-1").ToUnixTimeMilliseconds();
  719. stringBuilder.Append($" and c.startTime >= {stime} and c.startTime < {etime} ");
  720. }
  721. if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
  722. {
  723. stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
  724. }
  725. if (request.TryGetProperty("examType", out JsonElement examType) && !string.IsNullOrWhiteSpace($"{examType}"))
  726. {
  727. stringBuilder.Append($" and c.examType.id = '{examType}' ");
  728. }
  729. if (request.TryGetProperty("progress", out JsonElement progress) && !string.IsNullOrWhiteSpace($"{progress}"))
  730. {
  731. stringBuilder.Append($" and c.progress = '{progress}' ");
  732. }
  733. if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
  734. {
  735. stringBuilder.Append($" and c.source = '{source}' ");
  736. }
  737. if (request.TryGetProperty("creatorId", out JsonElement creatorId) && !string.IsNullOrWhiteSpace($"{creatorId}"))
  738. {
  739. stringBuilder.Append($" and c.creatorId = '{creatorId}' ");
  740. }
  741. stringBuilder.Append("order by c.createTime desc");
  742. string token = default;
  743. //是否需要进行分页查询,默认不分页
  744. bool iscontinuation = false;
  745. if (request.TryGetProperty("token", out JsonElement token_1))
  746. {
  747. token = token_1.GetString();
  748. };
  749. //默认不指定返回大小
  750. int? topcout = null;
  751. if (request.TryGetProperty("count", out JsonElement jcount))
  752. {
  753. if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
  754. {
  755. topcout = data;
  756. }
  757. }
  758. if (topcout != null && topcout.Value > 0)
  759. {
  760. iscontinuation = true;
  761. }
  762. List<ExamInfo> examInfo = new List<ExamInfo>();
  763. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout }))
  764. {
  765. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  766. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  767. {
  768. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  769. {
  770. //obj.TryGetProperty("progress", out JsonElement progress);
  771. examInfo.Add(obj.ToObject<ExamInfo>());
  772. }
  773. }
  774. if (iscontinuation)
  775. {
  776. token = item.GetContinuationToken();
  777. break;
  778. }
  779. }
  780. List<ExamInfo> exams = new List<ExamInfo>();
  781. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: stringBuilder.ToString()))
  782. {
  783. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  784. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  785. {
  786. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  787. {
  788. exams.Add(obj.ToObject<ExamInfo>());
  789. }
  790. }
  791. }
  792. 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();
  793. return Ok(new { examInfo, token = token, year, count = exams.Count, groups });
  794. }
  795. catch (Exception e)
  796. {
  797. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-by-analysis()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  798. return BadRequest();
  799. }
  800. }
  801. [ProducesDefaultResponseType]
  802. [Authorize(Roles = "IES")]
  803. [AuthToken(Roles = "teacher,admin")]
  804. [HttpPost("find-summary")]
  805. public async Task<IActionResult> FindSummary(JsonElement request)
  806. {
  807. try
  808. {
  809. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  810. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  811. var client = _azureCosmos.GetCosmosClient();
  812. List<ExamInfo> examInfo = new List<ExamInfo>();
  813. //var query = $"select value(c) from c ";
  814. 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}") }))
  815. {
  816. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  817. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  818. {
  819. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  820. {
  821. //obj.TryGetProperty("progress", out JsonElement progress);
  822. examInfo.Add(obj.ToObject<ExamInfo>());
  823. }
  824. }
  825. }
  826. return Ok(new { examInfo });
  827. }
  828. catch (Exception e)
  829. {
  830. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/FindSummary()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  831. return BadRequest();
  832. }
  833. }
  834. /// <summary>
  835. /// 学生回答问题
  836. /// </summary>
  837. /// <param name="request"></param>
  838. /// <returns></returns>
  839. [ProducesDefaultResponseType]
  840. [Authorize(Roles = "IES")]
  841. [AuthToken(Roles = "student,teacher")]
  842. [HttpPost("upsert-record")]
  843. public async Task<IActionResult> upsertRecord(JsonElement request)
  844. {
  845. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  846. //学校编码
  847. //if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
  848. if (!request.TryGetProperty("answer", out JsonElement answer)) return BadRequest();
  849. if (!request.TryGetProperty("paperAns", out JsonElement paperAns)) return BadRequest();
  850. if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
  851. //if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  852. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  853. if (!request.TryGetProperty("classIds", out JsonElement classId)) return BadRequest();
  854. if (!request.TryGetProperty("multipleRule", out JsonElement multipleRule)) return BadRequest();
  855. //if (!request.TryGetProperty("answers ", out JsonElement tandardAnswer)) return BadRequest();
  856. //if (!request.TryGetProperty("paperId", out JsonElement paperId)) return BadRequest();
  857. //根据不同评测的类型返回对应的编码
  858. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  859. if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
  860. var (userId, name, picture, school) = HttpContext.GetAuthTokenInfo();
  861. try
  862. {
  863. List<string> ids = new List<string>();
  864. ids = classId.ToObject<List<string>>();
  865. var client = _azureCosmos.GetCosmosClient();
  866. ExamInfo info = new();
  867. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{scode}"));
  868. if (response.Status == 200)
  869. {
  870. using var cJson = await JsonDocument.ParseAsync(response.ContentStream);
  871. info = cJson.ToObject<ExamInfo>();
  872. }
  873. else
  874. {
  875. return Ok(new { code = 404, msg = "该活动未被找到" });
  876. }
  877. //ExamInfo info = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.GetString(), new PartitionKey($"{scode}"));
  878. //确定当前学生所在班级且该班级参与该活动
  879. //List<string> cIds = new();
  880. if (ids.Count == 0) return Ok(new { code = 404, msg = "未找到相关班级信息" });
  881. if (string.IsNullOrEmpty(userId)) return Ok(new { code = 404, msg = "当前用户信息未找到" });
  882. /*foreach (string cId in ids)
  883. {
  884. //List<string> stus = new List<string>();
  885. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(
  886. queryText: $"select c.classId as id from c where c.classId = '{cId}' and c.id = '{userId}'",
  887. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{info.school}") }))
  888. {
  889. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  890. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  891. {
  892. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  893. while (accounts.MoveNext())
  894. {
  895. JsonElement account = accounts.Current;
  896. cIds.Add(account.GetProperty("id").GetString());
  897. }
  898. break;
  899. }
  900. }
  901. if (info.scope.Equals("private"))
  902. {
  903. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(
  904. queryText: $"select c.id from c join A0 in c.members where c.id = '{cId}' and A0.id = '{userId}'",
  905. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
  906. {
  907. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  908. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  909. {
  910. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  911. while (accounts.MoveNext())
  912. {
  913. JsonElement account = accounts.Current;
  914. cIds.Add(account.GetProperty("id").GetString());
  915. }
  916. break;
  917. }
  918. }
  919. }
  920. else
  921. {
  922. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(
  923. queryText: $"select c.id from c join A0 in c.members where c.id = '{cId}' and A0.id = '{userId}'",
  924. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{info.school}") }))
  925. {
  926. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  927. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  928. {
  929. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  930. while (accounts.MoveNext())
  931. {
  932. JsonElement account = accounts.Current;
  933. cIds.Add(account.GetProperty("id").GetString());
  934. }
  935. break;
  936. }
  937. }
  938. }
  939. }*/
  940. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  941. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
  942. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id in ({string.Join(",", ids.Select(o => $"'{o}'"))})",
  943. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  944. {
  945. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  946. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  947. {
  948. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  949. {
  950. examClassResults.Add(obj.ToObject<ExamClassResult>());
  951. }
  952. }
  953. }
  954. examClassResults = examClassResults.Where(c => c.studentIds.Contains(userId)).ToList();
  955. ExamClassResult classResult = new ExamClassResult();
  956. /* List<PaperSimple> standerAnswers = new List<PaperSimple>();
  957. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
  958. queryText: $"select A0.point,A0.answers from c join A0 in c.papers where c.id = '{id}'and A0.id = '{paperId}'",
  959. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  960. {
  961. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  962. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  963. {
  964. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  965. {
  966. standerAnswers.Add(obj.ToObject<PaperSimple>());
  967. }
  968. }
  969. }*/
  970. List<List<string>> ans = answer.ToObject<List<List<string>>>();
  971. List<List<string>> standard = paperAns.ToObject<List<List<string>>>();
  972. List<double> points = point.ToObject<List<double>>();
  973. int rule = int.Parse(multipleRule.ToString());
  974. /* foreach (PaperSimple simple in standerAnswers)
  975. {
  976. standard = simple.answers;
  977. points = simple.point;
  978. }*/
  979. List<Task<string>> tasks = new List<Task<string>>();
  980. foreach (ExamClassResult result in examClassResults)
  981. {
  982. //int index = result.studentIds.IndexOf(userId.ToString());
  983. //存放客观题作答详情
  984. //if (result.ans.Count == 0)
  985. //{
  986. // foreach (string cc in result.studentIds)
  987. // {
  988. // List<List<string>> anc = new List<List<string>>();
  989. // foreach (List<string> opc in standard)
  990. // {
  991. // anc.Add(new List<string>());
  992. // }
  993. // result.ans.Add(anc);
  994. // }
  995. //}
  996. int newIndex = result.studentIds.IndexOf(userId.ToString());
  997. StringBuilder builder = new();
  998. builder.Append(result.examId).Append('/');
  999. builder.Append(result.subjectId).Append('/');
  1000. builder.Append(userId).Append('/');
  1001. builder.Append("ans.json");
  1002. /*string FileName = result.examId + "/" + result.subjectId + "/" + studentId;
  1003. string blob = FileName + "/" + "ans.json";*/
  1004. tasks.Add(_azureStorage.GetBlobContainerClient(code.ToString()).UploadFileByContainer(ans.ToJsonString(), "exam", builder.ToString(), false));
  1005. result.studentAnswers[newIndex].Add(builder.ToString());
  1006. result.status[newIndex] = 0;
  1007. //}
  1008. //List<(int index ,string content, double count)> acount = new List<(int index,string content, double count)>();
  1009. for (int i = 0; i < ans.Count; i++)
  1010. {
  1011. var sc = standard[i].Count;
  1012. var ac = ans[i].Where(a => a.Trim().Length > 0).ToList().Count;
  1013. //算分处理
  1014. if (sc > 0)
  1015. {
  1016. /* if (ans[i].Count == 0)
  1017. {
  1018. continue;
  1019. }*/
  1020. result.ans[newIndex][i] = ans[i];
  1021. if (ac == sc && sc == 1)
  1022. {
  1023. foreach (string right in ans[i])
  1024. {
  1025. if (standard[i].Contains(right.Trim()))
  1026. {
  1027. result.studentScores[newIndex][i] = points[i];
  1028. }
  1029. else
  1030. {
  1031. result.studentScores[newIndex][i] = 0;
  1032. }
  1033. }
  1034. }
  1035. else
  1036. {
  1037. if (rule > 0)
  1038. {
  1039. int falseCount = 0;
  1040. if (ac > 0)
  1041. {
  1042. foreach (string obj in ans[i])
  1043. {
  1044. if (!standard[i].Contains(obj))
  1045. {
  1046. falseCount++;
  1047. }
  1048. }
  1049. switch (rule)
  1050. {
  1051. case 1:
  1052. if (ac == sc)
  1053. {
  1054. if (falseCount == 0)
  1055. {
  1056. result.studentScores[newIndex][i] = points[i];
  1057. }
  1058. else
  1059. {
  1060. result.studentScores[newIndex][i] = 0;
  1061. }
  1062. }
  1063. else
  1064. {
  1065. result.studentScores[newIndex][i] = 0;
  1066. }
  1067. break;
  1068. case 2:
  1069. if (falseCount > 0)
  1070. {
  1071. result.studentScores[newIndex][i] = 0;
  1072. }
  1073. else
  1074. {
  1075. if (ac == sc)
  1076. {
  1077. result.studentScores[newIndex][i] = points[i];
  1078. }
  1079. else
  1080. {
  1081. result.studentScores[newIndex][i] = points[i] / 2;
  1082. }
  1083. }
  1084. break;
  1085. case 3:
  1086. if (falseCount > 0)
  1087. {
  1088. result.studentScores[newIndex][i] = 0;
  1089. }
  1090. else
  1091. {
  1092. if (ac == sc)
  1093. {
  1094. result.studentScores[newIndex][i] = points[i];
  1095. }
  1096. else
  1097. {
  1098. result.studentScores[newIndex][i] = System.Math.Round((double)ac / sc * points[i], 1);
  1099. }
  1100. }
  1101. break;
  1102. case 4:
  1103. if (ac == sc)
  1104. {
  1105. result.studentScores[newIndex][i] = points[i];
  1106. }
  1107. else
  1108. {
  1109. double persent = (double)(sc - 2 * falseCount) / sc;
  1110. if (persent <= 0)
  1111. {
  1112. result.studentScores[newIndex][i] = 0;
  1113. }
  1114. else
  1115. {
  1116. result.studentScores[newIndex][i] = System.Math.Round(persent * points[i], 1);
  1117. }
  1118. }
  1119. break;
  1120. }
  1121. }
  1122. else
  1123. {
  1124. result.studentScores[newIndex][i] = 0;
  1125. }
  1126. }
  1127. }
  1128. }
  1129. }
  1130. /*if (result.studentScores.Contains(-1)) {
  1131. }*/
  1132. bool flag = true;
  1133. var a = result.studentScores.Where(z => z.Contains(-1));
  1134. if (a.Any())
  1135. {
  1136. flag = false;
  1137. }
  1138. //foreach (List<double> scores in result.studentScores)
  1139. //{
  1140. // foreach (double score in scores)
  1141. // {
  1142. // if (score == -1)
  1143. // {
  1144. // flag = false;
  1145. // break;
  1146. // }
  1147. // }
  1148. //}
  1149. //bool isAns = true;
  1150. bool isAns = result.studentScores[newIndex].Exists(s => s == -1);
  1151. HttpContext.Items.TryGetValue("Scope", out object scope);
  1152. int userType = $"{scope}".Equals(Constant.ScopeStudent) ? 2 : 1;
  1153. if (flag)
  1154. {
  1155. result.progress = true;
  1156. info.subjects.ForEach(s =>
  1157. {
  1158. if (s.id.Equals(subjectId.ToString()))
  1159. {
  1160. s.classCount += 1;
  1161. }
  1162. if (s.classCount > info.classes.Count) {
  1163. s.classCount = info.classes.Count;
  1164. }
  1165. });
  1166. }
  1167. result.sum[newIndex] = result.studentScores[newIndex].Sum();
  1168. classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  1169. var target = info.scope.Equals("school") ? info.school : info.creatorId;
  1170. string _client = "web";
  1171. if (info.source.Equals("1")) {
  1172. _client="hiteach";
  1173. }
  1174. await SystemService.RecordAccumulateData(_azureRedis, _dingDing, new SDK.Models.Dtos.Accumulate { client =_client, count = 1, id = info.id, key = "exam-submit", name = info.name, scope = info.scope, target = target });
  1175. if (isAns)
  1176. {
  1177. //if ($"{scope}".Equals(Constant.ScopeStudent))
  1178. //{
  1179. // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
  1180. // activity.taskStatus = 0;
  1181. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
  1182. //}
  1183. //if ($"{scope}".Equals(Constant.ScopeTmdUser))
  1184. //{
  1185. // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
  1186. // activity.taskStatus = 0;
  1187. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
  1188. //}
  1189. //if ($"{scope}".Equals(Constant.ScopeTeacher))
  1190. //{
  1191. // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
  1192. // activity.taskStatus = 0;
  1193. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
  1194. //}
  1195. }
  1196. else
  1197. {
  1198. if (request.TryGetProperty("artId", out JsonElement artId) && request.TryGetProperty("quotaId", out JsonElement quotaId))
  1199. {
  1200. await getArtInfoAsync(client, artId.GetString(), school, result.sum[newIndex], id.GetString(), subjectId.GetString(), quotaId.GetString(), userId, picture, name, userType, ids);
  1201. };
  1202. //if ($"{scope}".Equals(Constant.ScopeStudent))
  1203. //{
  1204. // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
  1205. // activity.taskStatus = 1;
  1206. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
  1207. //}
  1208. //if ($"{scope}".Equals(Constant.ScopeTmdUser))
  1209. //{
  1210. // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
  1211. // activity.taskStatus = 1;
  1212. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
  1213. //}
  1214. //if ($"{scope}".Equals(Constant.ScopeTeacher))
  1215. //{
  1216. // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
  1217. // activity.taskStatus = 1;
  1218. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
  1219. //}
  1220. }
  1221. }
  1222. //当作答班级数量与实际班级数量一致时才触发结算
  1223. var ansCount = info.subjects.Where(c => c.id.Equals(subjectId)).FirstOrDefault()?.classCount;
  1224. if (ansCount == info.classes.Count)
  1225. {
  1226. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, id.ToString(), new PartitionKey($"{scode}"));
  1227. }
  1228. await Task.WhenAll(tasks);
  1229. return Ok(new { classResult });
  1230. }
  1231. catch (Exception e)
  1232. {
  1233. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecord()\n{e.Message}\n{e.StackTrace}\n\n{id.GetString()}\n{request.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1234. return BadRequest();
  1235. }
  1236. }
  1237. private async Task getArtInfoAsync(CosmosClient client, string artId, string school, double score, string acId, string subject, string quotaId, string userid, string picture, string name, int userType, List<string> cIds)
  1238. {
  1239. var aresponse = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(artId, new PartitionKey($"Art-{school}"));
  1240. ArtEvaluation art;
  1241. StudentArtResult artResult;
  1242. string rId = string.Format("{0}{1}{2}", school, "-", userid);
  1243. if (aresponse.Status == 200)
  1244. {
  1245. using var json = await JsonDocument.ParseAsync(aresponse.ContentStream);
  1246. art = json.ToObject<ArtEvaluation>();
  1247. var response = await client.GetContainer("TEAMModelOS", "Student").ReadItemStreamAsync(rId, new PartitionKey($"ArtResult-{artId}"));
  1248. if (response.Status == 200)
  1249. {
  1250. using var json_1 = await JsonDocument.ParseAsync(response.ContentStream);
  1251. artResult = json_1.ToObject<StudentArtResult>();
  1252. //bool flage = artResult.results.Exists(a => a.taskId == acId);
  1253. artResult.results.ForEach(a =>
  1254. {
  1255. if (a.taskId == acId)
  1256. {
  1257. a.score = score;
  1258. }
  1259. });
  1260. await client.GetContainer("TEAMModelOS", "Student").ReplaceItemAsync(artResult, artResult.id, new PartitionKey($"{artResult.code}"));
  1261. }
  1262. else
  1263. {
  1264. artResult = new StudentArtResult
  1265. {
  1266. id = rId,
  1267. pk = "ArtResult",
  1268. code = $"ArtResult-{artId}",
  1269. studentId = userid,
  1270. picture = picture,
  1271. studentName = name,
  1272. school = school,
  1273. userType = userType,
  1274. artId = artId,
  1275. classIds = cIds,
  1276. };
  1277. art.settings.ForEach(qIds =>
  1278. {
  1279. qIds.task.ForEach(task =>
  1280. {
  1281. ArtQuotaResult quotaResult = new()
  1282. {
  1283. quotaId = qIds.id,
  1284. quotaName = qIds.quotaname,
  1285. quotaType = (int)task.type,
  1286. taskId = task.acId,
  1287. subjectId = task.subject
  1288. };
  1289. if (!string.IsNullOrEmpty(quotaResult.taskId))
  1290. {
  1291. if (quotaResult.taskId.Equals(acId))
  1292. {
  1293. quotaResult.score = score;
  1294. }
  1295. }
  1296. artResult.results.Add(quotaResult);
  1297. });
  1298. });
  1299. //foreach (var qIds in art.settings)
  1300. //{
  1301. // foreach (var task in qIds.task)
  1302. // {
  1303. // ArtQuotaResult quotaResult = new()
  1304. // {
  1305. // quotaId = qIds.id,
  1306. // quotaName = qIds.quotaname,
  1307. // quotaType = (int)task.type,
  1308. // taskId = task.acId,
  1309. // subjectId = task.subject
  1310. // };
  1311. // if (!string.IsNullOrEmpty(quotaResult.taskId))
  1312. // {
  1313. // if (quotaResult.taskId.Equals(acId))
  1314. // {
  1315. // quotaResult.score = score;
  1316. // }
  1317. // }
  1318. // artResult.results.Add(quotaResult);
  1319. // }
  1320. //}
  1321. await client.GetContainer("TEAMModelOS", "Student").CreateItemAsync(artResult, new PartitionKey($"{artResult.code}"));
  1322. }
  1323. }
  1324. }
  1325. [ProducesDefaultResponseType]
  1326. [Authorize(Roles = "IES")]
  1327. [AuthToken(Roles = "teacher,admin")]
  1328. [HttpPost("upsert-record-by-teacher")]
  1329. public async Task<IActionResult> upsertRecordByTeacher(JsonElement request)
  1330. {
  1331. //ResponseBuilder builder = ResponseBuilder.custom();
  1332. try
  1333. {
  1334. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1335. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1336. if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
  1337. if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  1338. //if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  1339. //此参数表明此次操作对象为个人还是校本的评测内容
  1340. if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
  1341. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1342. //要先处理状态,判断卷子是否存在,并判断卷子归属的考试是否允许再次提交
  1343. //List<ExamInfo> exams = await _azureCosmos.FindByDict<ExamInfo>(new Dictionary<string, object> { { "id", request.examCode } });
  1344. List<List<double>> ans = point.ToObject<List<List<double>>>();
  1345. List<stus> sIds = studentId.ToObject<List<stus>>();
  1346. var client = _azureCosmos.GetCosmosClient();
  1347. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  1348. if (request.TryGetProperty("classId", out JsonElement classId))
  1349. {
  1350. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  1351. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
  1352. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  1353. {
  1354. examClassResults.Add(item);
  1355. }
  1356. }
  1357. else
  1358. {
  1359. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  1360. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  1361. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  1362. {
  1363. examClassResults.Add(item);
  1364. }
  1365. }
  1366. ExamClassResult classResult = new ExamClassResult();
  1367. //List<Task<ItemResponse<StuActivity>>> tasks = new List<Task<ItemResponse<StuActivity>>>();
  1368. foreach (ExamClassResult result in examClassResults)
  1369. {
  1370. int index_sc = 0;
  1371. foreach (stus s in sIds)
  1372. {
  1373. int index = result.studentIds.IndexOf(s.id.ToString());
  1374. for (int i = 0; i < ans[index_sc].Count; i++)
  1375. {
  1376. result.studentScores[index][i] = ans[index_sc][i];
  1377. }
  1378. result.sum[index] = result.studentScores[index].Sum();
  1379. bool flag = result.studentScores[index].Exists(r => r == -1);
  1380. if (!flag)
  1381. {
  1382. if (s.type == 1)
  1383. {
  1384. try
  1385. {
  1386. //StuActivity activity = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{s.id}"));
  1387. //activity.sStatus = 1;
  1388. //tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
  1389. }
  1390. catch (Exception ex)
  1391. {
  1392. await _dingDing.SendBotMsg($"{_option.Location}\n{ex.Message}\n{ex.StackTrace}\n\n,id:{id},code:{s.id},school:{result?.school}", GroupNames.醍摩豆服務運維群組);
  1393. }
  1394. }
  1395. else
  1396. {
  1397. try
  1398. {
  1399. var response = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Activity-{result.school}-{s.id}"));
  1400. if (response.Status == 200)
  1401. {
  1402. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1403. //StuActivity activity = json.ToObject<StuActivity>();
  1404. //activity.sStatus = 1;
  1405. //tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
  1406. }
  1407. else
  1408. {
  1409. List<string> scode = new();
  1410. 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'"))
  1411. {
  1412. using var stuJson = await JsonDocument.ParseAsync(item.ContentStream);
  1413. if (stuJson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1414. {
  1415. var accounts = stuJson.RootElement.GetProperty("Documents").EnumerateArray();
  1416. while (accounts.MoveNext())
  1417. {
  1418. JsonElement account = accounts.Current;
  1419. scode.Add(account.GetProperty("shoolId").GetString());
  1420. }
  1421. }
  1422. }
  1423. foreach (var sid in scode)
  1424. {
  1425. //StuActivity activity = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{sid}-{s.id}"));
  1426. //activity.sStatus = 1;
  1427. //tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
  1428. }
  1429. }
  1430. }
  1431. catch (Exception ex)
  1432. {
  1433. await _dingDing.SendBotMsg($"{_option.Location}\n{ex.Message}\n{ex.StackTrace}\n\n,id:{id},code:{s.id},school:{result?.school}", GroupNames.醍摩豆服務運維群組);
  1434. }
  1435. }
  1436. }
  1437. index_sc++;
  1438. }
  1439. if (!result.progress)
  1440. {
  1441. bool flag = true;
  1442. foreach (List<double> scores in result.studentScores)
  1443. {
  1444. foreach (double score in scores)
  1445. {
  1446. if (score == -1)
  1447. {
  1448. flag = false;
  1449. break;
  1450. }
  1451. }
  1452. }
  1453. if (flag)
  1454. {
  1455. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1456. result.progress = true;
  1457. exam.subjects.ForEach(s =>
  1458. {
  1459. if (s.id.Equals(subjectId.ToString()))
  1460. {
  1461. s.classCount += 1;
  1462. }
  1463. });
  1464. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
  1465. }
  1466. }
  1467. else
  1468. {
  1469. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  1470. exam.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1471. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
  1472. }
  1473. classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  1474. // await Task.WhenAll(tasks);
  1475. }
  1476. //检查所有成员是否完成打分
  1477. List<List<double>> ers = new List<List<double>>();
  1478. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
  1479. queryText: $"select c.studentScores as scores from c where c.examId = '{id}'",
  1480. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  1481. {
  1482. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1483. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1484. {
  1485. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1486. while (accounts.MoveNext())
  1487. {
  1488. JsonElement account = accounts.Current;
  1489. List<List<double>> sc = account.GetProperty("scores").ToObject<List<List<double>>>();
  1490. ers.AddRange(sc);
  1491. }
  1492. }
  1493. }
  1494. var isScore = !ers.Exists(c => c.Contains(-1));
  1495. return Ok(new { classResult, isScore });
  1496. }
  1497. catch (Exception ex)
  1498. {
  1499. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecordByTeacher()\n{ex.StackTrace}\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  1500. return BadRequest();
  1501. }
  1502. /*if (exams.IsNotEmpty())
  1503. {
  1504. ExamInfo examInfo = exams[0];
  1505. //提交答案时间必须是状态已发布,且时间在起止时间内
  1506. if (examInfo.startTime <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && examInfo.status == 200 &&
  1507. examInfo.endTime >= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
  1508. {
  1509. return builder.Data(await _azureCosmos.SaveOrUpdate(request)).build();
  1510. }
  1511. else
  1512. {
  1513. return builder.Error(ResponseCode.FAILED, "请在作答时间段内提交答案!").build();
  1514. }
  1515. }
  1516. else
  1517. {
  1518. return builder.Error(ResponseCode.DATA_EXIST, "考试不存在!").build();
  1519. }*/
  1520. }
  1521. /// <summary>
  1522. /// 查询评测详细信息(教师或者学生通用)
  1523. /// </summary>
  1524. /// <param name="request"></param>
  1525. /// <returns></returns>
  1526. [ProducesDefaultResponseType]
  1527. [Authorize(Roles = "IES")]
  1528. [AuthToken(Roles = "teacher,admin")]
  1529. [HttpPost("find-summary-record")]
  1530. public async Task<IActionResult> findSummaryRecord(JsonElement request)
  1531. {
  1532. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1533. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1534. //if (!request.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
  1535. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  1536. if (!request.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
  1537. if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  1538. if (!request.TryGetProperty("startTime", out JsonElement startTime)) return BadRequest();
  1539. try
  1540. {
  1541. // 如果只有学生id则返回学生参加过的考试 只返回相关摘要信息
  1542. var client = _azureCosmos.GetCosmosClient();
  1543. var (_, _, _, school) = HttpContext.GetAuthTokenInfo();
  1544. //string code = school_code.ToString().Substring(5);
  1545. //ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{school_code}"));
  1546. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  1547. 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}'",
  1548. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school_code}") }))
  1549. {
  1550. examClassResults.Add(item);
  1551. }
  1552. List<string> ids = new();
  1553. //List<string> codes = new();
  1554. foreach (ExamClassResult result in examClassResults)
  1555. {
  1556. ids.AddRange(result.studentIds);
  1557. //codes.AddRange(result.scIds);
  1558. }
  1559. List<string> cid = new()
  1560. {
  1561. classId.GetString()
  1562. };
  1563. (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, cid, $"{school}", null, -1, startTime.GetInt64());
  1564. //await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<GroupList>(classId.GetString, new PartitionKey($"Exam-{code}"));
  1565. ///获取真实的名称
  1566. List<ufo> ufos = new();
  1567. List<string> delIds = new();
  1568. if (groups.Count > 0)
  1569. {
  1570. string scode = groups[0].school;
  1571. if (ids.Count > 0)
  1572. {
  1573. List<string> sIds = new();
  1574. List<string> tIds = new();
  1575. List<ufo> students = new List<ufo>();
  1576. if (string.IsNullOrEmpty(scode))
  1577. {
  1578. var content = new StringContent(ids.ToJsonString(), Encoding.UTF8, "application/json");
  1579. string json = await _coreAPIHttpService.GetUserInfos(content);
  1580. if (!string.IsNullOrWhiteSpace(json))
  1581. {
  1582. try
  1583. {
  1584. List<ufo> tmdInfos = json.ToObject<List<ufo>>();
  1585. if (tmdInfos.IsNotEmpty())
  1586. {
  1587. foreach (ufo fo in tmdInfos)
  1588. {
  1589. fo.type = 1;
  1590. tIds.Add(fo.id);
  1591. }
  1592. ufos.AddRange(tmdInfos);
  1593. delIds = ids.Except(tIds).ToList();
  1594. }
  1595. }
  1596. catch (Exception ex)
  1597. {
  1598. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n ", GroupNames.醍摩豆服務運維群組);
  1599. }
  1600. }
  1601. }
  1602. else
  1603. {
  1604. 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'",
  1605. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{scode}") }))
  1606. {
  1607. using var stuJson = await JsonDocument.ParseAsync(item.ContentStream);
  1608. if (stuJson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1609. {
  1610. var accounts = stuJson.RootElement.GetProperty("Documents").EnumerateArray();
  1611. while (accounts.MoveNext())
  1612. {
  1613. JsonElement account = accounts.Current;
  1614. ufo fo = new()
  1615. {
  1616. id = account.GetProperty("id").GetString(),
  1617. name = account.GetProperty("name").GetString(),
  1618. //schoolId = account.GetProperty("schoolId").GetString(),
  1619. type = 2
  1620. };
  1621. students.Add(fo);
  1622. }
  1623. }
  1624. }
  1625. if (students.Count > 0)
  1626. {
  1627. ufos.AddRange(students);
  1628. foreach (ufo f in students)
  1629. {
  1630. sIds.Add(f.id);
  1631. }
  1632. if (ids.Count > sIds.Count)
  1633. {
  1634. tIds = ids.Except(sIds).ToList();
  1635. var content = new StringContent(tIds.ToJsonString(), Encoding.UTF8, "application/json");
  1636. string json = await _coreAPIHttpService.GetUserInfos(content);
  1637. if (!string.IsNullOrWhiteSpace(json))
  1638. {
  1639. try
  1640. {
  1641. List<ufo> tmdInfos = json.ToObject<List<ufo>>();
  1642. if (tmdInfos.IsNotEmpty())
  1643. {
  1644. foreach (ufo fo in tmdInfos)
  1645. {
  1646. fo.type = 1;
  1647. tIds.Add(fo.id);
  1648. }
  1649. ufos.AddRange(tmdInfos);
  1650. }
  1651. }
  1652. catch (Exception ex)
  1653. {
  1654. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n ", GroupNames.醍摩豆服務運維群組);
  1655. }
  1656. }
  1657. }
  1658. delIds = ids.Except(sIds.Union(tIds)).ToList();
  1659. }
  1660. }
  1661. }
  1662. }
  1663. //List<ufo> students = new List<ufo>();
  1664. /*if (StringHelper.getKeyCount(request) == 1 && request.TryGetProperty("code", out JsonElement code))
  1665. {
  1666. List<object> props = new List<object>();
  1667. 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}") }))
  1668. {
  1669. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1670. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1671. {
  1672. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1673. {
  1674. props.Add(obj.ToObject<object>());
  1675. }
  1676. }
  1677. }
  1678. return Ok(new { props });
  1679. }
  1680. else
  1681. {
  1682. if (request.TryGetProperty("examCode", out JsonElement _))
  1683. {
  1684. //List<string> props = new List<string> { "id", "code", "examCode", "status", "mark", "score" };
  1685. //List<ExamRecord> examRecords = await _azureCosmos.FindByDict<ExamRecord>(request, props);
  1686. //return builder.Data(examRecords).Extend(new Dictionary<string, object> { { "props", props } }).build();
  1687. List<object> props = new List<object>();
  1688. 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}") }))
  1689. {
  1690. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1691. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1692. {
  1693. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1694. {
  1695. props.Add(obj.ToObject<object>());
  1696. }
  1697. }
  1698. }
  1699. return Ok(new { props });
  1700. }
  1701. }*/
  1702. return Ok(new { examClassResults, ufos, delIds });
  1703. }
  1704. catch (Exception ex)
  1705. {
  1706. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findSummaryRecord()\n{ex.Message}\n{ex.StackTrace}\n\n{id.GetString()}", GroupNames.醍摩豆服務運維群組);
  1707. return BadRequest();
  1708. }
  1709. }
  1710. //学生端查询评测列表
  1711. [ProducesDefaultResponseType]
  1712. [Authorize(Roles = "IES")]
  1713. [AuthToken(Roles = "student,teacher,admin")]
  1714. [HttpPost("find-summary-by-student")]
  1715. public async Task<IActionResult> findSummaryStudent(JsonElement request)
  1716. {
  1717. //ResponseBuilder builder = ResponseBuilder.custom();
  1718. //var (id, school) = HttpContext.GetAuthTokenInfo();
  1719. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1720. if (!request.TryGetProperty("cIds", out JsonElement cIds)) return BadRequest();
  1721. if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  1722. if (!request.TryGetProperty("code", out JsonElement school)) return BadRequest();
  1723. if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
  1724. try
  1725. {
  1726. var client = _azureCosmos.GetCosmosClient();
  1727. //var query = $"select value(c) where c.id ='{id}'";
  1728. //List<ExamInfo> exams = new List<ExamInfo>();
  1729. List<object> subjects = new List<object>();
  1730. List<string> classIds = new List<string>();
  1731. //List<string> stus = new List<string>();
  1732. //存放当前学生所在班级ID或者名单ID
  1733. /*HashSet<string> resultIds = new();
  1734. //List<string> ids = new List<string>();
  1735. //处理班级人数(公共部分的校本名单)
  1736. //List<Student> students = new List<Student>();
  1737. 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}") }))
  1738. {
  1739. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1740. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1741. {
  1742. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1743. while (accounts.MoveNext())
  1744. {
  1745. JsonElement account = accounts.Current;
  1746. resultIds.Add(account.GetProperty("id").GetString());
  1747. }
  1748. }
  1749. }
  1750. //获取自定义名单信息
  1751. List<GroupList> stuLists = new List<GroupList>();
  1752. 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}'",
  1753. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
  1754. {
  1755. stuLists.Add(item);
  1756. }
  1757. 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}'",
  1758. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
  1759. {
  1760. stuLists.Add(item);
  1761. }
  1762. if (stuLists.Count > 0)
  1763. {
  1764. foreach (GroupList stuList in stuLists)
  1765. {
  1766. resultIds.Add(stuList.id);
  1767. }
  1768. }
  1769. var queryClassId = $"select c.classes id,c.stuLists stus from c where c.id ='{id}'";
  1770. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: queryClassId, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  1771. {
  1772. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1773. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1774. {
  1775. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1776. {
  1777. classIds.AddRange(obj.GetProperty("id").ToObject<List<string>>());
  1778. classIds.AddRange(obj.GetProperty("stus").ToObject<List<string>>());
  1779. //classIds = obj.ToObject<List<string>>();
  1780. }
  1781. }
  1782. }
  1783. //存放该学生所在班级参与当前评测的ID
  1784. List<string> infoIds = new List<string>();
  1785. foreach (string ids in resultIds)
  1786. {
  1787. if (classIds.Contains(ids))
  1788. {
  1789. infoIds.Add(ids);
  1790. }
  1791. }*/
  1792. //List<string> infoIds = cIds.ToObject<List<string>>();
  1793. List<string> infoIds = new();
  1794. ExamInfo info = new();
  1795. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{scode}"));
  1796. if (response.Status == 200)
  1797. {
  1798. using var cJson = await JsonDocument.ParseAsync(response.ContentStream);
  1799. info = cJson.ToObject<ExamInfo>();
  1800. }
  1801. /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamInfo>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  1802. {
  1803. exams.Add(item);
  1804. }*/
  1805. var querySubject = $"select A0.id,A0.name from c join A0 in c.subjects where c.id ='{id}'";
  1806. //List<object> props = new List<object>();
  1807. List<string> subId = new();
  1808. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: querySubject, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
  1809. {
  1810. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1811. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1812. {
  1813. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1814. {
  1815. subjects.Add(obj.ToObject<object>());
  1816. subId.Add(obj.GetProperty("id").GetString());
  1817. }
  1818. }
  1819. }
  1820. 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' ";
  1821. List<ExamClassResult> answers = new List<ExamClassResult>();
  1822. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: queryAnswers,
  1823. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  1824. {
  1825. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1826. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1827. {
  1828. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1829. {
  1830. answers.Add(obj.ToObject<ExamClassResult>());
  1831. infoIds.Add(obj.GetProperty("cId").GetString());
  1832. }
  1833. }
  1834. }
  1835. var queryResult = $"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 c.pk = 'ExamClassResult' ";
  1836. List<ExamClassResult> classResults = new List<ExamClassResult>();
  1837. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(queryText: queryResult,
  1838. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  1839. {
  1840. classResults.Add(item);
  1841. }
  1842. //查询结果
  1843. List<ExamResult> results = new();
  1844. 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}") }))
  1845. {
  1846. results.Add(item);
  1847. }
  1848. List<List<string>> stuAns = new();
  1849. List<List<double>> stuScore = new();
  1850. List<List<List<Details>>> mark = new();
  1851. List<List<double>> total = new();
  1852. List<double> average = new();
  1853. if (answers.Count > 0)
  1854. {
  1855. foreach (ExamClassResult result in answers)
  1856. {
  1857. List<double> sTotal = new();
  1858. int index = result.studentIds.IndexOf(studentId.ToString());
  1859. if (index == -1)
  1860. {
  1861. break;
  1862. }
  1863. stuAns.Add(result.studentAnswers[index]);
  1864. stuScore.Add(result.studentScores[index]);
  1865. mark.Add(result.mark[index]);
  1866. average.Add(result.average);
  1867. sTotal.Add(result.sum.Where(s => s <= 59).Count());
  1868. sTotal.Add(result.sum.Where(s => s > 59 && s <= 70).Count());
  1869. sTotal.Add(result.sum.Where(s => s > 70 && s <= 80).Count());
  1870. sTotal.Add(result.sum.Where(s => s > 80 && s <= 90).Count());
  1871. sTotal.Add(result.sum.Where(s => s > 90 && s <= 100).Count());
  1872. total.Add(sTotal);
  1873. }
  1874. }
  1875. List<(List<string> kn, List<double> kps, List<double> ckps, List<double> akps)> know = new();
  1876. List<(List<int> fs, List<double> fps, List<double> cfps, List<double> afps)> fp = new();
  1877. List<List<double>> wno = new();
  1878. List<KeyValuePair<string, List<KeyValuePair<string, Dictionary<string, string>>>>> subjectScatter = new();
  1879. if (!string.IsNullOrEmpty(info.progress) && info.progress.Equals("finish"))
  1880. {
  1881. (List<RMember> members, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, infoIds, info.school, null,-1,info.startTime);
  1882. await foreach (var s in stuTask(subId, info.papers, answers, classResults, studentId.GetString()))
  1883. {
  1884. know = s.know;
  1885. fp = s.filed;
  1886. }
  1887. foreach (ExamResult exam in results)
  1888. {
  1889. subjectScatter.Add(DoSubjectScatter(exam, members));
  1890. //确定当前循环科目索引位置
  1891. int index = subId.IndexOf(exam.subjectId);
  1892. //根据索引找到试卷分数
  1893. List<double> points = info.papers[index].point;
  1894. List<double> wn = await getWrongNum(exam, points, infoIds);
  1895. wno.Add(wn);
  1896. }
  1897. if (info.papers.IsNotEmpty())
  1898. {
  1899. var knowledge = know.Select(k => new { k.kn, k.kps, k.ckps, k.akps });
  1900. var filed = fp.Select(k => new { k.fs, k.fps, k.cfps, k.afps });
  1901. //papers = papers
  1902. return Ok(new { info.cloudas, info.papers, subjects, stuScore, stuAns, mark, total, claId = infoIds, knowledge, filed, average, wno, subjectScatter, status = 200 });
  1903. }
  1904. }
  1905. return Ok(new { info.cloudas, info.papers, subjects, stuScore, stuAns, mark, total, claId = infoIds, knowledge = new List<object>(), filed = new List<object>(), average, wno, subjectScatter, status = 200 });
  1906. }
  1907. catch (Exception ex)
  1908. {
  1909. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-summary-by-student()\n{ex.Message}\n{ex.StackTrace}\n\n{id.GetString()}", GroupNames.醍摩豆服務運維群組);
  1910. return Ok(new { status = 500 });
  1911. }
  1912. }
  1913. private async IAsyncEnumerable<(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, List<ExamClassResult> results, string stuId)
  1914. {
  1915. 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)>();
  1916. 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)>();
  1917. int no = 0;
  1918. foreach (string sub in subjectIds)
  1919. {
  1920. List<double> kp = new();
  1921. List<double> akp = new();
  1922. List<double> fp = new();
  1923. List<double> afp = new();
  1924. List<double> ckp = new();
  1925. List<double> cfp = new();
  1926. List<int> fields = new() { 1, 2, 3, 4, 5, 6 };
  1927. //获取该试卷所有知识点和认知层次分布
  1928. List<List<string>> kones = papers[no].knowledge;
  1929. List<int> fs = papers[no].field;
  1930. List<double> point = papers[no].point;
  1931. //去重知识点
  1932. HashSet<string> knowles = new();
  1933. List<string> knowledges = new();
  1934. if (kones.Count > 0)
  1935. {
  1936. knowles = new HashSet<string>(kones.SelectMany(z => z));
  1937. }
  1938. knowledges.AddRange(knowles.Where(z => !string.IsNullOrWhiteSpace(z)));
  1939. List<ExamClassResult> classResults = answers.Where(result => !string.IsNullOrWhiteSpace(result?.subjectId) && result.subjectId.Equals(sub)).ToList();
  1940. List<ExamClassResult> allResults = results.Where(result => !string.IsNullOrWhiteSpace(result?.subjectId) && result.subjectId.Equals(sub)).ToList();
  1941. foreach (ExamClassResult result in classResults)
  1942. {
  1943. int index = result.studentIds.IndexOf(stuId.ToString());
  1944. //处理知识点
  1945. foreach (string k in knowledges)
  1946. {
  1947. //初始化单个知识点得分
  1948. double score = 0;
  1949. double allScore = 0;
  1950. int n = 0;
  1951. foreach (List<string> str in kones)
  1952. {
  1953. if (str.Contains(k))
  1954. {
  1955. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  1956. allScore += point.Count > 0 ? point[n] * itemPersent : 0;
  1957. if (result.studentScores.Count > 0)
  1958. {
  1959. if (result.studentScores[index].Count > 0)
  1960. {
  1961. score += result.studentScores[index][n] == -1 ? 0 : result.studentScores[index][n] * itemPersent;
  1962. }
  1963. }
  1964. }
  1965. n++;
  1966. }
  1967. kp.Add(allScore > 0 ? Math.Round(score / allScore, 2) : 0);
  1968. }
  1969. //处理认知层次
  1970. foreach (int k in fields)
  1971. {
  1972. //初始化认知层次得分
  1973. double score = 0;
  1974. double allScore = 0;
  1975. int n = 0;
  1976. foreach (int str in fs)
  1977. {
  1978. if (str == k)
  1979. {
  1980. var itemPersent = 1;
  1981. allScore += point.Count > 0 ? point[n] * itemPersent : 0;
  1982. if (result.studentScores.Count > 0)
  1983. {
  1984. if (result.studentScores[index].Count > 0)
  1985. {
  1986. score += result.studentScores[index][n] == -1 ? 0 : result.studentScores[index][n];
  1987. }
  1988. }
  1989. }
  1990. n++;
  1991. }
  1992. fp.Add(allScore > 0 ? Math.Round(score / allScore, 2) : 0);
  1993. }
  1994. ckp = result.krate;
  1995. cfp = result.frate;
  1996. }
  1997. foreach (string k in knowledges)
  1998. {
  1999. double score = 0;
  2000. double allScore = 0;
  2001. int count = 0;
  2002. foreach (ExamClassResult result in allResults)
  2003. {
  2004. int n = 0;
  2005. foreach (List<string> str in kones)
  2006. {
  2007. if (str.Contains(k))
  2008. {
  2009. var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
  2010. allScore += point.Count > 0 ? point[n] * itemPersent : 0;
  2011. if (result.studentScores.Count > 0)
  2012. {
  2013. /*score += result.studentScores.ForEach(r => r[n]) * itemPersent;*/
  2014. foreach (List<double> sc in result.studentScores)
  2015. {
  2016. double tsc = sc[n] == -1 ? 0 : sc[n];
  2017. score += tsc * itemPersent;
  2018. }
  2019. }
  2020. }
  2021. n++;
  2022. }
  2023. count += result.studentIds.Count;
  2024. }
  2025. double per = count > 0 ? Math.Round(score / count, 2) : 0;
  2026. akp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
  2027. }
  2028. //处理认知层次
  2029. foreach (int k in fields)
  2030. {
  2031. //初始化认知层次得分
  2032. double score = 0;
  2033. double allScore = 0;
  2034. int count = 0;
  2035. foreach (ExamClassResult result in allResults)
  2036. {
  2037. if (result.subjectId.Equals(sub))
  2038. {
  2039. int n = 0;
  2040. foreach (int str in fs)
  2041. {
  2042. if (str == k)
  2043. {
  2044. var itemPersent = 1;
  2045. allScore += point.Count > 0 ? point[n] * itemPersent : 0;
  2046. if (result.studentScores.Count > 0)
  2047. {
  2048. foreach (List<double> sc in result.studentScores)
  2049. {
  2050. double tsc = sc[n] == -1 ? 0 : sc[n];
  2051. score += tsc * itemPersent;
  2052. }
  2053. }
  2054. }
  2055. n++;
  2056. }
  2057. count += result.studentIds.Count;
  2058. }
  2059. }
  2060. double per = count > 0 ? Math.Round(score / count, 2) : 0;
  2061. afp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
  2062. }
  2063. know.Add((knowledges, kp, ckp, akp));
  2064. filed.Add((fields, fp, cfp, afp));
  2065. no++;
  2066. }
  2067. yield return (know, filed);
  2068. }
  2069. private KeyValuePair<string, List<KeyValuePair<string, Dictionary<string, string>>>> DoSubjectScatter(ExamResult e, List<RMember> members)
  2070. {
  2071. List<KeyValuePair<string, Dictionary<string, string>>> datas = new();
  2072. double[] point = StringHelper.ListTodouble(e.paper.point);
  2073. double[,] result = StringHelper.ListToDouble(e.studentScores);
  2074. List<string> scatterKey = new List<string>
  2075. {
  2076. "name",
  2077. "className",
  2078. "x",
  2079. "y",
  2080. "memberId",
  2081. "score",
  2082. "trueNum",
  2083. "falseNum",
  2084. "hardList",
  2085. "carefulList",
  2086. "scatter"
  2087. };
  2088. try
  2089. {
  2090. var cdm = new ClouDASMatrix(result, point);
  2091. //学生通过率
  2092. List<double> pass = cdm.ScoringRate;
  2093. //学生稳定度
  2094. List<double> sta = cdm.StabilityRate;
  2095. //落点区域
  2096. List<string> stu = cdm.StuFallArea;
  2097. //需努力的题型
  2098. List<int[]> strive = cdm.StriveTopic;
  2099. //需小心的题型
  2100. List<int[]> careful = cdm.CarefulTopic;
  2101. int i = 0;
  2102. for (int k = e.studentIds.Count - 1; k >= 0; k--)
  2103. {
  2104. if (e.studentIds[k].Equals("0"))
  2105. {
  2106. e.studentIds.Remove(e.studentIds[k]);
  2107. }
  2108. }
  2109. e.studentIds.ForEach(s =>
  2110. {
  2111. List<string> info = new()
  2112. {
  2113. members.Where(c => c.id.Equals(s)).FirstOrDefault()?.name,
  2114. "-",
  2115. sta[i] > 1 ? "1": sta[i].ToString(),
  2116. pass[i].ToString(),
  2117. i + 1 + "",
  2118. Math.Round(e.studentScores[i].Sum(),2).ToString()
  2119. };
  2120. int right = 0;
  2121. int wrong = 0;
  2122. foreach (double p in e.studentScores[i])
  2123. {
  2124. if (p > 0)
  2125. {
  2126. right++;
  2127. }
  2128. else
  2129. {
  2130. wrong++;
  2131. }
  2132. }
  2133. info.Add(right + "");
  2134. info.Add(wrong + "");
  2135. int[] str = strive[i];
  2136. string striveAll = "";
  2137. foreach (int n in str)
  2138. {
  2139. striveAll += n.ToString() + ",";
  2140. }
  2141. int[] care = careful[i];
  2142. string careAll = "";
  2143. foreach (int n in care)
  2144. {
  2145. careAll += n.ToString() + ",";
  2146. }
  2147. if (string.IsNullOrEmpty(striveAll))
  2148. {
  2149. info.Add("-");
  2150. }
  2151. else
  2152. {
  2153. info.Add(striveAll.Substring(0, striveAll.Length - 1));
  2154. }
  2155. if (string.IsNullOrEmpty(careAll))
  2156. {
  2157. info.Add("-");
  2158. }
  2159. else
  2160. {
  2161. info.Add(careAll.Substring(0, careAll.Length - 1)); ;
  2162. }
  2163. info.Add(stu[i].ToString());
  2164. int m = 0;
  2165. Dictionary<string, string> scatter = new();
  2166. foreach (string key in info)
  2167. {
  2168. scatter.Add(scatterKey[m], key);
  2169. m++;
  2170. }
  2171. KeyValuePair<string, Dictionary<string, string>> keyValue = new(s, scatter);
  2172. datas.Add(keyValue);
  2173. //}
  2174. i++;
  2175. });
  2176. return new KeyValuePair<string, List<KeyValuePair<string, Dictionary<string, string>>>>(e.subjectId, datas);
  2177. }
  2178. catch (Exception ex)
  2179. {
  2180. BadRequest(ex.Message + ex.StackTrace);
  2181. }
  2182. return default;
  2183. }
  2184. //查询学生活动列表
  2185. [ProducesDefaultResponseType]
  2186. [Authorize(Roles = "IES")]
  2187. [AuthToken(Roles = "student")]
  2188. [HttpPost("find-all-by-student")]
  2189. public async Task<IActionResult> findAllStudent(JsonElement request)
  2190. {
  2191. //ResponseBuilder builder = ResponseBuilder.custom();
  2192. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2193. try
  2194. {
  2195. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2196. if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  2197. List<string> resultIds = new List<string>();
  2198. var client = _azureCosmos.GetCosmosClient();
  2199. //查询校本班级ID
  2200. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(
  2201. queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
  2202. {
  2203. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  2204. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2205. {
  2206. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  2207. while (accounts.MoveNext())
  2208. {
  2209. JsonElement account = accounts.Current;
  2210. resultIds.Add(account.GetProperty("id").GetString());
  2211. }
  2212. }
  2213. }
  2214. //查询私人班级ID
  2215. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(
  2216. queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
  2217. {
  2218. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  2219. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2220. {
  2221. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  2222. while (accounts.MoveNext())
  2223. {
  2224. JsonElement account = accounts.Current;
  2225. resultIds.Add(account.GetProperty("id").GetString());
  2226. }
  2227. }
  2228. }
  2229. //StringBuilder builder = new StringBuilder();
  2230. HashSet<string> strs = new HashSet<string>();
  2231. if (resultIds.Count > 1)
  2232. {
  2233. foreach (string str in resultIds)
  2234. {
  2235. strs.Add($"array_contains(c.classes,'{str}')");
  2236. //builder.Append($"array_contains(c.targetClassIds,'{str}')").Append("or");
  2237. }
  2238. //builder.ToString().Substring(0, builder.ToString().Length - 2);
  2239. }
  2240. else
  2241. {
  2242. string ssr = resultIds.Count > 0 ? resultIds[0] : "";
  2243. strs.Add($"array_contains(c.classes,'{ssr}')");
  2244. //builder.Append($" array_contains(c.targetClassIds,'{ssr}')");
  2245. }
  2246. string ss = string.Join(" or ", strs);
  2247. //if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
  2248. 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' ";
  2249. List<object> props = new List<object>();
  2250. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: query))
  2251. {
  2252. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  2253. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2254. {
  2255. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2256. {
  2257. props.Add(obj.ToObject<object>());
  2258. }
  2259. }
  2260. }
  2261. 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'";
  2262. List<ExamClassResult> Classes = new List<ExamClassResult>();
  2263. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: queryClass))
  2264. {
  2265. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  2266. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2267. {
  2268. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2269. {
  2270. Classes.Add(obj.ToObject<ExamClassResult>());
  2271. }
  2272. }
  2273. }
  2274. List<ExamClassResult> result = new List<ExamClassResult>();
  2275. foreach (ExamClassResult classResult in Classes)
  2276. {
  2277. int index = classResult.studentIds.IndexOf(studentId.ToString());
  2278. ExamClassResult result1 = new ExamClassResult();
  2279. result1.examId = classResult.examId;
  2280. result1.subjectId = classResult.subjectId;
  2281. result1.studentAnswers.Add(classResult.studentAnswers[index]);
  2282. result1.studentScores.Add(classResult.studentScores[index]);
  2283. result.Add(result1);
  2284. }
  2285. return Ok(new { props, result });
  2286. }
  2287. catch (Exception ex)
  2288. {
  2289. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2290. return Ok(new { status = 500 });
  2291. }
  2292. }
  2293. //查询学生活动列表
  2294. [ProducesDefaultResponseType]
  2295. [Authorize(Roles = "IES")]
  2296. [AuthToken(Roles = "student")]
  2297. [HttpPost("find-score-by-student")]
  2298. public async Task<IActionResult> findScoreByStudent(JsonElement request)
  2299. {
  2300. //ResponseBuilder builder = ResponseBuilder.custom();
  2301. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2302. try
  2303. {
  2304. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2305. //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2306. var client = _azureCosmos.GetCosmosClient();
  2307. var query = $"select c.examId,c.subjectId,c.studentScores from c where array_contains(c.studentIds,'{id}') ";
  2308. List<object> props = new List<object>();
  2309. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: query))
  2310. {
  2311. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  2312. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  2313. {
  2314. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  2315. {
  2316. props.Add(obj.ToObject<object>());
  2317. }
  2318. }
  2319. }
  2320. return Ok(props);
  2321. }
  2322. catch (Exception ex)
  2323. {
  2324. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2325. return Ok(new { status = 500 });
  2326. }
  2327. }
  2328. //查询学生活动列表
  2329. [ProducesDefaultResponseType]
  2330. [Authorize(Roles = "IES")]
  2331. [AuthToken(Roles = "teacher,admin")]
  2332. [HttpPost("finish")]
  2333. public async Task<IActionResult> finish(JsonElement request)
  2334. {
  2335. //ResponseBuilder builder = ResponseBuilder.custom();
  2336. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2337. try
  2338. {
  2339. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2340. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2341. var client = _azureCosmos.GetCosmosClient();
  2342. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  2343. info.progress = "finish";
  2344. info.endTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  2345. List<ExamClassResult> classResults = new();
  2346. if (info.scope.Equals("school"))
  2347. {
  2348. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  2349. queryText: $"select value(c) from c where c.examId = '{id}'",
  2350. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  2351. {
  2352. classResults.Add(item);
  2353. }
  2354. }
  2355. else
  2356. {
  2357. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  2358. queryText: $"select value(c) from c where c.examId = '{id}'",
  2359. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  2360. {
  2361. classResults.Add(item);
  2362. }
  2363. }
  2364. foreach (ExamClassResult examClass in classResults)
  2365. {
  2366. examClass.progress = true;
  2367. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(examClass, examClass.id, new PartitionKey($"{examClass.code}"));
  2368. }
  2369. info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  2370. return Ok(info);
  2371. }
  2372. catch (Exception ex)
  2373. {
  2374. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/finish\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2375. return Ok(new { status = 500 });
  2376. }
  2377. }
  2378. /*//查询任务列表
  2379. [ProducesDefaultResponseType]
  2380. //[AuthToken(Roles = "Student")]
  2381. [HttpPost("scoring")]
  2382. public async Task<IActionResult> Scoring(JsonElement request)
  2383. {
  2384. //ResponseBuilder builder = ResponseBuilder.custom();
  2385. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2386. try
  2387. {
  2388. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2389. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2390. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  2391. var client = _azureCosmos.GetCosmosClient();
  2392. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  2393. int index = 0;
  2394. foreach (ExamSubject subject in info.subjects) {
  2395. if (!subject.id.Equals(subjectId.ToString()))
  2396. {
  2397. index++;
  2398. }
  2399. else {
  2400. break;
  2401. }
  2402. }
  2403. List<string> stuAns = new();
  2404. Dictionary<string, List<List<double>>> keyValues = new();
  2405. List<ExamClassResult> classResults = new();
  2406. if (info.scope.Equals("school"))
  2407. {
  2408. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  2409. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  2410. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
  2411. {
  2412. classResults.Add(item);
  2413. }
  2414. }
  2415. else
  2416. {
  2417. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  2418. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  2419. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
  2420. {
  2421. classResults.Add(item);
  2422. }
  2423. }
  2424. List<List<double>> itemScore = new();
  2425. for (int i = 0; i < info.papers[index].point.Count; i++)
  2426. {
  2427. List<double> score = new();
  2428. foreach (ExamClassResult examClass in classResults)
  2429. {
  2430. foreach (List<double> sc in examClass.studentScores)
  2431. {
  2432. score.Add(sc[i]);
  2433. }
  2434. }
  2435. itemScore.Add(score);
  2436. }
  2437. foreach (ExamClassResult examClass in classResults)
  2438. {
  2439. foreach (List<string> ans in examClass.studentAnswers)
  2440. {
  2441. if (ans.Count > 0)
  2442. {
  2443. stuAns.Add(ans[0]);
  2444. }
  2445. else
  2446. {
  2447. stuAns.Add("");
  2448. }
  2449. }
  2450. }
  2451. //info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
  2452. return Ok(new { score = itemScore , stuAns, paper = info.papers });
  2453. }
  2454. catch (Exception ex)
  2455. {
  2456. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2457. return BadRequest();
  2458. }
  2459. }*/
  2460. [ProducesDefaultResponseType]
  2461. [Authorize(Roles = "IES")]
  2462. [AuthToken(Roles = "teacher,admin")]
  2463. [HttpPost("scoring")]
  2464. public async Task<IActionResult> scoring(JsonElement request)
  2465. {
  2466. //ResponseBuilder builder = ResponseBuilder.custom();
  2467. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2468. try
  2469. {
  2470. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2471. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2472. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  2473. //if (!request.TryGetProperty("type", out JsonElement type)) return BadRequest();
  2474. if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  2475. if (!request.TryGetProperty("count", out JsonElement scount)) return BadRequest();
  2476. var client = _azureCosmos.GetCosmosClient();
  2477. //var redisClient = _azureRedis.GetRedisClient(8);
  2478. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  2479. List<ExamClassResult> classResults = new();
  2480. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  2481. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2482. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and array_contains(c.tIds,'{tId}') ",
  2483. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2484. {
  2485. attr.Add(item);
  2486. }
  2487. List<SDK.Models.Cosmos.Common.Scoring> attrSc = new List<SDK.Models.Cosmos.Common.Scoring>();
  2488. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2489. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  2490. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2491. {
  2492. attrSc.Add(item);
  2493. }
  2494. int index = 0;
  2495. foreach (ExamSubject subject in info.subjects)
  2496. {
  2497. if (!subject.id.Equals(subjectId.ToString()))
  2498. {
  2499. index++;
  2500. }
  2501. else
  2502. {
  2503. break;
  2504. }
  2505. }
  2506. List<dynamic> objs = new List<dynamic>();
  2507. List<dynamic> wobjs = new List<dynamic>();
  2508. /*if (type.GetInt32() != 1) {
  2509. return Ok(new { attr, paper = info.papers[index].blob });
  2510. }*/
  2511. //List<SDK.Models.Cosmos.Common.Scoring> errs = new();
  2512. //List<SDK.Models.Cosmos.Common.Scoring> arbs = new();
  2513. Correct correct = null;
  2514. var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
  2515. if (cResponse.Status == 200)
  2516. {
  2517. using var cJson = await JsonDocument.ParseAsync(cResponse.ContentStream);
  2518. correct = cJson.ToObject<Correct>();
  2519. }
  2520. int finishCount = 0;
  2521. foreach (SDK.Models.Cosmos.Common.Scoring ss in attrSc)
  2522. {
  2523. for (int i = 0; i < correct.num; i++)
  2524. {
  2525. List<double> tsc = new List<double>();
  2526. foreach (Item item in ss.items)
  2527. {
  2528. if (item.scores.Count > 0)
  2529. {
  2530. if (i >= item.scores.Count)
  2531. {
  2532. break;
  2533. }
  2534. else
  2535. {
  2536. tsc.Add(item.scores[i].sc);
  2537. }
  2538. }
  2539. }
  2540. bool flag = tsc.Exists(s => s == -1);
  2541. if (!flag && tsc.Count > 0)
  2542. {
  2543. finishCount++;
  2544. }
  2545. }
  2546. }
  2547. if (attr.Count > 0)
  2548. {
  2549. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  2550. {
  2551. //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});
  2552. List<dynamic> sc = new List<dynamic>();
  2553. List<dynamic> allSc = new List<dynamic>();
  2554. ss.qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
  2555. int indexScore = 0;
  2556. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code.GetString());
  2557. foreach (Item item in ss.items)
  2558. {
  2559. var count = item.scores.GroupBy(i => new { i.tmdId, i.sc }).Select(c => c.Key.sc).ToList();
  2560. allSc.Add(count.FirstOrDefault());
  2561. List<double> scc = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).ToList();
  2562. List<string> blob = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.mark).ToList();
  2563. //item.scores.Where(x => x.tmdId.Equals(tId.GetString())).SelectMany(p => p.sc, (p, d) => new { });
  2564. if (scc.Count > 0)
  2565. {
  2566. sc.Add(new { sc = scc.FirstOrDefault(), blob = blob.FirstOrDefault(), item.ssc });
  2567. }
  2568. else
  2569. {
  2570. ss.scores = scores;
  2571. sc.Add(new { sc = ss.scores[indexScore], blob = "", item.ssc });
  2572. }
  2573. indexScore++;
  2574. }
  2575. 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 };
  2576. objs.Add(obj);
  2577. }
  2578. }
  2579. else
  2580. {
  2581. if (request.TryGetProperty("stuId", out JsonElement stuId))
  2582. {
  2583. objs = await Review(attrSc, id.GetString(), code.GetString(), subjectId.GetString(), scount.GetInt32(), tId.GetString(), stuId.GetString());
  2584. }
  2585. else
  2586. {
  2587. objs = await Review(attrSc, id.GetString(), code.GetString(), subjectId.GetString(), scount.GetInt32(), tId.GetString(), "");
  2588. }
  2589. }
  2590. var fp = attr.Count > 0 ? Math.Round(finishCount * 1.0 / (attrSc.Count * correct.num), 2) : 0;
  2591. return Ok(new { objs, paper = info.papers[index].blob, fp });
  2592. }
  2593. catch (Exception ex)
  2594. {
  2595. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  2596. return Ok(new { status = 500 });
  2597. }
  2598. }
  2599. //查找异常卷
  2600. [ProducesDefaultResponseType]
  2601. [Authorize(Roles = "IES")]
  2602. [AuthToken(Roles = "teacher,admin")]
  2603. [HttpPost("find-err")]
  2604. public async Task<IActionResult> findErr(JsonElement request)
  2605. {
  2606. //ResponseBuilder builder = ResponseBuilder.custom();
  2607. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2608. try
  2609. {
  2610. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2611. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2612. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  2613. //if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  2614. var client = _azureCosmos.GetCosmosClient();
  2615. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
  2616. if (response.Status == 200)
  2617. {
  2618. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  2619. ExamInfo info = json.ToObject<ExamInfo>();
  2620. //ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  2621. List<ExamClassResult> classResults = new();
  2622. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  2623. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2624. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  2625. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2626. {
  2627. attr.Add(item);
  2628. }
  2629. int index = 0;
  2630. foreach (ExamSubject subject in info.subjects)
  2631. {
  2632. if (!subject.id.Equals(subjectId.ToString()))
  2633. {
  2634. index++;
  2635. }
  2636. else
  2637. {
  2638. break;
  2639. }
  2640. }
  2641. List<dynamic> objs = new List<dynamic>();
  2642. List<SDK.Models.Cosmos.Common.Scoring> errs = new();
  2643. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  2644. {
  2645. List<Qs> qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.err)).ToList();
  2646. if (qs.Count > 0)
  2647. {
  2648. ss.qs = qs;
  2649. errs.Add(ss);
  2650. }
  2651. }
  2652. return Ok(new { errs, paper = info.papers[index].blob });
  2653. }
  2654. else
  2655. {
  2656. return Ok(new { status = response.Status });
  2657. }
  2658. }
  2659. catch (Exception ex)
  2660. {
  2661. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-err\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  2662. return Ok(new { status = 500 });
  2663. }
  2664. }
  2665. [ProducesDefaultResponseType]
  2666. [AuthToken(Roles = "teacher,admin")]
  2667. [HttpPost("find-arb")]
  2668. [Authorize(Roles = "IES")]
  2669. public async Task<IActionResult> findArb(JsonElement request)
  2670. {
  2671. //ResponseBuilder builder = ResponseBuilder.custom();
  2672. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2673. try
  2674. {
  2675. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2676. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2677. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  2678. if (!request.TryGetProperty("et", out JsonElement et)) return BadRequest();
  2679. //if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  2680. var client = _azureCosmos.GetCosmosClient();
  2681. long time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  2682. if (et.GetInt64() > time)
  2683. {
  2684. return Ok(new { msg = "还在进行中", code = 202 });
  2685. }
  2686. ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
  2687. List<ExamClassResult> classResults = new();
  2688. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  2689. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2690. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  2691. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2692. {
  2693. attr.Add(item);
  2694. }
  2695. int index = 0;
  2696. foreach (ExamSubject subject in info.subjects)
  2697. {
  2698. if (!subject.id.Equals(subjectId.ToString()))
  2699. {
  2700. index++;
  2701. }
  2702. else
  2703. {
  2704. break;
  2705. }
  2706. }
  2707. List<dynamic> objs = new List<dynamic>();
  2708. /*if (type.GetInt32() != 1) {
  2709. return Ok(new { attr, paper = info.papers[index].blob });
  2710. }*/
  2711. //List<SDK.Models.Cosmos.Common.Scoring> errs = new();
  2712. List<SDK.Models.Cosmos.Common.Scoring> arbs = new();
  2713. //List<(string id,List<double>)> osc = new List<(string id, List<double>)>();
  2714. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  2715. {
  2716. //List<double> original = new List<double>();
  2717. List<Item> arb = ss.items.Where(s => s.flag == false).ToList();
  2718. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code.GetString());
  2719. ss.blob = ansBlob;
  2720. ss.scores = scores;
  2721. if (arb.Count > 0)
  2722. {
  2723. ss.items = arb;
  2724. arbs.Add(ss);
  2725. }
  2726. }
  2727. 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 });
  2728. }
  2729. catch (Exception ex)
  2730. {
  2731. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-arb\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  2732. return Ok(new { status = 500 });
  2733. }
  2734. }
  2735. //批阅,给老师随机分配阅卷数据,以及查询改老师已有的阅卷数据
  2736. 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)
  2737. {
  2738. //ResponseBuilder builder = ResponseBuilder.custom();
  2739. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2740. try
  2741. {
  2742. var client = _azureCosmos.GetCosmosClient();
  2743. //var redisClient = _azureRedis.GetRedisClient(8);
  2744. List<ExamClassResult> classResults = new();
  2745. List<SDK.Models.Cosmos.Common.Scoring> recs = new();
  2746. List<SDK.Models.Cosmos.Common.Scoring> all = new();
  2747. //List<SDK.Models.Cosmos.Common.Scoring> attr = new();
  2748. /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2749. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' ",
  2750. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2751. {
  2752. attr.Add(item);
  2753. }*/
  2754. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  2755. {
  2756. if (scoring.tIds.Contains(tId.ToString()))
  2757. {
  2758. recs.Add(scoring);
  2759. }
  2760. else if (scoring.tIds.Count < scoring.count * scoring.model)
  2761. {
  2762. all.Add(scoring);
  2763. }
  2764. }
  2765. if (!string.IsNullOrEmpty(stuId))
  2766. {
  2767. List<SDK.Models.Cosmos.Common.Scoring> value = new();
  2768. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2769. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.stuId = '{stuId}' ",
  2770. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2771. {
  2772. value.Add(item);
  2773. }
  2774. if (value.Count > 0)
  2775. {
  2776. foreach (SDK.Models.Cosmos.Common.Scoring scoring in value)
  2777. {
  2778. if (scoring.tIds.Contains(tId.ToString()))
  2779. {
  2780. break;
  2781. }
  2782. else
  2783. {
  2784. scoring.tIds.Add(tId.ToString());
  2785. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
  2786. }
  2787. }
  2788. }
  2789. List<dynamic> objs = new List<dynamic>();
  2790. List<SDK.Models.Cosmos.Common.Scoring> val = new List<SDK.Models.Cosmos.Common.Scoring>();
  2791. foreach (SDK.Models.Cosmos.Common.Scoring ss in value)
  2792. {
  2793. //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 });
  2794. List<dynamic> sc = new List<dynamic>();
  2795. int indexScore = 0;
  2796. ss.qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
  2797. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code);
  2798. foreach (Item item in ss.items)
  2799. {
  2800. List<double> scc = item.scores.Where(x => x.tmdId.Equals(tId)).Select(c => c.sc).ToList();
  2801. //item.scores.Where(x => x.tmdId.Equals(tId.GetString())).SelectMany(p => p.sc, (p, d) => new { });
  2802. if (scc.Count > 0)
  2803. {
  2804. sc.Add(new { sc = scc.FirstOrDefault(), item.ssc });
  2805. }
  2806. else
  2807. {
  2808. ss.scores = scores;
  2809. sc.Add(new { sc = ss.scores[indexScore], item.ssc });
  2810. }
  2811. indexScore++;
  2812. }
  2813. 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 };
  2814. objs.Add(obj);
  2815. }
  2816. return objs;
  2817. }
  2818. else
  2819. {
  2820. List<SDK.Models.Cosmos.Common.Scoring> notYet = new();
  2821. notYet = all.Where(x => x.tIds.Count < x.count * x.model - 1).ToList();
  2822. List<dynamic> objs = new List<dynamic>();
  2823. for (int i = 0; i < count; i++)
  2824. {
  2825. Random random = new Random();
  2826. SDK.Models.Cosmos.Common.Scoring item = new();
  2827. if (notYet.Count > 0)
  2828. {
  2829. int index = random.Next(notYet.Count);
  2830. item = notYet[index];
  2831. notYet.RemoveAt(index);
  2832. }
  2833. else
  2834. {
  2835. int index = random.Next(all.Count);
  2836. item = all[index];
  2837. all.RemoveAt(index);
  2838. }
  2839. if (!item.tIds.Contains(tId.ToString()))
  2840. {
  2841. item.tIds.Add(tId.ToString());
  2842. }
  2843. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  2844. List<dynamic> sc = new List<dynamic>();
  2845. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, item.stuId, item.examId, item.subjectId, code);
  2846. int indexScore = 0;
  2847. item.qs = item.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
  2848. foreach (Item its in item.items)
  2849. {
  2850. List<double> ssc = its.scores.Where(x => x.tmdId.Equals(tId)).Select(c => c.sc).ToList();
  2851. if (ssc.Count > 0)
  2852. {
  2853. sc.Add(new { sc = ssc.FirstOrDefault(), its.ssc });
  2854. }
  2855. else
  2856. {
  2857. item.scores = scores;
  2858. sc.Add(new { sc = item.scores[indexScore], its.ssc });
  2859. }
  2860. indexScore++;
  2861. }
  2862. 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 };
  2863. objs.Add(obj);
  2864. }
  2865. return objs;
  2866. /*if (recs.Count == count.GetInt32())
  2867. {
  2868. return Ok(new { msg = "分配人数已到上限" });
  2869. }
  2870. else
  2871. {
  2872. if (all.Count == 0)
  2873. {
  2874. return Ok(new { msg = "暂无可选学生" });
  2875. }
  2876. //随机选取一名学生打分
  2877. Random random = new Random();
  2878. SDK.Models.Cosmos.Common.Scoring item = new();
  2879. List<SDK.Models.Cosmos.Common.Scoring> notYet = new();
  2880. notYet = all.Where(x => x.tIds.Count < x.count * x.model - 1).ToList();
  2881. if (notYet.Count > 0)
  2882. {
  2883. item = notYet[random.Next(notYet.Count)];
  2884. }
  2885. else
  2886. {
  2887. item = all[random.Next(all.Count)];
  2888. }
  2889. if (!item.tIds.Contains(tId.ToString()))
  2890. {
  2891. item.tIds.Add(tId.ToString());
  2892. }
  2893. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  2894. List<dynamic> sc = new List<dynamic>();
  2895. (string ansBlob, List<double> scores) = await getMoreStuInfo(client, item.stuId, item.examId, item.subjectId, code.GetString());
  2896. int indexScore = 0;
  2897. foreach (Item its in item.items)
  2898. {
  2899. List<double> ssc = its.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).ToList();
  2900. if (ssc.Count > 0)
  2901. {
  2902. sc.Add(new { sc = ssc.FirstOrDefault(), its.ssc });
  2903. }
  2904. else
  2905. {
  2906. item.scores = scores;
  2907. sc.Add(new { sc = item.scores[indexScore], its.ssc });
  2908. }
  2909. indexScore++;
  2910. }
  2911. 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 };
  2912. return Ok(obj);
  2913. }*/
  2914. }
  2915. }
  2916. catch (Exception ex)
  2917. {
  2918. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/review\n", GroupNames.醍摩豆服務運維群組);
  2919. return new List<dynamic>() { new { code = 404, msg = "分配任务异常" } };
  2920. }
  2921. }
  2922. //批阅 提交分数
  2923. [ProducesDefaultResponseType]
  2924. [AuthToken(Roles = "teacher,admin")]
  2925. [HttpPost("sub-result")]
  2926. [Authorize(Roles = "IES")]
  2927. public async Task<IActionResult> SubResult(JsonElement request)
  2928. {
  2929. //ResponseBuilder builder = ResponseBuilder.custom();
  2930. //var (id, school) = HttpContext.GetAuthTokenInfo();
  2931. try
  2932. {
  2933. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  2934. if (!request.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
  2935. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  2936. if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  2937. if (!request.TryGetProperty("score", out JsonElement score)) return BadRequest();
  2938. if (!request.TryGetProperty("count", out JsonElement count)) return BadRequest();
  2939. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  2940. request.TryGetProperty("mark", out JsonElement mark);
  2941. var client = _azureCosmos.GetCosmosClient();
  2942. var (userid, name, _, school) = HttpContext.GetAuthTokenInfo();
  2943. //取得学校基本信息
  2944. var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school.ToString(), new PartitionKey("Base"));
  2945. string schname = string.Empty;
  2946. if (schresponse.Status == 200)
  2947. {
  2948. using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
  2949. schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
  2950. schname = jsonschname.ToString();
  2951. }
  2952. List<ExamClassResult> classResults = new();
  2953. List<SDK.Models.Cosmos.Common.Scoring> attr = new();
  2954. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  2955. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.stuId = '{sId}' and array_contains(c.tIds,'{tId}') ",
  2956. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  2957. {
  2958. attr.Add(item);
  2959. }
  2960. List<double> ssc = score.ToObject<List<double>>();
  2961. List<string> marks = mark.ToObject<List<string>>();
  2962. StringBuilder builder = new();
  2963. if (attr.Count > 0)
  2964. {
  2965. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  2966. {
  2967. int itemIndex = 0;
  2968. //int tIdIndex = scoring.tIds.IndexOf(tId.GetString());
  2969. if (request.TryGetProperty("qu", out JsonElement qu))
  2970. {
  2971. List<int> nos = qu.ToObject<List<int>>();
  2972. foreach (int number in nos)
  2973. {
  2974. List<Info> items = scoring.items[number].scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  2975. if (items.Count > 0)
  2976. {
  2977. foreach (Info info in items)
  2978. {
  2979. info.sc = ssc[number];
  2980. info.mark = marks.Count > 0 ? marks[number] : "";
  2981. }
  2982. }
  2983. else
  2984. {
  2985. Info info = new();
  2986. info.sc = ssc[number];
  2987. info.tmdId = tId.GetString();
  2988. info.mark = marks.Count > 0 ? marks[number] : "";
  2989. info.index = number;
  2990. scoring.items[number].scores.Add(info);
  2991. }
  2992. }
  2993. }
  2994. else
  2995. {
  2996. foreach (Item item in scoring.items)
  2997. {
  2998. List<Info> items = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  2999. if (items.Count > 0)
  3000. {
  3001. foreach (Info info in items)
  3002. {
  3003. info.sc = ssc[itemIndex];
  3004. info.mark = marks.Count > 0 ? marks[itemIndex] : "";
  3005. }
  3006. }
  3007. else
  3008. {
  3009. if (ssc[itemIndex] >= 0)
  3010. {
  3011. Info info = new();
  3012. info.sc = ssc[itemIndex];
  3013. info.tmdId = tId.GetString();
  3014. info.mark = marks.Count > 0 ? marks[itemIndex] : "";
  3015. info.index = itemIndex;
  3016. item.scores.Add(info);
  3017. }
  3018. }
  3019. itemIndex++;
  3020. }
  3021. }
  3022. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
  3023. }
  3024. }
  3025. else
  3026. {
  3027. return BadRequest();
  3028. }
  3029. Correct correct = null;
  3030. var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
  3031. if (cResponse.Status == 200)
  3032. {
  3033. using var cJson = await JsonDocument.ParseAsync(cResponse.ContentStream);
  3034. correct = cJson.ToObject<Correct>();
  3035. }
  3036. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  3037. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
  3038. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  3039. {
  3040. classResults.Add(item);
  3041. }
  3042. bool isFinish = false;
  3043. int scount = attr.Select(a => a.items[0].scores).ToList().Count;
  3044. foreach (SDK.Models.Cosmos.Common.Scoring sc in attr)
  3045. {
  3046. foreach (var item in sc.items)
  3047. {
  3048. if (item.scores.Count == 0)
  3049. {
  3050. isFinish = false;
  3051. break;
  3052. }
  3053. else
  3054. {
  3055. if (item.scores.Count != correct.num)
  3056. {
  3057. isFinish = false;
  3058. break;
  3059. }
  3060. else
  3061. {
  3062. isFinish = true;
  3063. }
  3064. }
  3065. }
  3066. }
  3067. if (isFinish)
  3068. {
  3069. foreach (ExamClassResult exam in classResults)
  3070. {
  3071. foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
  3072. {
  3073. int index = exam.studentIds.IndexOf(scoring.stuId);
  3074. if (index != -1)
  3075. {
  3076. int itemIndex = 0;
  3077. foreach (Item item in scoring.items)
  3078. {
  3079. var ace = item.scores.Where(x => string.IsNullOrEmpty(x.tmdId)).ToList();
  3080. if (ace.Count > 0)
  3081. {
  3082. return Ok(new { code = 1, msg = "用户信息未找到" });
  3083. }
  3084. //判定是否仲裁卷
  3085. if (!item.flag)
  3086. {
  3087. item.isArb = 0;
  3088. string bizcode = "scoring-arb";
  3089. List<string> ids = new List<string>();
  3090. foreach (CorSub sub in correct.subs)
  3091. {
  3092. ids = sub.arb;
  3093. }
  3094. //request.subs.Select(r => r.markers).ToList();
  3095. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
  3096. string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
  3097. List<IdNameCode> idNameCodes = new List<IdNameCode>();
  3098. await foreach (var idNameCode in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  3099. .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  3100. {
  3101. idNameCodes.Add(idNameCode);
  3102. }
  3103. _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_school", Constant.NotifyType_IES5_Task,
  3104. new Dictionary<string, object> { { "tmdname", name }, { "schoolName", schname }, { "schoolId", $"{school}" }, { "tmdid", userid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  3105. return Ok(new { msg = "需要仲裁", code = 2 });
  3106. }
  3107. if (item.scores.Count > 0)
  3108. {
  3109. double sc = item.scores.Select(x => x.sc).ToList().Aggregate((i, j) => (i + j) / item.scores.Count);
  3110. scoring.scores[itemIndex] = sc;
  3111. }
  3112. string tmdId = tId.GetString();
  3113. //定位老师是几阅
  3114. int indexOfSc = 0;
  3115. foreach (Info info in item.scores)
  3116. {
  3117. if (info.tmdId.Equals(tmdId))
  3118. {
  3119. break;
  3120. }
  3121. else
  3122. {
  3123. indexOfSc++;
  3124. }
  3125. }
  3126. //判定是否已经存在对应的批注信息
  3127. bool flag = exam.mark[index][itemIndex].Exists(x => x.tmdId.Equals(tmdId));
  3128. if (flag)
  3129. {
  3130. //重复打分更新部分值
  3131. exam.mark[index][itemIndex].Where(x => x.tmdId.Equals(tmdId)).ToList().ForEach(score =>
  3132. {
  3133. score.sc = item.scores[indexOfSc].sc;
  3134. score.mark = item.scores[indexOfSc].mark;
  3135. });
  3136. }
  3137. else
  3138. {
  3139. Details dt = new()
  3140. {
  3141. index = item.scores[indexOfSc].index,
  3142. sc = item.scores[indexOfSc].sc,
  3143. tmdId = item.scores[indexOfSc].tmdId,
  3144. mark = item.scores[indexOfSc].mark,
  3145. identity = item.scores[indexOfSc].identity
  3146. };
  3147. exam.mark[index][itemIndex].Add(dt);
  3148. }
  3149. itemIndex++;
  3150. }
  3151. exam.studentScores[index] = scoring.scores;
  3152. exam.sum[index] = exam.studentScores[index].Sum();
  3153. }
  3154. }
  3155. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  3156. }
  3157. }
  3158. return Ok(new { code = 200 });
  3159. }
  3160. catch (Exception ex)
  3161. {
  3162. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/sub-result\n", GroupNames.醍摩豆服務運維群組);
  3163. return Ok(new { status = 500 });
  3164. }
  3165. }
  3166. //查询阅卷类型数据
  3167. [ProducesDefaultResponseType]
  3168. [Authorize(Roles = "IES")]
  3169. [AuthToken(Roles = "teacher,admin")]
  3170. [HttpPost("find-scoring")]
  3171. public async Task<IActionResult> findScoring(JsonElement request)
  3172. {
  3173. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3174. if (!request.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
  3175. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  3176. if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  3177. if (!request.TryGetProperty("type", out JsonElement type)) return BadRequest();
  3178. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3179. var client = _azureCosmos.GetCosmosClient();
  3180. List<SDK.Models.Cosmos.Common.Scoring> attr = new();
  3181. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  3182. 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}') ",
  3183. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  3184. {
  3185. attr.Add(item);
  3186. }
  3187. return Ok(attr);
  3188. }
  3189. //申报异常卷内容
  3190. [ProducesDefaultResponseType]
  3191. [AuthToken(Roles = "teacher,admin")]
  3192. [HttpPost("save-err")]
  3193. [Authorize(Roles = "IES")]
  3194. public async Task<IActionResult> saveErr(JsonElement request)
  3195. {
  3196. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3197. if (!request.TryGetProperty("err", out JsonElement err)) return BadRequest();
  3198. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3199. if (!request.TryGetProperty("index", out JsonElement index)) return BadRequest();
  3200. if (!request.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
  3201. var client = _azureCosmos.GetCosmosClient();
  3202. var (userid, name, _, school) = HttpContext.GetAuthTokenInfo();
  3203. //取得学校基本信息
  3204. var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school.ToString(), new PartitionKey("Base"));
  3205. string schname = string.Empty;
  3206. if (schresponse.Status == 200)
  3207. {
  3208. using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
  3209. schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
  3210. schname = jsonschname.ToString();
  3211. }
  3212. SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
  3213. if (null != scoring)
  3214. {
  3215. Correct correct = null;
  3216. var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(scoring.examId, new PartitionKey($"Correct-{code}"));
  3217. if (cResponse.Status == 200)
  3218. {
  3219. using var cJson = await JsonDocument.ParseAsync(cResponse.ContentStream);
  3220. correct = cJson.ToObject<Correct>();
  3221. }
  3222. if (string.IsNullOrEmpty(scoring.qs[index.GetInt32()].tId))
  3223. {
  3224. scoring.qs[index.GetInt32()].err = err.GetString();
  3225. scoring.qs[index.GetInt32()].tId = tId.GetString();
  3226. scoring.qs[index.GetInt32()].index = index.GetInt32();
  3227. }
  3228. else
  3229. {
  3230. return Ok(new { msg = "改题已经被申报", code = 404 });
  3231. }
  3232. string bizcode = "scoring-err";
  3233. List<string> ids = new List<string>();
  3234. foreach (CorSub sub in correct.subs)
  3235. {
  3236. ids = sub.err;
  3237. }
  3238. //request.subs.Select(r => r.markers).ToList();
  3239. string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
  3240. List<IdNameCode> idNameCodes = new List<IdNameCode>();
  3241. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  3242. .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  3243. {
  3244. idNameCodes.Add(item);
  3245. }
  3246. _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_school", Constant.NotifyType_IES5_Task,
  3247. new Dictionary<string, object> { { "tmdname", name }, { "schoolName", schname }, { "schoolId", $"{school}" }, { "tmdid", userid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  3248. /* scoring.type = 2;
  3249. scoring.err = err.GetString();*/
  3250. }
  3251. else
  3252. {
  3253. return Ok(new { code = 404 });
  3254. }
  3255. var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
  3256. return Ok(new { sc });
  3257. }
  3258. //处理异常卷内容
  3259. [ProducesDefaultResponseType]
  3260. [Authorize(Roles = "IES")]
  3261. [AuthToken(Roles = "teacher,admin")]
  3262. [HttpPost("fd-err")]
  3263. public async Task<IActionResult> fdErr(JsonElement request)
  3264. {
  3265. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3266. if (!request.TryGetProperty("improve", out JsonElement improve)) return BadRequest();
  3267. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3268. if (!request.TryGetProperty("index", out JsonElement index)) return BadRequest();
  3269. //if (!request.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
  3270. var client = _azureCosmos.GetCosmosClient();
  3271. SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
  3272. if (null != scoring)
  3273. {
  3274. if (string.IsNullOrEmpty(scoring.qs[index.GetInt32()].improve))
  3275. {
  3276. scoring.qs[index.GetInt32()].improve = improve.GetString();
  3277. //scoring.qs[index.GetInt32()].tId = tId.GetString();
  3278. //scoring.qs[index.GetInt32()].index = index.GetInt32();
  3279. }
  3280. else
  3281. {
  3282. return Ok(new { msg = "改题已经被处理", code = 404 });
  3283. }
  3284. /* scoring.type = 2;
  3285. scoring.err = err.GetString();*/
  3286. }
  3287. else
  3288. {
  3289. return Ok(new { code = 404 });
  3290. }
  3291. var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
  3292. return Ok(new { sc });
  3293. }
  3294. //处理仲裁卷内容
  3295. [ProducesDefaultResponseType]
  3296. [AuthToken(Roles = "teacher,admin")]
  3297. [HttpPost("save-arb")]
  3298. [Authorize(Roles = "IES")]
  3299. public async Task<IActionResult> saveArb(JsonElement request)
  3300. {
  3301. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3302. if (!request.TryGetProperty("score", out JsonElement score)) return BadRequest();
  3303. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3304. if (!request.TryGetProperty("index", out JsonElement indexScore)) return BadRequest();
  3305. var client = _azureCosmos.GetCosmosClient();
  3306. //List<double> scs = score.ToObject<List<double>>();
  3307. List<ExamClassResult> classResults = new();
  3308. int sin = indexScore.GetInt32();
  3309. SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
  3310. if (null != scoring)
  3311. {
  3312. scoring.scores[sin] = score.GetDouble();
  3313. scoring.items[sin].isArb = 1;
  3314. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(
  3315. queryText: $"select value(c) from c where c.examId = '{scoring.examId}' and c.subjectId = '{scoring.subjectId}'",
  3316. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  3317. {
  3318. classResults.Add(item);
  3319. }
  3320. foreach (ExamClassResult exam in classResults)
  3321. {
  3322. int index = exam.studentIds.IndexOf(scoring.stuId);
  3323. if (index != -1)
  3324. {
  3325. exam.studentScores[index][sin] = score.GetDouble();
  3326. //exam.mark[index] = scoring.marks;
  3327. }
  3328. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
  3329. }
  3330. }
  3331. else
  3332. {
  3333. return Ok(new { code = 404 });
  3334. }
  3335. var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
  3336. return Ok(new { sc });
  3337. }
  3338. [ProducesDefaultResponseType]
  3339. [AuthToken(Roles = "teacher,admin,student")]
  3340. [HttpPost("score")]
  3341. [Authorize(Roles = "IES")]
  3342. public async Task<IActionResult> score(JsonElement request)
  3343. {
  3344. if (!request.TryGetProperty("courseId", out JsonElement courseId)) return BadRequest();
  3345. if (!request.TryGetProperty("cId", out JsonElement cId)) return BadRequest();
  3346. //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3347. var client = _azureCosmos.GetCosmosClient();
  3348. List<(string eId, string cId, string cname, List<string> sIds, List<double> sum)> classResults = new();
  3349. List<string> eIds = new();
  3350. List<string> cIds = cId.ToObject<List<string>>();
  3351. string soc = courseId.GetString();
  3352. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
  3353. 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}'"))})"))
  3354. {
  3355. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  3356. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3357. {
  3358. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  3359. while (accounts.MoveNext())
  3360. {
  3361. JsonElement account = accounts.Current;
  3362. List<string> sIds = account.GetProperty("studentIds").ToObject<List<string>>();
  3363. List<double> sum = account.GetProperty("sum").ToObject<List<double>>();
  3364. eIds.Add(account.GetProperty("eId").GetString());
  3365. List<double> nsum = new();
  3366. foreach (double s in sum)
  3367. {
  3368. double ns = 0;
  3369. if (s < 0)
  3370. {
  3371. ns = 0;
  3372. }
  3373. else
  3374. {
  3375. ns = s;
  3376. }
  3377. nsum.Add(ns);
  3378. }
  3379. classResults.Add((account.GetProperty("eId").GetString(), account.GetProperty("cId").GetString(), account.GetProperty("cName").GetString(), sIds, nsum));
  3380. }
  3381. }
  3382. }
  3383. string sub = string.Empty;
  3384. if (request.TryGetProperty("subjectId", out JsonElement subjectId))
  3385. {
  3386. sub = subjectId.GetString();
  3387. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
  3388. 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}'"))})"))
  3389. {
  3390. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  3391. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3392. {
  3393. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  3394. while (accounts.MoveNext())
  3395. {
  3396. JsonElement account = accounts.Current;
  3397. List<string> sIds = account.GetProperty("studentIds").ToObject<List<string>>();
  3398. List<double> sum = account.GetProperty("sum").ToObject<List<double>>();
  3399. List<double> nsum = new();
  3400. foreach (double s in sum)
  3401. {
  3402. double ns = 0;
  3403. if (s < 0)
  3404. {
  3405. ns = 0;
  3406. }
  3407. else
  3408. {
  3409. ns = s;
  3410. }
  3411. nsum.Add(ns);
  3412. }
  3413. eIds.Add(account.GetProperty("eId").GetString());
  3414. classResults.Add((account.GetProperty("eId").GetString(), account.GetProperty("cId").GetString(), account.GetProperty("cName").GetString(), sIds, nsum));
  3415. }
  3416. }
  3417. }
  3418. }
  3419. 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();
  3420. if (eIds.Count == 0)
  3421. {
  3422. return Ok(new { code = 404 });
  3423. }
  3424. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
  3425. 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}'"))})"))
  3426. {
  3427. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  3428. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3429. {
  3430. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  3431. while (accounts.MoveNext())
  3432. {
  3433. JsonElement account = accounts.Current;
  3434. SDK.Models.Custom eType = new();
  3435. List<ExamSubject> subs = new();
  3436. List<PaperSimple> ps = new();
  3437. if (account.TryGetProperty("examType", out JsonElement examType))
  3438. {
  3439. eType = examType.ToObject<SDK.Models.Custom>();
  3440. }
  3441. if (account.TryGetProperty("papers", out JsonElement papers))
  3442. {
  3443. ps = papers.ToObject<List<PaperSimple>>();
  3444. }
  3445. if (account.TryGetProperty("subjects", out JsonElement subject))
  3446. {
  3447. subs = subject.ToObject<List<ExamSubject>>();
  3448. }
  3449. exam.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), eType, account.GetProperty("scope").GetString(),
  3450. account.GetProperty("owner").GetString(), account.GetProperty("createTime").GetInt64(), ps, subs, account.GetProperty("source").GetString()));
  3451. }
  3452. }
  3453. }
  3454. var scores = classResults.Select(x => new
  3455. {
  3456. examId = x.eId,
  3457. examName = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().name,
  3458. scope = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().scope,
  3459. eType = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().eType,
  3460. classId = x.cId,
  3461. cname = x.cname,
  3462. studentIds = x.sIds,
  3463. source = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().source,
  3464. owner = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().owner,
  3465. createTime = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().ctime,
  3466. subject = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().subject,
  3467. papers = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().points,
  3468. sum = x.sum
  3469. });
  3470. if (request.TryGetProperty("stuId", out JsonElement stuId))
  3471. {
  3472. var info = scores.Where(x => !string.IsNullOrEmpty(x.examName) && x.studentIds.Contains(stuId.GetString())).Select(x => new
  3473. {
  3474. x.examId,
  3475. x.examName,
  3476. x.cname,
  3477. studentId = stuId.GetString(),
  3478. x.owner,
  3479. x.createTime,
  3480. x.eType,
  3481. x.source,
  3482. point = x.papers.Select(p => p.point),
  3483. x.subject,
  3484. sum = x.sum.ToList()[x.studentIds.IndexOf(stuId.GetString())]
  3485. });
  3486. return Ok(new { info });
  3487. }
  3488. else
  3489. {
  3490. var info = scores.Where(x => !string.IsNullOrEmpty(x.examName)).Select(x => new
  3491. {
  3492. x.examId,
  3493. x.examName,
  3494. x.cname,
  3495. x.studentIds,
  3496. x.owner,
  3497. x.createTime,
  3498. x.eType,
  3499. x.source,
  3500. point = x.papers.Select(p => p.point),
  3501. x.subject,
  3502. x.sum
  3503. });
  3504. return Ok(new { info });
  3505. };
  3506. }
  3507. [ProducesDefaultResponseType]
  3508. [Authorize(Roles = "IES")]
  3509. [AuthToken(Roles = "teacher,admin,student")]
  3510. [HttpPost("get-error-item")]
  3511. public async Task<IActionResult> getErrorItems(JsonElement request)
  3512. {
  3513. //stuId
  3514. if (!request.TryGetProperty("stuId", out JsonElement stuId)) return BadRequest();
  3515. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  3516. StringBuilder stringBuilder = new($"select value(c) from c where c.stuId = '{stuId}' and c.subjectId = '{subjectId}'");
  3517. /*if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
  3518. {
  3519. stringBuilder.Append($" and c.period.id = '{period}' ");
  3520. }
  3521. if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
  3522. {
  3523. stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
  3524. }
  3525. if (request.TryGetProperty("progress", out JsonElement progress) && !string.IsNullOrWhiteSpace($"{progress}"))
  3526. {
  3527. stringBuilder.Append($" and c.progress = '{progress}' ");
  3528. }
  3529. if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
  3530. {
  3531. stringBuilder.Append($" and c.source = '{source}' ");
  3532. }*/
  3533. string pk = "ErrorItems";
  3534. if (request.TryGetProperty("code", out JsonElement code) && !string.IsNullOrWhiteSpace($"{code}"))
  3535. {
  3536. stringBuilder.Append($" and c.school = '{code}' ");
  3537. pk = $"ErrorItems-{code}";
  3538. };
  3539. stringBuilder.Append("order by c._ts desc");
  3540. //string token = null;
  3541. string token = default;
  3542. //默认不指定返回大小
  3543. int? topcout = null;
  3544. if (request.TryGetProperty("count", out JsonElement jcount))
  3545. {
  3546. if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
  3547. {
  3548. topcout = data;
  3549. }
  3550. }
  3551. //是否需要进行分页查询,默认不分页
  3552. bool iscontinuation = false;
  3553. if (topcout != null && topcout.Value > 0)
  3554. {
  3555. iscontinuation = true;
  3556. }
  3557. //如果指定了返回大小
  3558. if (request.TryGetProperty("token", out JsonElement token_1))
  3559. {
  3560. if (!token_1.ValueKind.Equals(JsonValueKind.Null) && token_1.ValueKind.Equals(JsonValueKind.String))
  3561. {
  3562. token = token_1.GetString();
  3563. }
  3564. }
  3565. try
  3566. {
  3567. var client = _azureCosmos.GetCosmosClient();
  3568. //var queryTeacher = $"select value(c) from c where c.stuId = '{stuId}' and c.school = '{code}' and c.subjectId = '{subjectId}'";
  3569. List<ErrorItems> errorItems = new();
  3570. List<string> ids = new();
  3571. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: $"select A0.id from c join A0 in c.its where c.stuId = '{stuId}' and c.subjectId = '{subjectId}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{pk}") }))
  3572. {
  3573. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  3574. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3575. {
  3576. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  3577. {
  3578. ids.Add(obj.GetProperty("id").ToString());
  3579. }
  3580. }
  3581. }
  3582. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"{pk}") }))
  3583. {
  3584. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  3585. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3586. {
  3587. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  3588. {
  3589. errorItems.Add(obj.ToObject<ErrorItems>());
  3590. }
  3591. }
  3592. if (iscontinuation)
  3593. {
  3594. token = item.GetContinuationToken();
  3595. break;
  3596. }
  3597. }
  3598. errorItems = errorItems.Where((x, i) => errorItems.FindIndex(z => z.id == x.id) == i).ToList();
  3599. return Ok(new { errorItems, token,ids.Count });
  3600. }
  3601. catch (Exception ex)
  3602. {
  3603. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/get-error-item()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  3604. return BadRequest(new { code = 500 });
  3605. }
  3606. }
  3607. //取得錯題庫前日錯題數及現在錯題數
  3608. [ProducesDefaultResponseType]
  3609. [Authorize(Roles = "IES")]
  3610. [AuthToken(Roles = "teacher,admin,student")]
  3611. [HttpPost("get-error-item-cnt")]
  3612. public async Task<IActionResult> getErrorItemsCount(JsonElement request)
  3613. {
  3614. //輸入值
  3615. if (!request.TryGetProperty("stuId", out JsonElement stuId)) return BadRequest();
  3616. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  3617. string code = (request.TryGetProperty("code", out JsonElement codeJobj)) ? codeJobj.GetString() : string.Empty;
  3618. string schCode = (!string.IsNullOrWhiteSpace(code)) ? code : "noschoolid";
  3619. string teacherid = (request.TryGetProperty("teacherId", out JsonElement teacherId)) ? teacherId.GetString() : string.Empty;
  3620. //取得Redis該學生該科目的錯題數 [算法變更,昨日錯題總數不再計入redis]
  3621. int record = 0; //昨日取得的錯題數
  3622. //var redisClient = _azureRedis.GetRedisClient(8);
  3623. //string hkey = $"ErrorItems:{schCode}";
  3624. //string hval = await redisClient.HashGetAsync(hkey, $"{stuId}");
  3625. //List<stuErrorItemCnt> stuErrCntList = (hval != null) ? JsonSerializer.Deserialize<List<stuErrorItemCnt>>(hval) : new List<stuErrorItemCnt>();
  3626. //stuErrorItemCnt stuErrCnt = stuErrCntList.Where(s => s.subjectId.Equals($"{subjectId}")).FirstOrDefault();
  3627. //if (stuErrCnt != null)
  3628. //{
  3629. // record = stuErrCnt.number;
  3630. //}
  3631. //取得CosmosDB該學生該科目現在錯題數
  3632. HashSet<string> avaliableQidList = new HashSet<string>(); //最終去重後可取得的錯題ID
  3633. List<string> itemIdList = new List<string>();
  3634. var client = _azureCosmos.GetCosmosClient();
  3635. string qryAdd = (!string.IsNullOrWhiteSpace(code)) ? $" AND c.school = '{code}' " : string.Empty;
  3636. //string qry = $"SELECT SUM(ARRAY_LENGTH(c.its)) AS number, c.stuId, c.school, c.subjectId FROM c WHERE CONTAINS(c.code, 'ErrorItems') AND c.stuId = '{stuId}' AND c.subjectId = '{subjectId}'{qryAdd} GROUP BY c.stuId, c.school, c.subjectId";
  3637. string pk = "ErrorItems";
  3638. //string qry = "SELECT ARRAY(SELECT VALUE t.id FROM t IN c.its ) AS itemIds, c.stuId, c.school AS schoolId, c.subjectId, c.code FROM c WHERE " +
  3639. // $"c.stuId = '{stuId}' AND c.subjectId = '{subjectId}'{qryAdd} ";
  3640. string qry = $"SELECT i.blob, i.id, i.pId, c.stuId, c.school AS schoolId, c.subjectId, c.code FROM c JOIN i IN c.its WHERE " +
  3641. $" c.stuId = '{stuId}' AND c.subjectId = '{subjectId}' {qryAdd} ";
  3642. if (!string.IsNullOrWhiteSpace(code))
  3643. {
  3644. //qry += $"AND c.school = '{code}' ";
  3645. pk = $"ErrorItems-{code}";
  3646. };
  3647. Dictionary<string, List<string>> dict = new();
  3648. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: qry, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{pk}") }))
  3649. {
  3650. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  3651. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3652. {
  3653. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  3654. {
  3655. if(dict.ContainsKey(obj.GetProperty("id").ToString()))
  3656. {
  3657. if (!dict[obj.GetProperty("id").ToString()].Contains(obj.GetProperty("blob").ToString()))
  3658. {
  3659. dict[obj.GetProperty("id").ToString()].Add(obj.GetProperty("blob").ToString());
  3660. }
  3661. }
  3662. else
  3663. {
  3664. dict.Add(obj.GetProperty("id").ToString(), new List<string> { obj.GetProperty("blob").ToString() });
  3665. }
  3666. }
  3667. }
  3668. }
  3669. foreach (var obj in dict)
  3670. {
  3671. if (schCode != null && schCode != "noschoolid")
  3672. {
  3673. string qid = obj.Key;
  3674. List<string> blobs = obj.Value;
  3675. foreach(string blob in blobs)
  3676. {
  3677. if (_azureStorage.GetBlobContainerClient(schCode).GetBlobClient($"{blob}/{qid}.json").Exists())
  3678. {// 去除blob不存在項目
  3679. avaliableQidList.Add(qid);
  3680. }
  3681. }
  3682. }
  3683. else if (!string.IsNullOrWhiteSpace(teacherid))
  3684. {
  3685. string qid = obj.Key;
  3686. List<string> blobs = obj.Value;
  3687. foreach (string blob in blobs)
  3688. {
  3689. if (_azureStorage.GetBlobContainerClient(teacherid).GetBlobClient($"{blob}/{qid}.json").Exists())
  3690. {
  3691. avaliableQidList.Add(qid);
  3692. }
  3693. }
  3694. }
  3695. }
  3696. return Ok(new { record, avaliable = avaliableQidList.Count });
  3697. }
  3698. //取得錯題庫新增數
  3699. [ProducesDefaultResponseType]
  3700. [Authorize(Roles = "IES")]
  3701. [AuthToken(Roles = "teacher,admin,student")]
  3702. [HttpPost("get-error-item-today-cnt")]
  3703. public async Task<IActionResult> getErrorItemsTodayCount(JsonElement request)
  3704. {
  3705. //輸入值
  3706. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest(); //科目ID
  3707. if (!request.TryGetProperty("stuId", out JsonElement _stuId)) return BadRequest(); //學生ID 或 TMID
  3708. string stuId = _stuId.GetString();
  3709. string schoolid = (request.TryGetProperty("code", out JsonElement codeJobj)) ? codeJobj.GetString() : string.Empty; //學校簡碼,TMID時為空
  3710. string tmdid = string.Empty;
  3711. if (string.IsNullOrWhiteSpace(schoolid)) tmdid = stuId;
  3712. string maLearnCode = string.Empty;
  3713. //檢查參數 必須有 teammodelId 或是同時有學校id及學號
  3714. if (!string.IsNullOrWhiteSpace(tmdid + ""))
  3715. {
  3716. maLearnCode = $"MaLearn-{tmdid}";
  3717. }
  3718. else if (!string.IsNullOrWhiteSpace(schoolid + "") && !string.IsNullOrWhiteSpace(stuId + ""))
  3719. {
  3720. maLearnCode = $"MaLearn-{schoolid}-{stuId}";
  3721. }
  3722. else { return BadRequest(); }
  3723. DateTime nowDate = DateTime.Now;
  3724. DateTime beforeDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
  3725. string qry_All = $"SELECT COUNT(1) as num FROM c WHERE c.type = 'answer' AND c.unitId = '{subjectId}' AND IS_DEFINED(c.createdTime) AND c.createdTime <= {DateTimeHelper.ToUnixTimestamp(nowDate)}";
  3726. string qry_before = $"SELECT COUNT(1) as num FROM c WHERE c.type = 'answer' AND c.unitId = '{subjectId}' AND IS_DEFINED(c.createdTime) AND c.createdTime <= {DateTimeHelper.ToUnixTimestamp(beforeDate)} ";
  3727. var client = _azureCosmos.GetCosmosClient();
  3728. int avaliable = 0;
  3729. int allNum = 0;
  3730. int berforeNum = 0;
  3731. // 取全部錯題數量
  3732. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: qry_All, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{maLearnCode}") }))
  3733. {
  3734. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  3735. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3736. {
  3737. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  3738. {
  3739. if (obj.TryGetProperty("num", out JsonElement num))
  3740. {
  3741. allNum = num.GetInt32();
  3742. }
  3743. }
  3744. }
  3745. }
  3746. // 取今天之前錯題的數量
  3747. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIterator(queryText: qry_before, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{maLearnCode}") }))
  3748. {
  3749. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  3750. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3751. {
  3752. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  3753. {
  3754. if (obj.TryGetProperty("num", out JsonElement num))
  3755. {
  3756. berforeNum = num.GetInt32();
  3757. }
  3758. }
  3759. }
  3760. }
  3761. avaliable = allNum - berforeNum;
  3762. return Ok(new { avaliable });
  3763. }
  3764. //阅卷信息统计
  3765. [ProducesDefaultResponseType]
  3766. [Authorize(Roles = "IES")]
  3767. [AuthToken(Roles = "teacher,admin")]
  3768. [HttpPost("analysis-scoring")]
  3769. public async Task<IActionResult> Analysis(JsonElement request)
  3770. {
  3771. try
  3772. {
  3773. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  3774. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  3775. //if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  3776. //if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  3777. var client = _azureCosmos.GetCosmosClient();
  3778. var queryTeacher = $"select c.id,c.name from c ";
  3779. //List<object> props = new List<object>();
  3780. List<(string id, string name)> tInfos = new();
  3781. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryTeacher, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  3782. {
  3783. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  3784. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3785. {
  3786. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  3787. {
  3788. tInfos.Add((obj.GetProperty("id").GetString(), obj.GetProperty("name").GetString()));
  3789. }
  3790. }
  3791. }
  3792. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
  3793. if (response.Status == 200)
  3794. {
  3795. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  3796. ExamInfo info = json.ToObject<ExamInfo>();
  3797. List<ExamClassResult> classResults = new();
  3798. List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
  3799. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<SDK.Models.Cosmos.Common.Scoring>(
  3800. queryText: $"select value(c) from c where c.examId = '{id}' ",
  3801. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
  3802. {
  3803. attr.Add(item);
  3804. }
  3805. List<SDK.Models.Cosmos.Common.Scoring> errs = new();
  3806. List<(string subjectId, int count)> ps = new List<(string subjectId, int count)>();
  3807. List<(string subjectId, int count)> tps = new List<(string subjectId, int count)>();
  3808. List<(string subjectId, int count)> arbs = new List<(string subjectId, int count)>();
  3809. List<(string subjectId, int count)> tarbs = new List<(string subjectId, int count)>();
  3810. List<(string subjectId, int count)> cs = new List<(string subjectId, int count)>();
  3811. foreach (ExamSubject subject in info.subjects)
  3812. {
  3813. int qsCount = 0;
  3814. int tqsCount = 0;
  3815. int arbCount = 0;
  3816. int tarbCount = 0;
  3817. int csCount = 0;
  3818. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  3819. {
  3820. if (subject.id.Equals(ss.subjectId))
  3821. {
  3822. List<Qs> qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.err)).ToList();
  3823. if (qs.Count > 0)
  3824. {
  3825. qsCount++;
  3826. }
  3827. List<Qs> tqs = ss.qs.Where(s => !string.IsNullOrEmpty(s.improve)).ToList();
  3828. if (tqs.Count > 0)
  3829. {
  3830. tqsCount++;
  3831. }
  3832. List<Item> arb = ss.items.Where(s => s.flag == false).ToList();
  3833. if (arb.Count > 0)
  3834. {
  3835. arbCount++;
  3836. }
  3837. List<Item> tarb = ss.items.Where(s => s.isArb == 1 && s.flag == false).ToList();
  3838. if (tarb.Count > 0)
  3839. {
  3840. tarbCount++;
  3841. }
  3842. bool flag = ss.scores.Exists(s => s == -1);
  3843. if (!flag) csCount++;
  3844. }
  3845. }
  3846. ps.Add((subject.id, qsCount));
  3847. tps.Add((subject.id, tqsCount));
  3848. arbs.Add((subject.id, arbCount));
  3849. tarbs.Add((subject.id, tarbCount));
  3850. cs.Add((subject.id, csCount));
  3851. }
  3852. //阅卷老师
  3853. List<object> teachers = new();
  3854. Correct correct = null;
  3855. List<(string sub, List<string> ids)> errIds = new();
  3856. List<(string sub, List<string> ids)> arbIds = new();
  3857. var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
  3858. if (cResponse.Status == 200)
  3859. {
  3860. using var cJson = await JsonDocument.ParseAsync(cResponse.ContentStream);
  3861. correct = cJson.ToObject<Correct>();
  3862. foreach (CorSub corSub in correct.subs)
  3863. {
  3864. List<string> eName = new();
  3865. List<string> aName = new();
  3866. foreach (string s in corSub.err)
  3867. {
  3868. eName.Add(tInfos.Where(t => t.id.Equals(s)).Select(s => s.name).First());
  3869. }
  3870. foreach (string s in corSub.arb)
  3871. {
  3872. aName.Add(tInfos.Where(t => t.id.Equals(s)).Select(s => s.name).First());
  3873. }
  3874. errIds.Add((corSub.id, eName));
  3875. arbIds.Add((corSub.id, aName));
  3876. foreach (CorTmd corTmd in corSub.markers)
  3877. {
  3878. int qus = 0;
  3879. int quf = 0;
  3880. int tArbs = 0;
  3881. int fArbs = 0;
  3882. int sCount = 0;
  3883. int fCount = 0;
  3884. foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
  3885. {
  3886. if (ss.subjectId.Equals(corSub.id))
  3887. {
  3888. foreach (Qs qs in ss.qs)
  3889. {
  3890. if (!string.IsNullOrEmpty(qs.err) && qs.tId.Equals(corTmd.id))
  3891. {
  3892. qus++;
  3893. }
  3894. if (!string.IsNullOrEmpty(qs.improve) && qs.tId.Equals(corTmd.id))
  3895. {
  3896. quf++;
  3897. }
  3898. }
  3899. List<double> sigles = new();
  3900. foreach (Item item in ss.items)
  3901. {
  3902. if (item.scores.Exists(sc => sc.tmdId.Equals(corTmd.id)) && item.isArb == 1)
  3903. {
  3904. tArbs++;
  3905. }
  3906. if (item.flag == true && item.isArb == 1)
  3907. {
  3908. fArbs++;
  3909. }
  3910. var tsc = item.scores.Where(t => t.tmdId.Equals(corTmd.id)).Select(s => s.sc).ToList();
  3911. sigles.AddRange(tsc);
  3912. }
  3913. bool flag = sigles.Exists(s => s == -1);
  3914. if (!flag && sigles.Count == ss.items.Count)
  3915. {
  3916. fCount++;
  3917. }
  3918. sCount = corTmd.count;
  3919. }
  3920. }
  3921. var obj = new
  3922. {
  3923. sId = corSub.id,
  3924. sName = corSub.name,
  3925. name = corTmd.name,
  3926. qus,
  3927. quf,
  3928. tArbs,
  3929. fArbs,
  3930. fCount,
  3931. sCount,
  3932. };
  3933. teachers.Add(obj);
  3934. }
  3935. }
  3936. }
  3937. var sc = info.subjects.Select(s => new
  3938. {
  3939. s.name,
  3940. count = info.stuCount,
  3941. num = info.stuCount * correct.num,
  3942. tqs = tps.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
  3943. qs = ps.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
  3944. errName = errIds.Where(q => q.sub.Equals(s.id)).Select(c => c.ids).FirstOrDefault(),
  3945. tarbs = tarbs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
  3946. arbs = arbs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
  3947. arbName = arbIds.Where(q => q.sub.Equals(s.id)).Select(c => c.ids).FirstOrDefault(),
  3948. cs = cs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First()
  3949. }); ;
  3950. return Ok(new { sc, teachers });
  3951. }
  3952. else
  3953. {
  3954. return Ok(new { status = response.Status });
  3955. }
  3956. }
  3957. catch (Exception ex)
  3958. {
  3959. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/analysis-scoring\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  3960. return Ok(new { status = 500 });
  3961. }
  3962. }
  3963. /*private async Task deleteAsync(CosmosClient client, string id, string tId)
  3964. {
  3965. List<string> correctIds = new List<string>();
  3966. 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}") }))
  3967. {
  3968. using var jsonTask = await JsonDocument.ParseAsync(item.ContentStream);
  3969. if (jsonTask.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3970. {
  3971. var accounts = jsonTask.RootElement.GetProperty("Documents").EnumerateArray();
  3972. while (accounts.MoveNext())
  3973. {
  3974. JsonElement account = accounts.Current;
  3975. correctIds.Add(account.GetProperty("id").GetString());
  3976. }
  3977. }
  3978. }
  3979. if (correctIds.Count > 0)
  3980. {
  3981. await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsStreamAsync(correctIds, $"CorrectTask-{tId}");
  3982. }
  3983. }*/
  3984. private async Task<(string blob, List<double>)> getMoreStuInfo(CosmosClient client, string stuId, string examId, string subjectId, string code)
  3985. {
  3986. 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}'";
  3987. List<List<string>> ans = new List<List<string>>();
  3988. List<string> ids = new List<string>();
  3989. List<List<double>> scs = new List<List<double>>();
  3990. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
  3991. {
  3992. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  3993. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  3994. {
  3995. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  3996. while (accounts.MoveNext())
  3997. {
  3998. JsonElement account = accounts.Current;
  3999. ans = account.GetProperty("studentAnswers").ToObject<List<List<string>>>();
  4000. ids = account.GetProperty("studentIds").ToObject<List<string>>();
  4001. scs = account.GetProperty("studentScores").ToObject<List<List<double>>>();
  4002. }
  4003. }
  4004. }
  4005. int num = ids.IndexOf(stuId);
  4006. string ansBlob = "";
  4007. List<double> scores = new List<double>();
  4008. if (num >= 0)
  4009. {
  4010. if (ans[num].Count > 0)
  4011. {
  4012. ansBlob = ans[num].First();
  4013. }
  4014. scores = scs[num];
  4015. }
  4016. return (ansBlob, scores);
  4017. }
  4018. private Task<List<double>> getWrongNum(ExamResult result, List<double> points, List<string> infoIds)
  4019. {
  4020. int num = 0;
  4021. List<double> wn = new List<double>();
  4022. foreach (var point in points)
  4023. {
  4024. int wnum = 0;
  4025. double p = point * 0.8;
  4026. foreach (ClassRange range in result.classes)
  4027. {
  4028. if (!infoIds.Contains(range.id)) continue;
  4029. for (int i = range.range[0]; i <= range.range[1]; i++)
  4030. {
  4031. //判断推送的数据中,学生正常得分数据
  4032. if (result.studentScores[i].Count > 0)
  4033. {
  4034. if (result.studentScores[i][num] < point)
  4035. {
  4036. if (result.studentScores[i][num] < p)
  4037. {
  4038. wnum++;
  4039. }
  4040. else
  4041. {
  4042. continue;
  4043. }
  4044. }
  4045. else
  4046. {
  4047. continue;
  4048. }
  4049. }
  4050. else
  4051. {
  4052. wnum++;
  4053. }
  4054. }
  4055. }
  4056. wn.Add(wnum);
  4057. num++;
  4058. }
  4059. return Task.FromResult(wn);
  4060. }
  4061. //获取题目信息
  4062. [ProducesDefaultResponseType]
  4063. //[AuthToken(Roles = "teacher,admin,student")]
  4064. [HttpPost("get-item")]
  4065. //[Authorize(Roles = "IES")]
  4066. public async Task<IActionResult> getItemInfo(JsonElement request)
  4067. {
  4068. if (!request.TryGetProperty("errorItems", out JsonElement items)) return BadRequest();
  4069. List<errorItemInfo> errors = items.ToObject<List<errorItemInfo>>();
  4070. var client = _azureCosmos.GetCosmosClient();
  4071. List<string> ids = errors.Select(c => c.activityId).Distinct().ToList();
  4072. var queryClass = $"select value(c) from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))}) and c.pk = 'Exam'";
  4073. List<ExamInfo> exams = new();
  4074. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamInfo>(queryText: queryClass))
  4075. {
  4076. exams.Add(item);
  4077. }
  4078. List<(JsonElement items, List<string> attachments,int qamode)> elements = new();
  4079. if (exams.Count > 0)
  4080. {
  4081. foreach (errorItemInfo itemInfo in errors) {
  4082. ExamInfo info = exams.Where(c => c.id.Equals(itemInfo.activityId)).FirstOrDefault();
  4083. if(info==null) continue; //[Jeff]無法取得評量紀錄報錯bug修正
  4084. List<ExamSubject> subjects = info.subjects;
  4085. int index = 0;
  4086. foreach (ExamSubject subject in subjects)
  4087. {
  4088. if (subject.id.Equals(itemInfo.unitId))
  4089. {
  4090. continue;
  4091. }
  4092. else
  4093. {
  4094. index++;
  4095. }
  4096. }
  4097. List<PaperSimple> simples = info.papers;
  4098. string blob = simples[index].blob;
  4099. try {
  4100. List<string> attachments = new();
  4101. if (info.qamode == 1)
  4102. {
  4103. BlobDownloadResult index_json;
  4104. if (info.scope.Equals("school"))
  4105. {
  4106. index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{blob}/index.json").DownloadContentAsync();
  4107. }
  4108. else
  4109. {
  4110. index_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{blob}/index.json").DownloadContentAsync();
  4111. }
  4112. JsonElement RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_json.Content.ToString()))).RootElement;
  4113. attachments = RecordingJson.GetProperty("attachments").ToObject<List<string>>();
  4114. if (attachments.Count == 0)
  4115. {
  4116. continue;
  4117. }
  4118. }
  4119. BlobDownloadResult index_item_json;
  4120. if (info.scope.Equals("school"))
  4121. {
  4122. index_item_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{blob}/{itemInfo.qId}.json").DownloadContentAsync();
  4123. }
  4124. else
  4125. {
  4126. index_item_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{blob}/{itemInfo.qId}.json").DownloadContentAsync();
  4127. }
  4128. JsonElement itemJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_item_json.Content.ToString()))).RootElement;
  4129. elements.Add((itemJson,attachments,info.qamode));
  4130. if (itemJson.TryGetProperty("pid", out JsonElement pid))
  4131. {
  4132. if (!string.IsNullOrEmpty(pid.ToString()))
  4133. {
  4134. BlobDownloadResult index_pid_item_json;
  4135. if (info.scope.Equals("school"))
  4136. {
  4137. index_pid_item_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{blob}/{pid}.json").DownloadContentAsync();
  4138. }
  4139. else
  4140. {
  4141. index_pid_item_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{blob}/{pid}.json").DownloadContentAsync();
  4142. }
  4143. JsonElement pidJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_pid_item_json.Content.ToString()))).RootElement;
  4144. elements.Add((pidJson, attachments, info.qamode));
  4145. }
  4146. }
  4147. } catch (Exception e) {
  4148. await _dingDing.SendBotMsg($"OS,{_option.Location},exam/get-item\n{e.Message}\n{e.StackTrace}\n{info.id}", GroupNames.成都开发測試群組);
  4149. continue;
  4150. //return BadRequest(new { msg = "blob 文件读取异常" });
  4151. }
  4152. }
  4153. }
  4154. else
  4155. {
  4156. var values = elements.Select(c => new {
  4157. c.items,
  4158. c.attachments,
  4159. c.qamode
  4160. });
  4161. return Ok(new { error = values });
  4162. }
  4163. var error = elements.Select(c => new {
  4164. c.items,
  4165. c.attachments,
  4166. c.qamode
  4167. });
  4168. return Ok(new { error });
  4169. }
  4170. }
  4171. public class stus
  4172. {
  4173. public string id { get; set; }
  4174. public int type { get; set; }
  4175. }
  4176. public class ufo
  4177. {
  4178. public string id { get; set; }
  4179. public string name { get; set; }
  4180. public int type { get; set; }
  4181. }
  4182. public class stuErrorItemCnt
  4183. {
  4184. public string subjectId { get; set; }
  4185. public int number { get; set; }
  4186. }
  4187. public class errorItemInfo {
  4188. public string activityId { get; set; }
  4189. public string qId { get; set; }
  4190. public string unitId { get; set; }
  4191. }
  4192. }