ExamController.cs 234 KB

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