StudentCommonController.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. using Microsoft.Azure.Cosmos;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Extensions.Options;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Text.Json;
  11. using System.Threading.Tasks;
  12. using TEAMModelOS.Filter;
  13. using TEAMModelOS.Models;
  14. using TEAMModelOS.SDK;
  15. using TEAMModelOS.SDK.DI;
  16. using TEAMModelOS.SDK.Extension;
  17. using TEAMModelOS.SDK.Models;
  18. using TEAMModelOS.SDK.Models.Cosmos;
  19. using TEAMModelOS.SDK.Models.Cosmos.Common;
  20. using TEAMModelOS.SDK.Models.Service;
  21. using TEAMModelOS.SDK.Services;
  22. using static TEAMModelOS.SDK.StudentService;
  23. namespace TEAMModelOS.Controllers
  24. {
  25. [ProducesResponseType(StatusCodes.Status200OK)]
  26. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  27. //
  28. [Route("student")]
  29. [ApiController]
  30. public class StudentCommonController : ControllerBase
  31. {
  32. private readonly AzureCosmosFactory _azureCosmos;
  33. private readonly AzureRedisFactory _azureRedis;
  34. private readonly DingDing _dingDing;
  35. private readonly Option _option;
  36. public StudentCommonController(AzureCosmosFactory azureCosmos, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option)
  37. {
  38. _azureCosmos = azureCosmos;
  39. _azureRedis = azureRedis;
  40. _dingDing = dingDing;
  41. _option = option?.Value;
  42. }
  43. /// <summary>
  44. /// 查询活动所有活动类型的列表,学生端
  45. /// </summary>
  46. /// <param name="request">
  47. ///加入的班级信息 ?classes:[{"classid":"S-C-00001","scope":"school"},{"classid":"P-C-00004","scope":"private"}]
  48. ///活动类型 ?"type":"Vote"/"Exam"/"Homework"/"Learn"/"Survey"" // Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
  49. ///时间筛选范围开始时间 默认30天之前 ?"stime":1608274766154
  50. ///时间筛选范围结束时间 默认当前时间 ?"etime":1608274766666
  51. ///是否展示列表的 Tips ? "tips":true/false
  52. ///每页大小 ?"count":10/null/Undefined
  53. ///分页Token ?"continuationToken":Undefined/null/"[{\"token\":\"+RID:~omxMAP3ipcSEEwAAAAAAAA==#RT:2#TRC:20#ISV:2#IEO:65551#QCF:1#FPC:AYQTAAAAAAAAiRMAAAAAAAA=\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}]"
  54. /// 当前状态 ?"progress":Undefined/null/"" 表示两种状态都要查询/ "going"/"finish" 表示查询进行中/ 或者已完成 学生端只能查询正在进行或已经结束 going 已发布|finish 已结束
  55. /// </param>
  56. ///
  57. /// <returns></returns>
  58. [ProducesDefaultResponseType]
  59. [HttpPost("student-activity")]
  60. [Authorize(Roles = "IES")]
  61. [AuthToken(Roles = "teacher,admin,student")]
  62. #if !DEBUG
  63. [Authorize(Roles = "IES")]
  64. #endif
  65. public async Task<IActionResult> StudentActivity(JsonElement request)
  66. {
  67. var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
  68. object _scope = null;
  69. List<string> groupListIds = new List<string>();
  70. List<string> subjects = new List<string>();
  71. if (request.TryGetProperty("groupListIds", out JsonElement _groupListIds)) {
  72. groupListIds= _groupListIds.ToObject<List<string>>();
  73. }
  74. if (request.TryGetProperty("subjects", out JsonElement _subjects))
  75. {
  76. subjects= _subjects.ToObject<List<string>>();
  77. }
  78. List<string> types = new List<string>();
  79. if (request.TryGetProperty("types", out JsonElement _types))
  80. {
  81. types= _types.ToObject<List<string>>();
  82. }
  83. HttpContext?.Items.TryGetValue("Scope", out _scope);
  84. List<StudentActivity> datas = await StudentService.FindActivity(request, id, $"{_scope}", groupListIds, subjects, school, types, _azureCosmos);
  85. return Ok(new { code =200, datas, serverTime=DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()});
  86. }
  87. /// <summary>
  88. /// 查询活动所有活动类型的列表,学生端
  89. /// </summary>
  90. /// <param name="request">
  91. ///加入的班级信息 ?classes:[{"classid":"S-C-00001","scope":"school"},{"classid":"P-C-00004","scope":"private"}]
  92. ///活动类型 ?"type":"Vote"/"Exam"/"Homework"/"Learn"/"Survey"" // Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
  93. ///时间筛选范围开始时间 默认30天之前 ?"stime":1608274766154
  94. ///时间筛选范围结束时间 默认当前时间 ?"etime":1608274766666
  95. ///是否展示列表的 Tips ? "tips":true/false
  96. ///每页大小 ?"count":10/null/Undefined
  97. ///分页Token ?"continuationToken":Undefined/null/"[{\"token\":\"+RID:~omxMAP3ipcSEEwAAAAAAAA==#RT:2#TRC:20#ISV:2#IEO:65551#QCF:1#FPC:AYQTAAAAAAAAiRMAAAAAAAA=\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}]"
  98. /// 当前状态 ?"progress":Undefined/null/"" 表示两种状态都要查询/ "going"/"finish" 表示查询进行中/ 或者已完成 学生端只能查询正在进行或已经结束 going 已发布|finish 已结束
  99. /// </param>
  100. ///
  101. /// <returns></returns>
  102. [ProducesDefaultResponseType]
  103. [HttpPost("stu-activity")]
  104. [Authorize(Roles = "IES")]
  105. [AuthToken(Roles = "teacher,admin,student")]
  106. #if !DEBUG
  107. [Authorize(Roles = "IES")]
  108. #endif
  109. public async Task<IActionResult> StuActivity(JsonElement request)
  110. {
  111. var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
  112. (List<StuActivity> datas, string continuationToken) = await ActivityStudentService.FindActivity(request, id, school, _azureCosmos, _azureRedis);
  113. return Ok(new { datas, continuationToken });
  114. }
  115. [ProducesDefaultResponseType]
  116. [HttpPost("stu-score")]
  117. [AuthToken(Roles = "teacher,admin,student")]
  118. #if !DEBUG
  119. [Authorize(Roles = "IES")]
  120. #endif
  121. public async Task<IActionResult> StuScore(JsonElement request)
  122. {
  123. var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
  124. //if (!HttpContext.Items.TryGetValue("Scope", out object _scope)) return BadRequest();
  125. (List<ExamInfo> datas, string continuationToken) = await ExamService.FindExam(request, id, school, _azureCosmos);
  126. List<(string id, string scope, string name, string source, List<string> cIds, int qamode, string createId, dynamic ext, long time, string owner)> eIds = new();
  127. //List<(string id, string scope, string name, List<string> cIds, string createId,long time)> wIds = new();
  128. foreach (var data in datas)
  129. {
  130. eIds.Add((data.id, data.scope, data.name, data.source, data.classes, data.qamode, data.creatorId, data.examType, data.createTime, data.owner));
  131. }
  132. if (eIds.Count == 0)
  133. {
  134. return Ok(new { code = 404, msg = "暂无数据" });
  135. }
  136. var client = _azureCosmos.GetCosmosClient();
  137. List<(string eId, string sub, string cId, string cname, List<string> sIds, List<double> sum)> classResults = await getExamClassResult(eIds, client);
  138. List<(string id, double ps)> points = new();
  139. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
  140. queryText: $"select A0.point,c.id from c join A0 in c.papers where c.id in ({string.Join(",", eIds.Select(o => $"'{o.id}'"))})"))
  141. {
  142. using var json = await JsonDocument.ParseAsync(item.Content);
  143. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  144. {
  145. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  146. while (accounts.MoveNext())
  147. {
  148. JsonElement account = accounts.Current;
  149. List<double> ps = new();
  150. if (account.TryGetProperty("point", out JsonElement point))
  151. {
  152. ps = point.ToObject<List<double>>();
  153. }
  154. points.Add((account.GetProperty("id").GetString(), ps.Sum()));
  155. }
  156. }
  157. }
  158. List<(string id, List<ExamSubject> sub)> subs = new();
  159. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
  160. queryText: $"select c.subjects,c.id from c where c.id in ({string.Join(",", eIds.Select(o => $"'{o.id}'"))})"))
  161. {
  162. using var json = await JsonDocument.ParseAsync(item.Content);
  163. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  164. {
  165. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  166. while (accounts.MoveNext())
  167. {
  168. JsonElement account = accounts.Current;
  169. List<ExamSubject> sj = new();
  170. if (account.TryGetProperty("subjects", out JsonElement sn))
  171. {
  172. sj = sn.ToObject<List<ExamSubject>>();
  173. }
  174. subs.Add((account.GetProperty("id").GetString(), sj));
  175. }
  176. }
  177. }
  178. var pst = points.GroupBy(x => x.id).Select(p => new { key = p.Key, po = p.Select(o => o.ps) });
  179. var sut = subs.GroupBy(x => x.id).Select(p => new { key = p.Key, po = p.Select(o => o.sub) });
  180. var exam = eIds.Select(e => new
  181. {
  182. e.id,
  183. e.name,
  184. e.scope,
  185. e.source,
  186. e.createId,
  187. e.ext,
  188. e.qamode,
  189. e.time,
  190. e.owner,
  191. point = pst.Where(s => s.key == e.id).Select(c => c.po),
  192. subject = subs.Where(s => s.id == e.id).FirstOrDefault().sub,
  193. result = classResults.Where(c => c.eId == e.id).Select(s => new { s.sub, s.cId, s.cname, s.sum, s.sIds })
  194. });
  195. var result = exam.Where(e => e.result.Any()).Select(s => new
  196. {
  197. s.id,
  198. s.name,
  199. s.scope,
  200. s.source,
  201. s.ext,
  202. s.createId,
  203. s.qamode,
  204. s.time,
  205. s.owner,
  206. point = s.point.FirstOrDefault(),
  207. s.subject,
  208. s.result
  209. });
  210. return Ok(new { result, continuationToken });
  211. }
  212. [ProducesDefaultResponseType]
  213. [HttpPost("stu-hw-score")]
  214. [Authorize(Roles = "IES")]
  215. [AuthToken(Roles = "teacher,student,admin")]
  216. public async Task<IActionResult> StuHwScore(JsonElement request)
  217. {
  218. var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
  219. //if (!HttpContext.Items.TryGetValue("Scope", out object _scope)) return BadRequest();
  220. (List<StuActivity> datas, string continuationToken) = await ActivityStudentService.FindActivity(request, id, school, _azureCosmos, _azureRedis);
  221. //List<(string id, string scope, string name, string source, List<string> cIds, int qamode, string createId, Dictionary<string, JsonElement> ext, long time, string owner)> eIds = new();
  222. List<(string id, string scope, string name, List<string> cIds, string createId, long time)> wIds = new();
  223. foreach (var data in datas)
  224. {
  225. wIds.Add((data.id, data.scope, data.name, data.classIds, data.creatorId, data.createTime));
  226. }
  227. var client = _azureCosmos.GetCosmosClient();
  228. string partitionKey = String.Empty;
  229. if (request.TryGetProperty("userType", out JsonElement userType)) {
  230. if (userType.GetString().Equals("schoolid"))
  231. {
  232. partitionKey = $"HomeworkRecord-{school}-{id}";
  233. }
  234. else {
  235. if (request.TryGetProperty("userid", out JsonElement userid)) {
  236. id = userid.GetString();
  237. partitionKey = $"HomeworkRecord-{id}";
  238. }
  239. }
  240. }
  241. List<(string id, double score, List<HomeworkComment> comments, string comid)> work = new();
  242. //List<string> comid = new();
  243. if (wIds.Count > 0) {
  244. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(
  245. queryText: $"select c.id,c.score,c.comments,c.comid from c where c.id in ({string.Join(",", wIds.Select(o => $"'{o.id}'"))})",
  246. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(partitionKey) }))
  247. {
  248. using var json = await JsonDocument.ParseAsync(item.Content);
  249. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  250. {
  251. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  252. while (accounts.MoveNext())
  253. {
  254. JsonElement account = accounts.Current;
  255. double sc = 0;
  256. List<HomeworkComment> hc = new();
  257. if (account.TryGetProperty("score", out JsonElement score))
  258. {
  259. sc = score.GetDouble();
  260. if (sc == -1)
  261. {
  262. sc = 0;
  263. }
  264. }
  265. if (account.TryGetProperty("comments", out JsonElement comments))
  266. {
  267. hc = comments.ToObject<List<HomeworkComment>>();
  268. }
  269. //comid.Add(account.GetProperty("comid").GetString());
  270. work.Add((account.GetProperty("id").GetString(), sc, hc, account.GetProperty("comid").GetString()));
  271. }
  272. }
  273. }
  274. }
  275. List<(string id, List<DebateReply> comments)> debates = new();
  276. List<string> scomid = new();
  277. List<string> tcomid = new();
  278. foreach (var cc in wIds)
  279. {
  280. if (cc.scope.Equals("school"))
  281. {
  282. scomid.Add(work.Where(w => w.id == cc.id).FirstOrDefault().comid);
  283. }
  284. else
  285. {
  286. tcomid.Add(work.Where(w => w.id == cc.id).FirstOrDefault().comid);
  287. }
  288. }
  289. if (scomid.Count > 0)
  290. {
  291. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(
  292. queryText: $"select c.id,c.replies from c where c.id in ({string.Join(",", scomid.Select(o => $"'{o}'"))})",
  293. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Debate-{school}") }))
  294. {
  295. using var json = await JsonDocument.ParseAsync(item.Content);
  296. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  297. {
  298. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  299. while (accounts.MoveNext())
  300. {
  301. JsonElement account = accounts.Current;
  302. List<DebateReply> debate = new();
  303. if (account.TryGetProperty("replies", out JsonElement replies))
  304. {
  305. debate = replies.ToObject<List<DebateReply>>();
  306. }
  307. debates.Add((account.GetProperty("id").GetString(), debate));
  308. }
  309. }
  310. }
  311. }
  312. if (tcomid.Count > 0)
  313. {
  314. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(
  315. queryText: $"select c.id,c.replies from c where c.pk = 'Debate' and c.id in ({string.Join(",", tcomid.Select(o => $"'{o}'"))})"))
  316. {
  317. using var json = await JsonDocument.ParseAsync(item.Content);
  318. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  319. {
  320. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  321. while (accounts.MoveNext())
  322. {
  323. JsonElement account = accounts.Current;
  324. List<DebateReply> debate = new();
  325. if (account.TryGetProperty("replies", out JsonElement replies))
  326. {
  327. debate = replies.ToObject<List<DebateReply>>();
  328. }
  329. debates.Add((account.GetProperty("id").GetString(), debate));
  330. }
  331. }
  332. }
  333. }
  334. var coment = work.Select(w => new
  335. {
  336. w.id,
  337. w.comid,
  338. reply = debates.Where(d => d.id == w.comid).FirstOrDefault().comments
  339. });
  340. var replay = coment.Where(c => c.reply != null);
  341. var works = wIds.Select(w => new
  342. {
  343. w.id,
  344. w.name,
  345. w.cIds,
  346. w.createId,
  347. w.time,
  348. score = work.Where(x => x.id == w.id).Select(s =>
  349. new
  350. {
  351. s.score,
  352. s.comments
  353. }),
  354. comment = replay.Any() ? replay.Where(c => c.id == w.id).Select(r => new { r.reply }) : null,
  355. });
  356. return Ok(new { works, continuationToken });
  357. }
  358. //获取学期信息
  359. [ProducesDefaultResponseType]
  360. [HttpPost("get-semesters")]
  361. [Authorize(Roles = "IES")]
  362. [AuthToken(Roles = "teacher,student,admin")]
  363. public async Task<IActionResult> getSemesters(JsonElement request) {
  364. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  365. if (!request.TryGetProperty("periodId", out JsonElement periodId)) return BadRequest();
  366. try {
  367. var client = _azureCosmos.GetCosmosClient();
  368. List<Semester> semesters = new();
  369. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(
  370. queryText: $"select A0.semesters from c join A0 in c.period where A0.id = '{periodId}' and c.id = '{code}'",
  371. requestOptions: new QueryRequestOptions() {PartitionKey = new PartitionKey("Base") }))
  372. {
  373. using var json = await JsonDocument.ParseAsync(item.Content);
  374. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  375. {
  376. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  377. {
  378. semesters.Add(obj.ToObject<Semester>());
  379. }
  380. }
  381. }
  382. return Ok(semesters);
  383. } catch (Exception ex) {
  384. await _dingDing.SendBotMsg($"OS,{_option.Location},student/get-semesters()\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  385. }
  386. return Ok(new { code = 404, msg = "未找到相应内容"});
  387. }
  388. [ProducesDefaultResponseType]
  389. [HttpPost("stu-record-score")]
  390. [Authorize(Roles = "IES")]
  391. [AuthToken(Roles = "teacher,student,admin")]
  392. public async Task<IActionResult> StuRecordScore(JsonElement request)
  393. {
  394. if (!HttpContext.Items.TryGetValue("Scope", out object _scope)) return BadRequest();
  395. var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
  396. /*if (!request.TryGetProperty("stime", out JsonElement stime)) return BadRequest();
  397. if (!request.TryGetProperty("etime", out JsonElement etime)) return BadRequest();*/
  398. var client = _azureCosmos.GetCosmosClient();
  399. List<StudentLessonRecord> records = new();
  400. try
  401. {
  402. //是否需要进行分页查询,默认不分页
  403. string token = default;
  404. bool iscontinuation = false;
  405. if (request.TryGetProperty("token", out JsonElement token_1))
  406. {
  407. token = token_1.GetString();
  408. };
  409. //默认不指定返回大小
  410. int? topcout = null;
  411. if (request.TryGetProperty("count", out JsonElement jcount))
  412. {
  413. if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
  414. {
  415. topcout = data;
  416. }
  417. }
  418. if (topcout != null && topcout.Value > 0)
  419. {
  420. iscontinuation = true;
  421. }
  422. StringBuilder stringBuilder = null ;
  423. if ($"{_scope}".Equals(Constant.ScopeStudent)) {
  424. stringBuilder = new($"select A0.tmdid,A0.school,A0.scope,A0.lessonId,A0.courseId,A0.periodId,A0.subjectId,A0.gscore,A0.pscore,A0.tscore,A0.time from c join A0 in c.lessonRecords where c.stuid = '{id}'");
  425. } else {
  426. stringBuilder = new($"select A0.tmdid,A0.school,A0.scope,A0.lessonId,A0.courseId,A0.periodId,A0.subjectId,A0.gscore,A0.pscore,A0.tscore,A0.time from c join A0 in c.lessonRecords where c.tmdid = '{id}'");
  427. }
  428. if (request.TryGetProperty("stime", out JsonElement stime)) {
  429. stringBuilder.Append($" and A0.time >= {stime} ");
  430. }
  431. if (request.TryGetProperty("etime", out JsonElement etime))
  432. {
  433. stringBuilder.Append($" and A0.time <= {etime} ");
  434. }
  435. if (request.TryGetProperty("courseId", out JsonElement courseId))
  436. {
  437. stringBuilder.Append($" and A0.courseId = '{courseId}' ");
  438. }
  439. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(
  440. queryText: stringBuilder.ToString(),
  441. continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey("StudentScoreRecord") }))
  442. {
  443. using var json = await JsonDocument.ParseAsync(item.Content);
  444. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  445. {
  446. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  447. {
  448. records.Add(obj.ToObject<StudentLessonRecord>());
  449. }
  450. }
  451. if (iscontinuation)
  452. {
  453. token = item.ContinuationToken;
  454. break;
  455. }
  456. }
  457. //List<string> ids = records.Select(x => x.lessonId).ToList();
  458. List<(string id, string name)> info = new();
  459. if (records.Count > 0) {
  460. List<string> slessons = records.Where(r => r.scope.Equals("school")).Select(o => o.lessonId).ToList();
  461. if (slessons.Count > 0) {
  462. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(
  463. queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", slessons.Select(o => $"'{o}'"))})",
  464. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{school}") }))
  465. {
  466. using var json = await JsonDocument.ParseAsync(item.Content);
  467. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  468. {
  469. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  470. while (accounts.MoveNext())
  471. {
  472. JsonElement account = accounts.Current;
  473. info.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
  474. }
  475. }
  476. }
  477. }
  478. List<string> plessons = records.Where(r => r.scope.Equals("private")).Select(o => o.lessonId).ToList();
  479. if (plessons.Count > 0) {
  480. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(
  481. queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", plessons.Select(o => $"'{o}'"))})",
  482. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord") }))
  483. {
  484. using var json = await JsonDocument.ParseAsync(item.Content);
  485. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  486. {
  487. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  488. while (accounts.MoveNext())
  489. {
  490. JsonElement account = accounts.Current;
  491. info.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
  492. }
  493. }
  494. }
  495. }
  496. }
  497. var score = records.Select(x => new
  498. {
  499. x.tmdid,
  500. x.school,
  501. x.scope,
  502. x.lessonId,
  503. lessonName = info.Count > 0 ? info.Where(c => c.id.Equals(x.lessonId)).FirstOrDefault().name : "",
  504. x.courseId,
  505. x.subjectId,
  506. x.gscore,
  507. x.pscore,
  508. x.tscore,
  509. x.time
  510. }).OrderByDescending(c => c.time);
  511. return Ok(new { score });
  512. }
  513. catch (Exception e)
  514. {
  515. return Ok(new { code = 404, msg = e.StackTrace });
  516. }
  517. }
  518. private async Task<List<(string eId, string sub, string cId, string cname, List<string> sIds, List<double> sum)>> getExamClassResult(List<(string id, string scope, string name, string source, List<string> cIds, int qamode, string createId, dynamic ext,long time, string owner)> eIds, CosmosClient client)
  519. {
  520. List<(string eId, string sub, string cId, string cname, List<string> sIds, List<double> sum)> classResults = new();
  521. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
  522. queryText: $"select c.examId as eId,c.info.id as cId,c.info.name as cName,c.studentIds,c.sum,c.subjectId from c where c.pk = 'ExamClassResult' and c.examId in ({string.Join(",", eIds.Select(o => $"'{o.id}'"))})"))
  523. {
  524. using var json = await JsonDocument.ParseAsync(item.Content);
  525. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  526. {
  527. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  528. while (accounts.MoveNext())
  529. {
  530. JsonElement account = accounts.Current;
  531. List<string> sIds = new();
  532. List<double> sums = new();
  533. string sub = string.Empty;
  534. string cid = string.Empty;
  535. string cname = string.Empty;
  536. if (account.TryGetProperty("studentIds", out JsonElement stu))
  537. {
  538. sIds = stu.ToObject<List<string>>();
  539. }
  540. if (account.TryGetProperty("sum", out JsonElement sum))
  541. {
  542. sums = sum.ToObject<List<double>>();
  543. }
  544. if (account.TryGetProperty("subjectId", out JsonElement subject))
  545. {
  546. sub = subject.GetString();
  547. }
  548. if (account.TryGetProperty("cId", out JsonElement cc))
  549. {
  550. cid = cc.GetString();
  551. }
  552. if (account.TryGetProperty("cName", out JsonElement cn))
  553. {
  554. cname = cn.GetString();
  555. }
  556. classResults.Add((account.GetProperty("eId").GetString(), sub, cid, cname, sIds, sums));
  557. }
  558. }
  559. }
  560. return classResults;
  561. }
  562. /// <summary>
  563. /// 查询活动所有活动类型的列表,学生端
  564. /// </summary>
  565. /// <param name="request">
  566. /// userid
  567. /// school
  568. /// </param>
  569. ///
  570. /// <returns></returns>
  571. [ProducesDefaultResponseType]
  572. [HttpPost("stu-course")]
  573. #if !DEBUG
  574. [Authorize(Roles = "IES")]
  575. #endif
  576. [AuthToken(Roles = "student")]
  577. public async Task<IActionResult> StuCourse(JsonElement request)
  578. {
  579. var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
  580. if (string.IsNullOrWhiteSpace(id))
  581. {
  582. if (request.TryGetProperty("userid", out JsonElement userid))
  583. {
  584. if (!userid.ValueKind.Equals(JsonValueKind.Undefined) && !userid.ValueKind.Equals(JsonValueKind.Null) && userid.ValueKind.Equals(JsonValueKind.String))
  585. {
  586. id = userid.GetString();
  587. }
  588. }
  589. }
  590. if (string.IsNullOrWhiteSpace(school))
  591. {
  592. if (request.TryGetProperty("school", out JsonElement schooljson))
  593. {
  594. if (!schooljson.ValueKind.Equals(JsonValueKind.Undefined) && !schooljson.ValueKind.Equals(JsonValueKind.Null) && schooljson.ValueKind.Equals(JsonValueKind.String))
  595. {
  596. school = schooljson.GetString();
  597. }
  598. }
  599. }
  600. /// tmdid, schoolid
  601. var userType = "tmdid";
  602. if (request.TryGetProperty("userType", out JsonElement usertype))
  603. {
  604. if (!usertype.ValueKind.Equals(JsonValueKind.Undefined) && !usertype.ValueKind.Equals(JsonValueKind.Null) && usertype.ValueKind.Equals(JsonValueKind.String))
  605. {
  606. userType = usertype.GetString();
  607. }
  608. }
  609. string containerId = "";
  610. string PartitionKey = "";
  611. if (!string.IsNullOrWhiteSpace(school) && userType.Equals("schoolid"))
  612. {
  613. containerId = "Student";
  614. PartitionKey = $"StuCourse-{school}-{id}";
  615. }
  616. else
  617. {
  618. containerId = "Student";
  619. PartitionKey = $"StuCourse-{id}";
  620. }
  621. List<StuCourse> stus = new List<StuCourse>();
  622. List<StuCourseDto> sc = new List<StuCourseDto>();
  623. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, containerId).GetItemQueryIteratorSql<StuCourse>(queryText: $"select value(c) from c ",
  624. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(PartitionKey) }))
  625. {
  626. stus.Add(item);
  627. }
  628. foreach (var cos in stus)
  629. {
  630. if (cos.scope.Equals("school"))
  631. {
  632. Course course = new();
  633. try
  634. {
  635. course = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Course>(cos.id, new PartitionKey(cos.scode));
  636. }
  637. catch (CosmosException ex) { course = null; }
  638. sc.Add(new StuCourseDto { course = course, stuCourse = cos });
  639. }
  640. else
  641. {
  642. Course course = new();
  643. try
  644. {
  645. course = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(cos.id, new PartitionKey(cos.scode));
  646. var list = course.schedule.Where(x => string.IsNullOrWhiteSpace(x.stulist)).Select(x => x.stulist);
  647. }
  648. //需要处理 当前这个老师已经不在相关名单内。
  649. catch (CosmosException ex) { course = null; }
  650. sc.Add(new StuCourseDto { course = course, stuCourse = cos });
  651. }
  652. }
  653. //获取老师详细信息
  654. HashSet<string> info = new HashSet<string>();
  655. HashSet<string> room = new HashSet<string>();
  656. foreach (StuCourseDto dto in sc)
  657. {
  658. if (dto.course != null)
  659. {
  660. if (dto.course.schedule.Count > 0)
  661. {
  662. foreach (Schedule schedule in dto.course.schedule)
  663. {
  664. if (!string.IsNullOrEmpty(schedule.teacherId))
  665. {
  666. info.Add(schedule.teacherId);
  667. }
  668. if (!string.IsNullOrEmpty(schedule.room))
  669. {
  670. room.Add(schedule.room);
  671. }
  672. }
  673. }
  674. }
  675. }
  676. //处理教师基础信息
  677. List<(string id, string name)> teachers = new();
  678. if (info.Count > 0)
  679. {
  680. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(
  681. queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", info.Select(o => $"'{o}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  682. {
  683. using var json = await JsonDocument.ParseAsync(item.Content);
  684. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  685. {
  686. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  687. while (accounts.MoveNext())
  688. {
  689. JsonElement account = accounts.Current;
  690. teachers.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
  691. }
  692. }
  693. }
  694. }
  695. //处理教室基础信息
  696. List<(string id, string name)> rooms = new();
  697. if (room.Count > 0)
  698. {
  699. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(
  700. queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", room.Select(o => $"'{o}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Room-{school}") }))
  701. {
  702. using var json = await JsonDocument.ParseAsync(item.Content);
  703. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  704. {
  705. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  706. while (accounts.MoveNext())
  707. {
  708. JsonElement account = accounts.Current;
  709. rooms.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
  710. }
  711. }
  712. }
  713. }
  714. var courses = sc.Select(s => new
  715. {
  716. course = s.course != null ? new
  717. {
  718. id = s.course.id,
  719. name = s.course.name,
  720. code = s.course.code,
  721. creatorId = s.course.creatorId,
  722. no = s.course.no,
  723. period = s.course.period,
  724. desc = s.course.desc,
  725. school = s.course.school,
  726. scope = s.course.scope,
  727. pk = s.course.pk,
  728. subject = s.course.subject,
  729. schedule = s.course.schedule.Select(c => new
  730. {
  731. room = c.room,
  732. roomName = rooms.FirstOrDefault(t => t.id == c.room).name,
  733. classId = c.classId,
  734. teacherId = c.teacherId,
  735. teacherName = teachers.FirstOrDefault(t => t.id == c.teacherId).name,
  736. time = c.time,
  737. stulist = c.stulist
  738. })
  739. } : null,
  740. s.stuCourse
  741. });
  742. return Ok(new { courses });
  743. }
  744. }
  745. public class StuCourseDto
  746. {
  747. public StuCourse stuCourse { get; set; }
  748. public Course course { get; set; }
  749. }
  750. }