ClassRoomController.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. using Azure.Cosmos;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Dynamic;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Text.Json;
  11. using System.Threading.Tasks;
  12. using TEAMModelOS.Models;
  13. using TEAMModelOS.SDK.DI;
  14. using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
  15. using TEAMModelOS.SDK.Extension;
  16. using TEAMModelOS.SDK.Models;
  17. using TEAMModelOS.SDK.Models.Cosmos.Common;
  18. namespace TEAMModelOS.Controllers
  19. {
  20. [ProducesResponseType(StatusCodes.Status200OK)]
  21. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  22. //[Authorize(Roles = "IES5")]
  23. [Route("school/classroom")]
  24. [ApiController]
  25. public class ClassroomController : ControllerBase
  26. {
  27. public readonly AzureCosmosFactory _azureCosmos;
  28. private readonly Option _option;
  29. private readonly DingDing _dingDing;
  30. public ClassroomController(AzureCosmosFactory azureCosmos, DingDing dingDing,
  31. IOptionsSnapshot<Option> option)
  32. {
  33. _azureCosmos = azureCosmos;
  34. _dingDing = dingDing;
  35. _option = option?.Value;
  36. }
  37. [ProducesDefaultResponseType]
  38. //[AuthToken(Roles = "Teacher")]
  39. [HttpPost("upsert")]
  40. public async ValueTask<IActionResult> Upsert(JsonElement requert)
  41. {
  42. //ResponseBuilder builder = ResponseBuilder.custom();
  43. //List<Student> students = null;
  44. Class classroom;
  45. if (!requert.TryGetProperty("classroom", out JsonElement room)) return BadRequest();
  46. if (!requert.TryGetProperty("option", out JsonElement option)) return BadRequest();
  47. if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  48. try
  49. {
  50. classroom = room.ToObject<Class>();
  51. var client = _azureCosmos.GetCosmosClient();
  52. classroom.code = "Class-" + school_code.ToString();
  53. //students = await _azureCosmos.FindByDict<Student>(new Dictionary<string, object>() { { "classroomCode", classroom.id } });
  54. if (option.ToString().Equals("insert"))
  55. {
  56. if (classroom.scope.Equals("private"))
  57. {
  58. List<string> resultIds = new List<string>();
  59. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.periodId = '{classroom.periodId}' and c.no = '{classroom.no}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
  60. {
  61. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  62. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  63. {
  64. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  65. while (accounts.MoveNext())
  66. {
  67. JsonElement account = accounts.Current;
  68. resultIds.Add(account.GetProperty("id").GetString());
  69. }
  70. }
  71. }
  72. if (resultIds.Count > 0)
  73. {
  74. return Ok(new { error = ResponseCode.DATA_EXIST, V = "班级编码已经存在!" });
  75. }
  76. var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(classroom.id, new PartitionKey($"Class-{school_code}"));
  77. if (response.Status == 200)
  78. {
  79. //classroom = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").UpsertItemAsync(requert, new PartitionKey($"Classroom-{classroom.code}"));
  80. return Ok(new { error = ResponseCode.DATA_EXIST, V = "班级信息已经存在!" });
  81. }
  82. else
  83. {
  84. //string code = classroom.code;
  85. //classroom.code = "Class-" + school_code;
  86. classroom = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(classroom, new PartitionKey($"Class-{school_code}"));
  87. }
  88. }
  89. else
  90. {
  91. List<string> resultIds = new List<string>();
  92. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.periodId = '{classroom.periodId}' and c.no = '{classroom.no}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
  93. {
  94. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  95. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  96. {
  97. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  98. while (accounts.MoveNext())
  99. {
  100. JsonElement account = accounts.Current;
  101. resultIds.Add(account.GetProperty("id").GetString());
  102. }
  103. }
  104. }
  105. if (resultIds.Count > 0)
  106. {
  107. return Ok(new { error = ResponseCode.DATA_EXIST, V = "班级编码已经存在!" });
  108. }
  109. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(classroom.id, new PartitionKey($"Class-{school_code}"));
  110. if (response.Status == 200)
  111. {
  112. //classroom = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").UpsertItemAsync(requert, new PartitionKey($"Classroom-{classroom.code}"));
  113. return Ok(new { error = ResponseCode.DATA_EXIST, V = "班级信息已经存在!" });
  114. }
  115. else
  116. {
  117. //string code = classroom.code;
  118. //classroom.code = "Class-" + school_code;
  119. classroom = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync(classroom, new PartitionKey($"Class-{school_code}"));
  120. }
  121. }
  122. }
  123. else
  124. {
  125. if (classroom.scope.Equals("private"))
  126. {
  127. List<string> resultIds = new List<string>();
  128. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.periodId = '{classroom.periodId}' and c.no = '{classroom.no}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
  129. {
  130. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  131. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  132. {
  133. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  134. while (accounts.MoveNext())
  135. {
  136. JsonElement account = accounts.Current;
  137. resultIds.Add(account.GetProperty("id").GetString());
  138. }
  139. }
  140. }
  141. if (resultIds.Count > 0)
  142. {
  143. return Ok(new { error = ResponseCode.DATA_EXIST, V = "班级编码已经存在!" });
  144. }
  145. //Class own = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Class>(classroom.id, new PartitionKey($"Class-{school_code}"));
  146. classroom = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(classroom, classroom.id, new PartitionKey($"Class-{school_code}"));
  147. }
  148. else
  149. {
  150. //检查该教室是否是老师创建的个人校本教室
  151. var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(classroom.id, new PartitionKey($"Class-{school_code}"));
  152. if (response.Status == 200)
  153. {
  154. List<string> resultIds = new List<string>();
  155. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.periodId = '{classroom.periodId}' and c.no = '{classroom.no}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
  156. {
  157. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  158. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  159. {
  160. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  161. while (accounts.MoveNext())
  162. {
  163. JsonElement account = accounts.Current;
  164. resultIds.Add(account.GetProperty("id").GetString());
  165. }
  166. }
  167. }
  168. if (resultIds.Count > 0)
  169. {
  170. return Ok(new { error = ResponseCode.DATA_EXIST, V = "班级编码已经存在!" });
  171. }
  172. classroom = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(classroom, classroom.id, new PartitionKey($"Class-{school_code}"));
  173. }
  174. else
  175. {
  176. List<string> resultIds = new List<string>();
  177. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.periodId = '{classroom.periodId}' and c.no = '{classroom.no}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
  178. {
  179. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  180. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  181. {
  182. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  183. while (accounts.MoveNext())
  184. {
  185. JsonElement account = accounts.Current;
  186. resultIds.Add(account.GetProperty("id").GetString());
  187. }
  188. }
  189. }
  190. if (resultIds.Count > 0)
  191. {
  192. return Ok(new { error = ResponseCode.DATA_EXIST, V = "班级编码已经存在!" });
  193. }
  194. /*List<StudentSimple> studentSimples = new List<StudentSimple>();
  195. StringBuilder sql = new StringBuilder();
  196. sql.Append("select A0.id,A0.name,A0.no from c join A0 in c.students ");
  197. Dictionary<string, object> dict = new Dictionary<string, object>();
  198. dict.Add("scope", classroom.scope);
  199. dict.Add("id", classroom.id);
  200. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  201. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
  202. {
  203. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  204. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  205. {
  206. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  207. {
  208. studentSimples.Add(obj.ToObject<StudentSimple>());
  209. }
  210. }
  211. }
  212. classroom.students = studentSimples;*/
  213. List<TeacherCourse> course = new List<TeacherCourse>();
  214. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: $"select value(c) from c join A0 in c.classes where A0.id = '{classroom.id}'"))
  215. {
  216. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  217. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  218. {
  219. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  220. {
  221. course.Add(obj.ToObject<TeacherCourse>());
  222. }
  223. }
  224. }
  225. for (int i = 0; i < course.Count; i++)
  226. {
  227. bool flag = false;
  228. for (int j = 0; j < course[i].classes.Count; j++)
  229. {
  230. if (!course[i].classes[j].name.Equals(classroom.name))
  231. {
  232. flag = true;
  233. course[i].classes[j].name = classroom.name;
  234. //break;
  235. }
  236. if (!course[i].classes[j].teacher.id.Equals(classroom.teacher.id))
  237. {
  238. flag = true;
  239. course[i].classes[j].teacher.id = classroom.teacher.id;
  240. course[i].classes[j].teacher.name = classroom.teacher.name;
  241. //break;
  242. }
  243. }
  244. if (flag)
  245. {
  246. await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(course[i], course[i].id, new PartitionKey($"{course[i].code}"));
  247. }
  248. }
  249. //string code = classroom.code.Substring(classroom.pk.Length + 1);
  250. //[Jeff] CourseManagement表廢除 刪除預定:以下CourseManagement更新程序
  251. var sresponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(classroom.id, new PartitionKey($"CourseManagement-{school_code}"));
  252. if (sresponse.Status == 200)
  253. {
  254. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  255. CourseManagement classroom1 = json.ToObject<CourseManagement>();
  256. if (!classroom1.name.Equals(classroom.name))
  257. {
  258. classroom1.name = classroom.name;
  259. await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(classroom1, classroom1.id, new PartitionKey($"{classroom1.code}"));
  260. }
  261. if (!string.IsNullOrEmpty(classroom1.teacher.id) && !string.IsNullOrEmpty(classroom.teacher.id) && !classroom1.teacher.id.Equals(classroom.teacher.id))
  262. {
  263. classroom1.teacher.name = classroom.teacher.name;
  264. classroom1.teacher.id = classroom.teacher.id;
  265. await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(classroom1, classroom1.id, new PartitionKey($"{classroom1.code}"));
  266. }
  267. }
  268. ////[Jeff] CourseManagement表廢除 刪除預定:以下CourseManagement更新程序
  269. classroom = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync(classroom, classroom.id, new PartitionKey($"Class-{school_code}"));
  270. }
  271. }
  272. }
  273. return Ok(new { classroom });
  274. }
  275. catch (Exception ex)
  276. {
  277. await _dingDing.SendBotMsg($"OS,{_option.Location},class/Upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  278. return BadRequest();
  279. }
  280. }
  281. [ProducesDefaultResponseType]
  282. //[AuthToken(Roles = "Teacher")]
  283. [HttpPost("upsert-group")]
  284. public async ValueTask<IActionResult> UpsertGroup(JsonElement requert)
  285. {
  286. try
  287. {
  288. List<Student> students = new List<Student>();
  289. if (!requert.TryGetProperty("students", out JsonElement stus)) return BadRequest();
  290. students = stus.ToObject<List<Student>>();
  291. var client = _azureCosmos.GetCosmosClient();
  292. foreach (Student stu in students)
  293. {
  294. var response = await client.GetContainer("TEAMModelOS", "Student").ReadItemStreamAsync(stu.id, new PartitionKey($"{stu.code}"));
  295. if (response.Status == 200)
  296. {
  297. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  298. Student stuInfo = json.ToObject<Student>();
  299. stuInfo.groupId = stu.groupId;
  300. stuInfo.groupName = stu.groupName;
  301. await client.GetContainer("TEAMModelOS", "Student").ReplaceItemAsync(stuInfo, stuInfo.id, new PartitionKey($"{stuInfo.code}"));
  302. }
  303. }
  304. /*Class classroom = new Class();
  305. if (!requert.TryGetProperty("classroom", out JsonElement room)) return BadRequest();
  306. //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  307. classroom = room.ToObject<Class>();
  308. var sresponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(classroom.id, new PartitionKey($"{classroom.code}"));
  309. if (sresponse.Status == 200)
  310. {
  311. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  312. Class classroom1 = json.ToObject<Class>();
  313. //classroom1.students = classroom.students;
  314. var response = await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(classroom1, classroom1.id, new PartitionKey($"{classroom.code}"));
  315. }*/
  316. return Ok(new { students });
  317. }
  318. catch (Exception ex)
  319. {
  320. await _dingDing.SendBotMsg($"OS,{_option.Location},class/UpsertGroup()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  321. return BadRequest();
  322. }
  323. }
  324. [ProducesDefaultResponseType]
  325. //[AuthToken(Roles = "Teacher")]
  326. [HttpPost("find")]
  327. public async Task<IActionResult> Find(JsonElement requert)
  328. {
  329. //ResponseBuilder builder = ResponseBuilder.custom();
  330. if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  331. try
  332. {
  333. var client = _azureCosmos.GetCosmosClient();
  334. List<object> classrooms = new List<object>();
  335. StringBuilder sql = new StringBuilder();
  336. sql.Append("select c.id,c.no,c.point,c.name,c.teacher,c.periodId,c.gradeId,c.sn,c.style,c.scope,c.type,c.code,c.openType,c.x,c.y,ARRAY_LENGTH(c.students) AS studCount from c ");
  337. Dictionary<string, object> dict = new Dictionary<string, object>();
  338. var emobj = requert.EnumerateObject();
  339. while (emobj.MoveNext())
  340. {
  341. dict[emobj.Current.Name] = emobj.Current.Value;
  342. }
  343. //处理code
  344. if (dict.TryGetValue("school_code", out object _))
  345. {
  346. dict.Remove("school_code");
  347. }
  348. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  349. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
  350. {
  351. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  352. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  353. {
  354. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  355. {
  356. classrooms.Add(obj.ToObject<object>());
  357. }
  358. }
  359. }
  360. return Ok(new { classrooms });
  361. /*List<Classroom> sc = await _azureCosmos.FindByDict<Classroom>(request);
  362. return builder.Data(sc).build();*/
  363. }
  364. catch (Exception ex)
  365. {
  366. await _dingDing.SendBotMsg($"OS,{_option.Location},class/Find()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  367. return BadRequest();
  368. }
  369. }
  370. [ProducesDefaultResponseType]
  371. //[AuthToken(Roles = "Teacher")]
  372. [HttpPost("find-students")]
  373. public async Task<IActionResult> FindStudent(JsonElement requert)
  374. {
  375. //ResponseBuilder builder = ResponseBuilder.custom();
  376. //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  377. if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  378. if (!requert.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
  379. if (!requert.TryGetProperty("school_code", out JsonElement schoolId)) return BadRequest();
  380. try
  381. {
  382. var client = _azureCosmos.GetCosmosClient();
  383. List<object> stus = new List<object>();
  384. List<string> stuIds = new List<string>();
  385. string info = "";
  386. for (int i = 0; i < ids.GetArrayLength(); i++)
  387. {
  388. //ids.Add(id[i].ToJsonString());
  389. info += ids[i].ToJsonString() + ",";
  390. }
  391. //List<object> scList = new List<object>();
  392. List<object> suList = new List<object>();
  393. List<(string id, string name, string pic, string code, string classId ,string groupId, string groupName, string no)> listStudent = new List<(string id, string name, string pic, string code, string classId, string groupId, string groupName, string no)>();
  394. //var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(ids[i].GetString(), new PartitionKey($"Class-{schoolId}"));
  395. string className = "";
  396. /* if (response.Status == 200)
  397. {
  398. using var document = await JsonDocument.ParseAsync(response.ContentStream);
  399. Class @class = document.ToObject<Class>();
  400. className = @class.name;
  401. }*/
  402. List<(string id, string name)> listClassList = new List<(string id,string name)>();
  403. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(
  404. queryText: $"select c.id,c.name from c where c.id in ({info[0..^1]})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
  405. {
  406. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  407. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  408. {
  409. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  410. while (accounts.MoveNext())
  411. {
  412. JsonElement account = accounts.Current;
  413. listClassList.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
  414. //stuIds.Add(account.GetProperty("id").GetString());
  415. }
  416. }
  417. }
  418. await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(
  419. queryText: $"select c.id,c.name,c.classId,c.code,c.groupId,c.groupName,c.no,c.picture from c where c.classId in ({info[0..^1]})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  420. {
  421. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  422. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  423. {
  424. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  425. while (accounts.MoveNext())
  426. {
  427. JsonElement account = accounts.Current;
  428. stuIds.Add(account.GetProperty("id").GetString());
  429. listStudent.Add((account.GetProperty("id").GetString(),
  430. account.GetProperty("name").GetString(),
  431. account.GetProperty("picture").GetString(),
  432. account.GetProperty("code").GetString(),
  433. account.GetProperty("classId").GetString(),
  434. account.GetProperty("groupId").GetString(),
  435. account.GetProperty("groupName").GetString(),
  436. account.GetProperty("no").GetString()));
  437. }
  438. }
  439. }
  440. var grpBalance = listStudent.GroupBy(m => new { m.classId }).Distinct().Select(t =>t.ToList().Select(o =>
  441. new
  442. {
  443. o.id,
  444. o.name,
  445. o.pic,
  446. o.code,
  447. o.classId,
  448. className = listClassList.FirstOrDefault(c => c.id == o.classId).name,
  449. o.groupId,
  450. o.groupName,
  451. o.no
  452. })
  453. );
  454. stus.AddRange(grpBalance);
  455. List<(string id, string code, string stuId, string name)> listStuList = new List<(string id, string code, string stuId, string name)>();
  456. if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
  457. {
  458. List<StuList> stuLists = new List<StuList>();
  459. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<StuList>(queryText: $"select value(c) from c where c.id in ({info[0..^1]})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{schoolId}") }))
  460. {
  461. stuLists.Add(item);
  462. }
  463. if (stuLists.Count > 0)
  464. {
  465. foreach (StuList stuList in stuLists)
  466. {
  467. foreach (Students stu in stuList.students)
  468. {
  469. listStuList.Add((stu.id,
  470. stu.code,
  471. stuList.id,
  472. stuList.name));
  473. }
  474. }
  475. var infos = listStuList.GroupBy(m => new { m.stuId }).Distinct().Select(t =>
  476. t.ToList().Select(o =>
  477. new
  478. {
  479. o.id,
  480. o.code,
  481. o.stuId,
  482. o.name
  483. })
  484. );
  485. /* var infos = listStuList.Select(o =>
  486. new
  487. {
  488. o.id,
  489. o.code,
  490. o.stuId,
  491. o.name
  492. });*/
  493. stus.AddRange(infos);
  494. //stus.Add(suList);
  495. }
  496. }
  497. else
  498. {
  499. //处理发布对象为自选名单(个人)
  500. List<StuList> stuLists1 = new List<StuList>();
  501. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<StuList>(queryText: $"select value(c) from c where c.id in ({info[0..^1]})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
  502. {
  503. stuLists1.Add(item);
  504. }
  505. if (stuLists1.Count > 0)
  506. {
  507. foreach (StuList stuList in stuLists1)
  508. {
  509. foreach (Students students in stuList.students)
  510. {
  511. listStuList.Add((students.id,
  512. students.code,
  513. stuList.id,
  514. stuList.name));
  515. }
  516. if (stuList.tmids.Count > 0)
  517. {
  518. foreach (string tid in stuList.tmids)
  519. {
  520. listStuList.Add((tid,
  521. default,
  522. stuList.id,
  523. stuList.name));
  524. }
  525. }
  526. }
  527. var infos = listStuList.GroupBy(m => new { m.stuId }).Distinct().Select(t =>
  528. t.ToList().Select(o =>
  529. new
  530. {
  531. o.id,
  532. o.code,
  533. o.stuId,
  534. o.name
  535. })
  536. );
  537. stus.AddRange(infos);
  538. //stus.Add(suList);
  539. }
  540. }
  541. return Ok(new { stus });
  542. }
  543. catch (Exception ex)
  544. {
  545. await _dingDing.SendBotMsg($"OS,{_option.Location},class/FindStudent()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  546. return BadRequest();
  547. }
  548. }
  549. [ProducesDefaultResponseType]
  550. //[AuthToken(Roles = "Teacher")]
  551. [HttpPost("delete")]
  552. public async Task<IActionResult> Delete(JsonElement request)
  553. {
  554. if (!request.TryGetProperty("school_code", out JsonElement code)) return BadRequest();
  555. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  556. if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  557. try
  558. {
  559. //string school_code = code.ToString().Substring(6);
  560. string school_code = code.ToString();
  561. Class classroom = new Class();
  562. var client = _azureCosmos.GetCosmosClient();
  563. if (scope.ToString().Equals("school"))
  564. {
  565. var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Class-{code}"));
  566. if (response.Status == 200)
  567. {
  568. classroom = await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemAsync<Class>(id.ToString(), new PartitionKey($"Class-{code}"));
  569. }
  570. else
  571. {
  572. List<TeacherCourse> classes = new List<TeacherCourse>();
  573. classroom = await client.GetContainer("TEAMModelOS", "School").DeleteItemAsync<Class>(id.ToString(), new PartitionKey($"Class-{school_code}"));
  574. await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"CourseManagement-{school_code}"));
  575. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: $"select value(c) from c join A0 in c.classes where A0.id = '{id}'"))
  576. {
  577. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  578. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  579. {
  580. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  581. {
  582. classes.Add(obj.ToObject<TeacherCourse>());
  583. }
  584. }
  585. }
  586. for (int i = 0; i < classes.Count; i++)
  587. {
  588. bool flag = false;
  589. for (int j = 0; j < classes[i].classes.Count; j++)
  590. {
  591. if (classes[i].classes[j].id.Equals(id.ToString()))
  592. {
  593. classes[i].classes.Remove(classes[i].classes[j]);
  594. flag = true;
  595. }
  596. }
  597. if (flag)
  598. {
  599. await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(classes[i], classes[i].id, new PartitionKey($"{classes[i].code}"));
  600. }
  601. }
  602. }
  603. }
  604. else
  605. {
  606. classroom = await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemAsync<Class>(id.ToString(), new PartitionKey($"Class-{school_code}"));
  607. }
  608. return Ok(new { classroom });
  609. }
  610. catch (Exception ex)
  611. {
  612. await _dingDing.SendBotMsg($"OS,{_option.Location},class/Delete()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  613. return BadRequest();
  614. }
  615. //ResponseBuilder builder = ResponseBuilder.custom();
  616. /*List<IdPk> idPks = new List<IdPk>();
  617. if (request.TryGetProperty("id", out JsonElement id))
  618. {
  619. List<Classroom> sc = await _azureCosmos.FindByDict<Classroom>(request);
  620. if (sc.IsNotEmpty())
  621. {
  622. await _azureCosmos.DeleteAll<ClassStudent>(new Dictionary<string, object> { { "id", sc.Select(x => x.code).ToArray() } });
  623. idPks = await _azureCosmos.DeleteAll<Classroom>(sc);
  624. //builder.Data(idPks);
  625. }
  626. }
  627. else
  628. {
  629. return Ok(new { erro = ResponseCode.PARAMS_ERROR, V = "参数未定义!" });
  630. }
  631. return Ok(new { idPks });*/
  632. /*List<VoteRecord> sc = await _azureCosmos.FindByDict<VoteRecord>(request);
  633. await _azureCosmos.DeleteAll<VoteRecord>(sc);
  634. return Ok();*/
  635. //await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync("", new PartitionKey($"Class-{code}"));
  636. }
  637. [ProducesDefaultResponseType]
  638. //[AuthToken(Roles = "Teacher")]
  639. [HttpPost("hiteach-link")]
  640. public async Task<IActionResult> HiteachLink(JsonElement request)
  641. {
  642. // 必要檢查
  643. if (!request.TryGetProperty("school_code", out JsonElement code)) return BadRequest();
  644. // if (!request.TryGetProperty("linkList", out JsonElement links)) return BadRequest();
  645. if (!request.TryGetProperty("uuid", out JsonElement a)) return BadRequest();
  646. if (!request.TryGetProperty("uuid2", out JsonElement b)) return BadRequest();
  647. if (!request.TryGetProperty("pid", out JsonElement d)) return BadRequest();
  648. if (!request.TryGetProperty("action", out JsonElement e)) return BadRequest();
  649. if (!request.TryGetProperty("classId", out JsonElement c)) return BadRequest();
  650. // 如果是link classId 必填
  651. string action = e.ToString();
  652. if (action != "link" && action != "unLink") return BadRequest();
  653. try
  654. {
  655. // [變數宣告]
  656. string school_code = code.GetString(); // 學校簡碼
  657. string uuid = a.GetString(); // uuid
  658. string uuid2 = b.GetString(); // uuid2
  659. string pid = d.GetString(); // id
  660. string classId = c.GetString(); // classId
  661. // [取得DB資料]
  662. var client = _azureCosmos.GetCosmosClient();
  663. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school_code, new PartitionKey("Product"));
  664. var error = 0;
  665. if (response.Status == 200)
  666. {
  667. var json = await JsonDocument.ParseAsync(response.ContentStream);
  668. //軟體
  669. SchoolProduct schoolProductItem = json.ToObject<SchoolProduct>();
  670. SerialInfoBaseWithdeviceBound updSerialInfo = schoolProductItem.serial.Where(s => s.id == pid).FirstOrDefault();
  671. if (updSerialInfo != null)
  672. {
  673. deviceBound updDeviceBound = updSerialInfo.deviceBound.Where(d => d.uuid == uuid && d.uuid2 == uuid2).FirstOrDefault();
  674. if (updDeviceBound != null)
  675. {
  676. if (action == "link")
  677. {
  678. if (updDeviceBound.classId != null)
  679. {
  680. error = 1;
  681. }
  682. else
  683. {
  684. updDeviceBound.classId = classId;
  685. }
  686. }
  687. else if (action == "unLink")
  688. {
  689. updDeviceBound.classId = null;
  690. }
  691. if (error == 0) await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolProduct>(schoolProductItem, school_code, new PartitionKey("Product"));
  692. }
  693. }
  694. }
  695. return Ok(new { error });
  696. }
  697. catch (Exception ex)
  698. {
  699. return BadRequest();
  700. }
  701. }
  702. [ProducesDefaultResponseType]
  703. //[AuthToken(Roles = "Teacher")]
  704. [HttpPost("hiteach-unlink-classId")]
  705. public async Task<IActionResult> HiteachUnlinkByClassId(JsonElement request)
  706. {
  707. // 必要檢查
  708. if (!request.TryGetProperty("school_code", out JsonElement code)) return BadRequest();
  709. if (!request.TryGetProperty("classId", out JsonElement id)) return BadRequest();
  710. try
  711. {
  712. // [變數宣告]
  713. string school_code = code.ToString(); // 學校簡碼
  714. string classId = id.ToString(); // 教室ID
  715. // [取得DB資料]
  716. var client = _azureCosmos.GetCosmosClient();
  717. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school_code, new PartitionKey("Product"));
  718. if (response.Status == 200)
  719. {
  720. var json = await JsonDocument.ParseAsync(response.ContentStream);
  721. //軟體
  722. SchoolProduct schoolProductItem = json.ToObject<SchoolProduct>();
  723. foreach (SerialInfoBaseWithdeviceBound updSerialInfo in schoolProductItem.serial)
  724. {
  725. if (updSerialInfo.deviceBound != null)
  726. {
  727. deviceBound updDeviceBound = updSerialInfo.deviceBound.Where(d => d.classId == classId).FirstOrDefault();
  728. if (updDeviceBound != null)
  729. {
  730. updDeviceBound.classId = null;
  731. }
  732. }
  733. }
  734. await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolProduct>(schoolProductItem, school_code, new PartitionKey("Product"));
  735. }
  736. return Ok(new { error = 0 });
  737. }
  738. catch (Exception ex)
  739. {
  740. return BadRequest();
  741. }
  742. }
  743. [ProducesDefaultResponseType]
  744. //[AuthToken(Roles = "Teacher")]
  745. [HttpPost("name")]
  746. public async Task<IActionResult> GetNameList(JsonElement request)
  747. {
  748. if (!request.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
  749. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  750. try
  751. {
  752. var client = _azureCosmos.GetCosmosClient();
  753. //List<string> id = ids.ToObject<List<string>>();
  754. string info = "";
  755. for (int i = 0; i < ids.GetArrayLength(); i++)
  756. {
  757. //ids.Add(id[i].ToJsonString());
  758. info += ids[i].ToJsonString() + ",";
  759. }
  760. List<object> ClassName = new List<object>();
  761. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(
  762. queryText: $"select c.id,c.name from c where c.id in ({info[0..^1]})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{code}") }))
  763. {
  764. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  765. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  766. {
  767. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  768. {
  769. ClassName.Add(obj.ToObject<object>());
  770. }
  771. }
  772. }
  773. return Ok(new { ClassName });
  774. }
  775. catch (Exception ex)
  776. {
  777. await _dingDing.SendBotMsg($"OS,{_option.Location},class/name()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  778. return BadRequest();
  779. }
  780. }
  781. }
  782. }