ExamController.cs 179 KB

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