ExamController.cs 203 KB

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