1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954 |
- 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;
- using TEAMModelOS.SDK.Helper.Common.StringHelper;
- using System.Dynamic;
- using Azure;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using Azure.Messaging.ServiceBus;
- using Microsoft.Extensions.Configuration;
- using TEAMModelOS.Filter;
- using Azure.Storage.Blobs.Models;
- 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;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly AzureStorageFactory _azureStorage;
- public IConfiguration _configuration { get; set; }
- public CourseController(AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option, AzureServiceBusFactory serviceBus, AzureStorageFactory azureStorage, IConfiguration configuration)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _option = option?.Value;
- _serviceBus = serviceBus;
- _configuration = configuration;
- _azureStorage = azureStorage;
- }
- /// <summary>
- /// 更新保存课程
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher")]
- [HttpPost("upsert")]
- public async Task<IActionResult> upsert(JsonElement requert)
- {
- try
- {
- (string id, _, _, string school) = HttpContext.GetAuthTokenInfo();
- Course course = new Course();
- if (!requert.TryGetProperty("course", out JsonElement _course)) return BadRequest();
- if (!requert.TryGetProperty("option", out JsonElement option)) return BadRequest();
- if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- course = _course.ToObject<Course>();
- var client = _azureCosmos.GetCosmosClient();
- course.pk = typeof(Course).Name;
- if (course.scope.Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- course.school = school;
- course.creatorId = id;
- }
- else
- {
- course.creatorId = id;
- }
- string code = course.code;
- course.code = typeof(Course).Name + "-" + course.code;
- if (option.ToString().Equals("insert"))
- {
- if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- 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
- {
- CourseChange courseChange = new CourseChange { id = course.id, code = course.code, name = course.name, scope = course.scope, school = course.school, creatorId = course.creatorId };
- courseChange.addClass = course.schedule.Select(x => x.classId).ToList();
- courseChange.addList = course.schedule.Select(x => x.stulist).ToList();
- course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync(course, new PartitionKey($"Course-{code}"));
- }
- }
- else
- {
- 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
- {
- CourseChange courseChange = new CourseChange { id = course.id, code = course.code, name = course.name, scope = course.scope, school = course.school, creatorId = course.creatorId };
- courseChange.addClass = course.schedule.Select(x => x.classId).ToList();
- courseChange.addList = course.schedule.Select(x => x.stulist).ToList();
- var messageBlob = new ServiceBusMessage(courseChange.ToJsonString()); ;
- messageBlob.ApplicationProperties.Add("name", "Course");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
- course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(course, new PartitionKey($"Course-{code}"));
- }
- }
- }
- else
- {
- if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- Course odlCourse = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReadItemAsync<Course>(course.id, new PartitionKey($"Course-{code}"));
- CourseChange courseChange = new CourseChange { id = course.id, code = course.code, name = course.name, scope = course.scope, school = code };
- var oldCls = odlCourse.schedule.Select(x => x.classId).ToList();
- var oldLst = odlCourse.schedule.Select(x => x.stulist).ToList();
- var newCls = course.schedule.Select(x => x.classId).ToList();
- var newLst = course.schedule.Select(x => x.stulist).ToList();
- List<string> addCls = new List<string>();
- List<string> addLst = new List<string>();
- List<string> delCls = new List<string>();
- List<string> delLst = new List<string>();
- oldCls.ForEach(x =>
- {
- if (!newCls.Contains(x))
- {
- delCls.Add(x);
- }
- });
- newCls.ForEach(x =>
- {
- if (!oldCls.Contains(x))
- {
- addCls.Add(x);
- }
- });
- oldLst.ForEach(x =>
- {
- if (!newLst.Contains(x))
- {
- delLst.Add(x);
- }
- });
- newLst.ForEach(x =>
- {
- if (!oldLst.Contains(x))
- {
- addLst.Add(x);
- }
- });
- courseChange.addClass = addCls;
- courseChange.addList = addLst;
- courseChange.delClass = delCls;
- courseChange.delList = delLst;
- course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync(course, course.id, new PartitionKey($"Course-{code}"));
- var messageBlob = new ServiceBusMessage(courseChange.ToJsonString()); ;
- messageBlob.ApplicationProperties.Add("name", "Course");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
- }
- else
- {
- Course odlCourse = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Course>(course.id, new PartitionKey($"Course-{code}"));
- CourseChange courseChange = new CourseChange { id = course.id, code = course.code, name = course.name, scope = course.scope, creatorId = code };
- var oldCls = odlCourse.schedule.Select(x => x.classId).ToList();
- var oldLst = odlCourse.schedule.Select(x => x.stulist).ToList();
- var newCls = course.schedule.Select(x => x.classId).ToList();
- var newLst = course.schedule.Select(x => x.stulist).ToList();
- List<string> addCls = new List<string>();
- List<string> addLst = new List<string>();
- List<string> delCls = new List<string>();
- List<string> delLst = new List<string>();
- oldCls.ForEach(x =>
- {
- if (!newCls.Contains(x))
- {
- delCls.Add(x);
- }
- });
- newCls.ForEach(x =>
- {
- if (!oldCls.Contains(x))
- {
- addCls.Add(x);
- }
- });
- oldLst.ForEach(x =>
- {
- if (!newLst.Contains(x))
- {
- delLst.Add(x);
- }
- });
- newLst.ForEach(x =>
- {
- if (!oldLst.Contains(x))
- {
- addLst.Add(x);
- }
- });
- courseChange.addClass = addCls;
- courseChange.addList = addLst;
- courseChange.delClass = delCls;
- courseChange.delList = delLst;
- course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(course, course.id, new PartitionKey($"Course-{code}"));
- var messageBlob = new ServiceBusMessage(courseChange.ToJsonString()); ;
- messageBlob.ApplicationProperties.Add("name", "Course");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
- }
- }
- return Ok(new { course });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},course/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [HttpPost("check")]
- public async Task<IActionResult> check(JsonElement json)
- {
- try
- {
- if (!json.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- if (!json.TryGetProperty("timeId", out JsonElement timeId)) return BadRequest();
- if (!json.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!json.TryGetProperty("week", out JsonElement week)) return BadRequest();
- if (!json.TryGetProperty("cId", out JsonElement cId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var query = $"SELECT A0.room,A0.classId,A0.teacherId,A0.stulist,A0.time FROM c join A0 in c.schedule join A1 in A0.time where A0.teacherId = '{tId}'and A1.id = '{timeId}' and A1.week = '{week}' ";
- List<Schedule> teachers = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code}") }))
- {
- using var jsonCheck = await JsonDocument.ParseAsync(item.ContentStream);
- if (jsonCheck.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in jsonCheck.RootElement.GetProperty("Documents").EnumerateArray())
- {
- teachers.Add(obj.ToObject<Schedule>());
- }
- }
- }
- if (teachers.Count > 0)
- {
- return Ok(new { msg = "该教师已有课程安排", code = 1 });
- }
- else
- {
- var queryClass = $"SELECT A0.room,A0.classId,A0.teacherId,A0.stulist,A0.time FROM c join A0 in c.schedule join A1 in A0.time where A1.id = '{timeId}' and A1.week = '{week}' and (A0.classId = '{cId}' or A0.stulist = '{cId}')";
- List<Schedule> courses = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code}") }))
- {
- using var jsonCheck = await JsonDocument.ParseAsync(item.ContentStream);
- if (jsonCheck.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in jsonCheck.RootElement.GetProperty("Documents").EnumerateArray())
- {
- courses.Add(obj.ToObject<Schedule>());
- }
- }
- }
- if (courses.Count > 0)
- {
- return Ok(new { msg = "该名单已有课程安排", code = 2 });
- }
- }
- return Ok(new { code = 0 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},course/check()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /*
- {
- "stuListNo": "1124582",
- "studentId": "19990005",//tmdId/studentId 只能是其中一个有值
- "tmdId":"1538614518",
- }
- */
- /// <summary>
- /// 扫码加入名单
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("scan-code-join-list")]
- public async Task<IActionResult> ScanCodeJoinList(JsonElement json)
- {
- try
- {
- if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
- json.TryGetProperty("school", out JsonElement _school);
- string school = $"{_school}";
- var client = _azureCosmos.GetCosmosClient();
- var queryNo = $"SELECT * FROM c where c.no ='{_stuListNo}'";
- StuList stuList = null;
- json.TryGetProperty("studentId", out JsonElement _studentId);
- json.TryGetProperty("tmdId", out JsonElement _tmdId);
- if (!string.IsNullOrEmpty(school) && !string.IsNullOrEmpty($"{_studentId}"))
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: queryNo,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList-{school}") }))
- {
- using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
- if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var stuDoc = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
- while (stuDoc.MoveNext())
- {
- JsonElement data = stuDoc.Current;
- stuList = data.ToObject<StuList>();
- if (stuList != null)
- {
- (int status, StuList stuLis) = JoinList(stuList, $"{_studentId}", $"{_tmdId}", school);
- stuLis = await upsertList(stuList, "school");
- return Ok(new { status, stuLis });
- }
- }
- }
- }
- }
- json.TryGetProperty("id_token", out JsonElement id_token);
- if (!string.IsNullOrEmpty($"{_tmdId}") && !string.IsNullOrEmpty($"{id_token}"))
- {
- var jwt = new JwtSecurityToken(id_token.GetString());
- var id = jwt.Payload.Sub;
- jwt.Payload.TryGetValue("name", out object name);
- jwt.Payload.TryGetValue("picture", out object picture);
- try
- {
- Teacher teacher = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
- }
- catch (CosmosException ex)
- {
- if (ex.Status == 404)
- {
- //如果沒有,則初始化Teacher基本資料到Cosmos
- Teacher teacher = new Teacher
- {
- id = id,
- pk = "Base",
- code = "Base",
- name = name?.ToString(),
- picture = picture?.ToString(),
- //创建账号并第一次登录IES5则默认赠送1G
- size = 1,
- defaultSchool = null,
- schools = new List<Teacher.School>(),
- };
- var container = _azureStorage.GetBlobContainerClient(id);
- await container.CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器,如存在則不做任何事,保障容器一定存在
- teacher = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
- }
- }
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: queryNo,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList") }))
- {
- using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
- if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var stuDoc = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
- while (stuDoc.MoveNext())
- {
- JsonElement data = stuDoc.Current;
- stuList = data.ToObject<StuList>();
- if (stuList != null)
- {
- (int status, StuList stuLis) = JoinList(stuList, $"{_studentId}", $"{_tmdId}", school);
- stuLis = await upsertList(stuList, "private");
- return Ok(new { status, stuLis });
- }
- }
- }
- }
- return Ok(new { status = -1 });
- }
- else
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},course/scan-code-join-list()\n扫码加入课程参数异常{json}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},course/scan-code-join-list()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 根据邀请码加入名单
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,teacher,student")]
- [HttpPost("get-list-by-no")]
- public async Task<IActionResult> GetListByNo(JsonElement json)
- {
- try
- {
- if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- var client = _azureCosmos.GetCosmosClient();
- var queryNo = $"SELECT * FROM c where c.no ='{_stuListNo}'";
- StuList stuList = null;
- json.TryGetProperty("studentId", out JsonElement _studentId);
- json.TryGetProperty("tmdId", out JsonElement _tmdId);
- if (!string.IsNullOrEmpty(school))
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: queryNo,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList-{school}") }))
- {
- using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
- if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var stuDoc = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
- while (stuDoc.MoveNext())
- {
- JsonElement data = stuDoc.Current;
- stuList = data.ToObject<StuList>();
- if (stuList != null)
- {
- (int status, StuList stuLis) = JoinList(stuList, $"{_studentId}", $"{_tmdId}", school);
- stuLis = await upsertList(stuList, "school");
- return Ok(new { status, stuLis });
- }
- }
- }
- }
- }
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: queryNo,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList") }))
- {
- using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
- if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var stuDoc = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
- while (stuDoc.MoveNext())
- {
- JsonElement data = stuDoc.Current;
- stuList = data.ToObject<StuList>();
- if (stuList != null)
- {
- (int status, StuList stuLis) = JoinList(stuList, $"{_studentId}", $"{_tmdId}", school);
- stuLis = await upsertList(stuList, "private");
- return Ok(new { status, stuLis });
- }
- }
- }
- }
- return Ok(new { status = -1 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},course/get-list-by-no()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- public (int status, StuList stuList) JoinList(StuList stuList, string _studentId, string _tmdId, string school)
- {
- int status = -1;
- if (string.IsNullOrEmpty($"{_studentId}") && string.IsNullOrEmpty($"{_tmdId}"))
- {
- //加入学生或醍摩豆ID为空
- status = 1;
- }
- else
- {
- if (!string.IsNullOrEmpty($"{_studentId}") && !string.IsNullOrEmpty(school))
- {
- string _stuid = $"{_studentId}";
- var student = stuList.students.Find(x => x.id == _stuid);
- if (student != null)
- {
- //重复加入
- status = 2;
- }
- else
- {
- status = 0;
- stuList.students.Add(new Students { id = _stuid, code = $"Base-{school}", schoolId = $"{school}" });
- }
- }
- if (!string.IsNullOrEmpty($"{_tmdId}"))
- {
- string tmdid = $"{_tmdId}";
- var tmd = stuList.tmids.Find(x => x == tmdid);
- if (!string.IsNullOrEmpty(tmd))
- {
- //重复加入
- status = 2;
- }
- else
- {
- status = 0;
- stuList.tmids.Add(tmdid);
- }
- }
- }
- return (status, stuList);
- }
- //处理通用名单
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("upsert-list")]
- public async Task<IActionResult> upsertList(JsonElement json)
- {
- try
- {
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- StuList stuList = new StuList();
- if (!json.TryGetProperty("stuList", out JsonElement student)) return BadRequest();
- if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- stuList = student.ToObject<StuList>();
- stuList.creatorId = userid;
- stuList.school = school;
- stuList = await upsertList(stuList, $"{scope}");
- return Ok(new { stuList });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},course/upsert-list()\n{ex.Message}{ex.StackTrace}\n{json}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- private async Task<StuList> upsertList(StuList stuList, string scope)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- //todo 需要校验是否重复
- if (string.IsNullOrEmpty(stuList.no))
- {
- stuList.no = $"{Utils.CreatSaltString(6, "0123456789")}";
- //string table = $"{scope}" != "school" ? "Teacher" : "School";
- for (int i = 0; i < 10; i++)
- {
- var queryNo = $"SELECT c.no FROM c where c.no ='{stuList.no}'";
- List<string> noStus = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: queryNo,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{stuList.code}") }))
- {
- using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
- if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- noStus.Add(account.GetProperty("no").GetString());
- }
- }
- }
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: queryNo,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey("StuList") }))
- {
- using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
- if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- noStus.Add(account.GetProperty("no").GetString());
- }
- }
- }
- if (noStus.Count == 0)
- {
- break;
- }
- else
- {
- if (i == 9)
- {
- string msg = $"OS,{_option.Location},school/course/upsert-list()\n 编号生成异常,重复生成次数超过10次";
- await _dingDing.SendBotMsg(msg, GroupNames.醍摩豆服務運維群組);
- throw new Exception(msg);
- }
- else
- {
- stuList.no = $"{Utils.CreatSaltString(6, "0123456789")}";
- }
- }
- }
- }
- stuList.code = stuList.pk + "-" + stuList.code.Replace("StuList-", "");
- if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- stuList.scope = "school";
- StuListChange change = new StuListChange()
- {
- listid = stuList.id,
- scope = $"{scope}",
- originCode = stuList.school,
- school = stuList.school,
- creatorId = stuList.creatorId
- };
- var query = $"SELECT distinct value(c) FROM c where c.id='{stuList.id}'";
- List<StuList> odlStus = new List<StuList>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<StuList>(queryText: query,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList-{stuList.school}") }))
- {
- odlStus.Add(item);
- }
- if (odlStus.Count > 0)
- {
- if (stuList.students != null)
- {
- if (odlStus[0].students != null)
- {
- StuList oldStu = odlStus[0];
- foreach (var stu in stuList.students)
- {
- bool flag = false;
- //判断新增名单成员不在已经存在的名单
- foreach (var old in oldStu.students)
- {
- if (old.id == stu.id && old.code == stu.code)
- {
- flag = true;
- }
- }
- if (flag == false)
- {
- change.stujoin.Add(stu);
- }
- }
- }
- }
- if (stuList.tmids != null)
- {
- if (odlStus[0].tmids != null)
- {
- StuList oldStu = odlStus[0];
- foreach (var tmdid in stuList.tmids)
- {
- bool flag = false;
- //判断新增名单成员不在已经存在的名单
- foreach (var old in oldStu.tmids)
- {
- if (old == tmdid)
- {
- flag = true;
- }
- }
- if (flag == false)
- {
- change.tmdjoin.Add(tmdid);
- }
- }
- }
- }
- if (change.tmdjoin.Count != 0 || change.tmdhleave.Count != 0 || change.stujoin.Count != 0 || change.stuleave.Count != 0)
- {
- var messageChange = new ServiceBusMessage(change.ToJsonString());
- messageChange.ApplicationProperties.Add("name", "StuList");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
- }
- }
- stuList = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").UpsertItemAsync(stuList, new PartitionKey($"StuList-{stuList.school}"));
- }
- else
- {
- stuList.scope = "private";
- if (stuList.students.IsNotEmpty())
- {
- stuList.school = stuList.students[0].code.Replace("Base-", "");
- }
- StuListChange change = new StuListChange()
- {
- listid = stuList.id,
- scope = $"{scope}",
- originCode = stuList.creatorId,
- school = stuList.school,
- creatorId = stuList.creatorId
- };
- var query = $"SELECT distinct value(c) FROM c where c.id='{stuList.id}'";
- List<StuList> odlStus = new List<StuList>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<StuList>(queryText: query,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList") }))
- {
- odlStus.Add(item);
- }
- if (odlStus.Count > 0)
- {
- if (stuList.students != null)
- {
- if (odlStus[0].students != null)
- {
- StuList oldStu = odlStus[0];
- foreach (var stu in stuList.students)
- {
- bool flag = false;
- //判断新增名单成员不在已经存在的名单
- foreach (var old in oldStu.students)
- {
- if (old.id == stu.id && old.code == stu.code)
- {
- flag = true;
- }
- }
- if (flag == false)
- {
- change.stujoin.Add(stu);
- }
- }
- }
- }
- if (stuList.tmids != null)
- {
- if (odlStus[0].tmids != null)
- {
- StuList oldStu = odlStus[0];
- foreach (var tmdid in stuList.tmids)
- {
- bool flag = false;
- //判断新增名单成员不在已经存在的名单
- foreach (var old in oldStu.tmids)
- {
- if (old == tmdid)
- {
- flag = true;
- }
- }
- if (flag == false)
- {
- change.tmdjoin.Add(tmdid);
- }
- }
- }
- else
- {
- }
- }
- if (change.tmdjoin.Count != 0 || change.tmdhleave.Count != 0 || change.stujoin.Count != 0 || change.stuleave.Count != 0)
- {
- var messageChange = new ServiceBusMessage(change.ToJsonString());
- messageChange.ApplicationProperties.Add("name", "StuList");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
- }
- }
- stuList.code = "StuList";
- stuList = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync(stuList, new PartitionKey($"StuList"));
- }
- return stuList;
- }
- catch (Exception ex)
- {
- string msg = $"OS,{_option.Location},course/upsert-list()\n{ex.Message}{ex.StackTrace}\n{stuList.ToJsonString()}";
- await _dingDing.SendBotMsg(msg, GroupNames.醍摩豆服務運維群組);
- throw new Exception(msg, ex);
- }
- }
- //查询名单
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("find-list")]
- public async Task<IActionResult> FindList(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<object> stuList = new List<object>();
- //List<int> stuCount = new List<int>();
- var query = $"select c.id,c.name,c.students,c.tmids,c.periodId from c";
- if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{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())
- {
- //List<Students> stu = obj.GetProperty("students").ToObject<List<Students>>();
- stuList.Add(obj.ToObject<object>());
- //stuList.Add(stu.Count);
- //stuCount.Add(stu.Count);
- }
- }
- }
- }
- else
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
- {
- 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())
- {
- //List<Students> stu = obj.GetProperty("students").ToObject<List<Students>>();
- stuList.Add(obj.ToObject<object>());
- //stuList.Add(stu.Count);
- //stuCount.Add(stu.Count);
- }
- }
- }
- }
- return Ok(new { stuList });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},course/find-list()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //查询名单
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("get-summary-list")]
- public async Task<IActionResult> getSummary(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- if (!requert.TryGetProperty("ids", out JsonElement classId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<object> stuList = new();
- //List<int> stuCount = new List<int>();
- List<string> ids = new();
- ids = classId.ToObject<List<string>>();
- //List<Students> stu = new();
- var query = $"select c.id,c.name,c.students,c.tmids,c.no,c.code,c.scope,c.school,c.creatorId from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))})";
- if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{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())
- {
- //stu = obj.GetProperty("students").ToObject<List<Students>>();
- stuList.Add(obj.ToObject<object>());
- //stuList.Add(stu.Count);
- //stuCount.Add(stu.Count);
- }
- }
- }
- }
- else
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
- {
- 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())
- {
- //stu = obj.GetProperty("students").ToObject<List<Students>>();
- stuList.Add(obj.ToObject<object>());
- //stuList.Add(stu.Count);
- //stuCount.Add(stu.Count);
- }
- }
- }
- }
- return Ok(new { stuList });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},course/get-summary-list()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //查询名单
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("delete-list")]
- public async Task<IActionResult> deleteList(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- //var query = $"select c.id,c.name,c.students,c.tmids from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))})";
- if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- /*List<string> classIds = new List<string>();
- var query = $"select c.id from c join A0 in c.schedule where A0.teacherId = '{id}'";
- 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)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- if (string.IsNullOrEmpty(account.GetProperty("id").GetString()))
- {
- continue;
- }
- classIds.Add(account.GetProperty("id").GetString());
- listClassInfo.Add((account.GetProperty("id").GetString(), account.GetProperty("scope").GetString()));
- }
- }
- }*/
- await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"StuList-{code}"));
- }
- else
- {
- await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"StuLis"));
- /*await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
- {
- 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())
- {
- List<Students> stu = obj.GetProperty("students").ToObject<List<Students>>();
- stuList.Add(obj.ToObject<object>());
- //stuList.Add(stu.Count);
- //stuCount.Add(stu.Count);
- }
- }
- }*/
- }
- return Ok(new { id });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},course/delete-list()\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)
- {
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- List<object> courses = new List<object>();
- /*string continuationToken = string.Empty;
- string token = default;
- //是否需要进行分页查询,默认不分页
- //bool iscontinuation = false;
- if (requert.TryGetProperty("token", out JsonElement token_1))
- {
- token = token_1.GetString();
- //iscontinuation = true;
- };
- //默认不指定返回大小
- int? topcout = null;
- if (requert.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }*/
- var query = $"select c.code,c.id,c.no,c.name,c.period,c.subject,c.scope from c";
- if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code.GetString()}") }))
- {
- //continuationToken = item.GetContinuationToken();
- 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>());
- }
- }
- //break;
- }
- }
- else
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code.GetString()}") }))
- {
- //continuationToken = item.GetContinuationToken();
- 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>());
- }
- }
- //break;
- }
- if (requert.TryGetProperty("schoolId", out JsonElement schoolId))
- {
- var querySchool = $"select distinct c.code,c.id,c.no,c.name,c.period,c.subject,c.scope from c join A0 in c.schedule where A0.teacherId = '{code}'";
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: querySchool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{schoolId.GetString()}") }))
- {
- //continuationToken = item.GetContinuationToken();
- 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>());
- }
- }
- //break;
- }
- };
- }
- return Ok(new { courses, courses.Count });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_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("find-all-by-teacher")]
- public async Task<IActionResult> FindByTeacher(JsonElement requert)
- {
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- //if (!requert.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- //if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- List<object> courses = new List<object>();
- List<(string id, string name, string scope)> teacherCourse = new();
- List<(string id, string name, string scope)> tcCourse = new();
- List<(string id, string name,string scope,List<(string id, string name, string type)> stuName)> ps = new();
- var query = $"select c.id,c.name,c.scope from c";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code.GetString()}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- teacherCourse.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(),account.GetProperty("scope").GetString()));
- }
- }
- }
- foreach ((string s, string n,string sc) in teacherCourse)
- {
- List<(string id, string name,string type)> sName = new();
- List<Schedule> schedules = new List<Schedule>();
- var querySc = $"SELECT A0.room,A0.classId,A0.teacherId,A0.stulist,A0.time FROM c join A0 in c.schedule where c.id = '{s}'";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Schedule>(queryText: querySc, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code.GetString()}") }))
- {
- schedules.Add(item);
- }
- var queryInfo = $"select c.id ,c.name from c where c.id in ({string.Join(",", schedules.Select(o => $"'{o.stulist}'"))})";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: queryInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- sName.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(),"stuList"));
- }
- }
- }
- ps.Add((s,n,sc, sName));
- }
- if (requert.TryGetProperty("schoolId", out JsonElement schoolId))
- {
- var querySchool = $"select distinct c.code,c.id,c.no,c.name,c.scope from c join A0 in c.schedule where A0.teacherId = '{code}'";
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: querySchool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{schoolId.GetString()}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- tcCourse.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), account.GetProperty("scope").GetString()));
- }
- }
- }
- foreach ((string s, string n, string sc) in tcCourse)
- {
- List<Schedule> schedules = new List<Schedule>();
- var querySc = $"SELECT A0.room,A0.classId,A0.teacherId,A0.stulist,A0.time FROM c join A0 in c.schedule where c.id = '{s}' and A0.teacherId = '{code}'";
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Schedule>(queryText: querySc, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{schoolId.GetString()}") }))
- {
- schedules.Add(item);
- }
- List<(string id, string name,string type)> sName = new();
- var queryInfo = $"select c.id ,c.name from c where c.id in ({string.Join(",", schedules.Select(o => $"'{o.stulist}'"))})";
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: queryInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{schoolId.GetString()}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- sName.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), "stuList"));
- }
- }
- }
- var queryClass = $"select c.id ,c.name from c where c.id in ({string.Join(",", schedules.Select(o => $"'{o.classId}'"))})";
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId.GetString()}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- sName.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(),"class"));
- }
- }
- }
- ps.Add((s,n, sc,sName));
- }
- }
- var obj = ps.Select(p => new
- {
- p.id,
- p.name,
- p.scope,
- classes = p.stuName.Select(s => new { s.id, s.name,s.type })
- });
- return Ok(new { obj });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},course/find-all-by-teacher()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 查询课程详情
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "Teacher")]
- [HttpPost("find-summary")]
- public async Task<IActionResult> FindSummary(JsonElement requert)
- {
- if (!requert.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
- if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- List<object> courses = new List<object>();
- List<Course> courseList = new List<Course>();
- var query = $"select value(c) from c where c.id = '{id}'";
- //List<(string id, string code, string name)> listCourse = new List<(string id, string code, string name)>();
- if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Course>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_code.GetString()}") }))
- {
- courseList.Add(item);
- }
- }
- else
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Course>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_code.GetString()}") }))
- {
- courseList.Add(item);
- }
- }
- foreach (Course course in courseList)
- {
- dynamic courseExtobj = new ExpandoObject();
- courseExtobj.id = course.id;
- courseExtobj.name = course.name;
- courseExtobj.id = course.id;
- courseExtobj.subject = course.subject;
- courseExtobj.period = course.period;
- courseExtobj.scope = course.scope;
- courseExtobj.no = course.no;
- courseExtobj.code = course.code;
- List<object> scheList = new List<object>();
- foreach (Schedule schedule in course.schedule)
- {
- dynamic scheduleExtobj = new ExpandoObject();
- scheduleExtobj.classId = schedule.classId;
- scheduleExtobj.teacherId = schedule.teacherId;
- if (!string.IsNullOrEmpty(schedule.teacherId))
- {
- var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(schedule.teacherId, new PartitionKey("Base"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- Teacher teacher = json.ToObject<Teacher>();
- scheduleExtobj.teacherName = teacher.name;
- }
- }
- scheduleExtobj.stulist = schedule.stulist;
- scheduleExtobj.time = schedule.time;
- scheduleExtobj.notice = schedule.notice;
- scheduleExtobj.room = schedule.room;
- scheList.Add(scheduleExtobj);
- }
- courseExtobj.schedule = scheList;
- courses.Add(courseExtobj);
- }
- return Ok(new { courses, courses.Count });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},course/find-summary()\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"))
- {
- Course course = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<Course>(id.ToString(), new PartitionKey($"Course-{code}"));
- CourseChange courseChange = new CourseChange { id = course.id, code = course.code, name = course.name, scope = course.scope, school = course.school, creatorId = course.creatorId };
- courseChange.delClass = course.schedule.Select(x => x.classId).ToList();
- courseChange.delList = course.schedule.Select(x => x.stulist).ToList();
- var messageBlob = new ServiceBusMessage(courseChange.ToJsonString()); ;
- messageBlob.ApplicationProperties.Add("name", "Course");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
- await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Course-{code}"));
- }
- else
- {
- Course course = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Course>(id.ToString(), new PartitionKey($"Course-{code}"));
- CourseChange courseChange = new CourseChange { id = course.id, code = course.code, name = course.name, scope = course.scope, school = course.school, creatorId = course.creatorId };
- courseChange.delClass = course.schedule.Select(x => x.classId).ToList();
- courseChange.delList = course.schedule.Select(x => x.stulist).ToList();
- var messageBlob = new ServiceBusMessage(courseChange.ToJsonString()); ;
- messageBlob.ApplicationProperties.Add("name", "Course");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
- await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Course-{code}"));
- }
- return Ok(new { id });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"CN,{_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();
- string school_code = request.code;
- if (request.scope.Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- List<Response> res = await client.GetContainer("TEAMModelOS", "School").DeleteItemsStreamAsync(request.ids, $"Course-{school_code}");
- }
- else
- {
- List<Response> res = await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemsStreamAsync(request.ids, $"Course-{school_code}");
- }
- return Ok(new { ids = request.ids });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"CN,{_option.Location},course/delete()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <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)
- // {
- // 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>());
- // }
- // }
- // }
- // return Ok(new { courses });
- //}
- //[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("find-course-by-room")]
- public async Task<IActionResult> FindCourseByRoom(JsonElement requert)
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- HashSet<Course> courseList = new HashSet<Course>();
- List<object> courses = new List<object>();
- //var query = $"select c.code,c.id,c.name from c join A0 in c.schedule where A0.classId = '{id}'";
- //此处存在不同老师在同一间教室上相同的课程
- if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- var query = $"select distinct value(c) from c join A0 in c.schedule where A0.room = '{id}'";
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Course>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code}") }))
- {
- courseList.Add(item);
- }
- }
- else
- {
- var query = $"select distinct value(c) from c join A0 in c.schedule where A0.room = '{id}'";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Course>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code}") }))
- {
- courseList.Add(item);
- }
- }
- HashSet<string> teacherIds = new HashSet<string>();
- foreach (Course course in courseList)
- {
- foreach (Schedule schedule in course.schedule)
- {
- teacherIds.Add(schedule.teacherId);
- }
- }
- List<(string id, string name)> teachers = new List<(string id, string name)>();
- if (teacherIds.Count > 0)
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(
- queryText: $"select c.id,c.name from c where c.id in ({ string.Join(",", teacherIds.Select(o => $"'{o}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- teachers.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
- }
- }
- }
- }
- foreach (Course course in courseList)
- {
- dynamic courseExtobj = new ExpandoObject();
- courseExtobj.id = course.id;
- courseExtobj.name = course.name;
- courseExtobj.subject = course.subject;
- courseExtobj.period = course.period;
- courseExtobj.scope = course.scope;
- courseExtobj.no = course.no;
- courseExtobj.code = course.code;
- courseExtobj.pk = course.pk;
- List<object> scheList = new List<object>();
- foreach (Schedule schedule in course.schedule)
- {
- dynamic scheduleExtobj = new ExpandoObject();
- scheduleExtobj.classId = schedule.classId;
- scheduleExtobj.teacherId = schedule.teacherId;
- if (!string.IsNullOrEmpty(schedule.teacherId))
- {
- scheduleExtobj.teacherName = teachers.FirstOrDefault(c => c.id == schedule.teacherId).name;
- }
- scheduleExtobj.stulist = schedule.stulist;
- scheduleExtobj.time = schedule.time;
- scheduleExtobj.notice = schedule.notice;
- scheduleExtobj.room = schedule.room;
- scheList.Add(scheduleExtobj);
- }
- courseExtobj.schedule = scheList;
- courses.Add(courseExtobj);
- }
- 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>();
- // 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 });
- //}
- [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)
- {
- 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<object> courses = new List<object>();
- List<string> classIds = new List<string>();
- List<(string id, string scope)> listClassInfo = new List<(string id, string scope)>();
- var query = $"select distinct c.scope,A0.stulist id from c join A0 in c.schedule where A0.teacherId = '{id}'";
- 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)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- if (string.IsNullOrEmpty(account.GetProperty("id").GetString()))
- {
- continue;
- }
- classIds.Add(account.GetProperty("id").GetString());
- listClassInfo.Add((account.GetProperty("id").GetString(), account.GetProperty("scope").GetString()));
- }
- }
- }
- var querySchool = $"select distinct c.scope,A0.classId id from c join A0 in c.schedule where A0.teacherId = '{id}'";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: querySchool, 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)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- if (string.IsNullOrEmpty(account.GetProperty("id").GetString()))
- {
- continue;
- }
- classIds.Add(account.GetProperty("id").GetString());
- listClassInfo.Add((account.GetProperty("id").GetString(), account.GetProperty("scope").GetString()));
- }
- }
- }
- //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: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- if (string.IsNullOrEmpty(account.GetProperty("id").GetString()))
- {
- continue;
- }
- classIds.Add(account.GetProperty("id").GetString());
- listClassInfo.Add((account.GetProperty("id").GetString(), account.GetProperty("scope").GetString()));
- }
- }
- }
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: querySchool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- if (string.IsNullOrEmpty(account.GetProperty("id").GetString()))
- {
- continue;
- }
- classIds.Add(account.GetProperty("id").GetString());
- listClassInfo.Add((account.GetProperty("id").GetString(), account.GetProperty("scope").GetString()));
- }
- }
- }
- List<(string id, string name)> listClassList = new List<(string id, string name)>();
- if (classIds.Count > 0)
- {
- //List<(string id, string name)> listClassList = new List<(string id, string name)>();
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(
- queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", classIds.Select(o => $"'{o}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- listClassList.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
- //stuIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(
- queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", classIds.Select(o => $"'{o}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- listClassList.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
- //stuIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(
- queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", classIds.Select(o => $"'{o}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- listClassList.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
- //stuIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- }
- var courses = listClassInfo.Select(o =>
- new
- {
- o.id,
- o.scope,
- name = listClassList.FirstOrDefault(c => c.id == o.id).name,
- }
- );
- //courses.Add(grpBalance);
- //courses = courses.Distinct().ToList();
- return Ok(new { courses });
- }
- 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; }
- public string scope { get; set; }
- }
- }
|