using Azure.Cosmos;
using Azure.Messaging.ServiceBus;
using HTEXLib.COMM.Helpers;
using Microsoft.AspNetCore.Authorization;
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.DI.AzureCosmos.Inner;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Models.Service;
namespace TEAMModelOS.Controllers
{
///
/// 课堂记录
///
[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, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration)
{
_azureCosmos = azureCosmos;
_serviceBus = serviceBus;
_snowflakeId = snowflakeId;
_dingDing = dingDing;
_option = option?.Value;
_azureStorage = azureStorage;
_azureRedis = azureRedis;
_configuration = configuration;
}
///
/// 更新课堂记录
///
///
///
[ProducesDefaultResponseType]
[HttpPost("update-lesson-baseinfo")]
[AuthToken(Roles = "admin,teacher")]
public async Task 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 dict = new Dictionary();
if (_grant_types.ValueKind.Equals(JsonValueKind.Array)) {
LessonRecord lessonRecord = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync($"{_lessonId}", new PartitionKey(code));
List updates = _grant_types.ToObject>();
foreach (var item in updates) {
if (item.grant_type.Equals("up-baseinfo")) {
JsonElement element = item.data.ToJsonString().ToObject();
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>();
}
if (_category.ValueKind.Equals(JsonValueKind.Array))
{
lessonRecord.category = _category.ToObject>();
}
if (_show.ValueKind.Equals(JsonValueKind.Array))
{
lessonRecord.show = _show.ToObject>();
}
await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, $"{_lessonId}", new PartitionKey(code));
dict["up-baseinfo"] = new { status= 1 ,code="ok"};
}
if (item.grant_type.Equals("up-expire")) {
if (_scope.Equals("private"))
{
Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync($"{_tmdid}", new PartitionKey("Base"));
HashSet ids = new HashSet();
//未定义的 以及过期时间小于等于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).GetItemQueryIterator(
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).GetItemQueryIterator(
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, $"{_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.Equals("school")) {
lessonRecord.expire = -1;
await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, $"{_lessonId}", new PartitionKey(code));
dict["up-expire"] = new { status = 1, code = "ok" };
}
}
}
var ActiveTask = _configuration.GetValue("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.Status == 404)
{
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字段必须有值
}
*/
///
/// 删除课堂记录
///
///
///
[ProducesDefaultResponseType]
// [AuthToken(Roles = "teacher,admin")]
[HttpPost("delete-lesson-record")]
[Authorize(Roles = "IES")]
[AuthToken(Roles = "admin,teacher")]
public async Task 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 lessonIds = new List();
//string lessonId = $"{_delete_id}";
if (_delete_id.ValueKind.Equals(JsonValueKind.Array))
{
lessonIds.AddRange(_delete_id.ToObject>());
}
else {
lessonIds.Add($"{_delete_id}");
}
if (lessonIds.IsNotEmpty())
{
foreach (var lessonId in lessonIds) {
Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
if (response.Status == 200)
{
LessonRecord lessonRecord;
var doc = JsonDocument.Parse(response.ContentStream);
lessonRecord = doc.RootElement.ToObject();
lessonRecord.status = 404;
await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
var ActiveTask = _configuration.GetValue("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();
}
}
///
/// 获取开课记录 (c.status<>404 or IS_DEFINED(c.status)=false )
///
///
///
[ProducesDefaultResponseType]
//[AuthToken(Roles = "teacher,admin")]
[HttpPost("get-lesson-record-count")]
[Authorize(Roles = "IES")]
[AuthToken(Roles = "admin,teacher,student")]
public async Task GetLessonRecordCont(JsonElement request)
{
object _roles = null;
HttpContext?.Items.TryGetValue("Roles", out _roles);
List roles = new List();
if (_roles != null)
{
roles = _roles.ToJsonString().ToObject>();
}
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 dict = LessonService.GetLessonCond(request);
AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
string tbname = "";
string code = "";
string school = null;
List autoTch = new List();
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 ids = new List();
//只查询某个老师的课例
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)
.GetItemQueryIterator(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)
.GetItemQueryIterator(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 ids = new List();
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)
.GetItemQueryIterator(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} ) ";
}
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 ");
}
List records = new List();
await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIterator(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(item.id, new PartitionKey(code));
record.groupIds = item.groupIds;
await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(record, item.id, new PartitionKey(code));
} catch (CosmosException ex) when (ex.Status == 404) {
continue;
}
}
}
}
}
}
count = records.Count;
return Ok(new { count=count, records });
}
///
/// 获取开课记录
///
///
///
[ProducesDefaultResponseType]
// [AuthToken(Roles = "teacher,admin")]
[HttpPost("get-lesson-record-schorpvt")]
[Authorize(Roles = "IES")]
[AuthToken(Roles = "admin,teacher,student")]
public async Task GetLessonRecordSchOrPvt(JsonElement request) {
object _roles = null;
HttpContext?.Items.TryGetValue("Roles", out _roles);
List roles = new List();
if (_roles != null)
{
roles = _roles.ToJsonString().ToObject>();
}
StringBuilder sql = new StringBuilder();
sql.Append("select value(c) from c ");
Dictionary 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 lessonRecords = new List();
//获取学校的
{
string tbname = "School";
string code = "";
string sqlPrivate = "";
List autoTch = new List();
request.TryGetProperty("school", out JsonElement _school);
if (!string.IsNullOrEmpty($"{_school}"))
{
code = $"LessonRecord-{_school}";
tbname = "School";
school = $"{_school}";
List ids = new List();
//只查询某个老师的课例
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)
.GetItemQueryIterator(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)
.GetItemQueryIterator(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)
.GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
{
using var json = await JsonDocument.ParseAsync(item.ContentStream);
if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
{
foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
{
lessonRecords.Add(obj.ToObject());
}
break;
}
}
}
}
//获取个人的
{
string code = $"LessonRecord";
string tbname = "Teacher";
List autoTch = new List();
request.TryGetProperty("tmdid", out JsonElement _tmdid);
if (!string.IsNullOrEmpty($"{_tmdid}"))
{
string sqlPrivate = $" and c.tmdid='{_tmdid}'";
List ids = new List();
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)
.GetItemQueryIterator(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)
.GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
{
using var json = await JsonDocument.ParseAsync(item.ContentStream);
if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
{
foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
{
lessonRecords.Add(obj.ToObject());
}
break;
}
}
}
}
var tmdids = lessonRecords.Select(x => x.tmdid).ToHashSet();
if (tmdids != null && tmdids.Count > 0)
{
List codes = new List();
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").GetItemQueryIterator(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 groupLists = await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToList(), school);
lessonRecords.ForEach(x => {
List groupNmae = new List();
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;
});
}
return Ok(new { currCount = lessonRecords.Count, lessonRecords });
}
///
/// 获取开课记录
///
///
///
[ProducesDefaultResponseType]
// [AuthToken(Roles = "teacher,admin")]
[HttpPost("get-lesson-record")]
[Authorize(Roles = "IES")]
[AuthToken(Roles ="admin,teacher,student")]
public async Task GetLessonRecord(JsonElement request)
{
object _roles = null;
HttpContext?.Items.TryGetValue("Roles", out _roles);
List roles = new List();
if (_roles != null) {
roles = _roles.ToJsonString().ToObject>();
}
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 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 autoTch = new List();
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 ids = new List();
//只查询某个老师的课例
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)
.GetItemQueryIterator(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)
.GetItemQueryIterator(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 ids = new List();
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)
.GetItemQueryIterator(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 lessonRecords = new List();
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)
.GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, continuationToken: continuationToken,
requestOptions: new QueryRequestOptions() { MaxItemCount = pageCount, PartitionKey = new PartitionKey(code) }))
{
using var json = await JsonDocument.ParseAsync(item.ContentStream);
if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
{
foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
{
var rcd = obj.ToObject();
if (rcd.hitaClientCmpCount <= 0 && rcd.collateTaskCount > 0) {
rcd.hitaClientCmpCount= rcd.collateTaskCount;
}
lessonRecords.Add(rcd);
}
continuationToken = item.GetContinuationToken();
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("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 codes = new List();
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").GetItemQueryIterator(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 groupLists= await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToList(), school);
lessonRecords.ForEach(x => {
List groupNmae = new List();
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;
});
}
return Ok(new { currCount = lessonRecords.Count, continuationToken, lessonRecords });
}
catch (Exception )
{
continuationToken = null;
return Ok(new { currCount = 0, continuationToken = continuationToken, lessonRecords });
}
}
///
/// 获取开课记录
///
///
///
[ProducesDefaultResponseType]
// [AuthToken(Roles = "teacher,admin")]
[HttpPost("get-lesson-record-id")]
[Authorize(Roles = "IES")]
[AuthToken(Roles = "admin,teacher,student")]
public async Task 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($"{_id}", new PartitionKey(code));
return Ok(new { lessonRecord });
}
catch (CosmosException ex) when (ex.Status == 404)
{
return Ok(new { status = 404 });
}
}
///
/// 获取开课记录
///
///
///
[ProducesDefaultResponseType]
// [AuthToken(Roles = "teacher,admin")]
[HttpPost("get-other-lesson-record")]
[Authorize(Roles = "IES")]
[AuthToken(Roles = "admin,teacher,student")]
public async Task 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();
//专家好客
var doubleGreen = new JsonObject
{
["doubleGreen"] = true,
["periodId"] = $"{_periodId}",
["stime"] = $"{_stime}",
["etime"] = $"{_etime}",
}.ToJsonString().ToObject();
//今日课程
var today = new JsonObject
{
["today"] = true,
["periodId"] = $"{_periodId}",
}.ToJsonString().ToObject();
List excellentRcd =await GetOtherLessonCond(excellent, code, tbname, sqlPrivate);
List doubleGreenRcd = await GetOtherLessonCond(doubleGreen, code, tbname, sqlPrivate);
List 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 tmdids=new List();
tmdids.AddRange(tmdids_excellent);
tmdids.AddRange(tmdids_doubleGreen);
tmdids.AddRange(tmdids_today);
if (tmdids != null && tmdids.Count > 0) {
List< IdNameCode > codes= new List ();
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").GetItemQueryIterator(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> GetOtherLessonCond(JsonElement request,string code ,string tbname,string sqlPrivate) {
StringBuilder sql = new StringBuilder();
sql.Append("select value(c) from c ");
Dictionary dict = LessonService.GetLessonCond(request);
AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
List lessonRecords = new List();
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)
.GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
{
using var json = await JsonDocument.ParseAsync(item.ContentStream);
if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
{
foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
{
lessonRecords.Add(obj.ToObject());
}
}
}
return lessonRecords;
}
}
}