12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756 |
- 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;
- 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.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;
- using TEAMModelOS.SDK.Models.Cosmos.OpenEntity;
- using HTEX.Lib.ETL.Lesson;
- 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();
- }
- }
- /// <summary>
- /// 离线版本学生作答接口
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student,teacher")]
- [HttpPost("upsert-new-record")]
- public async Task<IActionResult> upsertNewRecord(JsonElement request)
- {
- //评测活动Id
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //学生作答结果
- if (!request.TryGetProperty("answer", out JsonElement answer)) return BadRequest();
- //科目ID
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- //班级ID
- if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
- //活动code
- if (!request.TryGetProperty("ownerId", out JsonElement ownerId)) return BadRequest();
- if (!request.TryGetProperty("paperId", out JsonElement paperId)) return BadRequest();
- if (!request.TryGetProperty("studentId", out JsonElement studentId)) 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($"Exam-{ownerId}"));
- 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 = "该活动未被找到" });
- }
- string code = string.Empty;
- if (info.scope.Equals("school"))
- {
- code = info.school;
- }
- else {
- code = info.creatorId;
- }
- 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 = '{classId}' ",
- 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>());
- }
- }
- }
- //获取试卷详情
- PaperSimple paper = info.papers.Where(c => c.id.Equals(paperId.GetString())).FirstOrDefault();
- examClassResults = examClassResults.Where(c => c.studentIds.Contains(studentId.GetString())).ToList();
- ExamClassResult classResult = new ExamClassResult();
-
- List<List<string>> ans = answer.ToObject<List<List<string>>>();
- List<List<string>> standard = paper.answers;
- List<double> points = paper.point;
- int rule = paper.multipleRule;
- List<Task<string>> tasks = new List<Task<string>>();
- foreach (ExamClassResult result in examClassResults)
- {
-
- int newIndex = result.studentIds.IndexOf(studentId.ToString());
- StringBuilder builder = new();
- builder.Append(result.examId).Append('/');
- builder.Append(result.subjectId).Append('/');
- builder.Append(studentId.GetString()).Append('/');
- builder.Append("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;
- 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;
- }
- }
- }
- }
- }
- bool isAns = result.studentScores[newIndex].Exists(s => s == -1);
- HttpContext.Items.TryGetValue("Scope", out object type);
- int userType = $"{type}".Equals(Constant.ScopeStudent) ? 2 : 1;
- 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 (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, new List<string> { classId.GetString()});
- };
- }
- }
- await Task.WhenAll(tasks);
- return Ok(new { classResult });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertNewRecord()\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;
- }
- });
- if (string.IsNullOrWhiteSpace(artResult.zyanswer?.thirdAnswerId!))
- {
- var res = artResult.results.Find(x => x.subjectId.Equals("subject_music")&&x.quotaId.Equals("quota_22"));
- if (res!=null)
- {
- string fileName = $"{artResult.artId}--{res.taskId}--{artResult.studentId}.json";
- try {
- bool exists = _azureStorage.GetBlobContainerClient("0-public").GetBlobClient(fileName).Exists();
- if (exists)
- {
- BlobDownloadResult blobDownload = await _azureStorage.GetBlobContainerClient("0-public").GetBlobClient(fileName).DownloadContentAsync();
- var jsonElement = blobDownload.Content.ToObjectFromJson<JsonElement>();
- if (jsonElement.TryGetProperty("answer", out JsonElement _answer))
- {
- OAnswerUp oAnswer = _answer.ToObject<OAnswerUp>();
- if (oAnswer!=null)
- {
- artResult.zyanswer= new OAnswer
- {
- questionId = oAnswer.questionId,
- thirdAnswerId = oAnswer.thirdAnswerId,
- score = oAnswer.score,
- detail = oAnswer.detail,
- time = DateTimeOffset.Now.ToUnixTimeMilliseconds()
- };
- }
- }
- }
- } catch (Exception ex) { }
- }
- }
- 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);
- }
- //string str = result.studentScores.ToJsonString();
- //await _dingDing.SendBotMsg($"變更學生成績 班級:{result.info.name} 分數:{str}", GroupNames.醍摩豆服務運維群組);
- 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]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student,teacher,admin")]
- #endif
- [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.status,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<double>> stuTotalScore = 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> subjectScore = new();
- List<double> sTotal = new();
- foreach (var ss in result.studentScores) {
- subjectScore.Add(ss.Sum());
- }
- stuTotalScore.Add(subjectScore);
- 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);
- }
- }
- var scoreOrder = stuTotalScore.Select(c => c.OrderByDescending(z => z).ToList()).ToList();
- int k = 0;
- List<int> rank = new();
- if (scoreOrder.Count > 0) {
- foreach (var stuRank in stuScore)
- {
- int rk = scoreOrder[k].IndexOf(stuRank.Sum());
- if (rk != -1)
- {
- rank.Add(rk + 1);
- }
- else
- {
- rank.Add(scoreOrder[k].Count);
- }
- }
- }
-
- 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, rank, 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()}{request.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- //学生端查询评测列表
- [ProducesDefaultResponseType]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "student,teacher,admin")]
- #endif
- [HttpPost("find-simple-by-student")]
- public async Task<IActionResult> findSimpleStudent(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) 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();
- //List<object> subjects = new List<object>();
- List<string> classIds = new 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>();
- }
- 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 = [subjectId.ToObject<string>()];
- /* 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());
- }
- }
- }*/
- int index_subject = info.subjects.Select(c => c.id).ToList().IndexOf(subjectId.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' and c.subjectId = '{subjectId}' ";
- 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.status,c.sum,c.mark,c.krate,c.frate,c.info.id as cId from c where c.examId ='{id}' and c.pk = 'ExamClassResult' and c.subjectId = '{subjectId}'";
- 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 where c.subjectId = '{subjectId}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamResult-{id}") }))
- {
- results.Add(item);
- }
- List<List<string>> stuAns = new();
- List<List<double>> stuScore = new();
- List<List<double>> stuTotalScore = 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> subjectScore = new();
- List<double> sTotal = new();
- foreach (var ss in result.studentScores)
- {
- subjectScore.Add(ss.Sum());
- }
- stuTotalScore.Add(subjectScore);
- 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);
- }
- }
- var scoreOrder = stuTotalScore.Select(c => c.OrderByDescending(z => z).ToList()).ToList();
- int k = 0;
- List<int> rank = new();
- if (scoreOrder.Count > 0)
- {
- foreach (var stuRank in stuScore)
- {
- int rk = scoreOrder[k].IndexOf(stuRank.Sum());
- if (rk != -1)
- {
- rank.Add(rk + 1);
- }
- else
- {
- rank.Add(scoreOrder[k].Count);
- }
- }
- }
- 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 { papers = info.papers[index_subject], info.subjects, stuScore, stuAns, mark, total, claId = infoIds, knowledge, filed, average, wno, rank, status = 200 });
- }
- }
- return Ok(new { papers = info.papers[index_subject], info.subjects, stuScore, stuAns, mark, total, claId = infoIds, knowledge = new List<object>(), filed = new List<object>(), average, wno, status = 200 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-simple-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 = [];
- List<double> akp = [];
- List<double> fp = [];
- List<double> afp = [];
- List<double> ckp = [];
- List<double> cfp = [];
- List<int> fields = [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 = [];
- List<string> knowledges = [];
- 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.status.Where(c => c == 0).Count();
- }
- double per = count > 0 ? Math.Round(score / count, 2) : 0;
- akp.Add(allScore > 0 ? Math.Round(per * 1.0 / allScore, 4) : 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.status.Where(c => c == 0).Count();
- }
- }
- double per = count > 0 ? Math.Round(score / count, 2) : 0;
- afp.Add(allScore > 0 ? Math.Round(per * 1.0 / allScore, 4) : 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.Scoring> attr = new List<SDK.Models.Cosmos.Scoring>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.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.Scoring> attrSc = new List<SDK.Models.Cosmos.Scoring>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.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.Scoring> errs = new();
- //List<SDK.Models.Cosmos.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.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.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.Scoring> attr = new List<SDK.Models.Cosmos.Scoring>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.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.Scoring> errs = new();
- foreach (SDK.Models.Cosmos.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.Scoring> attr = new List<SDK.Models.Cosmos.Scoring>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.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.Scoring> errs = new();
- List<SDK.Models.Cosmos.Scoring> arbs = new();
- //List<(string id,List<double>)> osc = new List<(string id, List<double>)>();
- foreach (SDK.Models.Cosmos.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.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.Scoring> recs = new();
- List<SDK.Models.Cosmos.Scoring> all = new();
- //List<SDK.Models.Cosmos.Scoring> attr = new();
- /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.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.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.Scoring> value = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.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.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.Scoring> val = new List<SDK.Models.Cosmos.Scoring>();
- foreach (SDK.Models.Cosmos.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.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.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.Scoring item = new();
- List<SDK.Models.Cosmos.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.Scoring> attr = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.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.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.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.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.Scoring> attr = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.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.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.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.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.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.Scoring scoring = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SDK.Models.Cosmos.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.Scoring> attr = new List<SDK.Models.Cosmos.Scoring>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<SDK.Models.Cosmos.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.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.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.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 });
- }
- //刪除不存在的錯題
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("delete-wrong-item")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> deleteWrongItem(JsonElement request)
- {
- if (!request.TryGetProperty("data", out JsonElement items)) return BadRequest();
- if(!request.TryGetProperty("sid", out JsonElement _sid)) return BadRequest();
- try
- {
- List<errorItemInfo> errors = items.ToObject<List<errorItemInfo>>();
- string sid = _sid.GetString();
- var client = _azureCosmos.GetCosmosClient();
- List<string> ReqExamIds = errors.Select(c => c.activityId).Distinct().ToList(); //
- var queryClass = $"select value(c) from c where c.id in ({string.Join(",", ReqExamIds.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<errorItemInfo> existItems = new List<errorItemInfo>();
- if (exams.Count > 0)
- {
- foreach (errorItemInfo itemInfo in errors)
- {
- ExamInfo info = exams.Where(c => c.id.Equals(itemInfo.activityId)).FirstOrDefault();
- if (info == null) continue;
- string subjectId = itemInfo.unitId;
- int subjectIndex = info.subjects.Select((item, index) => (item, index)).FirstOrDefault(s => s.item.id.Equals(subjectId)).index;
- string itemId = itemInfo.qId;
- string container = (info.scope.Equals("school")) ? $"{info.school}" : $"{info.creatorId}";
- string blob = info.papers[subjectIndex].blob;
- if (_azureStorage.GetBlobContainerClient($"{container}").GetBlobClient($"{blob}/{itemInfo.qId}.json").Exists())
- {
- existItems.Add(itemInfo);
- }
- }
- }
- if (existItems.Count > 0)
- {
- foreach (errorItemInfo existItem in existItems)
- {
- errors.RemoveAll(e => e.activityId.Equals(existItem.activityId) && e.qId.Equals(existItem.qId) && e.unitId.Equals(existItem.unitId));
- }
- }
- //呼叫刪除API
- int delFlg = 0;
- if (errors.Count > 0)
- {
- string domain = _configuration.GetValue<string>("MaLearn:url");
- string key = _configuration.GetValue<string>("MaLearn:key");
- string url = $"{domain}/api/qdelete";
- var httpClient = _httpClient.CreateClient();
- httpClient.DefaultRequestHeaders.Add("x-functions-key", key);
- Dictionary<string, string> dataDic = new Dictionary<string, string>();
- dataDic.Add("sid", sid);
- dataDic.Add("data", errors.ToJsonString());
- HttpContent content = new StringContent(dataDic.ToJsonString(), Encoding.UTF8, "application/json");
- HttpResponseMessage httpResponse = await httpClient.PostAsync(url, content);
- if (httpResponse.IsSuccessStatusCode)
- {
- delFlg = 1;
- }
- }
- return Ok(new { del = delFlg, errors });
- }
- catch (Exception ex)
- {
- return BadRequest(ex.Message);
- }
- }
- //記入班級評量結果批改結果 ※目前只套用統測結果批改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; }
- }
- }
|