ExamController.cs 314 KB

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