123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507 |
- using Microsoft.Azure.Cosmos;
- using Azure.Messaging.ServiceBus;
-
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.Dynamic;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Filter;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- [Route("school/classroom")]
- [ApiController]
- public class ClassController : ControllerBase
- {
- public readonly AzureCosmosFactory _azureCosmos;
- private readonly Option _option;
- private readonly DingDing _dingDing;
- public IConfiguration _configuration { get; set; }
- private readonly AzureServiceBusFactory _serviceBus;
- public ClassController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureServiceBusFactory serviceBus, IConfiguration configuration,
- IOptionsSnapshot<Option> option)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _option = option?.Value;
- _serviceBus = serviceBus;
- _configuration = configuration;
- }
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("upsert")]
-
- [AuthToken(Roles = "teacher,admin,student")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async ValueTask<IActionResult> Upsert(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("classroom", out JsonElement room)) return BadRequest();
- Class classroom = room.ToObject<Class>();
- var client = _azureCosmos.GetCosmosClient();
- classroom.code = "Class-" + classroom.school;
- if (string.IsNullOrEmpty(classroom.id))
- {
- if (classroom.graduate != 0) {
- return Ok(new { error = 409, V = "已毕业的班级不能被编辑!" });
- }
- List<string> resultIds = new List<string>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(queryText: $"select c.id from c where c.periodId = '{classroom.periodId}' and c.no = '{classroom.no}' and c.year = '{classroom.year}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(classroom.code) }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- resultIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- if (resultIds.Count > 0)
- {
- return Ok(new { error = ResponseCode.DATA_EXIST, V = "班级编码已经存在!" });
- }
- classroom.id = Guid.NewGuid().ToString();
- classroom = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(classroom, new PartitionKey(classroom.code));
- }
- else
- {
- var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(classroom.id, new PartitionKey(classroom.code));
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- Class @class = json.ToObject<Class>();
- if (classroom.graduate != 0)
- {
- return Ok(new { error = 409, V = "已毕业的班级不能被编辑!" });
- }
- if (!@class.no.Equals(classroom.no))
- {
- List<string> resultIds = new List<string>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(queryText: $"select c.id from c where c.year = '{classroom.year}' and c.no = '{classroom.no}' and c.periodId = '{classroom.periodId}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(classroom.code) }))
- {
- using var document = await JsonDocument.ParseAsync(item.Content);
- if (document.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = document.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- resultIds.Add(account.GetProperty("id").GetString());
- }
- }
- }
- if (resultIds.Count > 0)
- {
- return Ok(new { error = ResponseCode.DATA_EXIST, V = "班级编码已经存在!" });
- }
- }
- classroom = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(classroom, classroom.id, new PartitionKey(classroom.code));
- }
- else
- {
- classroom = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(classroom, new PartitionKey(classroom.code));
- }
- }
- return Ok(new { classroom });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},class/Upsert()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("upsert-group")]
- [AuthToken(Roles = "teacher,admin")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async ValueTask<IActionResult> UpsertGroup(JsonElement request)
- {
- try
- {
- List<Student> students = new List<Student>();
- if (!request.TryGetProperty("students", out JsonElement stus)) return BadRequest();
- students = stus.ToObject<List<Student>>();
- var client = _azureCosmos.GetCosmosClient();
- foreach (Student stu in students)
- {
- var response = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(stu.id, new PartitionKey($"Base-{stu.code}"));
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- Student stuInfo = json.ToObject<Student>();
- stuInfo.groupId = stu.groupId;
- stuInfo.groupName = stu.groupName;
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(stuInfo, stuInfo.id, new PartitionKey($"{stuInfo.code}"));
- }
- }
- return Ok(new { students });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},class/UpsertGroup()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 已弃用
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("find")]
- [AuthToken(Roles = "teacher,admin,student")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> Find(JsonElement request)
- {
- if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
- if (!request.TryGetProperty("periodId", out JsonElement _periodId)) return BadRequest();
- try
- {
- //增加毕业查询。当毕业查询字段1时,则需要传入入学年份。
- int graduate = 0;
- int inyear = 0;
- //讀取該間學校所有的學生資訊
- if (request.TryGetProperty("graduate", out JsonElement _graduate) && $"{_graduate}".Equals("1"))
- {
- if (request.TryGetProperty("year", out JsonElement _year) && _year.ValueKind.Equals(JsonValueKind.Number))
- {
- if (int.TryParse($"{_year}", out inyear) && inyear > 0)
- {
- graduate = 1;
- }
- else
- {
- return BadRequest("入学年份大于0");
- }
- }
- else
- {
- return BadRequest("请输入毕业学生的入学年份");
- }
- }
- string sql = "";
- if (graduate == 0) {
- sql = $"SELECT value c FROM c where c.periodId='{_periodId}'and (c.graduate = 0 or IS_DEFINED(c.graduate) = false) ";
- }
- else {
- sql = $"SELECT value c FROM c where c.periodId='{_periodId}'and c.graduate =1 and c.year ={inyear}";
- }
- List<Class> school_classes = new List<Class>();
- var client = _azureCosmos.GetCosmosClient();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<Class>
- (queryText:sql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
- {
- school_classes.Add(item);
- }
- return Ok(new { school_classes });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},class/Find()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("delete")]
- [AuthToken(Roles = "teacher,admin")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> Delete(JsonElement request)
- {
- if (!request.TryGetProperty("school_code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
-
- try
- {
- Class clssz = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<Class>($"{id}", new PartitionKey($"Class-{code}"));
- if (clssz.graduate == 1) {
- return Ok(new { error = 409, V = "已毕业的班级不能被编辑!" });
- }
- var client = _azureCosmos.GetCosmosClient();
- List<Student> students = new List<Student>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIteratorSql<Student>(queryText: $"select * from c where c.classId='{id}' ", requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base-{code}") }))
- {
- item.classId = null ;
- students.Add(item);
- }
- List<Task<ItemResponse<Student>>> tasks = new List<Task<ItemResponse<Student>>>();
- foreach (var stu in students)
- {
- tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(stu, stu.id, new PartitionKey(($"Base-{code}"))));
- }
- GroupChange change = new GroupChange() { client="web",name =clssz .name};
- if (students.IsNotEmpty()) {
- change.stuleave.AddRange(students.Select(x=> new Member {
- id = x.id,
- type = 2,
- nickname = x.name,
- irs = x.irs,
- no = x.no,
- groupId = x.groupId,
- groupName = x.groupName,
- code = $"{code}"
- }));
- }
- change.listid = $"{id}";
- change.scope = "school";
- change.originCode = $"{code}";
- change.school = $"{code}";
- change.type = "class";
- change.status = "delete";
- var messageChange = new ServiceBusMessage(change.ToJsonString());
- messageChange.ApplicationProperties.Add("name", "GroupChange");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
- await Task.WhenAll(tasks);
- Class classroom= await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemAsync<Class>(id.ToString(), new PartitionKey($"Class-{code}"));
- return Ok(new { classroom });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},class/Delete()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("hiteach-link-unlink")]
- [AuthToken(Roles = "teacher,admin,student")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> HiteachLink(JsonElement request)
- {
- // 必要檢查
- if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
- if (!request.TryGetProperty("serial_id", out JsonElement serial_id)) return BadRequest();
- if (!request.TryGetProperty("opt", out JsonElement opt)) return BadRequest();
- request.TryGetProperty("uuid", out JsonElement uuid);
- request.TryGetProperty("uuid2", out JsonElement uuid2);
- if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
- // 如果是link classId 必填
- if (!$"{opt}".Equals("link") &&!$"{opt}".Equals("unlink")) return BadRequest();
- try
- {
- // [取得DB資料]
- var client = _azureCosmos.GetCosmosClient();
- var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{serial_id}", new PartitionKey($"Product-{school_code}"));
- int status = 200;
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- deviceBound bound = null;
- var serial = JsonDocument.Parse(response.Content).RootElement.Deserialize<SchoolProductSerial>();
- if ($"{opt}".Equals("link"))
- {
- if (!string.IsNullOrWhiteSpace($"{uuid}") && !string.IsNullOrWhiteSpace($"{uuid2}"))
- {
- bound = serial.deviceBound.Find(x => $"{uuid}".Equals(x.uuid) && $"{uuid2}".Equals(x.uuid2));
- if (bound != null)
- {
- bound.classId = $"{classId}";
- }
- }
- else if (!string.IsNullOrWhiteSpace($"{uuid}") && string.IsNullOrWhiteSpace($"{uuid2}"))
- {
- bound = serial.deviceBound.Find(x => $"{uuid}".Equals(x.uuid));
- if (bound != null)
- {
- bound.classId = $"{classId}";
- }
- }
- else if (string.IsNullOrWhiteSpace($"{uuid}") && !string.IsNullOrWhiteSpace($"{uuid2}"))
- {
- bound = serial.deviceBound.Find(x => $"{uuid2}".Equals(x.uuid2));
- if (bound != null)
- {
- bound.classId = $"{classId}";
- }
- }
- }
- else if ($"{opt}".Equals("unlink")) {
- if (!string.IsNullOrWhiteSpace($"{uuid}") && !string.IsNullOrWhiteSpace($"{uuid2}"))
- {
- bound = serial.deviceBound.Find(x => $"{uuid}".Equals(x.uuid) && $"{uuid2}".Equals(x.uuid2) && $"{classId}".Equals(x.classId));
- if (bound != null)
- {
- bound.classId = null;
- }
- }
- else if (!string.IsNullOrWhiteSpace($"{uuid}") && string.IsNullOrWhiteSpace($"{uuid2}") )
- {
- bound = serial.deviceBound.Find(x => $"{uuid}".Equals(x.uuid) && $"{classId}".Equals(x.classId));
- if (bound != null)
- {
- bound.classId = null;
- }
- }
- else if (string.IsNullOrWhiteSpace($"{uuid}") && !string.IsNullOrWhiteSpace($"{uuid2}") )
- {
- bound = serial.deviceBound.Find(x => $"{uuid2}".Equals(x.uuid2) && $"{classId}".Equals(x.classId));
- if (bound != null)
- {
- bound.classId = null;
- }
- }
- }
- if (bound == null) {
- status = 404;
- }
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSerial>(serial, $"{serial_id}", new PartitionKey($"Product-{school_code}"));
- }
- else {
- status = 404;
- }
- return Ok(new { status });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"IES5,{_option.Location},hiteach-link()\n{ex.Message}\n{ex.StackTrace}{request.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("hiteach-unlink-classId")]
- [AuthToken(Roles = "teacher,admin,student")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> HiteachunlinkByClassId(JsonElement request)
- {
- // 必要檢查
- if (!request.TryGetProperty("school_code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("classId", out JsonElement id)) return BadRequest();
- try
- {
- // [變數宣告]
- string school_code = code.ToString(); // 學校簡碼
- string classId = id.ToString(); // 教室ID
- // [取得DB資料]
- var client = _azureCosmos.GetCosmosClient();
- var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code, new PartitionKey("Product"));
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- var json = await JsonDocument.ParseAsync(response.Content);
- //軟體
- SchoolProduct schoolProductItem = json.ToObject<SchoolProduct>();
- foreach (SerialInfoBaseWithdeviceBound updSerialInfo in schoolProductItem.serial)
- {
- if (updSerialInfo.deviceBound != null)
- {
- deviceBound updDeviceBound = updSerialInfo.deviceBound.Where(d => d.classId == classId).FirstOrDefault();
- if (updDeviceBound != null)
- {
- updDeviceBound.classId = null;
- }
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProduct>(schoolProductItem, school_code, new PartitionKey("Product"));
- }
- return Ok(new { error = 0 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"IES5,{_option.Location},hiteach-unlink-classId()\n{ex.Message}\n{ex.StackTrace}{request.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("name")]
- [AuthToken(Roles = "teacher,admin,student")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> GetNameList(JsonElement request)
- {
- if (!request.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- //List<string> id = ids.ToObject<List<string>>();
- string info = "";
- for (int i = 0; i < ids.GetArrayLength(); i++)
- {
- //ids.Add(id[i].ToJsonString());
- info += ids[i].ToJsonString() + ",";
- }
- List<object> ClassName = new List<object>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(
- queryText: $"select c.id,c.name from c where c.id in ({info[0..^1]})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- ClassName.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(new { ClassName });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},class/name()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- }
- }
|