123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775 |
- using Microsoft.Azure.Cosmos;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Filter;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Services;
- using static TEAMModelOS.SDK.StudentService;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- //
- [Route("student")]
- [ApiController]
- public class StudentCommonController : ControllerBase
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly AzureRedisFactory _azureRedis;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- public StudentCommonController(AzureCosmosFactory azureCosmos, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option)
- {
- _azureCosmos = azureCosmos;
- _azureRedis = azureRedis;
- _dingDing = dingDing;
- _option = option?.Value;
- }
- /// <summary>
- /// 查询活动所有活动类型的列表,学生端
- /// </summary>
- /// <param name="request">
- ///加入的班级信息 ?classes:[{"classid":"S-C-00001","scope":"school"},{"classid":"P-C-00004","scope":"private"}]
- ///活动类型 ?"type":"Vote"/"Exam"/"Homework"/"Learn"/"Survey"" // Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
- ///时间筛选范围开始时间 默认30天之前 ?"stime":1608274766154
- ///时间筛选范围结束时间 默认当前时间 ?"etime":1608274766666
- ///是否展示列表的 Tips ? "tips":true/false
- ///每页大小 ?"count":10/null/Undefined
- ///分页Token ?"continuationToken":Undefined/null/"[{\"token\":\"+RID:~omxMAP3ipcSEEwAAAAAAAA==#RT:2#TRC:20#ISV:2#IEO:65551#QCF:1#FPC:AYQTAAAAAAAAiRMAAAAAAAA=\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}]"
- /// 当前状态 ?"progress":Undefined/null/"" 表示两种状态都要查询/ "going"/"finish" 表示查询进行中/ 或者已完成 学生端只能查询正在进行或已经结束 going 已发布|finish 已结束
- /// </param>
- ///
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("student-activity")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> StudentActivity(JsonElement request)
- {
- var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
- object _scope = null;
- List<string> groupListIds = new List<string>();
- List<string> subjects = new List<string>();
- if (request.TryGetProperty("groupListIds", out JsonElement _groupListIds)) {
- groupListIds= _groupListIds.ToObject<List<string>>();
- }
- if (request.TryGetProperty("subjects", out JsonElement _subjects))
- {
- subjects= _subjects.ToObject<List<string>>();
- }
- List<string> types = new List<string>();
- if (request.TryGetProperty("types", out JsonElement _types))
- {
- types= _types.ToObject<List<string>>();
- }
- HttpContext?.Items.TryGetValue("Scope", out _scope);
- List<StudentActivity> datas = await StudentService.FindActivity(request, id, $"{_scope}", groupListIds, subjects, school, types, _azureCosmos);
- return Ok(new { code =200, datas, serverTime=DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()});
- }
- /// <summary>
- /// 查询活动所有活动类型的列表,学生端
- /// </summary>
- /// <param name="request">
- ///加入的班级信息 ?classes:[{"classid":"S-C-00001","scope":"school"},{"classid":"P-C-00004","scope":"private"}]
- ///活动类型 ?"type":"Vote"/"Exam"/"Homework"/"Learn"/"Survey"" // Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
- ///时间筛选范围开始时间 默认30天之前 ?"stime":1608274766154
- ///时间筛选范围结束时间 默认当前时间 ?"etime":1608274766666
- ///是否展示列表的 Tips ? "tips":true/false
- ///每页大小 ?"count":10/null/Undefined
- ///分页Token ?"continuationToken":Undefined/null/"[{\"token\":\"+RID:~omxMAP3ipcSEEwAAAAAAAA==#RT:2#TRC:20#ISV:2#IEO:65551#QCF:1#FPC:AYQTAAAAAAAAiRMAAAAAAAA=\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}]"
- /// 当前状态 ?"progress":Undefined/null/"" 表示两种状态都要查询/ "going"/"finish" 表示查询进行中/ 或者已完成 学生端只能查询正在进行或已经结束 going 已发布|finish 已结束
- /// </param>
- ///
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("stu-activity")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> StuActivity(JsonElement request)
- {
- var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
- (List<StuActivity> datas, string continuationToken) = await ActivityStudentService.FindActivity(request, id, school, _azureCosmos, _azureRedis);
- return Ok(new { datas, continuationToken });
- }
- [ProducesDefaultResponseType]
- [HttpPost("stu-score")]
- [AuthToken(Roles = "teacher,admin,student")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> StuScore(JsonElement request)
- {
- var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
- //if (!HttpContext.Items.TryGetValue("Scope", out object _scope)) return BadRequest();
- (List<ExamInfo> datas, string continuationToken) = await ExamService.FindExam(request, id, school, _azureCosmos);
- List<(string id, string scope, string name, string source, List<string> cIds, int qamode, string createId, dynamic ext, long time, string owner)> eIds = new();
- //List<(string id, string scope, string name, List<string> cIds, string createId,long time)> wIds = new();
- foreach (var data in datas)
- {
- eIds.Add((data.id, data.scope, data.name, data.source, data.classes, data.qamode, data.creatorId, data.examType, data.createTime, data.owner));
- }
- if (eIds.Count == 0)
- {
- return Ok(new { code = 404, msg = "暂无数据" });
- }
- var client = _azureCosmos.GetCosmosClient();
- List<(string eId, string sub, string cId, string cname, List<string> sIds, List<double> sum)> classResults = await getExamClassResult(eIds, client);
- List<(string id, double ps)> points = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
- queryText: $"select A0.point,c.id from c join A0 in c.papers where c.id in ({string.Join(",", eIds.Select(o => $"'{o.id}'"))})"))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- List<double> ps = new();
- if (account.TryGetProperty("point", out JsonElement point))
- {
- ps = point.ToObject<List<double>>();
- }
- points.Add((account.GetProperty("id").GetString(), ps.Sum()));
- }
- }
- }
- List<(string id, List<ExamSubject> sub)> subs = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
- queryText: $"select c.subjects,c.id from c where c.id in ({string.Join(",", eIds.Select(o => $"'{o.id}'"))})"))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- List<ExamSubject> sj = new();
- if (account.TryGetProperty("subjects", out JsonElement sn))
- {
- sj = sn.ToObject<List<ExamSubject>>();
- }
- subs.Add((account.GetProperty("id").GetString(), sj));
- }
- }
- }
- var pst = points.GroupBy(x => x.id).Select(p => new { key = p.Key, po = p.Select(o => o.ps) });
- var sut = subs.GroupBy(x => x.id).Select(p => new { key = p.Key, po = p.Select(o => o.sub) });
- var exam = eIds.Select(e => new
- {
- e.id,
- e.name,
- e.scope,
- e.source,
- e.createId,
- e.ext,
- e.qamode,
- e.time,
- e.owner,
- point = pst.Where(s => s.key == e.id).Select(c => c.po),
- subject = subs.Where(s => s.id == e.id).FirstOrDefault().sub,
- result = classResults.Where(c => c.eId == e.id).Select(s => new { s.sub, s.cId, s.cname, s.sum, s.sIds })
- });
- var result = exam.Where(e => e.result.Any()).Select(s => new
- {
- s.id,
- s.name,
- s.scope,
- s.source,
- s.ext,
- s.createId,
- s.qamode,
- s.time,
- s.owner,
- point = s.point.FirstOrDefault(),
- s.subject,
- s.result
- });
- return Ok(new { result, continuationToken });
- }
- [ProducesDefaultResponseType]
- [HttpPost("stu-hw-score")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,student,admin")]
- public async Task<IActionResult> StuHwScore(JsonElement request)
- {
- var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
- //if (!HttpContext.Items.TryGetValue("Scope", out object _scope)) return BadRequest();
- (List<StuActivity> datas, string continuationToken) = await ActivityStudentService.FindActivity(request, id, school, _azureCosmos, _azureRedis);
- //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();
- List<(string id, string scope, string name, List<string> cIds, string createId, long time)> wIds = new();
- foreach (var data in datas)
- {
- wIds.Add((data.id, data.scope, data.name, data.classIds, data.creatorId, data.createTime));
- }
- var client = _azureCosmos.GetCosmosClient();
- string partitionKey = String.Empty;
- if (request.TryGetProperty("userType", out JsonElement userType)) {
- if (userType.GetString().Equals("schoolid"))
- {
- partitionKey = $"HomeworkRecord-{school}-{id}";
- }
- else {
- if (request.TryGetProperty("userid", out JsonElement userid)) {
- id = userid.GetString();
- partitionKey = $"HomeworkRecord-{id}";
- }
- }
- }
- List<(string id, double score, List<HomeworkComment> comments, string comid)> work = new();
- //List<string> comid = new();
- if (wIds.Count > 0) {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(
- queryText: $"select c.id,c.score,c.comments,c.comid from c where c.id in ({string.Join(",", wIds.Select(o => $"'{o.id}'"))})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(partitionKey) }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- double sc = 0;
- List<HomeworkComment> hc = new();
- if (account.TryGetProperty("score", out JsonElement score))
- {
- sc = score.GetDouble();
- if (sc == -1)
- {
- sc = 0;
- }
- }
- if (account.TryGetProperty("comments", out JsonElement comments))
- {
- hc = comments.ToObject<List<HomeworkComment>>();
- }
- //comid.Add(account.GetProperty("comid").GetString());
- work.Add((account.GetProperty("id").GetString(), sc, hc, account.GetProperty("comid").GetString()));
- }
- }
- }
- }
- List<(string id, List<DebateReply> comments)> debates = new();
- List<string> scomid = new();
- List<string> tcomid = new();
- foreach (var cc in wIds)
- {
- if (cc.scope.Equals("school"))
- {
- scomid.Add(work.Where(w => w.id == cc.id).FirstOrDefault().comid);
- }
- else
- {
- tcomid.Add(work.Where(w => w.id == cc.id).FirstOrDefault().comid);
- }
- }
- if (scomid.Count > 0)
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(
- queryText: $"select c.id,c.replies from c where c.id in ({string.Join(",", scomid.Select(o => $"'{o}'"))})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Debate-{school}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- List<DebateReply> debate = new();
- if (account.TryGetProperty("replies", out JsonElement replies))
- {
- debate = replies.ToObject<List<DebateReply>>();
- }
- debates.Add((account.GetProperty("id").GetString(), debate));
- }
- }
- }
- }
- if (tcomid.Count > 0)
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(
- queryText: $"select c.id,c.replies from c where c.pk = 'Debate' and c.id in ({string.Join(",", tcomid.Select(o => $"'{o}'"))})"))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- List<DebateReply> debate = new();
- if (account.TryGetProperty("replies", out JsonElement replies))
- {
- debate = replies.ToObject<List<DebateReply>>();
- }
- debates.Add((account.GetProperty("id").GetString(), debate));
- }
- }
- }
- }
- var coment = work.Select(w => new
- {
- w.id,
- w.comid,
- reply = debates.Where(d => d.id == w.comid).FirstOrDefault().comments
- });
- var replay = coment.Where(c => c.reply != null);
- var works = wIds.Select(w => new
- {
- w.id,
- w.name,
- w.cIds,
- w.createId,
- w.time,
- score = work.Where(x => x.id == w.id).Select(s =>
- new
- {
- s.score,
- s.comments
- }),
- comment = replay.Any() ? replay.Where(c => c.id == w.id).Select(r => new { r.reply }) : null,
- });
- return Ok(new { works, continuationToken });
- }
- //获取学期信息
- [ProducesDefaultResponseType]
- [HttpPost("get-semesters")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,student,admin")]
- public async Task<IActionResult> getSemesters(JsonElement request) {
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("periodId", out JsonElement periodId)) return BadRequest();
- try {
- var client = _azureCosmos.GetCosmosClient();
- List<Semester> semesters = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(
- queryText: $"select A0.semesters from c join A0 in c.period where A0.id = '{periodId}' and c.id = '{code}'",
- requestOptions: new QueryRequestOptions() {PartitionKey = new PartitionKey("Base") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- semesters.Add(obj.ToObject<Semester>());
- }
- }
- }
- return Ok(semesters);
- } catch (Exception ex) {
- await _dingDing.SendBotMsg($"OS,{_option.Location},student/get-semesters()\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- return Ok(new { code = 404, msg = "未找到相应内容"});
- }
- [ProducesDefaultResponseType]
- [HttpPost("stu-record-score")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,student,admin")]
- public async Task<IActionResult> StuRecordScore(JsonElement request)
- {
- if (!HttpContext.Items.TryGetValue("Scope", out object _scope)) return BadRequest();
- var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
- /*if (!request.TryGetProperty("stime", out JsonElement stime)) return BadRequest();
- if (!request.TryGetProperty("etime", out JsonElement etime)) return BadRequest();*/
- var client = _azureCosmos.GetCosmosClient();
- List<StudentLessonRecord> records = new();
- try
- {
- //是否需要进行分页查询,默认不分页
- string token = default;
- bool iscontinuation = false;
- if (request.TryGetProperty("token", out JsonElement token_1))
- {
- token = token_1.GetString();
- };
- //默认不指定返回大小
- int? topcout = null;
- if (request.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- if (topcout != null && topcout.Value > 0)
- {
- iscontinuation = true;
- }
- StringBuilder stringBuilder = null ;
- if ($"{_scope}".Equals(Constant.ScopeStudent)) {
- 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}'");
- } else {
- 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}'");
- }
- if (request.TryGetProperty("stime", out JsonElement stime)) {
- stringBuilder.Append($" and A0.time >= {stime} ");
- }
- if (request.TryGetProperty("etime", out JsonElement etime))
- {
- stringBuilder.Append($" and A0.time <= {etime} ");
- }
- if (request.TryGetProperty("courseId", out JsonElement courseId))
- {
- stringBuilder.Append($" and A0.courseId = '{courseId}' ");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryStreamIteratorSql(
- queryText: stringBuilder.ToString(),
- continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey("StudentScoreRecord") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- records.Add(obj.ToObject<StudentLessonRecord>());
- }
- }
- if (iscontinuation)
- {
- token = item.ContinuationToken;
- break;
- }
- }
- //List<string> ids = records.Select(x => x.lessonId).ToList();
- List<(string id, string name)> info = new();
- if (records.Count > 0) {
- List<string> slessons = records.Where(r => r.scope.Equals("school")).Select(o => o.lessonId).ToList();
- if (slessons.Count > 0) {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(
- queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", slessons.Select(o => $"'{o}'"))})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{school}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- info.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
- }
- }
- }
- }
- List<string> plessons = records.Where(r => r.scope.Equals("private")).Select(o => o.lessonId).ToList();
- if (plessons.Count > 0) {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(
- queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", plessons.Select(o => $"'{o}'"))})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- info.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
- }
- }
- }
- }
-
- }
- var score = records.Select(x => new
- {
- x.tmdid,
- x.school,
- x.scope,
- x.lessonId,
- lessonName = info.Count > 0 ? info.Where(c => c.id.Equals(x.lessonId)).FirstOrDefault().name : "",
- x.courseId,
- x.subjectId,
- x.gscore,
- x.pscore,
- x.tscore,
- x.time
- }).OrderByDescending(c => c.time);
- return Ok(new { score });
- }
- catch (Exception e)
- {
- return Ok(new { code = 404, msg = e.StackTrace });
- }
- }
- 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)
- {
- List<(string eId, string sub, string cId, string cname, List<string> sIds, List<double> sum)> classResults = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(
- 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}'"))})"))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- List<string> sIds = new();
- List<double> sums = new();
- string sub = string.Empty;
- string cid = string.Empty;
- string cname = string.Empty;
- if (account.TryGetProperty("studentIds", out JsonElement stu))
- {
- sIds = stu.ToObject<List<string>>();
- }
- if (account.TryGetProperty("sum", out JsonElement sum))
- {
- sums = sum.ToObject<List<double>>();
- }
- if (account.TryGetProperty("subjectId", out JsonElement subject))
- {
- sub = subject.GetString();
- }
- if (account.TryGetProperty("cId", out JsonElement cc))
- {
- cid = cc.GetString();
- }
- if (account.TryGetProperty("cName", out JsonElement cn))
- {
- cname = cn.GetString();
- }
- classResults.Add((account.GetProperty("eId").GetString(), sub, cid, cname, sIds, sums));
- }
- }
- }
- return classResults;
- }
- /// <summary>
- /// 查询活动所有活动类型的列表,学生端
- /// </summary>
- /// <param name="request">
- /// userid
- /// school
- /// </param>
- ///
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("stu-course")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- [AuthToken(Roles = "student")]
- public async Task<IActionResult> StuCourse(JsonElement request)
- {
- var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
- if (string.IsNullOrWhiteSpace(id))
- {
- if (request.TryGetProperty("userid", out JsonElement userid))
- {
- if (!userid.ValueKind.Equals(JsonValueKind.Undefined) && !userid.ValueKind.Equals(JsonValueKind.Null) && userid.ValueKind.Equals(JsonValueKind.String))
- {
- id = userid.GetString();
- }
- }
- }
- if (string.IsNullOrWhiteSpace(school))
- {
- if (request.TryGetProperty("school", out JsonElement schooljson))
- {
- if (!schooljson.ValueKind.Equals(JsonValueKind.Undefined) && !schooljson.ValueKind.Equals(JsonValueKind.Null) && schooljson.ValueKind.Equals(JsonValueKind.String))
- {
- school = schooljson.GetString();
- }
- }
- }
- /// tmdid, schoolid
- var userType = "tmdid";
- if (request.TryGetProperty("userType", out JsonElement usertype))
- {
- if (!usertype.ValueKind.Equals(JsonValueKind.Undefined) && !usertype.ValueKind.Equals(JsonValueKind.Null) && usertype.ValueKind.Equals(JsonValueKind.String))
- {
- userType = usertype.GetString();
- }
- }
- string containerId = "";
- string PartitionKey = "";
- if (!string.IsNullOrWhiteSpace(school) && userType.Equals("schoolid"))
- {
- containerId = "Student";
- PartitionKey = $"StuCourse-{school}-{id}";
- }
- else
- {
- containerId = "Student";
- PartitionKey = $"StuCourse-{id}";
- }
- List<StuCourse> stus = new List<StuCourse>();
- List<StuCourseDto> sc = new List<StuCourseDto>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, containerId).GetItemQueryIteratorSql<StuCourse>(queryText: $"select value(c) from c ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(PartitionKey) }))
- {
- stus.Add(item);
- }
- foreach (var cos in stus)
- {
- if (cos.scope.Equals("school"))
- {
- Course course = new();
- try
- {
- course = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Course>(cos.id, new PartitionKey(cos.scode));
- }
- catch (CosmosException ex) { course = null; }
- sc.Add(new StuCourseDto { course = course, stuCourse = cos });
- }
- else
- {
- Course course = new();
- try
- {
- course = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(cos.id, new PartitionKey(cos.scode));
- var list = course.schedule.Where(x => string.IsNullOrWhiteSpace(x.stulist)).Select(x => x.stulist);
- }
- //需要处理 当前这个老师已经不在相关名单内。
- catch (CosmosException ex) { course = null; }
- sc.Add(new StuCourseDto { course = course, stuCourse = cos });
- }
- }
- //获取老师详细信息
- HashSet<string> info = new HashSet<string>();
- HashSet<string> room = new HashSet<string>();
- foreach (StuCourseDto dto in sc)
- {
- if (dto.course != null)
- {
- if (dto.course.schedule.Count > 0)
- {
- foreach (Schedule schedule in dto.course.schedule)
- {
- if (!string.IsNullOrEmpty(schedule.teacherId))
- {
- info.Add(schedule.teacherId);
- }
- if (!string.IsNullOrEmpty(schedule.room))
- {
- room.Add(schedule.room);
- }
- }
- }
- }
- }
- //处理教师基础信息
- List<(string id, string name)> teachers = new();
- if (info.Count > 0)
- {
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(
- 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") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- teachers.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
- }
- }
- }
- }
- //处理教室基础信息
- List<(string id, string name)> rooms = new();
- if (room.Count > 0)
- {
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(
- 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}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- rooms.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
- }
- }
- }
- }
- var courses = sc.Select(s => new
- {
- course = s.course != null ? new
- {
- id = s.course.id,
- name = s.course.name,
- code = s.course.code,
- creatorId = s.course.creatorId,
- no = s.course.no,
- period = s.course.period,
- desc = s.course.desc,
- school = s.course.school,
- scope = s.course.scope,
- pk = s.course.pk,
- subject = s.course.subject,
- schedule = s.course.schedule.Select(c => new
- {
- room = c.room,
- roomName = rooms.FirstOrDefault(t => t.id == c.room).name,
- classId = c.classId,
- teacherId = c.teacherId,
- teacherName = teachers.FirstOrDefault(t => t.id == c.teacherId).name,
- time = c.time,
- stulist = c.stulist
- })
- } : null,
- s.stuCourse
- });
- return Ok(new { courses });
- }
- }
- public class StuCourseDto
- {
- public StuCourse stuCourse { get; set; }
- public Course course { get; set; }
- }
- }
|