123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818 |
- using Azure.Cosmos;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.IdentityModel.Tokens.Jwt;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.Models.Dto;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
- using TEAMModelOS.SDK.Helper.Common.StringHelper;
- using System.Dynamic;
- using Azure;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- //[Authorize(Roles = "IES5")]
- [Route("school/course")]
- [ApiController]
- public class CourseController : ControllerBase
- {
- private AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- public CourseController(AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _option = option?.Value;
- }
- /// <summary>
- /// 更新保存课程
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("upsert")]
- public async Task<IActionResult> upsert(JsonElement requert)
- {
- try {
- /*//ResponseBuilder builder = ResponseBuilder.custom();
- if (!string.IsNullOrEmpty(requert.id))
- {
- List<int> count = await _azureCosmos.FindCountByDict<Course>(new Dictionary<string, object> { { "courseCode", requert.courseCode }, { "code", requert.code } });
- if (count.IsNotEmpty() && count[0] > 0)
- {
- // return builder.Error(ResponseCode.DATA_EXIST, "课程编码已经存在!").build();
- }
- requert.id = requert.code.Replace("#", "") + "-" + requert.courseCode;
- }
- Course response = await _azureCosmos.SaveOrUpdate<Course>(requert);
- return Ok(new { requert });*/
- Course course = new Course();
- if (!requert.TryGetProperty("course", out JsonElement room)) return BadRequest();
- if (!requert.TryGetProperty("option", out JsonElement option)) return BadRequest();
- course = room.ToObject<Course>();
- var client = _azureCosmos.GetCosmosClient();
- course.pk = typeof(Course).Name;
- string code = course.code;
- course.code = typeof(Course).Name + "-" + course.code;
- if (option.ToString().Equals("insert"))
- {
- var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(course.id, new PartitionKey($"Course-{code}"));
- if (response.Status == 200)
- {
- return Ok(new { error = ResponseCode.DATA_EXIST, V = "课程编码已经存在!" });
- }
- else
- {
- course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync(course, new PartitionKey($"Course-{code}"));
- }
- }
- else
- {
- course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").UpsertItemAsync(course, new PartitionKey($"Course-{code}"));
- }
- return Ok(new { course });
- }
- catch (Exception ex) {
- await _dingDing.SendBotMsg($"OS,{_option.Location},course/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
-
- }
- /// <summary>
- /// 查询课程
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("find")]
- public async Task<IActionResult> Find(JsonElement requert)
- {
- //ResponseBuilder builder = ResponseBuilder.custom();
- //if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
- if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
- //var jwt = new JwtSecurityToken(id_token.GetString());
- //if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
- //var id = jwt.Payload.Sub;
- //var id = "TBLCOURSE700";
- try {
- var client = _azureCosmos.GetCosmosClient();
- List<object> courses = new List<object>();
- var query = $"select c.code,c.id,c.name,c.period,c.subject,c.teachers from c";
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_code.GetString()}") }))
- {
- 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())
- {
- courses.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(new { courses, courses.Count });
- } catch (Exception ex) {
- await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},course/find()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
-
- /* List<Course> data = new List<Course>();
- if (StringHelper.getKeyCount(request) > 0) {
- data = await _azureCosmos.FindByDict<Course>(request);
- }
- return builder.Data(data).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();*/
- }
- /// <summary>
- /// 删除课程
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("delete")]
- public async Task<IActionResult> Delete(JsonElement request)
- {
- try {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- //string school_code = code.ToString().Substring(typeof(Course).Name.Length + 1);
- var client = _azureCosmos.GetCosmosClient();
- if (scope.ToString().Equals("school")){
- List<CourseManagement> managements = new List<CourseManagement>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"select value(c) from c join A0 in c.courses where A0.course.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{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())
- {
- managements.Add(obj.ToObject<CourseManagement>());
- }
- }
- }
- for (int i = 0; i < managements.Count; i++)
- {
- bool flag = false;
- for (int j = 0; j < managements[i].courses.Count; j++)
- {
- if (!managements[i].courses[j].course.id.Equals(id.ToString()))
- {
- flag = true;
- managements[i].courses.Remove(managements[i].courses[j]);
- break;
- }
- }
- if (flag)
- {
- await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(managements[i], managements[i].id, new PartitionKey($"{managements[i].code}"));
- }
- }
- } else {
- await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Course-{code}"));
- }
- //IdPk idPk= await _azureCosmos.DeleteAsync<Course>(request);
- return Ok(new { id });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},course/delete()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
-
- }
- /// <summary>
- /// 删除课程
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("delete-all")]
- public async Task<IActionResult> DeleteAll(BatchOption request)
- {
- try
- {
- /*if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();*/
- var client = _azureCosmos.GetCosmosClient();
- if (request == null) return BadRequest();
- StringBuilder sql = new StringBuilder();
- sql.Append("select value(c) from c ");
- /*Dictionary<string, object> dict = new Dictionary<string, object>();
- //处理id
- if (request.ids.IsNotEmpty())
- {
- dict.Add("id", request.ids.ToArray());
- }*/
- string school_code = request.code;
- /*AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
- List<Course> courses = new List<Course>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_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())
- {
- courses.Add(obj.ToObject<Course>());
- }
- }
- }*/
- List<Response> res = await client.GetContainer("TEAMModelOS", "School").DeleteItemsStreamAsync(request.ids, $"Course-{school_code}");
- // TODO JJ调整批量删除
- //await _azureCosmos.DeleteAll(courses);
- //List<IdPk> idPk = await _azureCosmos.DeleteAll<Course>(request);
- //await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Class-{code}"));
- //[Jeff] CourseManagement表廢除 刪除預定:以下CourseManagement更新程序
- StringBuilder sqlM = new StringBuilder();
- sqlM.Append("select value(c) from c ");
- Dictionary<string, object> dict_management = new Dictionary<string, object>();
- //处理ID
- if (request.ids.IsNotEmpty())
- {
- dict_management.Add("courses[*].course.id", request.ids.ToArray());
- }
- List<CourseManagement> managements = new List<CourseManagement>();
- AzureCosmosQuery cosmosDbQuery_1 = SQLHelper.GetSQL(dict_management, sqlM);
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery_1.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{school_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())
- {
- managements.Add(obj.ToObject<CourseManagement>());
- }
- }
- }
- for (int i = 0; i < managements.Count; i++)
- {
- bool flag = false;
- for (int k = 0; k < request.ids.Count; k++)
- {
- for (int j = 0; j < managements[i].courses.Count; j++)
- {
- if (managements[i].courses[j].course.id.Equals(request.ids[k].ToString()))
- {
- managements[i].courses.Remove(managements[i].courses[j]);
- flag = true;
- }
- }
- }
- if (flag)
- {
- await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(managements[i], managements[i].id, new PartitionKey($"{managements[i].code}"));
- }
- }
- ////[Jeff] CourseManagement表廢除 刪除預定:以下CourseManagement更新程序
- //IdPk idPk= await _azureCosmos.DeleteAsync<Course>(request);
- return Ok(new { ids = request.ids });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},course/delete()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- //ResponseBuilder builder = ResponseBuilder.custom();
- //return builder.Data(idPk).build();
- //return Ok(new { idPk });
- }
- /// <summary>
- /// 更新保存排课管理
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("upsert-management")]
- public async Task<IActionResult> upsertCourseManagement(CourseManagement requert)
- {
- try
- {
- CourseManagement course = new CourseManagement();
- //course = room.ToObject<CourseManagement>();
- var client = _azureCosmos.GetCosmosClient();
- string code = requert.code;
- requert.code = "CourseManagement-" + requert.code;
- /* if (requert.scope.Equals) {
- }*/
- var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(requert.id, new PartitionKey($"CourseManagement-{code}"));
- if (response.Status == 200)
- {
- /* using var json = await JsonDocument.ParseAsync(response.ContentStream);
- CourseManagement courseManagement = json.ToObject<CourseManagement>();
- courseManagement.courses = requert.courses;*/
- //return Ok(new { error = ResponseCode.DATA_EXIST, V = "课程编码已经存在!" });
- course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync(requert, requert.id, new PartitionKey($"CourseManagement-{code}"));
- }
- else
- {
- course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync(requert, new PartitionKey($"CourseManagement-{code}"));
- }
- return Ok(new { course });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},management/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 查询排课管理
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("find-management")]
- public async Task<IActionResult> FindManagement(JsonElement requert)
- {
- //if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<object> courses = new List<object>();
- StringBuilder sql = new StringBuilder();
- sql.Append("select c.code,c.id,c.name,c.courses,c.scope,c.teacher from c ");
- Dictionary<string, object> dict = new Dictionary<string, object>();
- var emobj = requert.EnumerateObject();
- while (emobj.MoveNext())
- {
- dict[emobj.Current.Name] = emobj.Current.Value;
- }
- //处理code
- if (dict.TryGetValue("code", out object _))
- {
- dict.Remove("code");
- }
- AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{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())
- {
- courses.Add(obj.ToObject<object>());
- }
- }
- }
- /* List<object> courses = new List<object>();
- var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(id.ToString(), new PartitionKey($"CourseManagement-{code}"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- foreach (var obj in json.RootElement.GetProperty("courseSimples").EnumerateArray())
- {
- courses.Add(obj.ToObject<object>());
- }
- *//*if (json.RootElement.TryGetProperty("courseSimples", out JsonElement value))
- {
- courses = (List<object>)value.ToObject<object>();
- }*//*
- }
- else {
- return Ok(new { error = ResponseCode.UNDEFINED, V = "数据未找到!" });
- }*/
- return Ok(new { courses });
- /* var query = $"select c.code,c.id,c.name,c.period,c.subject,c.teachers from c";
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_code.GetString()}") }))
- {
- 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())
- {
- courses.Add(obj.ToObject<object>());
- }
- }
- }*/
- //return Ok(new { courses, courses.Count });
- /* List<Course> data = new List<Course>();
- if (StringHelper.getKeyCount(request) > 0) {
- data = await _azureCosmos.FindByDict<Course>(request);
- }
- return builder.Data(data).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();*/
- }
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("find-course")]
- public async Task<IActionResult> FindCourse(JsonElement requert)
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<object> courses = new List<object>();
- var query = $"select c.code,c.id,c.name,A0.course.id courseId,A0.course.name courseName ,A0.course.notice notice ,A1,c.scope,c.teacher from c join A0 in c.courses join A1 in A0.teachers where A1.id = '{id}' ";
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{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())
- {
- courses.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(new { courses });
- }
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("upsert-notice")]
- public async Task<IActionResult> upsertNotice(JsonElement requert)
- {
- if (!requert.TryGetProperty("courseId", out JsonElement courseId)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("notice", out JsonElement notice)) return BadRequest();
- if (!requert.TryGetProperty("A1", out JsonElement teacherInfo)) return BadRequest();
- Teachers teachers = teacherInfo.ToObject<Teachers>();
- var client = _azureCosmos.GetCosmosClient();
- List<CourseManagement> courseManagements = new List<CourseManagement>();
- /*var sresponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{code}"));
- if (sresponse.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
- CourseManagement course = json.ToObject<CourseManagement>();
- for (int i =0; i < course.courses.Count;i++) {
- if (course.courses[i].course.id.Equals(courseId.ToString())) {
- course.courses[i].course.notice = notice.ToString();
- await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(course, course.id, new PartitionKey($"{course.code}"));
- break;
- }
- }
- }*/
- StringBuilder sql = new StringBuilder();
- sql.Append("select value(c) from c");
- Dictionary<string, object> dict = new Dictionary<string, object>();
- //dict.Add("id", id);
- dict.Add("courses[*].course.id", courseId);
- dict.Add("courses[*].teachers[*].id", teachers.id);
- //dict.Add("id", classroom.id);
- AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{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())
- {
- courseManagements.Add(obj.ToObject<CourseManagement>());
- }
- }
- }
- for (int i = 0; i < courseManagements.Count; i++)
- {
- for (int j = 0;j < courseManagements[i].courses.Count;j++) {
- if (courseManagements[i].courses[j].course.id.Equals(courseId.ToString()))
- {
- courseManagements[i].courses[j].course.notice = notice.ToString();
- await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(courseManagements[i], courseManagements[i].id, new PartitionKey($"{courseManagements[i].code}"));
- break;
- }
- }
- }
- return Ok(new { id });
- }
- internal class valitime {
- public string code { get; set; }
- public string courseId { get; set; }
- public string classroomCode { get; set; }
- public string time { get; set; }
- public string day { get; set; }
- public string notice { get; set; }
- public CourseTime courseTime { get; set; }
- /// <summary>
- /// 学生分组
- /// </summary>
- public List<GroupStudent> groups { get; set; }
- /// <summary>
- /// 助教
- /// </summary>
- public List<Assistant> assistant { get; set; }
- /// <summary>
- /// 学期代码
- /// </summary>
- public string semesterCode { get; set; }
- }
- // TODO 前端没在用
- /// <summary>
- /// 教师更新副属信息,助教,分组等。
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- //[ProducesDefaultResponseType]
- ////[AuthToken(Roles = "Teacher")]
- //[HttpPost("upsert-plan")]
- //public async Task<BaseResponse> UpsertPlan(CoursePlan request) {
- // ResponseBuilder builder = ResponseBuilder.custom();
- // CoursePlan datas = await _azureCosmos.FindByIdPk<CoursePlan>(request.id,request.code);
- // if (datas!=null) {
- // request.semesterCode = datas.semesterCode;
- // request.classes.ForEach(x => {
- // datas.classes.ForEach(m => {
- // if (m.classroomCode == x.classroomCode) {
- // x.courseTimes = m.courseTimes;
- // } });
- // });
- // await _azureCosmos.Update(request);
- // }
- // return builder.Data(request).build();
- //}
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("upsert-teacher-course")]
- public async Task<IActionResult> upsertCourse(JsonElement requert)
- {
- try
- {
- TeacherCourse course = new TeacherCourse();
- if (!requert.TryGetProperty("course", out JsonElement room)) return BadRequest();
- if (!requert.TryGetProperty("option", out JsonElement option)) return BadRequest();
- course = room.ToObject<TeacherCourse>();
- var client = _azureCosmos.GetCosmosClient();
- course.pk = typeof(Course).Name;
- string code = course.code;
- course.code = typeof(Course).Name + "-" + course.code;
- if (option.ToString().Equals("insert"))
- {
- var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(course.id, new PartitionKey($"Course-{code}"));
- if (response.Status == 200)
- {
- return Ok(new { error = ResponseCode.DATA_EXIST, V = "课程编码已经存在!" });
- }
- else
- {
- course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(course, new PartitionKey($"Course-{code}"));
- }
- }
- else
- {
- if (course.classes.Count > 0) {
- //TODO 教师创建的个人的校本班级待处理冗余数据
- foreach (ClassSimple classSimple in course.classes) {
- if (classSimple.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
- {
- Class cla = new Class();
- cla.id = classSimple.id;
- cla.code = cla.pk + "-" + code;
- cla.name = classSimple.name;
- cla.scope = classSimple.scope;
- cla.teacher.id = classSimple.teacher.id;
- cla.teacher.name = classSimple.teacher.name;
- await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync(cla, new PartitionKey($"Class-{code}"));
- }
- else {
- var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(classSimple.id, new PartitionKey($"Class-{classSimple.code}"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- Class cla = json.ToObject<Class>();
- Class newCla = new Class();
- newCla.id = cla.id;
- newCla.code = cla.pk + "-" + code;
- newCla.name = classSimple.name;
- newCla.scope = classSimple.scope;
- /*foreach (StudentSimple student in cla.students)
- {
- StudentSimple studentSimple = new StudentSimple();
- studentSimple.id = student.id;
- studentSimple.name = student.name;
- studentSimple.no = student.no;
- newCla.students.Add(studentSimple);
- }*/
- newCla.teacher.id = classSimple.teacher.id;
- newCla.teacher.name = classSimple.teacher.name;
- await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync(newCla, new PartitionKey($"Class-{code}"));
- classSimple.code = code;
- }
- else
- {
- Class cla = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Class>(classSimple.id, new PartitionKey($"Class-{classSimple.code}"));
- Class newCla = new Class();
- newCla.id = cla.id;
- newCla.code = cla.pk + "-" + code;
- newCla.name = classSimple.name;
- newCla.scope = classSimple.scope;
- //newCla.students = cla.students;
- newCla.teacher.id = classSimple.teacher.id;
- newCla.teacher.name = classSimple.teacher.name;
- await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync(newCla, new PartitionKey($"Class-{code}"));
- }
- }
- }
- }
- course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(course,course.id, new PartitionKey($"Course-{code}"));
- }
- return Ok(new { course });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},teacherCourse/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("find-teacher-course")]
- public async Task<IActionResult> FindTeacherCourse(JsonElement requert)
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<object> courses = new List<object>();
- var query = $"select c.code,c.id,c.name,c.subjectId,c.periodId,c.scope,c.notice,c.classes from c ";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{id}") }))
- {
- 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())
- {
- courses.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(new { courses });
- }
-
- /// <summary>
- /// 查询执教助教的课程班级
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("find-teach-class")]
- public async Task<IActionResult> FindPlanClass(JsonElement request)
- {
- ResponseBuilder builder = ResponseBuilder.custom();
- HashSet<string> data = new HashSet<string>();
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<Student> courses = new List<Student>();
- var query = $"select A0.id,A0.name,A0.scope from c join A0 in c.classes";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{id}") }))
- {
- 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())
- {
- courses.Add(obj.ToObject<Student>());
- }
- }
- }
- //List<object> coursesBySchool = new List<object>();
- var queryBySchool = $"select distinct c.id,c.name,c.scope from c join A0 in c.courses join A1 in A0.teachers where A1.id = '{id}' ";
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: queryBySchool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{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())
- {
- courses.Add(obj.ToObject<Student>());
- }
- }
- }
- courses = courses.Distinct(new ListDistinct()).ToList();
- //courses = courses.Distinct().ToList();
- return Ok(new { courses ,courses.Count});
- //request.TryGetProperty("assistant[*]", out JsonElement element);
- /*List<dynamic> room = new List<dynamic>();
- var prop = new List<string> { "classes" };
- if (request.TryGetProperty("code", out JsonElement code))
- {
- var teachers = await _azureCosmos.FindByDict<CoursePlan>(new Dictionary<string, object> { { "code", code.ToString() } }, prop);
- if (teachers.IsNotEmpty()) {
- teachers.Select(x => x.classes).ToList().ForEach(x => { x.ForEach(y => { data.Add(y.classroomCode); }); });
- }
- }
- if (request.TryGetProperty("assistant[*]", out JsonElement element)) {
- var assistant = await _azureCosmos.FindByDict<CoursePlan>(new Dictionary<string, object> { { "assistant[*]", element.ToString() } }, prop);
- if (assistant.IsNotEmpty()) {
- assistant.Select(x => x.classes).ToList().ForEach(x => { x.ForEach(y => { data.Add(y.classroomCode); }); });
- }
- }
- if (data.Count > 0) {
- var classRoom= await _azureCosmos.FindByDict<Classroom>(new Dictionary<string, object> { { "id",data.ToArray() } } );
- if (classRoom.IsNotEmpty()) {
- classRoom.ForEach(x => {
- room.Add(x);
- });
- }
- }*/
- //return builder.Data(room).Extend(new Dictionary<string, object> { { "count", room.Count } }).build();
- }
- // TODO 前端没在用
- /// <summary>
- /// 删除课程安排
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- //[ProducesDefaultResponseType]
- ////[AuthToken(Roles = "Teacher")]
- //[HttpPost("delete-time")]
- //public async Task<BaseResponse> DeletePlan(JsonElement request)
- //{
- // ResponseBuilder builder = ResponseBuilder.custom();
- // if (request.TryGetProperty("id",out JsonElement id) && request.TryGetProperty("code",out JsonElement code) && request.TryGetProperty("classroomCode",out JsonElement classroomCode)
- // && request.TryGetProperty("time",out JsonElement time) && request.TryGetProperty("day",out JsonElement day)) {
- // CoursePlan coursePlan = await _azureCosmos.FindByIdPk<CoursePlan>(id.ToString(), code.ToString());
- // List<CourseTime> courseTimes = new List<CourseTime>();
- // coursePlan.classes.ForEach(x=> {
- // if (x.classroomCode == classroomCode.ToString()) {
- // x.courseTimes.ForEach(y => {
- // if (y.time == time.ToString() && y.day == day.ToString())
- // {
- // courseTimes.Add(y);
- // }
- // });
- // }
- // });
- // coursePlan.classes.ForEach(x => { if (x.classroomCode == classroomCode.ToString()) {
- // courseTimes.ForEach(y => { x.courseTimes.Remove(y); });
- // } });
- // await _azureCosmos.Update(coursePlan);
- // return builder.Data(coursePlan).build();
- // }
- // return builder.Data(null).build();
- //}
-
- public class Student
- {
- public string id { get; set; }
- public string name { get; set; }
- public string scope { get; set; }
- }
-
- public class ListDistinct : IEqualityComparer<Student>
- {
- public bool Equals(Student s1, Student s2)
- {
- return (s1.id == s2.id);
- }
-
- public int GetHashCode(Student s)
- {
- return s==null?0:s.ToString().GetHashCode();
- }
- }
- }
- public class BatchOption {
- public List<string> ids { get; set; }
- public string code { get; set; }
- }
- }
|