123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205 |
- using Microsoft.Azure.Cosmos;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using TEAMModelOS.SDK.Models.Table;
- using Azure.Messaging.ServiceBus;
- using Microsoft.Extensions.Configuration;
- using TEAMModelOS.Filter;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Models.Cosmos;
- using Microsoft.AspNetCore.Authorization;
- using System.Net.Http;
- using Microsoft.AspNetCore.Hosting;
- using static TEAMModelOS.SDK.SchoolService;
- using Azure.Core;
- using Item = TEAMModelOS.SDK.Models.Cosmos.Common.Item;
- using TEAMModelOS.SDK.Services;
- using TEAMModelOS.SDK.Models.Service.BI;
- using MathNet.Numerics.RootFinding;
- using TEAMModelOS.SDK.Models.Cosmos.Student;
- using ClouDASLibx;
- using Azure.Storage.Blobs.Models;
- using System.IO;
- using TEAMModelOS.SDK.Helper.Common.StringHelper;
- using Microsoft.AspNetCore.SignalR;
- using static SKIT.FlurlHttpClient.Wechat.TenpayV3.Models.CreateApplyForSubjectApplymentRequest.Types;
- using TEAMModelOS.Controllers.Analysis;
- using DocumentFormat.OpenXml.Office2010.Excel;
- using DocumentFormat.OpenXml.Wordprocessing;
- using Microsoft.AspNetCore.Http.HttpResults;
- using DocumentFormat.OpenXml.Drawing.Charts;
- using TEAMModelOS.Models.Dto;
- using FastJSON;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- [Route("common/exam")]
- [ApiController]
- public class ExamController : ControllerBase
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly SnowflakeId _snowflakeId;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureRedisFactory _azureRedis;
- private readonly IHttpClientFactory _httpClient;
- public IConfiguration _configuration { get; set; }
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly IWebHostEnvironment _environment;
- public ExamController(IWebHostEnvironment environment, CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
- IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration, IHttpClientFactory httpClient)
- {
- _azureCosmos = azureCosmos;
- _serviceBus = serviceBus;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _configuration = configuration;
- _coreAPIHttpService = coreAPIHttpService;
- _environment = environment;
- _httpClient = httpClient;
- }
- /// <summary>
- /// 保存考试信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("save")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> Save(ExamInfo request)
- {
- try
- {
- //新增
- //string code = request.code;
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo exam;
- string code = request.code;
- request.ttl = -1;
- request.code = "Exam-" + request.code;
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- request.createTime = now;
- if (request.startTime <= 0)
- {
- request.startTime = now;
- }
- //查询所有学生名单
- /* List<string> sids = new List<string>();
- //List<Student> students = new List<Student>();
- 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}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- sids.Add(account.GetProperty("id").GetString());
- }
- }
- }*/
- //int stuCount = 0;
- List<(string pId, List<string> gid)> ps = new();
- var group = request.groupLists;
- if (group.Count > 0)
- {
- foreach (var keys in group)
- {
- foreach (KeyValuePair<string, List<string>> pp in keys)
- {
- ps.Add((pp.Key, pp.Value));
- }
- }
- }
- List<string> classes = ExamService.getClasses(request.classes, request.stuLists);
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, request.school, ps);
- request.stuCount = tchList.Count;
- /*for (int i = 0; i < classes.Count; i++)
- {
- List<string> ids = new List<string>();
- //处理班级人数(公共部分的校本名单)
- //List<Student> students = new List<Student>();
- 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}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- ids.Add(account.GetProperty("id").GetString());
- }
- }
- }
- if (request.scope.Equals("private"))
- {
- //处理发布对象为自选名单(个人)
- List<GroupList> stuLists = new List<GroupList>();
- 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") }))
- {
- stuLists.Add(item);
- }
- }
- else
- {
- //request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
- //发布对象为自选名单(校本)
- List<GroupList> stuLists = new List<GroupList>();
- 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}") }))
- {
- stuLists.Add(item);
- }
- }
- stuCount += ids.Count;
- }*/
- //var (grade, per) = await ThirdService.GetGradeAsync(client, request);
- /*var data = new
- {
- examName = request.name,
- examCategory = 1,
- //grade = int.Parse(grade),
- grade = 7,
- term = 2,
- examType = "单元测试",
- examDate = request.startTime,
- schId = 1,
- boeId = "",
- subjects = request.subjects.Select(c => c.name).ToList()
- };*/
- if (string.IsNullOrEmpty(request.id))
- {
- request.id = Guid.NewGuid().ToString();
- if (request.startTime > now)
- {
- request.progress = "pending";
- }
- else
- {
- request.progress = "going";
- }
- var messageBlob = new ServiceBusMessage();
- if (request.scope.Equals("school"))
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.school }, _serviceBus, _configuration, _azureRedis);
- }
- else
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.creatorId }, _serviceBus, _configuration, _azureRedis);
- }
- int n = 0;
- List<string> sheetIds = new List<string>();
- foreach (PaperSimple simple in request.papers)
- {
- simple.blob = $"/exam/{request.id}/paper/{request.subjects[n].id}";
- n++;
- simple.sheet = null;
- }
- //string moofenCode = await ThirdService.CreateMoofenExam(_httpClient, data.ToJsonString().ToObject<JsonElement>(),_dingDing);
- //request.moofenCode = moofenCode;
- exam = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
- await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
- //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" });
- }
- else
- {
- var response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- ExamInfo info = json.ToObject<ExamInfo>();
- if (info.progress.Equals("going"))
- {
- //exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
- return Ok(new { v = "活动正在进行中,无法修改", code = 200 });
- }
- var messageBlob = new ServiceBusMessage();
- if (request.scope.Equals("school"))
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = request.school }, _serviceBus, _configuration, _azureRedis);
- }
- else
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = request.creatorId }, _serviceBus, _configuration, _azureRedis);
- }
- request.progress = info.progress;
- int n = 0;
- foreach (PaperSimple simple in request.papers)
- {
- simple.blob = "/exam/" + request.id + "/paper/" + request.subjects[n].id;
- n++;
- }
- exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
- }
- else
- {
- if (request.startTime > now)
- {
- request.progress = "pending";
- }
- else
- {
- request.progress = "going";
- }
- var messageBlob = new ServiceBusMessage();
- if (request.scope.Equals("school"))
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"exam/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.school }, _serviceBus, _configuration, _azureRedis);
- }
- else
- {
- request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"exam/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = request.creatorId }, _serviceBus, _configuration, _azureRedis);
- }
- int n = 0;
- List<string> sheetIds = new List<string>();
- foreach (PaperSimple simple in request.papers)
- {
- if (!string.IsNullOrEmpty(simple.subjectId))
- {
- simple.blob = $"/exam/{request.id}/paper/{simple.subjectId}/{simple.id}";
- }
- else
- {
- simple.blob = $"/exam/{request.id}/paper/{request.subjects[n].id}";
- n++;
- }
- simple.sheet = null;
- }
- //string moofenCode = await ThirdService.CreateMoofenExam(_httpClient, data.ToJsonString().ToObject<JsonElement>());
- exam = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
- await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
- }
- }
- return Ok(new { exam });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/save()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /* [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher,admin")]
- [HttpPost("read-score")]
- // [Authorize(Roles = "IES")]
- public async Task<IActionResult> getAverage(JsonElement request) {
- var client = _azureCosmos.GetCosmosClient();
- var grades = ExamService.getGradeScore(_coreAPIHttpService,_dingDing,client,2021,"二年级", "463db08d-cbe7-48a0-a81a-fc39b3c1fep1","hbcn", 1688349974000, 1693706774000);
- return Ok(grades);
- }*/
- /// <summary>
- /// 保存考试信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("update-end-time")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> updateTime(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Exam-{code}"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- ExamInfo exam = json.ToObject<ExamInfo>();
- if (request.TryGetProperty("time", out JsonElement time))
- {
- exam.endTime = time.GetInt64();
- }
- if (request.TryGetProperty("name", out JsonElement name))
- {
- exam.name = name.GetString();
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
- }
- return Ok(new { code = 200 });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/update-end-time()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [HttpPost("get-exam-point")]
- #if !DEBUG
- [AuthToken(Roles = "teacher,admin")]
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> getExamPoint(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("classIds", out JsonElement classId)) return BadRequest();
- if (!request.TryGetProperty("school", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("periodId", out JsonElement periodId)) return BadRequest();
- if (!request.TryGetProperty("semesterId", out JsonElement semesterId)) return BadRequest();
- if (!request.TryGetProperty("studyYear", out JsonElement studyYear)) return BadRequest();
- if (!request.TryGetProperty("studentYear", out JsonElement studentYear)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<string> ids = [];
- List<string> clds = classId.ToObject<List<string>>().ToList();
- //List<string> clas = classId.ToObject<List<string>>().ToList();
- List<ExamSubject> subs = [];
- List<PaperSimple> paperSimples = [];
- List<(string id,string type)> source = [];
- List<(string id, double score)> averages = [];
- //获取学校基本信息
- School schoolBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(code.GetString(), new PartitionKey("Base"));
- var period = schoolBase.period.Find(x => x.id.Equals($"{periodId}"));
- var semesterData = SchoolService.GetSemester(period, time: SchoolService.GetOpensByStudyYearAndSemester(period.semesters, studyYear.GetInt32(), $"{semesterId}"));
- var sem = period.semesters.Find(x => x.id.Equals($"{semesterId}"));
- if (clds.Count == 0) {
- List<Class> classes = new();
- string sqlClassIds = $" select value(c) from c where c.periodId = '{periodId}'";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).
- GetItemQueryIteratorSql<Class>(queryText: sqlClassIds, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Class-{code}") }))
- {
- classes.Add(item);
- }
- foreach (var cla in classes)
- {
- if (cla.year == studentYear.GetInt32())
- {
- clds.Add(cla.id);
- }
- }
- if (clds.Count == 0)
- {
- return Ok(new { orderScore = Array.Empty<string>(), typeCount = Array.Empty<string>(), gradeRate = Array.Empty<string>(), pCount = 0, gradeExamAverageScore = 0, point = 0, code = 200 });
- }
- }
- //处理班级ID
- HashSet<string> strs = new HashSet<string>();
- if (clds.Count > 1)
- {
- foreach (string str in clds)
- {
- strs.Add($"array_contains(c.classes,'{str}')");
- }
- }
- else
- {
- string ssr = clds.Count > 0 ? clds[0] : "";
- strs.Add($"array_contains(c.classes,'{ssr}')");
- }
- string classInfos = string.Join(" or ", strs);
- List<ExamInfo> exams = new List<ExamInfo>();
- (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, clds, $"{code}");
- 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}) " +
- $"and c.progress = 'finish' and c.scope = 'school' and c.startTime > {semesterData.date.ToUnixTimeMilliseconds()} and c.startTime < {semesterData.nextSemester.ToUnixTimeMilliseconds()} ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: queryExam, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- exams.Add(account.ToObject<ExamInfo>());
- ids.Add(account.GetProperty("id").GetString());
- if (account.TryGetProperty("subjects", out JsonElement subject))
- {
- subs.AddRange(subject.ToObject<List<ExamSubject>>());
- }
- if (account.TryGetProperty("papers", out JsonElement papers))
- {
- paperSimples.AddRange(papers.ToObject<List<PaperSimple>>());
- }
- source.Add((account.GetProperty("id").GetString(), account.GetProperty("source").GetString()));
- averages.Add((account.GetProperty("id").GetString(), account.GetProperty("average").GetDouble()));
- }
- }
- }
- subs = subs.Where((x, i) => subs.FindIndex(z => z.id == x.id) == i).ToList();
- List<ExamClassResult> classResults = new();
- List<ExamClassResult> results = new();
- var point = paperSimples.Count > 0 ? paperSimples.FirstOrDefault().point.Sum() : 0;
- var gradeExamAverageScore = averages.Count >0 ? Math.Round(averages.Select(c => c.score).Sum() / averages.Count,2) : 0;
- if (clds.Count == 1)
- {
- var queryClass = $"select value(c) from c where c.info.id = '{clds[0]}'and c.examId in ({string.Join(",", ids.Select(o => $"'{o}'"))})";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- classResults.Add(item);
- }
-
- }
- else {
- 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}'"))})";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- results.Add(item);
- }
- }
-
-
- var typeCount = source.GroupBy(x => x.type).Select(z => new
- {
- z.Key,
- count = z.ToList().Count
- });
- //计算几次合并
- var examScore = classResults.GroupBy(c => c.subjectId).Select(x => new
- {
- x.Key,
- cc = x.ToList().Count,
- students = x.ToList().SelectMany(z => z.studentIds).Distinct().ToList(),
- classRate = x.ToList().Count > 0 ? Math.Round(x.ToList().Select(z => z.average).Sum() / x.ToList().Count,2) : 0
- //score = x.ToList().Select(k => k.sum).Aggregate((current, next) => current.Zip(next, (a, b) => a + b).ToList()),
- //gRate = Math.Round( x.ToList().SelectMany(k => k.sum).Sum() / x.ToList().Count / members.Count, 2)
- });
- List<(string sub, List<(string id, double score)> subScore,int cc,double average)> stuScore = [];
- foreach (var es in examScore) {
- List<(string id, double score)> subScore = [];
- foreach (var sId in es.students) {
- int count = classResults.Where(c => c.subjectId.Equals(es.Key) && c.studentIds.Contains(sId)).ToList().Count;
- var totalScore = classResults.Where(c => c.subjectId.Equals(es.Key) && c.studentIds.Contains(sId)).ToList().Select(z => z.sum[z.studentIds.IndexOf(sId)]).Sum();
- subScore.Add((sId, Math.Round(totalScore / count,2)));
- }
- stuScore.Add((es.Key, subScore,es.cc,es.classRate));
- }
- var examAllScore = results.GroupBy(c => c.subjectId).Select(x => new
- {
- x.Key,
- cc = x.ToList().Count,
- students = x.ToList().SelectMany(z => z.studentIds).Distinct().ToList(),
- classRate = x.ToList().GroupBy(z => z.info.id).Select(m => new {
- classId = m.Key,
- className = groups.Where(k => k.id.Equals(m.Key)).FirstOrDefault()?.name,
- rate = point > 0 ? Math.Round(m.ToList().Select(k => k.average).Sum() / m.ToList().Count / point,4) :0
- })
- //score = x.ToList().Select(k => k.sum).Aggregate((current, next) => current.Zip(next, (a, b) => a + b).ToList()),
- //gRate = Math.Round(x.ToList().SelectMany(k => k.sum).Sum() / x.ToList().Count / members.Count, 2)
- }) ;
- var gradeRate = examAllScore.Select(x => new
- {
- subjectId = x.Key,
- subjectName = subs.Where(z => z.id.Equals(x.Key)).FirstOrDefault()?.name,
- classRate = x.classRate.OrderByDescending(c => c.rate)
- //x.gRate
- });
- if (request.TryGetProperty("studentId", out JsonElement studentId) && !string.IsNullOrWhiteSpace($"{studentId}"))
- {
- bool flag = false;
- foreach (var os in stuScore) {
- foreach (var sos in os.subScore) {
- if (sos.id.Equals(studentId.GetString()))
- {
- flag = true; break;
- }
- }
- }
- if (!flag) {
- typeCount = typeCount.Select(c => new {
- c.Key,
- count = 0
- });
- }
- var orderScore = stuScore.Select(x => new
- {
- subjectId = x.sub,
- subjectName = subs.Where(z => z.id.Equals(x.sub)).FirstOrDefault()?.name,
- classRate = point > 0 ? Math.Round(x.average / point, 4) : 0,
- 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,
- stuRate = x.subScore.OrderByDescending(x => x.score).Select(z => new
- {
- z.id,
- members.Where(s => s.id.Equals(z.id)).FirstOrDefault()?.name,
- rate = point > 0 ? Math.Round(z.score / point, 4) :0
- }).ToList().Take(10),
- sper = x.subScore.Where(c => c.id.Equals(studentId.GetString())).Select(z => new
- {
- z.id,
- members.Where(s => s.id.Equals(z.id)).FirstOrDefault()?.name,
- rate = point>0 ? Math.Round(z.score / point, 4) :0
- })
- });
- return Ok(new { orderScore, typeCount, gradeRate, pCount = members.Count, gradeExamAverageScore, point, exams, code = 200 });
- }
- else
- {
- var orderScore = stuScore.Select(x => new
- {
- subjectId = x.sub,
- subjectName = subs.Where(z => z.id.Equals(x.sub)).FirstOrDefault()?.name,
- classRate = point > 0 ? Math.Round(x.average / point,4) : 0,
- stuRate = x.subScore.OrderByDescending(x => x.score).Select(z => new
- {
- z.id,
- members.Where(s => s.id.Equals(z.id)).FirstOrDefault()?.name,
- rate = point > 0 ? Math.Round(z.score / point, 4) : 0
- }).ToList().Take(10)
- });
- return Ok(new { orderScore, typeCount, gradeRate, pCount = members.Count, gradeExamAverageScore, exams, point, code = 200 });
- }
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/get-exam-point()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //TODO blob 批量删除
- /// <summary>
- /// 删除
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("delete")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> Delete(JsonElement request)
- {
- /* ResponseBuilder builder = ResponseBuilder.custom();
- IdPk items = await _azureCosmos.DeleteAsync<ExamInfo>(request.id, request.pk);
- await _azureCosmos.DeleteAll<Paper>(new Dictionary<string, object>() { { "code", request.id } });
- return builder.Data(items).build();*/
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo exam;
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Exam-{code}"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var jsonExam = await JsonDocument.ParseAsync(response.Content);
- exam = jsonExam.ToObject<ExamInfo>();
- bool flag = false;
- //必须是本人或者这个学校的管理者才能删除
- if (exam.creatorId == userid)
- {
- flag = true;
- }
- else
- {
- if (exam.scope == "school" && exam.school.Equals(school))
- {
- flag = true;
- }
- }
- if (flag)
- {
- exam.status = 404;
- exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
- //string school_code = code.ToString().Substring(typeof(ExamClassResult).Name.Length + 1);
- //var response = await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
- //删除blob 相关资料
- await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, code.ToString(), new List<string> { $"exam/{id}" });
- //通知评测删除信息
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "delete", root = $"exam", name = $"{code}" }, _serviceBus, _configuration, _azureRedis);
- //删除阅卷配置
- var cresponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
- if (cresponse.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(cresponse.Content);
- Correct correct = json.ToObject<Correct>();
- if (correct.subs.IsNotEmpty())
- {
- foreach (var sub in correct.subs)
- {
- //List<string> correctIds = new List<string>();
- if (sub.markers.IsNotEmpty())
- {
- foreach (var marker in sub.markers)
- {
- await ExamService.deleteAsync(client, id.GetString(), marker.id);
- }
- }
- if (sub.err.Count > 0)
- {
- foreach (var tId in sub.err)
- {
- await ExamService.deleteAsync(client, id.GetString(), tId);
- }
- }
- if (sub.arb.Count > 0)
- {
- foreach (var tId in sub.arb)
- {
- await ExamService.deleteAsync(client, id.GetString(), tId);
- }
- }
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(id.GetString(), new PartitionKey($"Correct-{code}"));
- }
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- 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}") }))
- {
- examClassResults.Add(item);
- }
- List<string> resultIds = new List<string>();
- 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}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- resultIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- foreach (ExamClassResult classResult in examClassResults)
- {
- await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(classResult.id, new PartitionKey($"ExamClassResult-{code}"));
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemsStreamAsync(resultIds, $"ExamResult-{id}");
- }
- return Ok(new { id });
- }
- else
- {
- return NotFound(new { msg = "未找到对应内容" });
- }
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/delete()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 查询考试信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find")]
- public async Task<IActionResult> Find(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- //if (request.TryGetProperty("period", out JsonElement period)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- //if (!request.TryGetProperty("userId", out JsonElement userId)) return BadRequest();
- //if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
- var (userId, _, _, school) = HttpContext.GetAuthTokenInfo();
- 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'");
- /*if (request.TryGetProperty("classIds", out JsonElement classIds))
- {
- List<string> ids = classIds.ToObject<List<string>>();
- HashSet<string> strs = new HashSet<string>();
- if (ids.Count > 1)
- {
- foreach (string id in ids)
- {
- strs.Add($"array_contains(c.classes,'{id}')");
- }
- }
- else
- {
- string ssr = ids.Count > 0 ? ids[0] : "";
- strs.Add($"array_contains(c.classes,'{ssr}')");
- }
- string ss = string.Join(" or ", strs);
- stringBuilder.Append($" and {ss}");
- };*/
- //开始时间,
- if (request.TryGetProperty("stime", out JsonElement stime))
- {
- if (long.TryParse($"{stime}", out long data))
- {
- stringBuilder.Append($" and c.createTime >= {data} ");
- };
- };
- //默认当前时间
- if (request.TryGetProperty("etime", out JsonElement etime))
- {
- if (long.TryParse($"{etime}", out long data))
- {
- stringBuilder.Append($" and c.createTime <= {data} ");
- };
- };
- string periodId = string.Empty;
- if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
- {
- stringBuilder.Append($" and (c.period.id = '{period}' or c.period.id = null)");
- periodId = period.GetString();
- }
- if (request.TryGetProperty("opt", out JsonElement opt))
- {
- if (opt.GetString().Equals("private"))
- {
- //针对于个人活动获取教师 任教或者助教大名单
- var groupList = await GroupListService.GetTeacherTeachGroupList(_coreAPIHttpService, client, _dingDing, userId, school, periodId);
- List<string> ids = new();
- foreach (var groups in groupList)
- {
- foreach (var gp in groups.groups)
- {
- ids.Add(gp.id);
- }
- }
- HashSet<string> strs = new HashSet<string>();
- if (ids.Count > 1)
- {
- foreach (string id in ids)
- {
- strs.Add($" array_contains(c.stuLists,'{id}') or array_contains(c.classes,'{id}')");
- }
- }
- else
- {
- string ssr = ids.Count > 0 ? ids[0] : "";
- strs.Add($" array_contains(c.stuLists,'{ssr}') or array_contains(c.classes,'{ssr}') ");
- }
- string ss = string.Join(" or ", strs);
- stringBuilder.Append($" and ({ss})");
- stringBuilder.Append($" and c.owner = 'teacher'");
- }
- else
- {
- stringBuilder.Append($" and c.code = 'Exam-{code}' ");
- }
- };
- if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
- {
- stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
- }
- if (request.TryGetProperty("progress", out JsonElement progress) && !string.IsNullOrWhiteSpace($"{progress}"))
- {
- stringBuilder.Append($" and c.progress = '{progress}' ");
- }
- if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
- {
- stringBuilder.Append($" and c.source = '{source}' ");
- }
- stringBuilder.Append("order by c.createTime desc");
- //string token = null;
- string token = default;
- //默认不指定返回大小
- int? topcout = null;
- if (request.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (topcout != null && topcout.Value > 0)
- {
- iscontinuation = true;
- }
- //如果指定了返回大小
- if (request.TryGetProperty("token", out JsonElement token_1))
- {
- if (!token_1.ValueKind.Equals(JsonValueKind.Null) && token_1.ValueKind.Equals(JsonValueKind.String))
- {
- token = token_1.GetString();
- }
- }
- List<ExamInfo> examInfo = new List<ExamInfo>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- //obj.TryGetProperty("progress", out JsonElement progress);
- examInfo.Add(obj.ToObject<ExamInfo>());
- }
- }
- if (iscontinuation)
- {
- token = item.ContinuationToken;
- break;
- }
- }
- return Ok(new { examInfo, token = token });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- #if !DEBUG
- [AuthToken(Roles = "teacher,admin,student")]
- [Authorize(Roles = "IES")]
- #endif
- [HttpPost("find-by-analysis")]
- public async Task<IActionResult> FindByAnalysis(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var table = _azureStorage.GetCloudTableClient().GetTableReference("SchoolYear");
- List<SchoolYear> years = await table.FindListByDict<SchoolYear>(new Dictionary<string, object>() { { "RowKey", code }, { "PartitionKey", "Exam" } });
- int year = 0;
- if (years.Count > 0)
- {
- year = years[0].year;
- if (year == 1970)
- {
- long ct = 0;
- 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}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- ct = account.GetProperty("createTime").GetInt64();
- }
- }
- }
- year = ct == 0 ? DateTimeOffset.UtcNow.Year : DateTimeOffset.FromUnixTimeMilliseconds(ct).Year;
- years[0].year = year;
- await table.SaveOrUpdate<SchoolYear>(years[0]);
- }
- }
- else
- {
- long ct = 0;
- 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}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- ct = account.GetProperty("createTime").GetInt64();
- }
- }
- }
- year = ct == 0 ? DateTimeOffset.UtcNow.Year : DateTimeOffset.FromUnixTimeMilliseconds(ct).Year;
- SchoolYear sy = new()
- {
- RowKey = code.ToString(),
- PartitionKey = "Exam",
- year = year
- };
- await table.Save<SchoolYear>(sy);
- }
- string sub = string.Empty;
- string subject = string.Empty;
- if (request.TryGetProperty("subjectId", out JsonElement subjectId) && !string.IsNullOrWhiteSpace($"{subjectId}"))
- {
- sub = $" join A0 in c.subjects ";
- subject = $" and A0.id = '{subjectId}'";
- }
- string grade = string.Empty;
- string grades = string.Empty;
- if (request.TryGetProperty("grades", out JsonElement gs) && !string.IsNullOrWhiteSpace($"{gs}"))
- {
- grade = $" join A1 in c.grades ";
- grades = $" and A1.id = '{gs}'";
- }
- 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}" +
- $"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}");
- if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
- {
- stringBuilder.Append($" and c.period.id = '{period}' ");
- }
- if (request.TryGetProperty("owner", out JsonElement owner) && !string.IsNullOrWhiteSpace($"{owner}"))
- {
- stringBuilder.Append($" and c.owner= '{owner}' ");
- }
- if (request.TryGetProperty("year", out JsonElement yy) && !string.IsNullOrWhiteSpace($"{yy}"))
- {
- int end = yy.GetInt32() + 1;
- long stime = DateTimeOffset.Parse($"{yy.GetInt32()}-1-1").ToUnixTimeMilliseconds();
- long etime = DateTimeOffset.Parse($"{end}-1-1").ToUnixTimeMilliseconds();
- stringBuilder.Append($" and c.startTime >= {stime} and c.startTime < {etime} ");
- }
- if (request.TryGetProperty("startTime", out JsonElement startTime) && !string.IsNullOrWhiteSpace($"{startTime}"))
- {
- stringBuilder.Append($" and c.startTime >= {startTime} ");
- }
- if (request.TryGetProperty("endTime", out JsonElement endTime) && !string.IsNullOrWhiteSpace($"{endTime}"))
- {
- stringBuilder.Append($" and c.startTime < {endTime} ");
- }
- if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
- {
- stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
- }
- if (request.TryGetProperty("examType", out JsonElement examType) && !string.IsNullOrWhiteSpace($"{examType}"))
- {
- stringBuilder.Append($" and c.examType.id = '{examType}' ");
- }
- if (request.TryGetProperty("progress", out JsonElement progress) && !string.IsNullOrWhiteSpace($"{progress}"))
- {
- stringBuilder.Append($" and c.progress = '{progress}' ");
- }
- if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
- {
- stringBuilder.Append($" and c.source = '{source}' ");
- }
- if (request.TryGetProperty("creatorId", out JsonElement creatorId) && !string.IsNullOrWhiteSpace($"{creatorId}"))
- {
- stringBuilder.Append($" and c.creatorId = '{creatorId}' ");
- }
- stringBuilder.Append("order by c.createTime desc");
- string token = default;
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (request.TryGetProperty("token", out JsonElement token_1))
- {
- token = token_1.GetString();
- };
- //默认不指定返回大小
- int? topcout = null;
- if (request.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- if (topcout != null && topcout.Value > 0)
- {
- iscontinuation = true;
- }
- List<ExamInfo> examInfo = new List<ExamInfo>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- //obj.TryGetProperty("progress", out JsonElement progress);
- examInfo.Add(obj.ToObject<ExamInfo>());
- }
- }
- if (iscontinuation)
- {
- token = item.ContinuationToken;
- break;
- }
- }
- List<ExamInfo> exams = new List<ExamInfo>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString()))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- exams.Add(obj.ToObject<ExamInfo>());
- }
- }
- }
- School schoolBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(code.GetString(), new PartitionKey("Base"));
- var periodInfo = schoolBase.period.Find(x => x.id.Equals($"{period}"));
- List<GroupListDto> allClasses = new List<GroupListDto>();
- //获取该学校某学段全部行政班级
- allClasses = await GroupListService.GetGroupListByType(_azureCosmos.GetCosmosClient(), "class", schoolBase, periodInfo, 0);
- var classData = allClasses.Select(x => new {
- x.id,
- x.name
- });
- 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();
- return Ok(new { examInfo, token, year, count = exams.Count, groups, classData });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-by-analysis()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-summary")]
- public async Task<IActionResult> FindSummary(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<ExamInfoEx> examInfo = new List<ExamInfoEx>();
- List<string> jointExamIds = new List<string>();
- //var query = $"select value(c) from c ";
- 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}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- //obj.TryGetProperty("progress", out JsonElement progress);
- ExamInfoEx exInfo = obj.ToObject<ExamInfoEx>();
- examInfo.Add(exInfo);
- if (!string.IsNullOrWhiteSpace(exInfo.jointExamId) && !jointExamIds.Contains(exInfo.jointExamId)) jointExamIds.Add(exInfo.jointExamId);
- }
- }
- }
- //加入統測資訊
- List<JointExam> jointExams = new List<JointExam>();
- if (jointExamIds.Count > 0)
- {
- 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) ");
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: stringBuilderJointEx.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"JointExam") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- jointExams.Add(obj.ToObject<JointExam>());
- }
- }
- }
- }
- foreach (ExamInfoEx exinfo in examInfo)
- {
- JointExam jointExamNow = jointExams.Where(j => !string.IsNullOrWhiteSpace(exinfo.jointExamId) && j.id.Equals(exinfo.jointExamId)).FirstOrDefault();
- if (jointExamNow != null)
- {
- exinfo.jointExamType = jointExamNow.examType;
- }
- }
- return Ok(new { examInfo });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/FindSummary()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 学生回答问题
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student,teacher")]
- [HttpPost("upsert-record")]
- public async Task<IActionResult> upsertRecord(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //学校编码
- //if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
- if (!request.TryGetProperty("answer", out JsonElement answer)) return BadRequest();
- if (!request.TryGetProperty("paperAns", out JsonElement paperAns)) return BadRequest();
- if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
- //if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("classIds", out JsonElement classId)) return BadRequest();
- if (!request.TryGetProperty("multipleRule", out JsonElement multipleRule)) return BadRequest();
- //if (!request.TryGetProperty("answers ", out JsonElement tandardAnswer)) return BadRequest();
- //if (!request.TryGetProperty("paperId", out JsonElement paperId)) return BadRequest();
- //根据不同评测的类型返回对应的编码
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
- var (userId, name, picture, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- List<string> ids = new List<string>();
- ids = classId.ToObject<List<string>>();
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo info = new();
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{scode}"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(response.Content);
- info = cJson.ToObject<ExamInfo>();
- }
- else
- {
- return Ok(new { code = 404, msg = "该活动未被找到" });
- }
- //ExamInfo info = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.GetString(), new PartitionKey($"{scode}"));
- //确定当前学生所在班级且该班级参与该活动
- //List<string> cIds = new();
- if (ids.Count == 0) return Ok(new { code = 404, msg = "未找到相关班级信息" });
- if (string.IsNullOrEmpty(userId)) return Ok(new { code = 404, msg = "当前用户信息未找到" });
- /*foreach (string cId in ids)
- {
- //List<string> stus = new List<string>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(
- queryText: $"select c.classId as id from c where c.classId = '{cId}' and c.id = '{userId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{info.school}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- cIds.Add(account.GetProperty("id").GetString());
- }
- break;
- }
- }
- if (info.scope.Equals("private"))
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(
- queryText: $"select c.id from c join A0 in c.members where c.id = '{cId}' and A0.id = '{userId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- cIds.Add(account.GetProperty("id").GetString());
- }
- break;
- }
- }
- }
- else
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(
- queryText: $"select c.id from c join A0 in c.members where c.id = '{cId}' and A0.id = '{userId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{info.school}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- cIds.Add(account.GetProperty("id").GetString());
- }
- break;
- }
- }
- }
- }*/
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
- 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}'"))})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- examClassResults.Add(obj.ToObject<ExamClassResult>());
- }
- }
- }
- examClassResults = examClassResults.Where(c => c.studentIds.Contains(userId)).ToList();
- ExamClassResult classResult = new ExamClassResult();
- /* List<PaperSimple> standerAnswers = new List<PaperSimple>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
- queryText: $"select A0.point,A0.answers from c join A0 in c.papers where c.id = '{id}'and A0.id = '{paperId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- standerAnswers.Add(obj.ToObject<PaperSimple>());
- }
- }
- }*/
- List<List<string>> ans = answer.ToObject<List<List<string>>>();
- List<List<string>> standard = paperAns.ToObject<List<List<string>>>();
- List<double> points = point.ToObject<List<double>>();
- int rule = int.Parse(multipleRule.ToString());
- /* foreach (PaperSimple simple in standerAnswers)
- {
- standard = simple.answers;
- points = simple.point;
- }*/
- List<Task<string>> tasks = new List<Task<string>>();
- foreach (ExamClassResult result in examClassResults)
- {
- //int index = result.studentIds.IndexOf(userId.ToString());
- //存放客观题作答详情
- //if (result.ans.Count == 0)
- //{
- // foreach (string cc in result.studentIds)
- // {
- // List<List<string>> anc = new List<List<string>>();
- // foreach (List<string> opc in standard)
- // {
- // anc.Add(new List<string>());
- // }
- // result.ans.Add(anc);
- // }
- //}
- int newIndex = result.studentIds.IndexOf(userId.ToString());
- StringBuilder builder = new();
- builder.Append(result.examId).Append('/');
- builder.Append(result.subjectId).Append('/');
- builder.Append(userId).Append('/');
- builder.Append("ans.json");
- /*string FileName = result.examId + "/" + result.subjectId + "/" + studentId;
- string blob = FileName + "/" + "ans.json";*/
- tasks.Add(_azureStorage.GetBlobContainerClient(code.ToString()).UploadFileByContainer(ans.ToJsonString(), "exam", builder.ToString(), false));
- result.studentAnswers[newIndex].Add(builder.ToString());
- result.status[newIndex] = 0;
- //}
- //List<(int index ,string content, double count)> acount = new List<(int index,string content, double count)>();
- for (int i = 0; i < ans.Count; i++)
- {
- var sc = standard[i].Count;
- var ac = ans[i].Where(a => a.Trim().Length > 0).ToList().Count;
- //算分处理
- if (sc > 0)
- {
- /* if (ans[i].Count == 0)
- {
- continue;
- }*/
- result.ans[newIndex][i] = ans[i];
- if (ac == sc && sc == 1)
- {
- foreach (string right in ans[i])
- {
- if (standard[i].Contains(right.Trim()))
- {
- result.studentScores[newIndex][i] = points[i];
- }
- else
- {
- result.studentScores[newIndex][i] = 0;
- }
- }
- }
- else
- {
- if (rule > 0)
- {
- int falseCount = 0;
- if (ac > 0)
- {
- foreach (string obj in ans[i])
- {
- if (!standard[i].Contains(obj))
- {
- falseCount++;
- }
- }
- switch (rule)
- {
- case 1:
- if (ac == sc)
- {
- if (falseCount == 0)
- {
- result.studentScores[newIndex][i] = points[i];
- }
- else
- {
- result.studentScores[newIndex][i] = 0;
- }
- }
- else
- {
- result.studentScores[newIndex][i] = 0;
- }
- break;
- case 2:
- if (falseCount > 0)
- {
- result.studentScores[newIndex][i] = 0;
- }
- else
- {
- if (ac == sc)
- {
- result.studentScores[newIndex][i] = points[i];
- }
- else
- {
- result.studentScores[newIndex][i] = points[i] / 2;
- }
- }
- break;
- case 3:
- if (falseCount > 0)
- {
- result.studentScores[newIndex][i] = 0;
- }
- else
- {
- if (ac == sc)
- {
- result.studentScores[newIndex][i] = points[i];
- }
- else
- {
- result.studentScores[newIndex][i] = System.Math.Round((double)ac / sc * points[i], 1);
- }
- }
- break;
- case 4:
- if (ac == sc)
- {
- result.studentScores[newIndex][i] = points[i];
- }
- else
- {
- double persent = (double)(sc - 2 * falseCount) / sc;
- if (persent <= 0)
- {
- result.studentScores[newIndex][i] = 0;
- }
- else
- {
- result.studentScores[newIndex][i] = System.Math.Round(persent * points[i], 1);
- }
- }
- break;
- }
- }
- else
- {
- result.studentScores[newIndex][i] = 0;
- }
- }
- }
- }
- }
- /*if (result.studentScores.Contains(-1)) {
- }*/
- bool flag = true;
- var a = result.studentScores.Where(z => z.Contains(-1));
- if (a.Any())
- {
- flag = false;
- }
- //foreach (List<double> scores in result.studentScores)
- //{
- // foreach (double score in scores)
- // {
- // if (score == -1)
- // {
- // flag = false;
- // break;
- // }
- // }
- //}
- //bool isAns = true;
- bool isAns = result.studentScores[newIndex].Exists(s => s == -1);
- HttpContext.Items.TryGetValue("Scope", out object scope);
- int userType = $"{scope}".Equals(Constant.ScopeStudent) ? 2 : 1;
- if (flag)
- {
- result.progress = true;
- info.subjects.ForEach(s =>
- {
- if (s.id.Equals(subjectId.ToString()))
- {
- s.classCount += 1;
- }
- if (s.classCount > info.classes.Count)
- {
- s.classCount = info.classes.Count;
- }
- });
- }
- result.sum[newIndex] = result.studentScores[newIndex].Sum();
- classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
- var target = info.scope.Equals("school") ? info.school : info.creatorId;
- string _client = "web";
- if (info.source.Equals("1"))
- {
- _client = "hiteach";
- }
- 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 });
- if (isAns)
- {
- //if ($"{scope}".Equals(Constant.ScopeStudent))
- //{
- // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
- // activity.taskStatus = 0;
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
- //}
- //if ($"{scope}".Equals(Constant.ScopeTmdUser))
- //{
- // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
- // activity.taskStatus = 0;
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
- //}
- //if ($"{scope}".Equals(Constant.ScopeTeacher))
- //{
- // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
- // activity.taskStatus = 0;
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
- //}
- }
- else
- {
- if (request.TryGetProperty("artId", out JsonElement artId) && request.TryGetProperty("quotaId", out JsonElement quotaId))
- {
- await getArtInfoAsync(client, artId.GetString(), school, result.sum[newIndex], id.GetString(), subjectId.GetString(), quotaId.GetString(), userId, picture, name, userType, ids);
- };
- //if ($"{scope}".Equals(Constant.ScopeStudent))
- //{
- // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
- // activity.taskStatus = 1;
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{school}-{userId}"));
- //}
- //if ($"{scope}".Equals(Constant.ScopeTmdUser))
- //{
- // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
- // activity.taskStatus = 1;
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
- //}
- //if ($"{scope}".Equals(Constant.ScopeTeacher))
- //{
- // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{userId}"));
- // activity.taskStatus = 1;
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<StuActivity>(activity, id.ToString(), new PartitionKey($"Activity-{userId}"));
- //}
- }
- }
- //当作答班级数量与实际班级数量一致时才触发结算
- var ansCount = info.subjects.Where(c => c.id.Equals(subjectId)).FirstOrDefault()?.classCount;
- if (ansCount == info.classes.Count)
- {
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, id.ToString(), new PartitionKey($"{scode}"));
- }
- await Task.WhenAll(tasks);
- return Ok(new { classResult });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecord()\n{e.Message}\n{e.StackTrace}\n\n{id.GetString()}\n{request.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student,teacher")]
- [HttpPost("update-ans")]
- public async Task<IActionResult> updateAns(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("paperId", out JsonElement paperId)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("paperAns", out JsonElement paperAns)) return BadRequest();
- if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
- if (!request.TryGetProperty("kno", out JsonElement kno)) return BadRequest();
- if (!request.TryGetProperty("multipleRule", out JsonElement multipleRule)) return BadRequest();
- //根据不同评测的类型返回对应的编码
- if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
- //var (userId, name, picture, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo info = new();
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{scode}"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(response.Content);
- info = cJson.ToObject<ExamInfo>();
- }
- else
- {
- return Ok(new { code = 404, msg = "该活动未被找到" });
- }
- //if (string.IsNullOrEmpty(userId)) return Ok(new { code = 404, msg = "当前用户信息未找到" });
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- examClassResults.Add(obj.ToObject<ExamClassResult>());
- }
- }
- }
- //examClassResults = examClassResults.Where(c => c.studentIds.Contains(userId)).ToList(); wo
- ExamClassResult classResult = new();
- List<List<string>> standard = paperAns.ToObject<List<List<string>>>();
- int rule = int.Parse(multipleRule.ToString());
- List<double> points = point.ToObject<List<double>>();
- List<Task<string>> tasks = new List<Task<string>>();
- info.papers.ForEach(c =>
- {
- if (c.id.Equals(paperId.GetString()))
- {
- c.answers = standard;
- c.point = points;
- }
- });
- foreach (ExamClassResult result in examClassResults)
- {
- int index = 0;
- foreach (var ans in result.ans)
- {
- if (ans.Count == 0) continue;
- for (int i = 0; i < ans.Count; i++)
- {
- var sc = standard[i].Count;
- var ac = ans[i].Where(a => a.Trim().Length > 0).ToList().Count;
- //算分处理
- if (sc > 0)
- {
- if (ac == sc && sc == 1)
- {
- foreach (string right in ans[i])
- {
- if (standard[i].Contains(right.Trim()))
- {
- result.studentScores[index][i] = points[i];
- }
- else
- {
- result.studentScores[index][i] = 0;
- }
- }
- }
- else
- {
- if (rule > 0)
- {
- int falseCount = 0;
- if (ac > 0)
- {
- foreach (string obj in ans[i])
- {
- if (!standard[i].Contains(obj))
- {
- falseCount++;
- }
- }
- switch (rule)
- {
- case 1:
- if (ac == sc)
- {
- if (falseCount == 0)
- {
- result.studentScores[index][i] = points[i];
- }
- else
- {
- result.studentScores[index][i] = 0;
- }
- }
- else
- {
- result.studentScores[index][i] = 0;
- }
- break;
- case 2:
- if (falseCount > 0)
- {
- result.studentScores[index][i] = 0;
- }
- else
- {
- if (ac == sc)
- {
- result.studentScores[index][i] = points[i];
- }
- else
- {
- result.studentScores[index][i] = points[i] / 2;
- }
- }
- break;
- case 3:
- if (falseCount > 0)
- {
- result.studentScores[index][i] = 0;
- }
- else
- {
- if (ac == sc)
- {
- result.studentScores[index][i] = points[i];
- }
- else
- {
- result.studentScores[index][i] = System.Math.Round((double)ac / sc * points[i], 1);
- }
- }
- break;
- case 4:
- if (ac == sc)
- {
- result.studentScores[index][i] = points[i];
- }
- else
- {
- double persent = (double)(sc - 2 * falseCount) / sc;
- if (persent <= 0)
- {
- result.studentScores[index][i] = 0;
- }
- else
- {
- result.studentScores[index][i] = System.Math.Round(persent * points[i], 1);
- }
- }
- break;
- }
- }
- else
- {
- result.studentScores[index][i] = 0;
- }
- }
- }
- }
- }
- result.sum[index] = result.studentScores[index].Sum();
- index++;
- }
- classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, id.ToString(), new PartitionKey($"{scode}"));
- return Ok(new { code = 200, info });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/updateAns()\n{e.Message}\n{e.StackTrace}\n\n{id.GetString()}\n{request.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- 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)
- {
- var aresponse = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(artId, new PartitionKey($"Art-{school}"));
- ArtEvaluation art;
- StudentArtResult artResult;
- string rId = string.Format("{0}{1}{2}", school, "-", userid);
- if (aresponse.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(aresponse.Content);
- art = json.ToObject<ArtEvaluation>();
- var response = await client.GetContainer("TEAMModelOS", "Student").ReadItemStreamAsync(rId, new PartitionKey($"ArtResult-{artId}"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var json_1 = await JsonDocument.ParseAsync(response.Content);
- artResult = json_1.ToObject<StudentArtResult>();
- //bool flage = artResult.results.Exists(a => a.taskId == acId);
- artResult.results.ForEach(a =>
- {
- if (a.taskId == acId)
- {
- a.score = score;
- }
- });
- await client.GetContainer("TEAMModelOS", "Student").ReplaceItemAsync(artResult, artResult.id, new PartitionKey($"{artResult.code}"));
- }
- else
- {
- artResult = new StudentArtResult
- {
- id = rId,
- pk = "ArtResult",
- code = $"ArtResult-{artId}",
- studentId = userid,
- picture = picture,
- studentName = name,
- school = school,
- userType = userType,
- artId = artId,
- classIds = cIds,
- };
- art.settings.ForEach(qIds =>
- {
- qIds.task.ForEach(task =>
- {
- ArtQuotaResult quotaResult = new()
- {
- quotaId = qIds.id,
- quotaName = qIds.quotaname,
- quotaType = (int)task.type,
- taskId = task.acId,
- subjectId = task.subject
- };
- if (!string.IsNullOrEmpty(quotaResult.taskId))
- {
- if (quotaResult.taskId.Equals(acId))
- {
- quotaResult.score = score;
- }
- }
- artResult.results.Add(quotaResult);
- });
- });
- //foreach (var qIds in art.settings)
- //{
- // foreach (var task in qIds.task)
- // {
- // ArtQuotaResult quotaResult = new()
- // {
- // quotaId = qIds.id,
- // quotaName = qIds.quotaname,
- // quotaType = (int)task.type,
- // taskId = task.acId,
- // subjectId = task.subject
- // };
- // if (!string.IsNullOrEmpty(quotaResult.taskId))
- // {
- // if (quotaResult.taskId.Equals(acId))
- // {
- // quotaResult.score = score;
- // }
- // }
- // artResult.results.Add(quotaResult);
- // }
- //}
- await client.GetContainer("TEAMModelOS", "Student").CreateItemAsync(artResult, new PartitionKey($"{artResult.code}"));
- }
- }
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("upsert-record-by-teacher")]
- public async Task<IActionResult> upsertRecordByTeacher(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- try
- {
- var (userid, username, _, _) = HttpContext.GetAuthTokenInfo(); //取得TMID
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
- if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
- //if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
- //此参数表明此次操作对象为个人还是校本的评测内容
- if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- //要先处理状态,判断卷子是否存在,并判断卷子归属的考试是否允许再次提交
- //List<ExamInfo> exams = await _azureCosmos.FindByDict<ExamInfo>(new Dictionary<string, object> { { "id", request.examCode } });
- List<List<double>> ans = point.ToObject<List<List<double>>>();
- List<stus> sIds = studentId.ToObject<List<stus>>();
- var client = _azureCosmos.GetCosmosClient();
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- if (request.TryGetProperty("classId", out JsonElement classId))
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
- {
- examClassResults.Add(item);
- }
- }
- else
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
- {
- examClassResults.Add(item);
- }
- }
- ExamClassResult classResult = new ExamClassResult();
- //List<Task<ItemResponse<StuActivity>>> tasks = new List<Task<ItemResponse<StuActivity>>>();
- foreach (ExamClassResult result in examClassResults)
- {
- int index_sc = 0;
- foreach (stus s in sIds)
- {
- int index = result.studentIds.IndexOf(s.id.ToString());
- for (int i = 0; i < ans[index_sc].Count; i++)
- {
- result.studentScores[index][i] = ans[index_sc][i];
- }
- result.sum[index] = result.studentScores[index].Sum();
- //bool flag = result.studentScores[index].Exists(r => r == -1);
- /*if (!flag)
- {
- if (s.type == 1)
- {
- try
- {
- //StuActivity activity = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{s.id}"));
- //activity.sStatus = 1;
- //tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_option.Location}\n{ex.Message}\n{ex.StackTrace}\n\n,id:{id},code:{s.id},school:{result?.school}", GroupNames.醍摩豆服務運維群組);
- }
- }
- else
- {
- try
- {
- var response = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Activity-{result.school}-{s.id}"));
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- //StuActivity activity = json.ToObject<StuActivity>();
- //activity.sStatus = 1;
- //tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
- }
- else
- {
- List<string> scode = new();
- 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'"))
- {
- using var stuJson = await JsonDocument.ParseAsync(item.Content);
- if (stuJson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = stuJson.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- scode.Add(account.GetProperty("schoolId").GetString());
- }
- }
- }
- foreach (var sid in scode)
- {
- //StuActivity activity = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(id.ToString(), new PartitionKey($"Activity-{sid}-{s.id}"));
- //activity.sStatus = 1;
- //tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, activity.id, new PartitionKey($"{activity.code}")));
- }
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_option.Location}\n{ex.Message}\n{ex.StackTrace}\n\n,id:{id},code:{s.id},school:{result?.school}", GroupNames.醍摩豆服務運維群組);
- }
- }
- }*/
- index_sc++;
- }
- if (!result.progress)
- {
- bool flag = true;
- foreach (List<double> scores in result.studentScores)
- {
- foreach (double score in scores)
- {
- if (score == -1)
- {
- flag = false;
- break;
- }
- }
- }
- if (flag)
- {
- ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- result.progress = true;
- exam.subjects.ForEach(s =>
- {
- if (s.id.Equals(subjectId.ToString()))
- {
- s.classCount += 1;
- }
- });
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
- //若為統測評量,紀錄修改分數內容
- if (!string.IsNullOrWhiteSpace(exam.jointExamId)) await upsertExamClassResultMark(result, userid, username, sIds, ans);
- }
- }
- else
- {
- ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- exam.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{code}"));
- //若為統測評量,紀錄修改分數內容
- if (!string.IsNullOrWhiteSpace(exam.jointExamId)) await upsertExamClassResultMark(result, userid, username, sIds, ans);
- }
- classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
- // await Task.WhenAll(tasks);
- }
- //检查所有成员是否完成打分
- List<List<double>> ers = new List<List<double>>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
- queryText: $"select c.studentScores as scores from c where c.examId = '{id}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- List<List<double>> sc = account.GetProperty("scores").ToObject<List<List<double>>>();
- ers.AddRange(sc);
- }
- }
- }
- var isScore = !ers.Exists(c => c.Contains(-1));
- return Ok(new { classResult, isScore });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecordByTeacher()\n{ex.StackTrace}\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- /*if (exams.IsNotEmpty())
- {
- ExamInfo examInfo = exams[0];
- //提交答案时间必须是状态已发布,且时间在起止时间内
- if (examInfo.startTime <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && examInfo.status == 200 &&
- examInfo.endTime >= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
- {
- return builder.Data(await _azureCosmos.SaveOrUpdate(request)).build();
- }
- else
- {
- return builder.Error(ResponseCode.FAILED, "请在作答时间段内提交答案!").build();
- }
- }
- else
- {
- return builder.Error(ResponseCode.DATA_EXIST, "考试不存在!").build();
- }*/
- }
- /// <summary>
- /// 查询评测详细信息(教师或者学生通用)
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-summary-record")]
- public async Task<IActionResult> findSummaryRecord(JsonElement request)
- {
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //if (!request.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
- if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
- if (!request.TryGetProperty("startTime", out JsonElement startTime)) return BadRequest();
- try
- {
- /* var data = new
- {
- examCode = 2001717656163218,
- subjects = new List<string> {"语文"}
- };
- var info = await ThirdService.CreateMoofenExamResult(_httpClient, data.ToJsonString().ToObject<JsonElement>(), _dingDing);*/
- // 如果只有学生id则返回学生参加过的考试 只返回相关摘要信息
- var client = _azureCosmos.GetCosmosClient();
- var (_, _, _, school) = HttpContext.GetAuthTokenInfo();
- //string code = school_code.ToString().Substring(5);
- //ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{school_code}"));
- Dictionary<string, List<string>> examClassResultCodeIdDic = new Dictionary<string, List<string>>(); //examClassResult code對應ID表 ※取得閱卷變更結果用
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- 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}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school_code}") }))
- {
- examClassResults.Add(item);
- }
- List<string> ids = new();
- //List<string> codes = new();
- foreach (ExamClassResult result in examClassResults)
- {
- ids.AddRange(result.studentIds);
- //codes.AddRange(result.scIds);
- if(!examClassResultCodeIdDic.ContainsKey(result.code)) examClassResultCodeIdDic.Add(result.code, new List<string>() { result.id });
- else if (!examClassResultCodeIdDic[result.code].Contains(result.id)) examClassResultCodeIdDic[result.code].Add(result.id);
- }
- List<string> cid = new()
- {
- classId.GetString()
- };
- (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, cid, $"{school}", null, -1, startTime.GetInt64());
- //await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<GroupList>(classId.GetString, new PartitionKey($"Exam-{code}"));
- ///获取真实的名称
- List<ufo> ufos = new();
- List<string> delIds = new();
- if (groups.Count > 0)
- {
- //string scode = groups[0].school;
- if (ids.Count > 0)
- {
- List<string> sIds = members.Where(c => c.type == 2).Select(z => z.id).ToList();
- List<string> tIds = members.Where(c => c.type == 1).Select(z => z.id).ToList();
- List<string> pIds = members.Where(c => c.type == 3).Select(z => z.id).ToList(); //簡易課程名單成員
- List<ufo> students = new List<ufo>();
- if (tIds.Any())
- {
- var tmds = ids.Intersect(tIds).ToList();
- delIds.AddRange(ids.Except(tIds).ToList());
- if (tmds.Any())
- {
- var content = new StringContent(tmds.ToJsonString(), Encoding.UTF8, "application/json");
- string json = await _coreAPIHttpService.GetUserInfos(content);
- if (!string.IsNullOrWhiteSpace(json))
- {
- try
- {
- List<ufo> tmdInfos = json.ToObject<List<ufo>>();
- if (tmdInfos.IsNotEmpty())
- {
- foreach (ufo fo in tmdInfos)
- {
- fo.type = 1;
- fo.no = members.Where(m => m.type == 1 && m.id.Equals(fo.id)).FirstOrDefault().no;
- }
- ufos.AddRange(tmdInfos);
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n ", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- }
- if (sIds.Any())
- {
- var stus = ids.Intersect(sIds).ToList();
- delIds.AddRange(ids.Except(sIds).ToList());
- if (stus.Any())
- {
- 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'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{school}") }))
- {
- using var stuJson = await JsonDocument.ParseAsync(item.Content);
- if (stuJson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = stuJson.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- ufo fo = new()
- {
- id = account.GetProperty("id").GetString(),
- name = account.GetProperty("name").GetString(),
- //schoolId = account.GetProperty("schoolId").GetString(),
- type = 2,
- no = account.GetProperty("no").GetString()
- };
- students.Add(fo);
- }
- }
- }
- ufos.AddRange(students);
- }
- }
- if (pIds.Any()) //簡易課程名單處理
- {
- var ptus = ids.Intersect(pIds).ToList();
- if (ptus.Any())
- {
- List<RMember> simples = members.Where(c => ptus.Contains(c.id)).ToList();
- foreach(RMember simple in simples)
- {
- ufos.Add(new ufo()
- {
- id = simple.id,
- name = (!string.IsNullOrWhiteSpace(simple.name)) ? simple.name : (!string.IsNullOrWhiteSpace(simple.nickname)) ? simple.nickname : "",
- type = simple.type,
- no = simple.no
- });
- }
- }
- }
- }
- }
- //List<ufo> students = new List<ufo>();
- /*if (StringHelper.getKeyCount(request) == 1 && request.TryGetProperty("code", out JsonElement code))
- {
- List<object> props = new List<object>();
- 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}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- props.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(new { props });
- }
- else
- {
- if (request.TryGetProperty("examCode", out JsonElement _))
- {
- //List<string> props = new List<string> { "id", "code", "examCode", "status", "mark", "score" };
- //List<ExamRecord> examRecords = await _azureCosmos.FindByDict<ExamRecord>(request, props);
- //return builder.Data(examRecords).Extend(new Dictionary<string, object> { { "props", props } }).build();
- List<object> props = new List<object>();
- 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}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- props.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(new { props });
- }
- }*/
- //取得教師批改紀錄 ※目前只有統測評量有紀錄
- List<ExamClassResultMark> markResult = new List<ExamClassResultMark>();
- foreach(KeyValuePair<string, List<string>> seed in examClassResultCodeIdDic) {
- string code = seed.Key.Replace("ExamClassResult", "ExamClassResultMark");
- List<string> idList = seed.Value;
- 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'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- markResult.Add(obj.ToObject<ExamClassResultMark>());
- }
- }
- }
- }
- return Ok(new { examClassResults, ufos, delIds, markResult });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findSummaryRecord()\n{ex.Message}\n{ex.StackTrace}\n\n{id.GetString()}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 查询複數评测详细信息(教师用)
- /// </summary>
- /// <param name="request"></param>find-summary-record
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-summary-records")]
- public async Task<IActionResult> findSummaryRecords(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("data", out JsonElement data)) return BadRequest();
- List<FindExamClassResultsReqParam> requestParams = data.ToObject<List<FindExamClassResultsReqParam>>();
- var client = _azureCosmos.GetCosmosClient();
- //取得評量結果
- 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' ");
- StringBuilder sqlExamWhere = new StringBuilder();
- foreach (FindExamClassResultsReqParam param in requestParams)
- {
- if(!sqlExamWhere.Length.Equals(0))
- {
- sqlExamWhere.Append(" OR ");
- }
- sqlExamWhere.Append($" c.examId = '{param.examId}' ");
- }
- sqlExam.Append(" AND ( ");
- sqlExam.Append(sqlExamWhere);
- sqlExam.Append(" ) ");
- List<ExamResult> examResults = new List<ExamResult>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamResult>(queryText: sqlExam.ToString(), requestOptions: null))
- {
- examResults.Add(item);
- }
- //取得作答結果
- 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 ");
- StringBuilder sqlClassResultWhere = new StringBuilder();
- foreach (FindExamClassResultsReqParam param in requestParams)
- {
- if(!sqlClassResultWhere.Length.Equals(0))
- {
- sqlClassResultWhere.Append(" OR ");
- }
- sqlClassResultWhere.Append($"( c.code = 'ExamClassResult-{param.creatorId}' ");
- sqlClassResultWhere.Append($" AND c.examId = '{param.examId}' ");
- sqlClassResultWhere.Append($" AND c.subjectId = '{param.subjectId}' ");
- sqlClassResultWhere.Append($" AND c.info.id = '{param.groupListId}' )");
- }
- sqlClassResult.Append(sqlClassResultWhere);
- List<string> ids = new(); //學生ID
- Dictionary<string, List<string>> examClassResultSchoolGroupDic = new Dictionary<string, List<string>>(); //examClassResult 學校ID=>班級ID對應表 ※成員訊息用
- Dictionary<string, List<string>> examClassResultCodeIdDic = new Dictionary<string, List<string>>(); //examClassResult code對應ID表 ※取得閱卷變更結果用
- List<ExamClassResult> examClassResults = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(queryText: sqlClassResult.ToString(), requestOptions: null ))
- {
- examClassResults.Add(item);
- ids.AddRange(item.studentIds);
- //code =>ID 對應表
- if (!examClassResultCodeIdDic.ContainsKey(item.code)) examClassResultCodeIdDic.Add(item.code, new List<string>() { item.id });
- else if (!examClassResultCodeIdDic[item.code].Contains(item.id)) examClassResultCodeIdDic[item.code].Add(item.id);
- //學校ID=>班級ID對應表
- string sid = (!string.IsNullOrWhiteSpace(item.school)) ? item.school : string.Empty;
- if (!examClassResultSchoolGroupDic.ContainsKey(sid)) examClassResultSchoolGroupDic.Add(sid, new List<string>() { item.info.id });
- else if (!examClassResultSchoolGroupDic[sid].Contains(item.info.id)) examClassResultSchoolGroupDic[sid].Add(item.info.id);
- }
- //取得成員名單
- List<RMember> members = new List<RMember>();
- List<RGroupList> groups = new List<RGroupList>();
- foreach (KeyValuePair<string, List<string>> item in examClassResultSchoolGroupDic)
- {
- string schId = item.Key;
- List<string> cids = item.Value;
- (List<RMember> member, List<RGroupList> group) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, cids, $"{schId}", null);
- members.AddRange(member);
- groups.AddRange(group);
- }
- members = members.Distinct().ToList();
- groups = groups.Distinct().ToList();
- ///获取真实的名称
- List<ufo> ufos = new();
- List<string> delIds = new();
- if (groups.Count > 0)
- {
- if (ids.Count > 0)
- {
- var sSchIds = members.Where(c => c.type == 2).Select(z => new { z.id, z.schoolId }).ToList();
- Dictionary<string, List<string>> SchIdDic = new Dictionary<string, List<string>>(); //學校ID => TMID 字典
- foreach(var schId in sSchIds)
- {
- string sch = schId.schoolId;
- string tmid = schId.id;
- if(SchIdDic.ContainsKey(sch))
- {
- if (!SchIdDic[sch].Contains(tmid))
- {
- SchIdDic[sch].Add(tmid);
- }
- }
- else
- {
- SchIdDic.Add(sch, new List<string>() { tmid });
- }
- }
- List<string> sIds = sSchIds.Select(z => z.id).ToList();
- List<string> tIds = members.Where(c => c.type == 1).Select(z => z.id).ToList();
- List<string> pIds = members.Where(c => c.type == 3).Select(z => z.id).ToList(); //簡易課程名單成員
- List<ufo> students = new List<ufo>();
- if (tIds.Any())
- {
- var tmds = ids.Intersect(tIds).ToList();
- if (tmds.Any())
- {
- var content = new StringContent(tmds.ToJsonString(), Encoding.UTF8, "application/json");
- string json = await _coreAPIHttpService.GetUserInfos(content);
- if (!string.IsNullOrWhiteSpace(json))
- {
- try
- {
- List<ufo> tmdInfos = json.ToObject<List<ufo>>();
- if (tmdInfos.IsNotEmpty())
- {
- foreach (ufo fo in tmdInfos)
- {
- fo.type = 1;
- }
- ufos.AddRange(tmdInfos);
- }
- }
- catch (Exception ex)
- {
- //await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location}用户转换失败:{_coreAPIHttpService.options.coreUrl}{json}\n ", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- }
- if (sIds.Any())
- {
- var stus = ids.Intersect(sIds).ToList();
- if (stus.Any())
- {
- foreach(KeyValuePair<string, List<string>> ipare in SchIdDic)
- {
- string schId = ipare.Key;
- List<string> stuIds = ipare.Value;
- 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}") }))
- {
- using var stuJson = await JsonDocument.ParseAsync(item.Content);
- if (stuJson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = stuJson.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- ufo fo = new()
- {
- id = account.GetProperty("id").GetString(),
- name = account.GetProperty("name").GetString(),
- //schoolId = account.GetProperty("schoolId").GetString(),
- type = 2
- };
- students.Add(fo);
- }
- }
- }
- }
- ufos.AddRange(students);
- }
- }
- if (pIds.Any()) //簡易課程名單處理
- {
- var ptus = ids.Intersect(pIds).ToList();
- if (ptus.Any())
- {
- List<RMember> simples = members.Where(c => ptus.Contains(c.id)).ToList();
- foreach (RMember simple in simples)
- {
- ufos.Add(new ufo()
- {
- id = simple.id,
- name = (!string.IsNullOrWhiteSpace(simple.name)) ? simple.name : (!string.IsNullOrWhiteSpace(simple.nickname)) ? simple.nickname : "",
- type = simple.type
- });
- }
- }
- }
- }
- }
- //取得教師批改紀錄 ※目前只有統測評量有紀錄
- List<ExamClassResultMark> markResult = new List<ExamClassResultMark>();
- foreach (KeyValuePair<string, List<string>> seed in examClassResultCodeIdDic)
- {
- string code = seed.Key.Replace("ExamClassResult", "ExamClassResultMark");
- List<string> idList = seed.Value;
- 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'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- markResult.Add(obj.ToObject<ExamClassResultMark>());
- }
- }
- }
- }
- return Ok(new { examResults, examClassResults, ufos, delIds, markResult });
- }
- catch (Exception ex)
- {
- //await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findSummaryRecord()\n{ex.Message}\n{ex.StackTrace}\n\n{id.GetString()}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //学生端查询评测列表
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student,teacher,admin")]
- [HttpPost("find-summary-by-student")]
- public async Task<IActionResult> findSummaryStudent(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //if (!request.TryGetProperty("cIds", out JsonElement cIds)) return BadRequest();
- if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement school)) return BadRequest();
- if (!request.TryGetProperty("scode", out JsonElement scode)) return BadRequest();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- //var query = $"select value(c) where c.id ='{id}'";
- //List<ExamInfo> exams = new List<ExamInfo>();
- List<object> subjects = new List<object>();
- List<string> classIds = new List<string>();
- //List<string> stus = new List<string>();
- //存放当前学生所在班级ID或者名单ID
- /*HashSet<string> resultIds = new();
- //List<string> ids = new List<string>();
- //处理班级人数(公共部分的校本名单)
- //List<Student> students = new List<Student>();
- 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}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- resultIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- //获取自定义名单信息
- List<GroupList> stuLists = new List<GroupList>();
- 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}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
- {
- stuLists.Add(item);
- }
- 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}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
- {
- stuLists.Add(item);
- }
- if (stuLists.Count > 0)
- {
- foreach (GroupList stuList in stuLists)
- {
- resultIds.Add(stuList.id);
- }
- }
- var queryClassId = $"select c.classes id,c.stuLists stus from c where c.id ='{id}'";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: queryClassId, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- classIds.AddRange(obj.GetProperty("id").ToObject<List<string>>());
- classIds.AddRange(obj.GetProperty("stus").ToObject<List<string>>());
- //classIds = obj.ToObject<List<string>>();
- }
- }
- }
- //存放该学生所在班级参与当前评测的ID
- List<string> infoIds = new List<string>();
- foreach (string ids in resultIds)
- {
- if (classIds.Contains(ids))
- {
- infoIds.Add(ids);
- }
- }*/
- //List<string> infoIds = cIds.ToObject<List<string>>();
- List<string> infoIds = new();
- ExamInfo info = new();
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{scode}"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(response.Content);
- info = cJson.ToObject<ExamInfo>();
- }
- /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamInfo>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
- {
- exams.Add(item);
- }*/
- var querySubject = $"select A0.id,A0.name from c join A0 in c.subjects where c.id ='{id}'";
- //List<object> props = new List<object>();
- List<string> subId = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: querySubject, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{scode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- subjects.Add(obj.ToObject<object>());
- subId.Add(obj.GetProperty("id").GetString());
- }
- }
- }
- 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' ";
- List<ExamClassResult> answers = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: queryAnswers,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- answers.Add(obj.ToObject<ExamClassResult>());
- infoIds.Add(obj.GetProperty("cId").GetString());
- }
- }
- }
- 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' ";
- List<ExamClassResult> classResults = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(queryText: queryResult,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
- {
- classResults.Add(item);
- }
- //查询结果
- List<ExamResult> results = new();
- 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}") }))
- {
- results.Add(item);
- }
- List<List<string>> stuAns = new();
- List<List<double>> stuScore = new();
- List<List<List<Details>>> mark = new();
- List<List<double>> total = new();
- List<double> average = new();
- if (answers.Count > 0)
- {
- foreach (ExamClassResult result in answers)
- {
- List<double> sTotal = new();
- int index = result.studentIds.IndexOf(studentId.ToString());
- if (index == -1)
- {
- break;
- }
- stuAns.Add(result.studentAnswers[index]);
- stuScore.Add(result.studentScores[index]);
- mark.Add(result.mark[index]);
- average.Add(result.average);
- sTotal.Add(result.sum.Where(s => s <= 59).Count());
- sTotal.Add(result.sum.Where(s => s > 59 && s <= 70).Count());
- sTotal.Add(result.sum.Where(s => s > 70 && s <= 80).Count());
- sTotal.Add(result.sum.Where(s => s > 80 && s <= 90).Count());
- sTotal.Add(result.sum.Where(s => s > 90 && s <= 100).Count());
- total.Add(sTotal);
- }
- }
- List<(List<string> kn, List<double> kps, List<double> ckps, List<double> akps)> know = new();
- List<(List<int> fs, List<double> fps, List<double> cfps, List<double> afps)> fp = new();
- List<List<double>> wno = new();
- List<KeyValuePair<string, List<KeyValuePair<string, Dictionary<string, string>>>>> subjectScatter = new();
- if (!string.IsNullOrEmpty(info.progress) && info.progress.Equals("finish"))
- {
- (List<RMember> members, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, infoIds, info.school, null, -1, info.startTime);
- await foreach (var s in stuTask(subId, info.papers, answers, classResults, studentId.GetString()))
- {
- know = s.know;
- fp = s.filed;
- }
- foreach (ExamResult exam in results)
- {
- subjectScatter.Add(DoSubjectScatter(exam, members));
- //确定当前循环科目索引位置
- int index = subId.IndexOf(exam.subjectId);
- //根据索引找到试卷分数
- List<double> points = info.papers[index].point;
- List<double> wn = await getWrongNum(exam, points, infoIds);
- wno.Add(wn);
- }
- if (info.papers.IsNotEmpty())
- {
- var knowledge = know.Select(k => new { k.kn, k.kps, k.ckps, k.akps });
- var filed = fp.Select(k => new { k.fs, k.fps, k.cfps, k.afps });
- //papers = papers
- return Ok(new { info.cloudas, info.papers, subjects, stuScore, stuAns, mark, total, claId = infoIds, knowledge, filed, average, wno, subjectScatter, status = 200 });
- }
- }
- 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 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-summary-by-student()\n{ex.Message}\n{ex.StackTrace}\n\n{id.GetString()}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- 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)
- {
- 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)>();
- 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)>();
- int no = 0;
- foreach (string sub in subjectIds)
- {
- List<double> kp = new();
- List<double> akp = new();
- List<double> fp = new();
- List<double> afp = new();
- List<double> ckp = new();
- List<double> cfp = new();
- List<int> fields = new() { 1, 2, 3, 4, 5, 6 };
- //获取该试卷所有知识点和认知层次分布
- List<List<string>> kones = papers[no].knowledge;
- List<int> fs = papers[no].field;
- List<double> point = papers[no].point;
- //去重知识点
- HashSet<string> knowles = new();
- List<string> knowledges = new();
- if (kones.Count > 0)
- {
- knowles = new HashSet<string>(kones.SelectMany(z => z));
- }
- knowledges.AddRange(knowles.Where(z => !string.IsNullOrWhiteSpace(z)));
- List<ExamClassResult> classResults = answers.Where(result => !string.IsNullOrWhiteSpace(result?.subjectId) && result.subjectId.Equals(sub)).ToList();
- List<ExamClassResult> allResults = results.Where(result => !string.IsNullOrWhiteSpace(result?.subjectId) && result.subjectId.Equals(sub)).ToList();
- foreach (ExamClassResult result in classResults)
- {
- int index = result.studentIds.IndexOf(stuId.ToString());
- //处理知识点
- foreach (string k in knowledges)
- {
- //初始化单个知识点得分
- double score = 0;
- double allScore = 0;
- int n = 0;
- foreach (List<string> str in kones)
- {
- if (str.Contains(k))
- {
- var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
- allScore += point.Count > 0 ? point[n] * itemPersent : 0;
- if (result.studentScores.Count > 0)
- {
- if (result.studentScores[index].Count > 0)
- {
- score += result.studentScores[index][n] == -1 ? 0 : result.studentScores[index][n] * itemPersent;
- }
- }
- }
- n++;
- }
- kp.Add(allScore > 0 ? Math.Round(score / allScore, 2) : 0);
- }
- //处理认知层次
- foreach (int k in fields)
- {
- //初始化认知层次得分
- double score = 0;
- double allScore = 0;
- int n = 0;
- foreach (int str in fs)
- {
- if (str == k)
- {
- var itemPersent = 1;
- allScore += point.Count > 0 ? point[n] * itemPersent : 0;
- if (result.studentScores.Count > 0)
- {
- if (result.studentScores[index].Count > 0)
- {
- score += result.studentScores[index][n] == -1 ? 0 : result.studentScores[index][n];
- }
- }
- }
- n++;
- }
- fp.Add(allScore > 0 ? Math.Round(score / allScore, 2) : 0);
- }
- ckp = result.krate;
- cfp = result.frate;
- }
- foreach (string k in knowledges)
- {
- double score = 0;
- double allScore = 0;
- int count = 0;
- foreach (ExamClassResult result in allResults)
- {
- int n = 0;
- foreach (List<string> str in kones)
- {
- if (str.Contains(k))
- {
- var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0;
- allScore += point.Count > 0 ? point[n] * itemPersent : 0;
- if (result.studentScores.Count > 0)
- {
- /*score += result.studentScores.ForEach(r => r[n]) * itemPersent;*/
- foreach (List<double> sc in result.studentScores)
- {
- double tsc = sc[n] == -1 ? 0 : sc[n];
- score += tsc * itemPersent;
- }
- }
- }
- n++;
- }
- count += result.studentIds.Count;
- }
- double per = count > 0 ? Math.Round(score / count, 2) : 0;
- akp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
- }
- //处理认知层次
- foreach (int k in fields)
- {
- //初始化认知层次得分
- double score = 0;
- double allScore = 0;
- int count = 0;
- foreach (ExamClassResult result in allResults)
- {
- if (result.subjectId.Equals(sub))
- {
- int n = 0;
- foreach (int str in fs)
- {
- if (str == k)
- {
- var itemPersent = 1;
- allScore += point.Count > 0 ? point[n] * itemPersent : 0;
- if (result.studentScores.Count > 0)
- {
- foreach (List<double> sc in result.studentScores)
- {
- double tsc = sc[n] == -1 ? 0 : sc[n];
- score += tsc * itemPersent;
- }
- }
- }
- n++;
- }
- count += result.studentIds.Count;
- }
- }
- double per = count > 0 ? Math.Round(score / count, 2) : 0;
- afp.Add(allScore > 0 ? Math.Round(per / allScore, 2) : 0);
- }
- know.Add((knowledges, kp, ckp, akp));
- filed.Add((fields, fp, cfp, afp));
- no++;
- }
- yield return (know, filed);
- }
- private KeyValuePair<string, List<KeyValuePair<string, Dictionary<string, string>>>> DoSubjectScatter(ExamResult e, List<RMember> members)
- {
- List<KeyValuePair<string, Dictionary<string, string>>> datas = new();
- double[] point = StringHelper.ListTodouble(e.paper.point);
- double[,] result = StringHelper.ListToDouble(e.studentScores);
- List<string> scatterKey = new List<string>
- {
- "name",
- "className",
- "x",
- "y",
- "memberId",
- "score",
- "trueNum",
- "falseNum",
- "hardList",
- "carefulList",
- "scatter"
- };
- try
- {
- var cdm = new ClouDASMatrix(result, point);
- //学生通过率
- List<double> pass = cdm.ScoringRate;
- //学生稳定度
- List<double> sta = cdm.StabilityRate;
- //落点区域
- List<string> stu = cdm.StuFallArea;
- //需努力的题型
- List<int[]> strive = cdm.StriveTopic;
- //需小心的题型
- List<int[]> careful = cdm.CarefulTopic;
- int i = 0;
- for (int k = e.studentIds.Count - 1; k >= 0; k--)
- {
- if (e.studentIds[k].Equals("0"))
- {
- e.studentIds.Remove(e.studentIds[k]);
- }
- }
- e.studentIds.ForEach(s =>
- {
- List<string> info = new()
- {
- members.Where(c => c.id.Equals(s)).FirstOrDefault()?.name,
- "-",
- sta[i] > 1 ? "1": sta[i].ToString(),
- pass[i].ToString(),
- i + 1 + "",
- Math.Round(e.studentScores[i].Sum(),2).ToString()
- };
- int right = 0;
- int wrong = 0;
- foreach (double p in e.studentScores[i])
- {
- if (p > 0)
- {
- right++;
- }
- else
- {
- wrong++;
- }
- }
- info.Add(right + "");
- info.Add(wrong + "");
- int[] str = strive[i];
- string striveAll = "";
- foreach (int n in str)
- {
- striveAll += n.ToString() + ",";
- }
- int[] care = careful[i];
- string careAll = "";
- foreach (int n in care)
- {
- careAll += n.ToString() + ",";
- }
- if (string.IsNullOrEmpty(striveAll))
- {
- info.Add("-");
- }
- else
- {
- info.Add(striveAll.Substring(0, striveAll.Length - 1));
- }
- if (string.IsNullOrEmpty(careAll))
- {
- info.Add("-");
- }
- else
- {
- info.Add(careAll.Substring(0, careAll.Length - 1)); ;
- }
- info.Add(stu[i].ToString());
- int m = 0;
- Dictionary<string, string> scatter = new();
- foreach (string key in info)
- {
- scatter.Add(scatterKey[m], key);
- m++;
- }
- KeyValuePair<string, Dictionary<string, string>> keyValue = new(s, scatter);
- datas.Add(keyValue);
- //}
- i++;
- });
- return new KeyValuePair<string, List<KeyValuePair<string, Dictionary<string, string>>>>(e.subjectId, datas);
- }
- catch (Exception ex)
- {
- BadRequest(ex.Message + ex.StackTrace);
- }
- return default;
- }
- //查询学生活动列表
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student")]
- [HttpPost("find-all-by-student")]
- public async Task<IActionResult> findAllStudent(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
- List<string> resultIds = new List<string>();
- var client = _azureCosmos.GetCosmosClient();
- //查询校本班级ID
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(
- queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- resultIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- //查询私人班级ID
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(
- queryText: $"select c.id from c join A0 in c.students where A0.id = '{studentId}' and c.pk = 'Class' "))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- resultIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- //StringBuilder builder = new StringBuilder();
- HashSet<string> strs = new HashSet<string>();
- if (resultIds.Count > 1)
- {
- foreach (string str in resultIds)
- {
- strs.Add($"array_contains(c.classes,'{str}')");
- //builder.Append($"array_contains(c.targetClassIds,'{str}')").Append("or");
- }
- //builder.ToString().Substring(0, builder.ToString().Length - 2);
- }
- else
- {
- string ssr = resultIds.Count > 0 ? resultIds[0] : "";
- strs.Add($"array_contains(c.classes,'{ssr}')");
- //builder.Append($" array_contains(c.targetClassIds,'{ssr}')");
- }
- string ss = string.Join(" or ", strs);
- //if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
- 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' ";
- List<object> props = new List<object>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: query))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- props.Add(obj.ToObject<object>());
- }
- }
- }
- 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'";
- List<ExamClassResult> Classes = new List<ExamClassResult>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: queryClass))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- Classes.Add(obj.ToObject<ExamClassResult>());
- }
- }
- }
- List<ExamClassResult> result = new List<ExamClassResult>();
- foreach (ExamClassResult classResult in Classes)
- {
- int index = classResult.studentIds.IndexOf(studentId.ToString());
- ExamClassResult result1 = new ExamClassResult();
- result1.examId = classResult.examId;
- result1.subjectId = classResult.subjectId;
- result1.studentAnswers.Add(classResult.studentAnswers[index]);
- result1.studentScores.Add(classResult.studentScores[index]);
- result.Add(result1);
- }
- return Ok(new { props, result });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- //查询学生活动列表
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student")]
- [HttpPost("find-score-by-student")]
- public async Task<IActionResult> findScoreByStudent(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var query = $"select c.examId,c.subjectId,c.studentScores from c where array_contains(c.studentIds,'{id}') ";
- List<object> props = new List<object>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: query))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- props.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(props);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findAllStudent\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- //查询学生活动列表
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("finish")]
- public async Task<IActionResult> finish(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- info.progress = "finish";
- info.endTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- List<ExamClassResult> classResults = new();
- if (info.scope.Equals("school"))
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
- {
- classResults.Add(item);
- }
- }
- else
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
- {
- classResults.Add(item);
- }
- }
- foreach (ExamClassResult examClass in classResults)
- {
- examClass.progress = true;
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(examClass, examClass.id, new PartitionKey($"{examClass.code}"));
- }
- info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
- return Ok(info);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/finish\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- /*//查询任务列表
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Student")]
- [HttpPost("scoring")]
- public async Task<IActionResult> Scoring(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- int index = 0;
- foreach (ExamSubject subject in info.subjects) {
- if (!subject.id.Equals(subjectId.ToString()))
- {
- index++;
- }
- else {
- break;
- }
- }
- List<string> stuAns = new();
- Dictionary<string, List<List<double>>> keyValues = new();
- List<ExamClassResult> classResults = new();
- if (info.scope.Equals("school"))
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.school}") }))
- {
- classResults.Add(item);
- }
- }
- else
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{info.creatorId}") }))
- {
- classResults.Add(item);
- }
- }
- List<List<double>> itemScore = new();
- for (int i = 0; i < info.papers[index].point.Count; i++)
- {
- List<double> score = new();
- foreach (ExamClassResult examClass in classResults)
- {
- foreach (List<double> sc in examClass.studentScores)
- {
- score.Add(sc[i]);
- }
- }
- itemScore.Add(score);
- }
- foreach (ExamClassResult examClass in classResults)
- {
- foreach (List<string> ans in examClass.studentAnswers)
- {
- if (ans.Count > 0)
- {
- stuAns.Add(ans[0]);
- }
- else
- {
- stuAns.Add("");
- }
- }
- }
- //info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"Exam-{code}"));
- return Ok(new { score = itemScore , stuAns, paper = info.papers });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }*/
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("scoring")]
- public async Task<IActionResult> scoring(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- //if (!request.TryGetProperty("type", out JsonElement type)) return BadRequest();
- if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- if (!request.TryGetProperty("count", out JsonElement scount)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- //var redisClient = _azureRedis.GetRedisClient(8);
- ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- List<ExamClassResult> classResults = new();
- List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and array_contains(c.tIds,'{tId}') ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }
- List<SDK.Models.Cosmos.Common.Scoring> attrSc = new List<SDK.Models.Cosmos.Common.Scoring>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attrSc.Add(item);
- }
- int index = 0;
- foreach (ExamSubject subject in info.subjects)
- {
- if (!subject.id.Equals(subjectId.ToString()))
- {
- index++;
- }
- else
- {
- break;
- }
- }
- List<dynamic> objs = new List<dynamic>();
- List<dynamic> wobjs = new List<dynamic>();
- /*if (type.GetInt32() != 1) {
- return Ok(new { attr, paper = info.papers[index].blob });
- }*/
- //List<SDK.Models.Cosmos.Common.Scoring> errs = new();
- //List<SDK.Models.Cosmos.Common.Scoring> arbs = new();
- Correct correct = null;
- var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
- if (cResponse.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(cResponse.Content);
- correct = cJson.ToObject<Correct>();
- }
- int finishCount = 0;
- attrSc = [.. attrSc.OrderBy(c => c.stuId)];
- foreach (SDK.Models.Cosmos.Common.Scoring ss in attrSc)
- {
- for (int i = 0; i < correct.num; i++)
- {
- List<double> tsc = new List<double>();
- foreach (Item item in ss.items)
- {
- if (item.scores.Count > 0)
- {
- if (i >= item.scores.Count)
- {
- break;
- }
- else
- {
- tsc.Add(item.scores[i].sc);
- }
- }
- }
- bool flag = tsc.Exists(s => s == -1);
- if (!flag && tsc.Count > 0)
- {
- finishCount++;
- }
- }
- }
- if (attr.Count > 0)
- {
- attr = [.. attr.OrderBy(c => c.stuId)];
- foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
- {
- //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});
- List<dynamic> sc = new List<dynamic>();
- List<dynamic> allSc = new List<dynamic>();
- ss.qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
- int indexScore = 0;
- (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code.GetString());
- foreach (Item item in ss.items)
- {
- var count = item.scores.GroupBy(i => new { i.tmdId, i.sc }).Select(c => c.Key.sc).ToList();
- allSc.Add(count.FirstOrDefault());
- List<double> scc = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).ToList();
- List<string> blob = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.mark).ToList();
- //item.scores.Where(x => x.tmdId.Equals(tId.GetString())).SelectMany(p => p.sc, (p, d) => new { });
- if (scc.Count > 0)
- {
- sc.Add(new { sc = scc.FirstOrDefault(), blob = blob.FirstOrDefault(), item.ssc });
- }
- else
- {
- ss.scores = scores;
- sc.Add(new { sc = ss.scores[indexScore], blob = "", item.ssc });
- }
- indexScore++;
- }
- 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 };
- objs.Add(obj);
- }
- }
- else
- {
- if (request.TryGetProperty("stuId", out JsonElement stuId))
- {
- objs = await Review(attrSc, id.GetString(), code.GetString(), subjectId.GetString(), scount.GetInt32(), tId.GetString(), stuId.GetString());
- }
- else
- {
- objs = await Review(attrSc, id.GetString(), code.GetString(), subjectId.GetString(), scount.GetInt32(), tId.GetString(), "");
- }
- }
- var fp = attr.Count > 0 ? Math.Round(finishCount * 1.0 / (attrSc.Count * correct.num), 2) : 0;
- return Ok(new { objs, paper = info.papers[index].blob, fp });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/scoring\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- //查找异常卷
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-err")]
- public async Task<IActionResult> findErr(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- //if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- ExamInfo info = json.ToObject<ExamInfo>();
- //ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- List<ExamClassResult> classResults = new();
- List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }
- int index = 0;
- foreach (ExamSubject subject in info.subjects)
- {
- if (!subject.id.Equals(subjectId.ToString()))
- {
- index++;
- }
- else
- {
- break;
- }
- }
- List<dynamic> objs = new List<dynamic>();
- List<SDK.Models.Cosmos.Common.Scoring> errs = new();
- foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
- {
- List<Qs> qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.err)).ToList();
- if (qs.Count > 0)
- {
- ss.qs = qs;
- errs.Add(ss);
- }
- }
- return Ok(new { errs, paper = info.papers[index].blob });
- }
- else
- {
- return Ok(new { status = response.StatusCode });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-err\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-arb")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> findArb(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("et", out JsonElement et)) return BadRequest();
- //if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- long time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- if (et.GetInt64() > time)
- {
- return Ok(new { msg = "还在进行中", code = 202 });
- }
- ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{code}"));
- List<ExamClassResult> classResults = new();
- List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }
- int index = 0;
- foreach (ExamSubject subject in info.subjects)
- {
- if (!subject.id.Equals(subjectId.ToString()))
- {
- index++;
- }
- else
- {
- break;
- }
- }
- List<dynamic> objs = new List<dynamic>();
- /*if (type.GetInt32() != 1) {
- return Ok(new { attr, paper = info.papers[index].blob });
- }*/
- //List<SDK.Models.Cosmos.Common.Scoring> errs = new();
- List<SDK.Models.Cosmos.Common.Scoring> arbs = new();
- //List<(string id,List<double>)> osc = new List<(string id, List<double>)>();
- foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
- {
- //List<double> original = new List<double>();
- List<Item> arb = ss.items.Where(s => s.flag == false).ToList();
- (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code.GetString());
- ss.blob = ansBlob;
- ss.scores = scores;
- if (arb.Count > 0)
- {
- ss.items = arb;
- arbs.Add(ss);
- }
- }
- 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 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-arb\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- //批阅,给老师随机分配阅卷数据,以及查询改老师已有的阅卷数据
- 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)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- //var redisClient = _azureRedis.GetRedisClient(8);
- List<ExamClassResult> classResults = new();
- List<SDK.Models.Cosmos.Common.Scoring> recs = new();
- List<SDK.Models.Cosmos.Common.Scoring> all = new();
- //List<SDK.Models.Cosmos.Common.Scoring> attr = new();
- /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }*/
- foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
- {
- if (scoring.tIds.Contains(tId.ToString()))
- {
- recs.Add(scoring);
- }
- else if (scoring.tIds.Count < scoring.count * scoring.model)
- {
- all.Add(scoring);
- }
- }
- if (!string.IsNullOrEmpty(stuId))
- {
- List<SDK.Models.Cosmos.Common.Scoring> value = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.stuId = '{stuId}' ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- value.Add(item);
- }
- if (value.Count > 0)
- {
- foreach (SDK.Models.Cosmos.Common.Scoring scoring in value)
- {
- if (scoring.tIds.Contains(tId.ToString()))
- {
- break;
- }
- else
- {
- scoring.tIds.Add(tId.ToString());
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
- }
- }
- }
- List<dynamic> objs = new List<dynamic>();
- List<SDK.Models.Cosmos.Common.Scoring> val = new List<SDK.Models.Cosmos.Common.Scoring>();
- foreach (SDK.Models.Cosmos.Common.Scoring ss in value)
- {
- //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 });
- List<dynamic> sc = new List<dynamic>();
- int indexScore = 0;
- ss.qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
- (string ansBlob, List<double> scores) = await getMoreStuInfo(client, ss.stuId, ss.examId, ss.subjectId, code);
- foreach (Item item in ss.items)
- {
- List<double> scc = item.scores.Where(x => x.tmdId.Equals(tId)).Select(c => c.sc).ToList();
- //item.scores.Where(x => x.tmdId.Equals(tId.GetString())).SelectMany(p => p.sc, (p, d) => new { });
- if (scc.Count > 0)
- {
- sc.Add(new { sc = scc.FirstOrDefault(), item.ssc });
- }
- else
- {
- ss.scores = scores;
- sc.Add(new { sc = ss.scores[indexScore], item.ssc });
- }
- indexScore++;
- }
- 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 };
- objs.Add(obj);
- }
- return objs;
- }
- else
- {
- List<SDK.Models.Cosmos.Common.Scoring> notYet = new();
- notYet = all.Where(x => x.tIds.Count < x.count * x.model - 1).ToList();
- List<dynamic> objs = new List<dynamic>();
- for (int i = 0; i < count; i++)
- {
- Random random = new Random();
- SDK.Models.Cosmos.Common.Scoring item = new();
- if (notYet.Count > 0)
- {
- int index = random.Next(notYet.Count);
- item = notYet[index];
- notYet.RemoveAt(index);
- }
- else
- {
- int index = random.Next(all.Count);
- item = all[index];
- all.RemoveAt(index);
- }
- if (!item.tIds.Contains(tId.ToString()))
- {
- item.tIds.Add(tId.ToString());
- }
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
- List<dynamic> sc = new List<dynamic>();
- (string ansBlob, List<double> scores) = await getMoreStuInfo(client, item.stuId, item.examId, item.subjectId, code);
- int indexScore = 0;
- item.qs = item.qs.Where(s => !string.IsNullOrEmpty(s.tId)).ToList();
- foreach (Item its in item.items)
- {
- List<double> ssc = its.scores.Where(x => x.tmdId.Equals(tId)).Select(c => c.sc).ToList();
- if (ssc.Count > 0)
- {
- sc.Add(new { sc = ssc.FirstOrDefault(), its.ssc });
- }
- else
- {
- item.scores = scores;
- sc.Add(new { sc = item.scores[indexScore], its.ssc });
- }
- indexScore++;
- }
- 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 };
- objs.Add(obj);
- }
- return objs;
- /*if (recs.Count == count.GetInt32())
- {
- return Ok(new { msg = "分配人数已到上限" });
- }
- else
- {
- if (all.Count == 0)
- {
- return Ok(new { msg = "暂无可选学生" });
- }
- //随机选取一名学生打分
- Random random = new Random();
- SDK.Models.Cosmos.Common.Scoring item = new();
- List<SDK.Models.Cosmos.Common.Scoring> notYet = new();
- notYet = all.Where(x => x.tIds.Count < x.count * x.model - 1).ToList();
- if (notYet.Count > 0)
- {
- item = notYet[random.Next(notYet.Count)];
- }
- else
- {
- item = all[random.Next(all.Count)];
- }
- if (!item.tIds.Contains(tId.ToString()))
- {
- item.tIds.Add(tId.ToString());
- }
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
- List<dynamic> sc = new List<dynamic>();
- (string ansBlob, List<double> scores) = await getMoreStuInfo(client, item.stuId, item.examId, item.subjectId, code.GetString());
- int indexScore = 0;
- foreach (Item its in item.items)
- {
- List<double> ssc = its.scores.Where(x => x.tmdId.Equals(tId.GetString())).Select(c => c.sc).ToList();
- if (ssc.Count > 0)
- {
- sc.Add(new { sc = ssc.FirstOrDefault(), its.ssc });
- }
- else
- {
- item.scores = scores;
- sc.Add(new { sc = item.scores[indexScore], its.ssc });
- }
- indexScore++;
- }
- 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 };
- return Ok(obj);
- }*/
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/review\n", GroupNames.醍摩豆服務運維群組);
- return new List<dynamic>() { new { code = 404, msg = "分配任务异常" } };
- }
- }
- //批阅 提交分数
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("sub-result")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> SubResult(JsonElement request)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- if (!request.TryGetProperty("score", out JsonElement score)) return BadRequest();
- if (!request.TryGetProperty("count", out JsonElement count)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- request.TryGetProperty("mark", out JsonElement mark);
- var client = _azureCosmos.GetCosmosClient();
- var (userid, name, _, school) = HttpContext.GetAuthTokenInfo();
- //取得学校基本信息
- var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school.ToString(), new PartitionKey("Base"));
- string schname = string.Empty;
- if (schresponse.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var schjson = await JsonDocument.ParseAsync(schresponse.Content);
- schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
- schname = jsonschname.ToString();
- }
- List<ExamClassResult> classResults = new();
- List<SDK.Models.Cosmos.Common.Scoring> attr = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.stuId = '{sId}' and array_contains(c.tIds,'{tId}') ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }
- List<double> ssc = score.ToObject<List<double>>();
- List<string> marks = mark.ToObject<List<string>>();
- StringBuilder builder = new();
- if (attr.Count > 0)
- {
- foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
- {
- int itemIndex = 0;
- //int tIdIndex = scoring.tIds.IndexOf(tId.GetString());
- if (request.TryGetProperty("qu", out JsonElement qu))
- {
- List<int> nos = qu.ToObject<List<int>>();
- foreach (int number in nos)
- {
- List<Info> items = scoring.items[number].scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
- if (items.Count > 0)
- {
- foreach (Info info in items)
- {
- info.sc = ssc[number];
- info.mark = marks.Count > 0 ? marks[number] : "";
- }
- }
- else
- {
- Info info = new();
- info.sc = ssc[number];
- info.tmdId = tId.GetString();
- info.mark = marks.Count > 0 ? marks[number] : "";
- info.index = number;
- scoring.items[number].scores.Add(info);
- }
- }
- }
- else
- {
- foreach (Item item in scoring.items)
- {
- List<Info> items = item.scores.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
- if (items.Count > 0)
- {
- foreach (Info info in items)
- {
- info.sc = ssc[itemIndex];
- info.mark = marks.Count > 0 ? marks[itemIndex] : "";
- }
- }
- else
- {
- if (ssc[itemIndex] >= 0)
- {
- Info info = new();
- info.sc = ssc[itemIndex];
- info.tmdId = tId.GetString();
- info.mark = marks.Count > 0 ? marks[itemIndex] : "";
- info.index = itemIndex;
- item.scores.Add(info);
- }
- }
- itemIndex++;
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
- }
- }
- else
- {
- return BadRequest();
- }
- Correct correct = null;
- var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
- if (cResponse.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(cResponse.Content);
- correct = cJson.ToObject<Correct>();
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- classResults.Add(item);
- }
- bool isFinish = false;
- int scount = attr.Select(a => a.items[0].scores).ToList().Count;
- foreach (SDK.Models.Cosmos.Common.Scoring sc in attr)
- {
- foreach (var item in sc.items)
- {
- if (item.scores.Count == 0)
- {
- isFinish = false;
- break;
- }
- else
- {
- if (item.scores.Count != correct.num)
- {
- isFinish = false;
- break;
- }
- else
- {
- isFinish = true;
- }
- }
- }
- }
- if (isFinish)
- {
- foreach (ExamClassResult exam in classResults)
- {
- foreach (SDK.Models.Cosmos.Common.Scoring scoring in attr)
- {
- int index = exam.studentIds.IndexOf(scoring.stuId);
- if (index != -1)
- {
- int itemIndex = 0;
- foreach (Item item in scoring.items)
- {
- var ace = item.scores.Where(x => string.IsNullOrEmpty(x.tmdId)).ToList();
- if (ace.Count > 0)
- {
- return Ok(new { code = 1, msg = "用户信息未找到" });
- }
- //判定是否仲裁卷
- if (!item.flag)
- {
- item.isArb = 0;
- string bizcode = "scoring-arb";
- List<string> ids = new List<string>();
- foreach (CorSub sub in correct.subs)
- {
- ids = sub.arb;
- }
- //request.subs.Select(r => r.markers).ToList();
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey(scoring.code));
- string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var idNameCode in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idNameCodes.Add(idNameCode);
- }
- _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_school", Constant.NotifyType_IES5_Task,
- new Dictionary<string, object> { { "tmdname", name }, { "schoolName", schname }, { "schoolId", $"{school}" }, { "tmdid", userid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- return Ok(new { msg = "需要仲裁", code = 2 });
- }
- if (item.scores.Count > 0)
- {
- double sc = item.scores.Select(x => x.sc).ToList().Aggregate((i, j) => (i + j) / item.scores.Count);
- scoring.scores[itemIndex] = sc;
- }
- string tmdId = tId.GetString();
- //定位老师是几阅
- int indexOfSc = 0;
- foreach (Info info in item.scores)
- {
- if (info.tmdId.Equals(tmdId))
- {
- break;
- }
- else
- {
- indexOfSc++;
- }
- }
- //判定是否已经存在对应的批注信息
- bool flag = exam.mark[index][itemIndex].Exists(x => x.tmdId.Equals(tmdId));
- if (flag)
- {
- //重复打分更新部分值
- exam.mark[index][itemIndex].Where(x => x.tmdId.Equals(tmdId)).ToList().ForEach(score =>
- {
- score.sc = item.scores[indexOfSc].sc;
- score.mark = item.scores[indexOfSc].mark;
- });
- }
- else
- {
- Details dt = new()
- {
- index = item.scores[indexOfSc].index,
- sc = item.scores[indexOfSc].sc,
- tmdId = item.scores[indexOfSc].tmdId,
- mark = item.scores[indexOfSc].mark,
- identity = item.scores[indexOfSc].identity
- };
- exam.mark[index][itemIndex].Add(dt);
- }
- itemIndex++;
- }
- exam.studentScores[index] = scoring.scores;
- exam.sum[index] = exam.studentScores[index].Sum();
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
- }
- }
- return Ok(new { code = 200 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/sub-result\n", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- //查询阅卷类型数据
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-scoring")]
- public async Task<IActionResult> findScoring(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("stuId", out JsonElement sId)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- if (!request.TryGetProperty("type", out JsonElement type)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<SDK.Models.Cosmos.Common.Scoring> attr = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
- 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}') ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }
- return Ok(attr);
- }
- //申报异常卷内容
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("save-err")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> saveErr(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("err", out JsonElement err)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("index", out JsonElement index)) return BadRequest();
- if (!request.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var (userid, name, _, school) = HttpContext.GetAuthTokenInfo();
- //取得学校基本信息
- var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school.ToString(), new PartitionKey("Base"));
- string schname = string.Empty;
- if (schresponse.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var schjson = await JsonDocument.ParseAsync(schresponse.Content);
- schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
- schname = jsonschname.ToString();
- }
- SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
- if (null != scoring)
- {
- Correct correct = null;
- var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(scoring.examId, new PartitionKey($"Correct-{code}"));
- if (cResponse.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(cResponse.Content);
- correct = cJson.ToObject<Correct>();
- }
- if (string.IsNullOrEmpty(scoring.qs[index.GetInt32()].tId))
- {
- scoring.qs[index.GetInt32()].err = err.GetString();
- scoring.qs[index.GetInt32()].tId = tId.GetString();
- scoring.qs[index.GetInt32()].index = index.GetInt32();
- }
- else
- {
- return Ok(new { msg = "改题已经被申报", code = 404 });
- }
- string bizcode = "scoring-err";
- List<string> ids = new List<string>();
- foreach (CorSub sub in correct.subs)
- {
- ids = sub.err;
- }
- //request.subs.Select(r => r.markers).ToList();
- string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idNameCodes.Add(item);
- }
- _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_school", Constant.NotifyType_IES5_Task,
- new Dictionary<string, object> { { "tmdname", name }, { "schoolName", schname }, { "schoolId", $"{school}" }, { "tmdid", userid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- /* scoring.type = 2;
- scoring.err = err.GetString();*/
- }
- else
- {
- return Ok(new { code = 404 });
- }
- var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
- return Ok(new { sc });
- }
- //处理异常卷内容
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("fd-err")]
- public async Task<IActionResult> fdErr(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("improve", out JsonElement improve)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("index", out JsonElement index)) return BadRequest();
- //if (!request.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
- if (null != scoring)
- {
- if (string.IsNullOrEmpty(scoring.qs[index.GetInt32()].improve))
- {
- scoring.qs[index.GetInt32()].improve = improve.GetString();
- //scoring.qs[index.GetInt32()].tId = tId.GetString();
- //scoring.qs[index.GetInt32()].index = index.GetInt32();
- }
- else
- {
- return Ok(new { msg = "改题已经被处理", code = 404 });
- }
- /* scoring.type = 2;
- scoring.err = err.GetString();*/
- }
- else
- {
- return Ok(new { code = 404 });
- }
- var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
- return Ok(new { sc });
- }
- //处理仲裁卷内容
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("save-arb")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> saveArb(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("score", out JsonElement score)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("index", out JsonElement indexScore)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- //List<double> scs = score.ToObject<List<double>>();
- List<ExamClassResult> classResults = new();
- int sin = indexScore.GetInt32();
- SDK.Models.Cosmos.Common.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.Common.Scoring>(id.GetString(), new PartitionKey($"Scoring-{code}"));
- if (null != scoring)
- {
- scoring.scores[sin] = score.GetDouble();
- scoring.items[sin].isArb = 1;
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamClassResult>(
- queryText: $"select value(c) from c where c.examId = '{scoring.examId}' and c.subjectId = '{scoring.subjectId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- classResults.Add(item);
- }
- foreach (ExamClassResult exam in classResults)
- {
- int index = exam.studentIds.IndexOf(scoring.stuId);
- if (index != -1)
- {
- exam.studentScores[index][sin] = score.GetDouble();
- //exam.mark[index] = scoring.marks;
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
- }
- }
- else
- {
- return Ok(new { code = 404 });
- }
- var sc = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(scoring, scoring.id, new PartitionKey($"{scoring.code}"));
- return Ok(new { sc });
- }
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("score")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> score(JsonElement request)
- {
- if (!request.TryGetProperty("courseId", out JsonElement courseId)) return BadRequest();
- if (!request.TryGetProperty("cId", out JsonElement cId)) return BadRequest();
- //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<(string eId, string cId, string cname, List<string> sIds, List<double> sum)> classResults = new();
- List<string> eIds = new();
- List<string> cIds = cId.ToObject<List<string>>();
- string soc = courseId.GetString();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
- 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}'"))})"))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- List<string> sIds = account.GetProperty("studentIds").ToObject<List<string>>();
- List<double> sum = account.GetProperty("sum").ToObject<List<double>>();
- eIds.Add(account.GetProperty("eId").GetString());
- List<double> nsum = new();
- foreach (double s in sum)
- {
- double ns = 0;
- if (s < 0)
- {
- ns = 0;
- }
- else
- {
- ns = s;
- }
- nsum.Add(ns);
- }
- classResults.Add((account.GetProperty("eId").GetString(), account.GetProperty("cId").GetString(), account.GetProperty("cName").GetString(), sIds, nsum));
- }
- }
- }
- string sub = string.Empty;
- if (request.TryGetProperty("subjectId", out JsonElement subjectId))
- {
- sub = subjectId.GetString();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
- 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}'"))})"))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- List<string> sIds = account.GetProperty("studentIds").ToObject<List<string>>();
- List<double> sum = account.GetProperty("sum").ToObject<List<double>>();
- List<double> nsum = new();
- foreach (double s in sum)
- {
- double ns = 0;
- if (s < 0)
- {
- ns = 0;
- }
- else
- {
- ns = s;
- }
- nsum.Add(ns);
- }
- eIds.Add(account.GetProperty("eId").GetString());
- classResults.Add((account.GetProperty("eId").GetString(), account.GetProperty("cId").GetString(), account.GetProperty("cName").GetString(), sIds, nsum));
- }
- }
- }
- }
- 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();
- if (eIds.Count == 0)
- {
- return Ok(new { code = 404 });
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
- 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}'"))})"))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- SDK.Models.Custom eType = new();
- List<ExamSubject> subs = new();
- List<PaperSimple> ps = new();
- if (account.TryGetProperty("examType", out JsonElement examType))
- {
- eType = examType.ToObject<SDK.Models.Custom>();
- }
- if (account.TryGetProperty("papers", out JsonElement papers))
- {
- ps = papers.ToObject<List<PaperSimple>>();
- }
- if (account.TryGetProperty("subjects", out JsonElement subject))
- {
- subs = subject.ToObject<List<ExamSubject>>();
- }
- exam.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), eType, account.GetProperty("scope").GetString(),
- account.GetProperty("owner").GetString(), account.GetProperty("createTime").GetInt64(), ps, subs, account.GetProperty("source").GetString()));
- }
- }
- }
- var scores = classResults.Select(x => new
- {
- examId = x.eId,
- examName = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().name,
- scope = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().scope,
- eType = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().eType,
- classId = x.cId,
- cname = x.cname,
- studentIds = x.sIds,
- source = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().source,
- owner = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().owner,
- createTime = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().ctime,
- subject = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().subject,
- papers = exam.Where(e => e.id.Equals(x.eId)).FirstOrDefault().points,
- sum = x.sum
- });
- if (request.TryGetProperty("stuId", out JsonElement stuId))
- {
- var info = scores.Where(x => !string.IsNullOrEmpty(x.examName) && x.studentIds.Contains(stuId.GetString())).Select(x => new
- {
- x.examId,
- x.examName,
- x.cname,
- studentId = stuId.GetString(),
- x.owner,
- x.createTime,
- x.eType,
- x.source,
- point = x.papers.Select(p => p.point),
- x.subject,
- sum = x.sum.ToList()[x.studentIds.IndexOf(stuId.GetString())]
- });
- return Ok(new { info });
- }
- else
- {
- var info = scores.Where(x => !string.IsNullOrEmpty(x.examName)).Select(x => new
- {
- x.examId,
- x.examName,
- x.cname,
- x.studentIds,
- x.owner,
- x.createTime,
- x.eType,
- x.source,
- point = x.papers.Select(p => p.point),
- x.subject,
- x.sum
- });
- return Ok(new { info });
- };
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-error-item")]
- public async Task<IActionResult> getErrorItems(JsonElement request)
- {
- //stuId
- if (!request.TryGetProperty("stuId", out JsonElement stuId)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- StringBuilder stringBuilder = new($"select value(c) from c where c.stuId = '{stuId}' and c.subjectId = '{subjectId}'");
- /*if (request.TryGetProperty("period", out JsonElement period) && !string.IsNullOrWhiteSpace($"{period}"))
- {
- stringBuilder.Append($" and c.period.id = '{period}' ");
- }
- if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
- {
- stringBuilder.Append($" and Contains( c.name , '{name}') = true ");
- }
- if (request.TryGetProperty("progress", out JsonElement progress) && !string.IsNullOrWhiteSpace($"{progress}"))
- {
- stringBuilder.Append($" and c.progress = '{progress}' ");
- }
- if (request.TryGetProperty("source", out JsonElement source) && !string.IsNullOrWhiteSpace($"{source}"))
- {
- stringBuilder.Append($" and c.source = '{source}' ");
- }*/
- string pk = "ErrorItems";
- if (request.TryGetProperty("code", out JsonElement code) && !string.IsNullOrWhiteSpace($"{code}"))
- {
- stringBuilder.Append($" and c.school = '{code}' ");
- pk = $"ErrorItems-{code}";
- };
- stringBuilder.Append("order by c._ts desc");
- //string token = null;
- string token = default;
- //默认不指定返回大小
- int? topcout = null;
- if (request.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (topcout != null && topcout.Value > 0)
- {
- iscontinuation = true;
- }
- //如果指定了返回大小
- if (request.TryGetProperty("token", out JsonElement token_1))
- {
- if (!token_1.ValueKind.Equals(JsonValueKind.Null) && token_1.ValueKind.Equals(JsonValueKind.String))
- {
- token = token_1.GetString();
- }
- }
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- //var queryTeacher = $"select value(c) from c where c.stuId = '{stuId}' and c.school = '{code}' and c.subjectId = '{subjectId}'";
- List<ErrorItems> errorItems = new();
- List<string> ids = new();
- 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}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- ids.Add(obj.GetProperty("id").ToString());
- }
- }
- }
- 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}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- errorItems.Add(obj.ToObject<ErrorItems>());
- }
- }
- if (iscontinuation)
- {
- token = item.ContinuationToken;
- break;
- }
- }
- errorItems = errorItems.Where((x, i) => errorItems.FindIndex(z => z.id == x.id) == i).ToList();
- return Ok(new { errorItems, token, ids.Count });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/get-error-item()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest(new { code = 500 });
- }
- }
- //取得錯題庫前日錯題數及現在錯題數
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-error-item-cnt")]
- public async Task<IActionResult> getErrorItemsCount(JsonElement request)
- {
- //輸入值
- if (!request.TryGetProperty("stuId", out JsonElement stuId)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- string code = (request.TryGetProperty("code", out JsonElement codeJobj)) ? codeJobj.GetString() : string.Empty;
- string schCode = (!string.IsNullOrWhiteSpace(code)) ? code : "noschoolid";
- string teacherid = (request.TryGetProperty("teacherId", out JsonElement teacherId)) ? teacherId.GetString() : string.Empty;
- //取得Redis該學生該科目的錯題數 [算法變更,昨日錯題總數不再計入redis]
- int record = 0; //昨日取得的錯題數
- //var redisClient = _azureRedis.GetRedisClient(8);
- //string hkey = $"ErrorItems:{schCode}";
- //string hval = await redisClient.HashGetAsync(hkey, $"{stuId}");
- //List<stuErrorItemCnt> stuErrCntList = (hval != null) ? JsonSerializer.Deserialize<List<stuErrorItemCnt>>(hval) : new List<stuErrorItemCnt>();
- //stuErrorItemCnt stuErrCnt = stuErrCntList.Where(s => s.subjectId.Equals($"{subjectId}")).FirstOrDefault();
- //if (stuErrCnt != null)
- //{
- // record = stuErrCnt.number;
- //}
- //取得CosmosDB該學生該科目現在錯題數
- HashSet<string> avaliableQidList = new HashSet<string>(); //最終去重後可取得的錯題ID
- List<string> itemIdList = new List<string>();
- var client = _azureCosmos.GetCosmosClient();
- string qryAdd = (!string.IsNullOrWhiteSpace(code)) ? $" AND c.school = '{code}' " : string.Empty;
- //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";
- string pk = "ErrorItems";
- //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 " +
- // $"c.stuId = '{stuId}' AND c.subjectId = '{subjectId}'{qryAdd} ";
- 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 " +
- $" c.stuId = '{stuId}' AND c.subjectId = '{subjectId}' {qryAdd} ";
- if (!string.IsNullOrWhiteSpace(code))
- {
- //qry += $"AND c.school = '{code}' ";
- pk = $"ErrorItems-{code}";
- };
- Dictionary<string, List<string>> dict = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(queryText: qry, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{pk}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- if (dict.ContainsKey(obj.GetProperty("id").ToString()))
- {
- if (!dict[obj.GetProperty("id").ToString()].Contains(obj.GetProperty("blob").ToString()))
- {
- dict[obj.GetProperty("id").ToString()].Add(obj.GetProperty("blob").ToString());
- }
- }
- else
- {
- dict.Add(obj.GetProperty("id").ToString(), new List<string> { obj.GetProperty("blob").ToString() });
- }
- }
- }
- }
- foreach (var obj in dict)
- {
- if (schCode != null && schCode != "noschoolid")
- {
- string qid = obj.Key;
- List<string> blobs = obj.Value;
- foreach (string blob in blobs)
- {
- if (_azureStorage.GetBlobContainerClient(schCode).GetBlobClient($"{blob}/{qid}.json").Exists())
- {// 去除blob不存在項目
- avaliableQidList.Add(qid);
- }
- }
- }
- else if (!string.IsNullOrWhiteSpace(teacherid))
- {
- string qid = obj.Key;
- List<string> blobs = obj.Value;
- foreach (string blob in blobs)
- {
- if (_azureStorage.GetBlobContainerClient(teacherid).GetBlobClient($"{blob}/{qid}.json").Exists())
- {
- avaliableQidList.Add(qid);
- }
- }
- }
- }
- return Ok(new { record, avaliable = avaliableQidList.Count });
- }
- //取得錯題庫新增數
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-error-item-today-cnt")]
- public async Task<IActionResult> getErrorItemsTodayCount(JsonElement request)
- {
- //輸入值
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest(); //科目ID
- if (!request.TryGetProperty("stuId", out JsonElement _stuId)) return BadRequest(); //學生ID 或 TMID
- string stuId = _stuId.GetString();
- string schoolid = (request.TryGetProperty("code", out JsonElement codeJobj)) ? codeJobj.GetString() : string.Empty; //學校簡碼,TMID時為空
- string tmdid = string.Empty;
- if (string.IsNullOrWhiteSpace(schoolid)) tmdid = stuId;
- string maLearnCode = string.Empty;
- //檢查參數 必須有 teammodelId 或是同時有學校id及學號
- if (!string.IsNullOrWhiteSpace(tmdid + ""))
- {
- maLearnCode = $"MaLearn-{tmdid}";
- }
- else if (!string.IsNullOrWhiteSpace(schoolid + "") && !string.IsNullOrWhiteSpace(stuId + ""))
- {
- maLearnCode = $"MaLearn-{schoolid}-{stuId}";
- }
- else { return BadRequest(); }
- DateTime nowDate = DateTime.Now;
- DateTime beforeDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
- 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)}";
- 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)} ";
- var client = _azureCosmos.GetCosmosClient();
- int avaliable = 0;
- int allNum = 0;
- int berforeNum = 0;
- // 取全部錯題數量
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(queryText: qry_All, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{maLearnCode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- if (obj.TryGetProperty("num", out JsonElement num))
- {
- allNum = num.GetInt32();
- }
- }
- }
- }
- // 取今天之前錯題的數量
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(queryText: qry_before, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{maLearnCode}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- if (obj.TryGetProperty("num", out JsonElement num))
- {
- berforeNum = num.GetInt32();
- }
- }
- }
- }
- avaliable = allNum - berforeNum;
- return Ok(new { avaliable });
- }
- //阅卷信息统计
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("analysis-scoring")]
- public async Task<IActionResult> Analysis(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- //if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- //if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var queryTeacher = $"select c.id,c.name from c ";
- //List<object> props = new List<object>();
- List<(string id, string name)> tInfos = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(queryText: queryTeacher, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- tInfos.Add((obj.GetProperty("id").GetString(), obj.GetProperty("name").GetString()));
- }
- }
- }
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Exam-{code}"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- ExamInfo info = json.ToObject<ExamInfo>();
- List<ExamClassResult> classResults = new();
- List<SDK.Models.Cosmos.Common.Scoring> attr = new List<SDK.Models.Cosmos.Common.Scoring>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.Common.Scoring>(
- queryText: $"select value(c) from c where c.examId = '{id}' ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Scoring-{code}") }))
- {
- attr.Add(item);
- }
- List<SDK.Models.Cosmos.Common.Scoring> errs = new();
- List<(string subjectId, int count)> ps = new List<(string subjectId, int count)>();
- List<(string subjectId, int count)> tps = new List<(string subjectId, int count)>();
- List<(string subjectId, int count)> arbs = new List<(string subjectId, int count)>();
- List<(string subjectId, int count)> tarbs = new List<(string subjectId, int count)>();
- List<(string subjectId, int count)> cs = new List<(string subjectId, int count)>();
- foreach (ExamSubject subject in info.subjects)
- {
- int qsCount = 0;
- int tqsCount = 0;
- int arbCount = 0;
- int tarbCount = 0;
- int csCount = 0;
- foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
- {
- if (subject.id.Equals(ss.subjectId))
- {
- List<Qs> qs = ss.qs.Where(s => !string.IsNullOrEmpty(s.err)).ToList();
- if (qs.Count > 0)
- {
- qsCount++;
- }
- List<Qs> tqs = ss.qs.Where(s => !string.IsNullOrEmpty(s.improve)).ToList();
- if (tqs.Count > 0)
- {
- tqsCount++;
- }
- List<Item> arb = ss.items.Where(s => s.flag == false).ToList();
- if (arb.Count > 0)
- {
- arbCount++;
- }
- List<Item> tarb = ss.items.Where(s => s.isArb == 1 && s.flag == false).ToList();
- if (tarb.Count > 0)
- {
- tarbCount++;
- }
- bool flag = ss.scores.Exists(s => s == -1);
- if (!flag) csCount++;
- }
- }
- ps.Add((subject.id, qsCount));
- tps.Add((subject.id, tqsCount));
- arbs.Add((subject.id, arbCount));
- tarbs.Add((subject.id, tarbCount));
- cs.Add((subject.id, csCount));
- }
- //阅卷老师
- List<object> teachers = new();
- Correct correct = null;
- List<(string sub, List<string> ids)> errIds = new();
- List<(string sub, List<string> ids)> arbIds = new();
- var cResponse = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Correct-{code}"));
- if (cResponse.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var cJson = await JsonDocument.ParseAsync(cResponse.Content);
- correct = cJson.ToObject<Correct>();
- foreach (CorSub corSub in correct.subs)
- {
- List<string> eName = new();
- List<string> aName = new();
- foreach (string s in corSub.err)
- {
- eName.Add(tInfos.Where(t => t.id.Equals(s)).Select(s => s.name).First());
- }
- foreach (string s in corSub.arb)
- {
- aName.Add(tInfos.Where(t => t.id.Equals(s)).Select(s => s.name).First());
- }
- errIds.Add((corSub.id, eName));
- arbIds.Add((corSub.id, aName));
- foreach (CorTmd corTmd in corSub.markers)
- {
- int qus = 0;
- int quf = 0;
- int tArbs = 0;
- int fArbs = 0;
- int sCount = 0;
- int fCount = 0;
- foreach (SDK.Models.Cosmos.Common.Scoring ss in attr)
- {
- if (ss.subjectId.Equals(corSub.id))
- {
- foreach (Qs qs in ss.qs)
- {
- if (!string.IsNullOrEmpty(qs.err) && qs.tId.Equals(corTmd.id))
- {
- qus++;
- }
- if (!string.IsNullOrEmpty(qs.improve) && qs.tId.Equals(corTmd.id))
- {
- quf++;
- }
- }
- List<double> sigles = new();
- foreach (Item item in ss.items)
- {
- if (item.scores.Exists(sc => sc.tmdId.Equals(corTmd.id)) && item.isArb == 1)
- {
- tArbs++;
- }
- if (item.flag == true && item.isArb == 1)
- {
- fArbs++;
- }
- var tsc = item.scores.Where(t => t.tmdId.Equals(corTmd.id)).Select(s => s.sc).ToList();
- sigles.AddRange(tsc);
- }
- bool flag = sigles.Exists(s => s == -1);
- if (!flag && sigles.Count == ss.items.Count)
- {
- fCount++;
- }
- sCount = corTmd.count;
- }
- }
- var obj = new
- {
- sId = corSub.id,
- sName = corSub.name,
- name = corTmd.name,
- qus,
- quf,
- tArbs,
- fArbs,
- fCount,
- sCount,
- };
- teachers.Add(obj);
- }
- }
- }
- var sc = info.subjects.Select(s => new
- {
- s.name,
- count = info.stuCount,
- num = info.stuCount * correct.num,
- tqs = tps.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
- qs = ps.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
- errName = errIds.Where(q => q.sub.Equals(s.id)).Select(c => c.ids).FirstOrDefault(),
- tarbs = tarbs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
- arbs = arbs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First(),
- arbName = arbIds.Where(q => q.sub.Equals(s.id)).Select(c => c.ids).FirstOrDefault(),
- cs = cs.Where(p => p.subjectId.Equals(s.id)).Select(c => c.count).First()
- }); ;
- return Ok(new { sc, teachers });
- }
- else
- {
- return Ok(new { status = response.StatusCode });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/analysis-scoring\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- /*private async Task deleteAsync(CosmosClient client, string id, string tId)
- {
- List<string> correctIds = new List<string>();
- 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}") }))
- {
- using var jsonTask = await JsonDocument.ParseAsync(item.Content);
- if (jsonTask.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = jsonTask.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- correctIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- if (correctIds.Count > 0)
- {
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsStreamAsync(correctIds, $"CorrectTask-{tId}");
- }
- }*/
- private async Task<(string blob, List<double>)> getMoreStuInfo(CosmosClient client, string stuId, string examId, string subjectId, string code)
- {
- 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}'";
- List<List<string>> ans = new List<List<string>>();
- List<string> ids = new List<string>();
- List<List<double>> scs = new List<List<double>>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- ans = account.GetProperty("studentAnswers").ToObject<List<List<string>>>();
- ids = account.GetProperty("studentIds").ToObject<List<string>>();
- scs = account.GetProperty("studentScores").ToObject<List<List<double>>>();
- }
- }
- }
- int num = ids.IndexOf(stuId);
- string ansBlob = "";
- List<double> scores = new List<double>();
- if (num >= 0)
- {
- if (ans[num].Count > 0)
- {
- ansBlob = ans[num].First();
- }
- scores = scs[num];
- }
- return (ansBlob, scores);
- }
- private Task<List<double>> getWrongNum(ExamResult result, List<double> points, List<string> infoIds)
- {
- int num = 0;
- List<double> wn = new List<double>();
- foreach (var point in points)
- {
- int wnum = 0;
- double p = point * 0.8;
- foreach (ClassRange range in result.classes)
- {
- if (!infoIds.Contains(range.id)) continue;
- for (int i = range.range[0]; i <= range.range[1]; i++)
- {
- //判断推送的数据中,学生正常得分数据
- if (result.studentScores[i].Count > 0)
- {
- if (result.studentScores[i][num] < point)
- {
- if (result.studentScores[i][num] < p)
- {
- wnum++;
- }
- else
- {
- continue;
- }
- }
- else
- {
- continue;
- }
- }
- else
- {
- wnum++;
- }
- }
- }
- wn.Add(wnum);
- num++;
- }
- return Task.FromResult(wn);
- }
- //获取题目信息
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-item")]
- //[Authorize(Roles = "IES")]
- public async Task<IActionResult> getItemInfo(JsonElement request)
- {
- if (!request.TryGetProperty("errorItems", out JsonElement items)) return BadRequest();
- List<errorItemInfo> errors = items.ToObject<List<errorItemInfo>>();
- var client = _azureCosmos.GetCosmosClient();
- List<string> ids = errors.Select(c => c.activityId).Distinct().ToList();
- var queryClass = $"select value(c) from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))}) and c.pk = 'Exam'";
- List<ExamInfo> exams = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<ExamInfo>(queryText: queryClass))
- {
- exams.Add(item);
- }
- List<(JsonElement items, List<string> attachments, int qamode)> elements = new();
- if (exams.Count > 0)
- {
- foreach (errorItemInfo itemInfo in errors)
- {
- ExamInfo info = exams.Where(c => c.id.Equals(itemInfo.activityId)).FirstOrDefault();
- if (info == null) continue; //[Jeff]無法取得評量紀錄報錯bug修正
- List<ExamSubject> subjects = info.subjects;
- int index = 0;
- foreach (ExamSubject subject in subjects)
- {
- if (subject.id.Equals(itemInfo.unitId))
- {
- continue;
- }
- else
- {
- index++;
- }
- }
- List<PaperSimple> simples = info.papers;
- string blob = simples[index].blob;
- try
- {
- List<string> attachments = new();
- int qamode = info.qamode;
- BlobDownloadResult index_json;
- if (info.scope.Equals("school"))
- {
- index_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{blob}/index.json").DownloadContentAsync();
- }
- else
- {
- index_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{blob}/index.json").DownloadContentAsync();
- }
- JsonElement RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_json.Content.ToString()))).RootElement;
- if (RecordingJson.TryGetProperty("attachments", out JsonElement _attachments))
- {
- attachments = _attachments.ToObject<List<string>>();
- }
- //attachments = RecordingJson.GetProperty("attachments").ToObject<List<string>>();
- if (RecordingJson.TryGetProperty("qamode", out JsonElement element))
- {
- qamode = element.GetInt32();
- }
- BlobDownloadResult index_item_json;
- if (info.scope.Equals("school"))
- {
- index_item_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{blob}/{itemInfo.qId}.json").DownloadContentAsync();
- }
- else
- {
- index_item_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{blob}/{itemInfo.qId}.json").DownloadContentAsync();
- }
- JsonElement itemJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_item_json.Content.ToString()))).RootElement;
- elements.Add((itemJson, attachments, qamode));
- if (itemJson.TryGetProperty("pid", out JsonElement pid))
- {
- if (!string.IsNullOrEmpty(pid.ToString()))
- {
- BlobDownloadResult index_pid_item_json;
- if (info.scope.Equals("school"))
- {
- index_pid_item_json = await _azureStorage.GetBlobContainerClient($"{info.school}").GetBlobClient($"{blob}/{pid}.json").DownloadContentAsync();
- }
- else
- {
- index_pid_item_json = await _azureStorage.GetBlobContainerClient($"{info.creatorId}").GetBlobClient($"{blob}/{pid}.json").DownloadContentAsync();
- }
- JsonElement pidJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(index_pid_item_json.Content.ToString()))).RootElement;
- elements.Add((pidJson, attachments, qamode));
- }
- }
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/get-item\n{e.Message}\n{e.StackTrace}\n{info.id}", GroupNames.成都开发測試群組);
- continue;
- //return BadRequest(new { msg = "blob 文件读取异常" });
- }
- }
- }
- else
- {
- var values = elements.Select(c => new
- {
- c.items,
- c.attachments,
- c.qamode
- });
- return Ok(new { error = values });
- }
- var error = elements.Select(c => new
- {
- c.items,
- c.attachments,
- c.qamode
- });
- return Ok(new { error });
- }
- //記入班級評量結果批改結果 ※目前只套用統測結果批改ReadItemAsync
- private async Task upsertExamClassResultMark(ExamClassResult examClassResult, string userId, string userName, List<stus> students, List<List<double>> points)
- {
- var client = _azureCosmos.GetCosmosClient();
- ExamClassResultMark exMark = new ExamClassResultMark();
- String code = examClassResult.code.Replace("ExamClassResult", "ExamClassResultMark");
- string id = examClassResult.id;
- try
- {
- exMark = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamClassResultMark>(id, new PartitionKey($"{code}"));
- }
- catch (Exception ex)
- {
- exMark.id = id;
- exMark.code = code;
- }
- exMark.markerId = userId;
- exMark.markerName = userName;
- exMark.studentIds = examClassResult.studentIds;
- //學生ID對應index字典
- Dictionary<string, int> stuIndexDic = new Dictionary<string, int>();
- foreach (var item in exMark.studentIds.Select((value, i) => new { i, value }))
- {
- string studentId = item.value;
- int index = item.i;
- stuIndexDic.Add(studentId, index);
- }
- //points內容數不足對應
- while (exMark.studentIds.Count - exMark.points.Count > 0)
- {
- exMark.points.Add(new List<double>());
- }
- //points分數記入
- foreach (var stu in students.Select((value, i) => new { i, value }))
- {
- List<double> point = points[stu.i];
- if (stuIndexDic.ContainsKey(stu.value.id))
- {
- int index = stuIndexDic[stu.value.id];
- exMark.points[index] = point;
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, Constant.Common).UpsertItemAsync<ExamClassResultMark>(exMark, new PartitionKey(code));
- }
- }
- public class stus
- {
- public string id { get; set; }
- public int type { get; set; }
- }
- public class ufo
- {
- public string id { get; set; }
- public string name { get; set; }
- public int type { get; set; }
- public string no { get; set; }
- }
- public class stuErrorItemCnt
- {
- public string subjectId { get; set; }
- public int number { get; set; }
- }
- public class errorItemInfo
- {
- public string activityId { get; set; }
- public string qId { get; set; }
- public string unitId { get; set; }
- }
- //延伸ExamInfo 追加額外顯示欄位 (目前只有find使用)
- public class ExamInfoEx : ExamInfo
- {
- public string jointExamType { get; set; }
- }
- //取得複數學生作答成績 Request參數
- public class FindExamClassResultsReqParam
- {
- public string creatorId { get; set; }
- public string examId { get; set; }
- public string subjectId { get; set; }
- public string groupListId { get; set; }
- }
- }
|