ExamController.cs 284 KB

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