123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182 |
- using Microsoft.Azure.Cosmos;
- using Azure.Messaging.ServiceBus;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Cors;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Text.Json;
- using System.Text.Json.Nodes;
- 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.OpenEntity;
- using TEAMModelOS.SDK.Models.Service;
- namespace TEAMModelOS.Controllers
- {
- /// <summary>
- /// 课堂记录
- /// </summary>
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- [Route("common/lesson-record")]
- [ApiController]
-
- public class LessonRecordController : ControllerBase
- {
-
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly SnowflakeId _snowflakeId;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureRedisFactory _azureRedis;
- public IConfiguration _configuration { get; set; }
- public LessonRecordController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
- IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration)
- {
- _azureCosmos = azureCosmos;
- _serviceBus = serviceBus;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _configuration = configuration;
- }
- /// <summary>
- /// 更新课堂记录
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("update-lesson-baseinfo")]
- #if !DEBUG
- [AuthToken(Roles = "teacher,admin")]
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> UpdateLessonBaseInfo(JsonElement request)
- {
- var client = _azureCosmos.GetCosmosClient();
- if (!request.TryGetProperty("lesson_id", out JsonElement _lessonId)) return BadRequest();
- if (!request.TryGetProperty("tmdid", out JsonElement _tmdid)) return BadRequest();
- request.TryGetProperty("school", out JsonElement _school);
- if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
- if (!request.TryGetProperty("grant_types", out JsonElement _grant_types)) return BadRequest();
- string tbname ;
- string code ;
- if (_scope.GetString().Equals("school") && !string.IsNullOrWhiteSpace(_school.GetString()))
- {
- code = $"LessonRecord-{_school}";
- tbname = "School";
- }
- else if ($"{_scope}".Equals("private"))
- {
- code = $"LessonRecord";
- tbname = "Teacher";
- }
- else
- {
- return BadRequest();
- }
- try
- {
- Dictionary<string, object> dict = new Dictionary<string, object>();
- if (_grant_types.ValueKind.Equals(JsonValueKind.Array)) {
- LessonRecord lessonRecord = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<LessonRecord>($"{_lessonId}", new PartitionKey(code));
- List<LessonUpdate> updates = _grant_types.ToObject<List<LessonUpdate>>();
- foreach (var item in updates) {
- if (item.grant_type.Equals("up-baseinfo")) {
- JsonElement element = item.data.ToJsonString().ToObject<JsonElement>();
- element.TryGetProperty("name", out JsonElement _name);
- element.TryGetProperty("subjectId", out JsonElement _subjectId);
- element.TryGetProperty("grade", out JsonElement _grade);
- element.TryGetProperty("category", out JsonElement _category);
- element.TryGetProperty("show", out JsonElement _show);
- if (_name.ValueKind.Equals(JsonValueKind.String) && !string.IsNullOrWhiteSpace($"{_name}"))
- {
- lessonRecord.name = $"{_name}";
- }
- if (_subjectId.ValueKind.Equals(JsonValueKind.String) && !string.IsNullOrWhiteSpace($"{_subjectId}"))
- {
- lessonRecord.subjectId = $"{_subjectId}";
- }
- if (_grade.ValueKind.Equals(JsonValueKind.Array))
- {
- lessonRecord.grade = _grade.ToObject<List<string>>();
- }
- if (_category.ValueKind.Equals(JsonValueKind.Array))
- {
- lessonRecord.category = _category.ToObject<List<string>>();
- }
- if (_show.ValueKind.Equals(JsonValueKind.Array))
- {
- lessonRecord.show = _show.ToObject<List<string>>();
- }
- await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, $"{_lessonId}", new PartitionKey(code));
- dict["up-baseinfo"] = new { status= 1 ,code="ok"};
- }
- if (item.grant_type.Equals("up-expire")) {
- if (_scope.GetString().Equals("private"))
- {
- Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{_tmdid}", new PartitionKey("Base"));
- HashSet<string> ids = new HashSet<string>();
- //未定义的 以及过期时间小于等于0 的 课例
- string private_count_sql = $"select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{_tmdid}' ";
- await foreach (var lid in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<string>(
- queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
- {
- ids.Add(lid);
- }
- //包含收藏的本人的个人课例
- string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.owner='{_tmdid}' and c.scope='private' ";
- await foreach (var lid in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<string>(
- queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{_tmdid}") }))
- {
- ids.Add(lid);
- }
- //教师个人预设的,可以通过设置的方式增加
- int limit = teacher.lessonLimit;
- if (teacher.lessonLimit == 0)
- {
- //未设置的的采用系统设置的默认值50
- limit = Constant.private_lesson_limit;
- }
- if (ids.Count < limit)
- {
- lessonRecord.expire = -1;
- await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, $"{_lessonId}", new PartitionKey(code));
- dict["up-expire"] = new { status = 1, code = "ok" };
- }
- else
- {
- dict["up-expire"] = new { status = 0, code = "lessonLimit", data = limit };
- }
- }
- else if (_scope.GetString().Equals("school")) {
- lessonRecord.expire = -1;
- await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, $"{_lessonId}", new PartitionKey(code));
- dict["up-expire"] = new { status = 1, code = "ok" };
- }
- }
- }
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- var messageChange = new ServiceBusMessage(request.ToJsonString());
- messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
- return Ok(new { status = 200,updateInfo= dict });
- }
- return BadRequest();
- }
- catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
- {
- return BadRequest("课堂记录不存在");
- }
- catch (Exception ex)
- {
- return BadRequest();
- }
- }
- /*
- {
- "scope":"school/private",
- "tmdid":"1595321354",
- "delete_id":"asdeeeqq-adfghnlr-pfkcmsss-ssadffgtre",
- "opt":"delete",
- "school":"hbcn" //如果scope=school 这 school字段必须有值
- }
- */
- /// <summary>
- /// 删除课堂记录
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- // [AuthToken(Roles = "teacher,admin")]
- [HttpPost("delete-lesson-record")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "admin,teacher")]
- public async Task<IActionResult> DeleteLessonRecord(JsonElement request)
- {
-
- string school;
- string tbname;
- string code;
- if (request.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
- // && request.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
- && request.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
- && request.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
- {
- request.TryGetProperty("school", out JsonElement _dschool);
- school = $"{_dschool}";
- var client = _azureCosmos.GetCosmosClient();
- if ($"{_opt}".Equals("delete"))
- {
- if ($"{_dscope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
- {
- code = $"LessonRecord-{school}";
- tbname = "School";
- }
- else if ($"{_dscope}".Equals("private"))
- {
- code = $"LessonRecord";
- tbname = "Teacher";
- }
- else
- {
- return BadRequest() ;
- }
- List<string> lessonIds = new List<string>();
- //string lessonId = $"{_delete_id}";
- if (_delete_id.ValueKind.Equals(JsonValueKind.Array))
- {
- lessonIds.AddRange(_delete_id.ToObject<List<string>>());
- }
- else {
- lessonIds.Add($"{_delete_id}");
- }
- if (lessonIds.IsNotEmpty())
- {
- foreach (var lessonId in lessonIds) {
- ResponseMessage response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- LessonRecord lessonRecord;
- var doc = JsonDocument.Parse(response.Content);
- lessonRecord = doc.RootElement.ToObject<LessonRecord>();
- lessonRecord.status = 404;
- await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- var messageChange = new ServiceBusMessage(request.ToJsonString());
- messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
-
- }
- }
- return Ok(new { status = 200 });
- }
- else { return BadRequest(); }
- }
- else { return BadRequest() ; }
- }
- else
- {
- return BadRequest();
- }
- }
- /// <summary>
- /// 获取开课记录 (c.status<>404 or IS_DEFINED(c.status)=false )
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher,admin")]
- [HttpPost("get-lesson-record-count")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "admin,teacher,student")]
- public async Task<IActionResult> GetLessonRecordCont(JsonElement request)
- {
- object _roles = null;
- HttpContext?.Items.TryGetValue("Roles", out _roles);
- List<string> roles = new List<string>();
- if (_roles != null)
- {
- roles = _roles.ToJsonString().ToObject<List<string>>();
- }
- if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
- request.TryGetProperty("managePage", out JsonElement _managePage);
- bool managePage = false;
- if (_managePage.ValueKind.Equals(JsonValueKind.True)) {
- managePage = true;
- }
- StringBuilder sql = new StringBuilder();
- sql.Append("select c.id,c.groupIds,c.courseId from c ");
- Dictionary<string ,object> dict = LessonService.GetLessonCond(request);
- AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
- string tbname = "";
- string code = "";
- string school = null;
- List<string> autoTch = new List<string>();
- string sqlPrivate = "";
- if (_scope.GetString().Equals("school"))
- {
- if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
- if (!string.IsNullOrEmpty($"{_school}"))
- {
- school = $"{_school}";
- code = $"LessonRecord-{_school}";
- tbname = "School";
- List<string> ids = new List<string>();
- //只查询某个老师的课例
- if (request.TryGetProperty("tmdid", out JsonElement tmdid) && !string.IsNullOrWhiteSpace($"{tmdid}"))
- {
- ids.Add($"{tmdid}");
- }
- else
- {
- string sqltch = "select distinct value(c.id) from c ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .GetItemQueryIteratorSql<string>(queryText: sqltch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{_school}") }))
- {
- ids.Add(item);
- }
- }
- if (ids.Any())
- {
- string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
- {
- autoTch.Add(item);
- }
- }
- }
- else {
- return BadRequest();
- }
-
- }
- else if ($"{_scope}".Equals("private"))
- {
- code = $"LessonRecord";
- tbname = "Teacher";
- request.TryGetProperty("tmdid", out JsonElement _tmdid);
- if (!string.IsNullOrEmpty($"{_tmdid}"))
- {
-
- sqlPrivate = $" and c.tmdid='{_tmdid}'";
- List<string> ids = new List<string>();
- ids.Add($"{_tmdid}");
- if (ids.Any())
- {
- string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
- {
- autoTch.Add(item);
- }
- }
- }
- else
- {
- //如果不传tmdid, 则必须传递,课程id或者名单列表
- // 如果不传递tmdid
- if (!request.TryGetProperty("groupIds", out JsonElement groupIds))
- {
- return BadRequest("个人课例不传醍摩豆id则必传 groupIds");
- }
- }
- }
- else
- {
- return BadRequest();
- }
- int count=0;
- string sqlShow = "";
- if (roles.Count == 1 && roles.Contains("student"))
- {
- string autoSql = "";
- if (autoTch.Any())
- {
- autoSql = $" or c.tmdid in ({string.Join(",", autoTch.Select(x => $"'{x}'"))})";
- }
- sqlShow = $" and (array_contains(c.show,'student') or array_contains(c.show,'all') {autoSql} ) ";
- }
- long now = DateTimeOffset.Now.ToUnixTimeMilliseconds();
- string sql_status_managePage = " (c.status<>404 or IS_DEFINED(c.status) = false ) and ";
- if (managePage) {
- sql_status_managePage = "";
- }
- cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where {sql_status_managePage} array_length(c.groupIds)>0 {sqlPrivate} {sqlShow} and ");
- if (request.TryGetProperty("singleGreen", out JsonElement doubleGreen) && doubleGreen.GetBoolean())
- {
- cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where ((c.tLevel=2 and c.pLevel<2 )or(c.tLevel<2 and c.pLevel=2 )) and ");
- }
- if (request.TryGetProperty("expire", out JsonElement expire) && expire.ValueKind.Equals(JsonValueKind.True))
- {
- cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where c.expire>{now} and ");
- }
- List<LessonRecord> records = new List<LessonRecord>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIteratorQuery<LessonRecord>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
- {
- records.Add(item);
- }
- if (records.Any()) {
- var groupIds= records.SelectMany(x => x.groupIds).ToHashSet();
- if (groupIds.Any()) {
- var groups = await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToList(), school," c.id ");
- //获取已经被删除的名单。
- var idsExp = groupIds.Except(groups.Select(x => x.id));
- if (idsExp.Any()) {
- foreach(var item in records)
- {
- int countRmv = item.groupIds.RemoveAll(x => idsExp.Contains(x));
- if (countRmv > 0)
- {
- try {
- LessonRecord record = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<LessonRecord>(item.id, new PartitionKey(code));
- record.groupIds = item.groupIds;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(record, item.id, new PartitionKey(code));
- } catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound) {
- continue;
- }
- }
- }
- }
- }
- }
- count = records.Count;
- return Ok(new { count=count, records });
- }
- /// <summary>
- /// 获取开课记录
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- // [AuthToken(Roles = "teacher,admin")]
- [HttpPost("get-lesson-record-schorpvt")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "admin,teacher,student")]
- public async Task<IActionResult> GetLessonRecordSchOrPvt(JsonElement request) {
- object _roles = null;
- HttpContext?.Items.TryGetValue("Roles", out _roles);
- List<string> roles = new List<string>();
- if (_roles != null)
- {
- roles = _roles.ToJsonString().ToObject<List<string>>();
- }
- StringBuilder sql = new StringBuilder();
- sql.Append("select value(c) from c ");
-
- Dictionary<string, object> dict = LessonService.GetLessonCond(request);
-
- if (request.TryGetProperty("DESC", out JsonElement desc))
- {
- dict.Add("@DESC", desc.ToString());
- }
- if (request.TryGetProperty("ASC", out JsonElement asc))
- {
- dict.Add("@ASC", asc.ToString());
- }
-
- string school = null;
- AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
- List<LessonRecord> lessonRecords = new List<LessonRecord>();
- //获取学校的
- {
- string tbname = "School";
- string code = "";
-
- string sqlPrivate = "";
- List<string> autoTch = new List<string>();
- request.TryGetProperty("school", out JsonElement _school);
- if (!string.IsNullOrEmpty($"{_school}"))
- {
- code = $"LessonRecord-{_school}";
- tbname = "School";
- school = $"{_school}";
- List<string> ids = new List<string>();
- //只查询某个老师的课例
- if (request.TryGetProperty("tmdid", out JsonElement tmdid) && !string.IsNullOrWhiteSpace($"{tmdid}"))
- {
- ids.Add($"{tmdid}");
- }
- else
- {
- string sqltch = "select distinct value(c.id) from c ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .GetItemQueryIteratorSql<string>(queryText: sqltch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{_school}") }))
- {
- ids.Add(item);
- }
- }
- if (ids.Any())
- {
- string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
- {
- autoTch.Add(item);
- }
- }
- string sqlShow = "";
- if (roles.Count == 1 && roles.Contains("student"))
- {
- string autoSql = "";
- if (autoTch.Any())
- {
- autoSql = $" or c.tmdid in ({string.Join(",", autoTch.Select(x => $"'{x}'"))})";
- }
- sqlShow = $" and (array_contains(c.show,'student') or array_contains(c.show,'all') {autoSql} ) ";
- }
- cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where (c.status<>404 or IS_DEFINED(c.status) = false ) and array_length(c.groupIds)>0 {sqlPrivate} {sqlShow} and ");
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname)
- .GetItemQueryStreamIteratorQuery(queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
- {
- 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())
- {
- lessonRecords.Add(obj.ToObject<LessonRecord>());
- }
- break;
- }
- }
- }
- }
- //获取个人的
- {
- string code = $"LessonRecord";
- string tbname = "Teacher";
- List<string> autoTch = new List<string>();
- request.TryGetProperty("tmdid", out JsonElement _tmdid);
- if (!string.IsNullOrEmpty($"{_tmdid}"))
- {
- string sqlPrivate = $" and c.tmdid='{_tmdid}'";
- List<string> ids = new List<string>();
- ids.Add($"{_tmdid}");
- if (ids.Any())
- {
- string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
- {
- autoTch.Add(item);
- }
- }
- string sqlShow = "";
- if (roles.Count == 1 && roles.Contains("student"))
- {
- string autoSql = "";
- if (autoTch.Any())
- {
- autoSql = $" or c.tmdid in ({string.Join(",", autoTch.Select(x => $"'{x}'"))})";
- }
- sqlShow = $" and (array_contains(c.show,'student') or array_contains(c.show,'all') {autoSql} ) ";
- }
- cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where (c.status<>404 or IS_DEFINED(c.status) = false ) and array_length(c.groupIds)>0 {sqlPrivate} {sqlShow} and ");
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname)
- .GetItemQueryStreamIteratorQuery(queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
- {
- 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())
- {
- lessonRecords.Add(obj.ToObject<LessonRecord>());
- }
- break;
- }
- }
- }
- }
- var tmdids = lessonRecords.Select(x => x.tmdid).ToHashSet();
- if (tmdids != null && tmdids.Count > 0)
- {
- List<IdNameCode> codes = new List<IdNameCode>();
- string sqltmd = $"select c.id,c.name,c.picture from c where c.id in ({string.Join(",", tmdids.Select(x => $"'{x}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<IdNameCode>(queryText: sqltmd, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- codes.Add(item);
- }
- if (codes.IsNotEmpty())
- {
- lessonRecords.ForEach(x => {
- var tmd = codes.Find(z => z.id.Equals(x.tmdid));
- if (tmd != null)
- {
- x.tmdname = tmd.name;
- x.tmdpicture = tmd.picture;
- }
- });
- }
- }
- var groupIds = lessonRecords.SelectMany(x => x.groupIds);
- if (groupIds.Any())
- {
- List<GroupListDto> groupLists = await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToList(), school);
- lessonRecords.ForEach(x => {
- List<string> groupNmae = new List<string>();
- x.groupIds.ForEach(y => {
- var dto = groupLists.Find(z => z.id.Equals(y));
- string name = dto != null ? dto.name : "-";
- groupNmae.Add(name);
- });
- x.groupNames = groupNmae;
- });
- }
- if(request.TryGetProperty("top", out JsonElement _top) && lessonRecords.Any())
- {
- var rcords= lessonRecords.OrderByDescending(x => x.startTime).Take(int.Parse($"{_top}"));
- return Ok(new { currCount =rcords.Count(), lessonRecords =rcords});
- }
- return Ok(new { currCount = lessonRecords.Count, lessonRecords });
- }
- /// <summary>
- /// 获取开课记录
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- // [AuthToken(Roles = "teacher,admin")]
- [HttpPost("get-lesson-record")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles ="admin,teacher,student")]
- public async Task<IActionResult> GetLessonRecord(JsonElement request)
- {
- object _roles = null;
- HttpContext?.Items.TryGetValue("Roles", out _roles);
- List<string> roles = new List<string>();
- if (_roles != null) {
- roles = _roles.ToJsonString().ToObject<List<string>>();
- }
- if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
- request.TryGetProperty("managePage", out JsonElement _managePage);
- bool managePage = false;
- if (_managePage.ValueKind.Equals(JsonValueKind.True))
- {
- managePage = true;
- }
- StringBuilder sql = new StringBuilder();
- sql.Append("select value(c) from c ");
- int pageCount = 10;
- Dictionary<string, object> dict = LessonService.GetLessonCond(request);
- if (request.TryGetProperty("pageCount", out JsonElement _pageCount))
- {
- int.TryParse($"{_pageCount}", out int pcount);
- if (pcount > 0)
- {
- pageCount = pcount;
- }
- }
- if (request.TryGetProperty("DESC", out JsonElement desc))
- {
- dict.Add("@DESC", desc.ToString());
- }
- if (request.TryGetProperty("ASC", out JsonElement asc))
- {
- dict.Add("@ASC", asc.ToString());
- }
- string continuationToken = null;
- if (request.TryGetProperty("continuationToken", out JsonElement _continuationToken))
- {
- if (!string.IsNullOrEmpty($"{_continuationToken}"))
- {
- continuationToken = $"{_continuationToken}";
- }
- }
- AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
- string tbname = "";
- string code = "";
- string school = null;
- string sqlPrivate = "";
- List<string> autoTch = new List<string>();
- if (_scope.GetString().Equals("school"))
- {
- if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
- if (!string.IsNullOrEmpty($"{_school}"))
- {
- code = $"LessonRecord-{_school}";
- tbname = "School";
- school = $"{_school}";
- List<string> ids = new List<string>();
- //只查询某个老师的课例
- if (request.TryGetProperty("tmdid", out JsonElement tmdid) && !string.IsNullOrWhiteSpace($"{tmdid}"))
- {
- ids.Add($"{tmdid}");
- }
- else {
- string sqltch = "select distinct value(c.id) from c ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .GetItemQueryIteratorSql<string>(queryText: sqltch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{_school}") }))
- {
- ids.Add(item);
- }
- }
- if (ids.Any()) {
- string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
- {
- autoTch.Add(item);
- }
- }
- }
- else
- {
- return BadRequest();
- }
- }
- else if ($"{_scope}".Equals("private"))
- {
- code = $"LessonRecord";
- tbname = "Teacher";
- request.TryGetProperty("tmdid", out JsonElement _tmdid);
- if (!string.IsNullOrEmpty($"{_tmdid}"))
- {
- sqlPrivate = $" and c.tmdid='{_tmdid}'";
- List<string> ids = new List<string>();
- ids.Add($"{_tmdid}");
- if (ids.Any())
- {
- string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
- {
- autoTch.Add(item);
- }
- }
- }
- else
- {
- //如果不传tmdid, 则必须传递,课程id或者名单列表
- // 如果不传递tmdid
- if (!request.TryGetProperty("groupIds", out JsonElement groupIds)) {
- return BadRequest("个人课例不传醍摩豆id则必传 groupIds");
- }
- }
- }
- else
- {
- return BadRequest();
- }
- List<LessonRecord> lessonRecords = new List<LessonRecord>();
- try
- {
- string sqlShow = "";
- if (roles.Count == 1 && roles.Contains("student"))
- {
- string autoSql = "";
- if (autoTch.Any()) {
- autoSql = $" or c.tmdid in ({string.Join(",",autoTch.Select(x=>$"'{x}'"))})";
- }
- sqlShow = $" and (array_contains(c.show,'student') or array_contains(c.show,'all') {autoSql} ) ";
- }
- string sql_status_managePage = "(c.status<>404 or IS_DEFINED(c.status) = false ) and ";
- if (managePage)
- {
- sql_status_managePage = "";
- }
- cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where {sql_status_managePage} array_length(c.groupIds)>0 {sqlPrivate} {sqlShow} and ");
- if (request.TryGetProperty("singleGreen", out JsonElement doubleGreen) && doubleGreen.GetBoolean())
- {
- cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where ((c.tLevel=2 and c.pLevel<2 )or(c.tLevel<2 and c.pLevel=2 )) and ");
- }
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname)
- .GetItemQueryStreamIteratorQuery(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, continuationToken: continuationToken,
- requestOptions: new QueryRequestOptions() { MaxItemCount = pageCount, PartitionKey = new PartitionKey(code) }))
- {
- 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())
- {
- var rcd = obj.ToObject<LessonRecord>();
- if (rcd.hitaClientCmpCount <= 0 && rcd.collateTaskCount > 0) {
- rcd.hitaClientCmpCount= rcd.collateTaskCount;
- }
- if (rcd.learningCategory == null)
- {
- rcd.learningCategory = new LearningCategory();
- }
- if (rcd.hitaClientCmpCount > 0)
- {
- rcd.learningCategory.cooperation = 1;
- }
- lessonRecords.Add(rcd);
- }
- continuationToken = item.ContinuationToken;
- break;
- }
- }
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- //查询时处理已经过期的课例。防止ServiceBus未触发的。
- var expireRecords= lessonRecords.Where(x=> x.expire > 0 && now > x.expire);
- try {
- foreach (var item in expireRecords)
- {
- //item.status = 404;
- //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- var messageChange = new ServiceBusMessage(new { delete_id = item.id, tmdid = item.tmdid, scope = item.scope, opt = "delete", school = item.school }.ToJsonString());
- messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
- }
- } catch (Exception ex) {
- await _dingDing.SendBotMsg($"{_option.Location},ServiceBus ,LessonRecordEvent 发送消息失败,检查是否配置正常。", GroupNames.成都开发測試群組);
- }
- var tmdids = lessonRecords.Select(x => x.tmdid).ToHashSet();
- if (tmdids != null && tmdids.Count > 0)
- {
- List<IdNameCode> codes = new List<IdNameCode>();
- string sqltmd = $"select c.id,c.name,c.picture from c where c.id in ({string.Join(",", tmdids.Select(x => $"'{x}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<IdNameCode>(queryText: sqltmd, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- codes.Add(item);
- }
- if (codes.IsNotEmpty())
- {
- lessonRecords.ForEach(x => {
- var tmd = codes.Find(z => z.id.Equals(x.tmdid));
- if (tmd != null)
- {
- x.tmdname = tmd.name;
- x.tmdpicture = tmd.picture;
- }
- });
- }
- }
- var groupIds = lessonRecords.SelectMany(x => x.groupIds);
- if (groupIds.Any()) {
- List<GroupListDto> groupLists= await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToList(), school);
- lessonRecords.ForEach(x => {
- List<string> groupNmae = new List<string>();
- x.groupIds.ForEach(y => {
- var dto= groupLists.Find(z => z.id.Equals(y));
- string name = dto != null ? dto.name : "-";
- groupNmae.Add(name);
- });
- x.groupNames = groupNmae;
- });
- }
- //已经过期的处理掉垃圾数据
- List<LessonRecord> lessonRecords404 = new List<LessonRecord>();
- foreach (var item in lessonRecords)
- {
- if (item.scope.Equals("school"))
- {
- if (item.expire>0 && item.expire<now && item.status!=404)
- {
- item.status=404;
- await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, item.school, new List<string> { $"records/{item.id}" });
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(item.id, new PartitionKey($"Bloblog-{item.school}"));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
- lessonRecords404.Add(item);
- }
- }
- }
- if (lessonRecords404.IsNotEmpty()) {
- foreach (var item in lessonRecords404) {
- lessonRecords.Remove(item);
- }
- }
- return Ok(new { currCount = lessonRecords.Count, continuationToken, lessonRecords });
- }
- catch (Exception )
- {
- continuationToken = null;
- return Ok(new { currCount = 0, continuationToken = continuationToken, lessonRecords });
- }
- }
- /// <summary>
- /// 获取开课记录
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- // [AuthToken(Roles = "teacher,admin")]
- [HttpPost("get-lesson-record-id")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "admin,teacher,student")]
- public async Task<IActionResult> GetLessonRecordId(JsonElement request)
- {
- if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
- if (!request.TryGetProperty("id", out JsonElement _id)) return BadRequest();
- string tbname = "";
- string code = "";
- if (_scope.GetString().Equals("school"))
- {
- if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
- if (!string.IsNullOrEmpty($"{_school}"))
- {
- code = $"LessonRecord-{_school}";
- tbname = "School";
- }
- else
- {
- return BadRequest();
- }
- }
- else if ($"{_scope}".Equals("private"))
- {
- if (!request.TryGetProperty("tmdid", out JsonElement _tmdid)) return BadRequest();
- if (!string.IsNullOrEmpty($"{_tmdid}"))
- {
- code = $"LessonRecord";
- tbname = "Teacher";
- }
- else
- {
- return BadRequest();
- }
- }
- else
- {
- return BadRequest();
- }
- try
- {
- LessonRecord lessonRecord = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<LessonRecord>($"{_id}", new PartitionKey(code));
- return Ok(new { lessonRecord });
- }
- catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
- {
- return Ok(new { status = 404 });
- }
- }
- /// <summary>
- /// 获取开课记录
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- // [AuthToken(Roles = "teacher,admin")]
- [HttpPost("get-other-lesson-record")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "admin,teacher,student")]
- public async Task<IActionResult> GetOtherLessonRecord(JsonElement request)
- {
- if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
- string tbname = "";
- string code = "";
- string sqlPrivate = "";
- if (_scope.GetString().Equals("school") )
- {
- if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
- if (!string.IsNullOrEmpty($"{_school}"))
- {
- code = $"LessonRecord-{_school}";
- tbname = "School";
- }
- else
- {
- return BadRequest();
- }
- }
- else if ($"{_scope}".Equals("private"))
- {
- if (!request.TryGetProperty("tmdid", out JsonElement _tmdid)) return BadRequest();
- if (!string.IsNullOrEmpty($"{_tmdid}"))
- {
- sqlPrivate = $" and c.tmdid='{_tmdid}'";
- code = $"LessonRecord";
- tbname = "Teacher";
- }
- else {
- return BadRequest();
- }
- }
- else
- {
- return BadRequest();
- }
- request.TryGetProperty("periodId", out JsonElement _periodId);
- request.TryGetProperty("stime", out JsonElement _stime);
- request.TryGetProperty("etime", out JsonElement _etime);
- //优质课程
- var excellent = new JsonObject
- {
- ["excellent"] = true,
- ["periodId"] = $"{_periodId}",
- ["stime"] = $"{_stime}",
- ["etime"] = $"{_etime}",
- }.ToJsonString().ToObject<JsonElement>();
- //专家好客
- var doubleGreen = new JsonObject
- {
- ["doubleGreen"] = true,
- ["periodId"] = $"{_periodId}",
- ["stime"] = $"{_stime}",
- ["etime"] = $"{_etime}",
- }.ToJsonString().ToObject<JsonElement>();
- //今日课程
- var today = new JsonObject
- {
- ["today"] = true,
- ["periodId"] = $"{_periodId}",
- }.ToJsonString().ToObject<JsonElement>();
-
- List<LessonRecord> excellentRcd =await GetOtherLessonCond(excellent, code, tbname, sqlPrivate);
- List<LessonRecord> doubleGreenRcd = await GetOtherLessonCond(doubleGreen, code, tbname, sqlPrivate);
- List<LessonRecord> todayRcd = await GetOtherLessonCond(today, code, tbname, sqlPrivate);
- try {
- var tmdids_excellent = excellentRcd.Select(x => x.tmdid);
- var tmdids_doubleGreen = excellentRcd.Select(x => x.tmdid);
- var tmdids_today = excellentRcd.Select(x => x.tmdid);
- List<string> tmdids=new List<string>();
- tmdids.AddRange(tmdids_excellent);
- tmdids.AddRange(tmdids_doubleGreen);
- tmdids.AddRange(tmdids_today);
- if (tmdids != null && tmdids.Count > 0) {
- List< IdNameCode > codes= new List<IdNameCode> ();
- string sqltmd = $"select c.id,c.name,c.picture from c where c.id in ({string.Join(",", tmdids.Select(x => $"'{x}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<IdNameCode>(queryText:sqltmd,requestOptions:new QueryRequestOptions { PartitionKey=new PartitionKey("Base") })){
- codes.Add(item);
- }
- if (codes.IsNotEmpty()) {
- excellentRcd.ForEach(x => {
- var tmd= codes.Find(z => z.id.Equals(x.tmdid));
- if (tmd != null) {
- x.tmdname = tmd.name;
- x.tmdpicture= tmd.picture;
- }
- });
- doubleGreenRcd.ForEach(x => {
- var tmd = codes.Find(z => z.id.Equals(x.tmdid));
- if (tmd != null)
- {
- x.tmdname = tmd.name;
- x.tmdpicture = tmd.picture;
- }
- });
- todayRcd.ForEach(x => {
- var tmd = codes.Find(z => z.id.Equals(x.tmdid));
- if (tmd != null)
- {
- x.tmdname = tmd.name;
- x.tmdpicture = tmd.picture;
- }
- });
- }
- }
- return Ok(new { excellentRcd , doubleGreenRcd, todayRcd });
- } catch (Exception ex) {
- return Ok(new { excellentRcd, doubleGreenRcd, todayRcd });
- }
- }
- private async Task<List<LessonRecord>> GetOtherLessonCond(JsonElement request,string code ,string tbname,string sqlPrivate) {
- StringBuilder sql = new StringBuilder();
- sql.Append("select value(c) from c ");
- Dictionary<string, object> dict = LessonService.GetLessonCond(request);
- AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
- List<LessonRecord> lessonRecords = new List<LessonRecord>();
- cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where (c.status<>404 or IS_DEFINED(c.status) = false ) and array_length(c.groupIds)>0 {sqlPrivate} and ");
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname)
- .GetItemQueryStreamIteratorQuery(queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
- {
- 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())
- {
- lessonRecords.Add(obj.ToObject<LessonRecord>());
- }
- }
- }
- return lessonRecords;
- }
- /// <summary>
- /// 验证IES课例
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpGet("lesson-record-verify")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher")]
- [EnableCors("AllowSpecificOrigin")]//跨域
- public async Task<IActionResult> LessonRecordVerify([FromQuery] string id , [FromQuery] string owner, [FromQuery] string scope, [FromQuery] string token )
- {
- (string tmdid, _, _, string school) = HttpContext.GetAuthTokenInfo();
- if (!string.IsNullOrWhiteSpace(id)) { return Ok(new { code=4001,msg="id不能为空" }); }
- if (!string.IsNullOrWhiteSpace(scope)) { return Ok(new { code = 4002, msg = "scope不能为空" }); }
- if (!string.IsNullOrWhiteSpace(owner)) { return Ok(new { code = 4003, msg = "owner不能为空" }); }
- if (!string.IsNullOrWhiteSpace(token)) { return Ok(new { code = 4004, msg = "token不能为空" }); }
- string tbname;
- string code;
- if (scope.Equals("school") && !string.IsNullOrWhiteSpace(owner))
- {
- code = $"LessonRecord-{owner}";
- tbname = "School";
- }
- else if ($"{scope}".Equals("private") && owner.Equals(tmdid))
- {
- code = $"LessonRecord";
- tbname = "Teacher";
- }
- else
- {
- { return Ok(new { code = 400, msg = "参数错误" }); }
- }
- ResponseMessage response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(id, new PartitionKey(code));
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- LessonRecord lessonRecord = JsonDocument.Parse(response.Content).RootElement.ToObject<LessonRecord>();
- if (lessonRecord.scope.Equals("school"))
- {
- if (lessonRecord.school.Equals(school))
- {
- if (lessonRecord.tmdid.Equals(tmdid))
- {
- return Ok(new { code = 200, lessonRecord });
- }
- else
- {
- ///不是本人的课例
- ///(非授权信息) 服务器已成功处理了请求,但返回的信息可能来自另一来源。
- return Ok(new { code = 2031, lessonRecord });
- }
- }
- else
- {
- //不是同一个学校的课例
- ///(非授权信息) 服务器已成功处理了请求,但返回的信息可能来自另一来源。
- return Ok(new { code = 2032, lessonRecord });
- }
- }
- else {
- if (lessonRecord.tmdid.Equals(tmdid))
- {
- return Ok(new { code = 200, lessonRecord });
- }
- else
- {
- ///不是本人的课例
- ///(非授权信息) 服务器已成功处理了请求,但返回的信息可能来自另一来源。
- return Ok(new { code = 2031, lessonRecord });
- }
- }
- }
- else {
- return Ok(new { code = 404, msg = "课例不存在" });
- }
- }
- }
- }
|