ClassRoomController.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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 scinfos = listStudent.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. scList.AddRange(scinfos);
  454. stus.Add(scList);
  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.Select(o =>
  476. new
  477. {
  478. o.id,
  479. o.code,
  480. o.stuId,
  481. o.name
  482. });
  483. suList.AddRange(infos);
  484. stus.Add(suList);
  485. }
  486. }
  487. else
  488. {
  489. //处理发布对象为自选名单(个人)
  490. List<StuList> stuLists1 = new List<StuList>();
  491. 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") }))
  492. {
  493. stuLists1.Add(item);
  494. }
  495. if (stuLists1.Count > 0)
  496. {
  497. foreach (StuList stuList in stuLists1)
  498. {
  499. foreach (Students students in stuList.students)
  500. {
  501. listStuList.Add((students.id,
  502. students.code,
  503. stuList.id,
  504. stuList.name));
  505. }
  506. if (stuList.tmids.Count > 0)
  507. {
  508. foreach (string tid in stuList.tmids)
  509. {
  510. listStuList.Add((tid,
  511. default,
  512. stuList.id,
  513. stuList.name));
  514. }
  515. }
  516. }
  517. var infos = listStuList.Select(o =>
  518. new
  519. {
  520. o.id,
  521. o.code,
  522. o.stuId,
  523. o.name
  524. });
  525. suList.AddRange(infos);
  526. stus.Add(suList);
  527. }
  528. }
  529. return Ok(new { stus });
  530. }
  531. catch (Exception ex)
  532. {
  533. await _dingDing.SendBotMsg($"OS,{_option.Location},class/FindStudent()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  534. return BadRequest();
  535. }
  536. }
  537. [ProducesDefaultResponseType]
  538. //[AuthToken(Roles = "Teacher")]
  539. [HttpPost("delete")]
  540. public async Task<IActionResult> Delete(JsonElement request)
  541. {
  542. if (!request.TryGetProperty("school_code", out JsonElement code)) return BadRequest();
  543. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  544. if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  545. try
  546. {
  547. //string school_code = code.ToString().Substring(6);
  548. string school_code = code.ToString();
  549. Class classroom = new Class();
  550. var client = _azureCosmos.GetCosmosClient();
  551. if (scope.ToString().Equals("school"))
  552. {
  553. var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Class-{code}"));
  554. if (response.Status == 200)
  555. {
  556. classroom = await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemAsync<Class>(id.ToString(), new PartitionKey($"Class-{code}"));
  557. }
  558. else
  559. {
  560. List<TeacherCourse> classes = new List<TeacherCourse>();
  561. classroom = await client.GetContainer("TEAMModelOS", "School").DeleteItemAsync<Class>(id.ToString(), new PartitionKey($"Class-{school_code}"));
  562. await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"CourseManagement-{school_code}"));
  563. 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}'"))
  564. {
  565. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  566. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  567. {
  568. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  569. {
  570. classes.Add(obj.ToObject<TeacherCourse>());
  571. }
  572. }
  573. }
  574. for (int i = 0; i < classes.Count; i++)
  575. {
  576. bool flag = false;
  577. for (int j = 0; j < classes[i].classes.Count; j++)
  578. {
  579. if (classes[i].classes[j].id.Equals(id.ToString()))
  580. {
  581. classes[i].classes.Remove(classes[i].classes[j]);
  582. flag = true;
  583. }
  584. }
  585. if (flag)
  586. {
  587. await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(classes[i], classes[i].id, new PartitionKey($"{classes[i].code}"));
  588. }
  589. }
  590. }
  591. }
  592. else
  593. {
  594. classroom = await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemAsync<Class>(id.ToString(), new PartitionKey($"Class-{school_code}"));
  595. }
  596. return Ok(new { classroom });
  597. }
  598. catch (Exception ex)
  599. {
  600. await _dingDing.SendBotMsg($"OS,{_option.Location},class/Delete()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  601. return BadRequest();
  602. }
  603. //ResponseBuilder builder = ResponseBuilder.custom();
  604. /*List<IdPk> idPks = new List<IdPk>();
  605. if (request.TryGetProperty("id", out JsonElement id))
  606. {
  607. List<Classroom> sc = await _azureCosmos.FindByDict<Classroom>(request);
  608. if (sc.IsNotEmpty())
  609. {
  610. await _azureCosmos.DeleteAll<ClassStudent>(new Dictionary<string, object> { { "id", sc.Select(x => x.code).ToArray() } });
  611. idPks = await _azureCosmos.DeleteAll<Classroom>(sc);
  612. //builder.Data(idPks);
  613. }
  614. }
  615. else
  616. {
  617. return Ok(new { erro = ResponseCode.PARAMS_ERROR, V = "参数未定义!" });
  618. }
  619. return Ok(new { idPks });*/
  620. /*List<VoteRecord> sc = await _azureCosmos.FindByDict<VoteRecord>(request);
  621. await _azureCosmos.DeleteAll<VoteRecord>(sc);
  622. return Ok();*/
  623. //await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync("", new PartitionKey($"Class-{code}"));
  624. }
  625. [ProducesDefaultResponseType]
  626. //[AuthToken(Roles = "Teacher")]
  627. [HttpPost("hiteach-link")]
  628. public async Task<IActionResult> HiteachLink(JsonElement request)
  629. {
  630. // 必要檢查
  631. if (!request.TryGetProperty("school_code", out JsonElement code)) return BadRequest();
  632. // if (!request.TryGetProperty("linkList", out JsonElement links)) return BadRequest();
  633. if (!request.TryGetProperty("uuid", out JsonElement a)) return BadRequest();
  634. if (!request.TryGetProperty("uuid2", out JsonElement b)) return BadRequest();
  635. if (!request.TryGetProperty("pid", out JsonElement d)) return BadRequest();
  636. if (!request.TryGetProperty("action", out JsonElement e)) return BadRequest();
  637. if (!request.TryGetProperty("classId", out JsonElement c)) return BadRequest();
  638. // 如果是link classId 必填
  639. string action = e.ToString();
  640. if (action != "link" && action != "unLink") return BadRequest();
  641. try
  642. {
  643. // [變數宣告]
  644. string school_code = code.GetString(); // 學校簡碼
  645. string uuid = a.GetString(); // uuid
  646. string uuid2 = b.GetString(); // uuid2
  647. string pid = d.GetString(); // id
  648. string classId = c.GetString(); // classId
  649. // [取得DB資料]
  650. var client = _azureCosmos.GetCosmosClient();
  651. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school_code, new PartitionKey("Product"));
  652. var error = 0;
  653. if (response.Status == 200)
  654. {
  655. var json = await JsonDocument.ParseAsync(response.ContentStream);
  656. //軟體
  657. SchoolProduct schoolProductItem = json.ToObject<SchoolProduct>();
  658. SerialInfoBaseWithdeviceBound updSerialInfo = schoolProductItem.serial.Where(s => s.id == pid).FirstOrDefault();
  659. if (updSerialInfo != null)
  660. {
  661. deviceBound updDeviceBound = updSerialInfo.deviceBound.Where(d => d.uuid == uuid && d.uuid2 == uuid2).FirstOrDefault();
  662. if (updDeviceBound != null)
  663. {
  664. if (action == "link")
  665. {
  666. if (updDeviceBound.classId != null)
  667. {
  668. error = 1;
  669. }
  670. else
  671. {
  672. updDeviceBound.classId = classId;
  673. }
  674. }
  675. else if (action == "unLink")
  676. {
  677. updDeviceBound.classId = null;
  678. }
  679. if (error == 0) await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolProduct>(schoolProductItem, school_code, new PartitionKey("Product"));
  680. }
  681. }
  682. }
  683. return Ok(new { error });
  684. }
  685. catch (Exception ex)
  686. {
  687. return BadRequest();
  688. }
  689. }
  690. [ProducesDefaultResponseType]
  691. //[AuthToken(Roles = "Teacher")]
  692. [HttpPost("hiteach-unlink-classId")]
  693. public async Task<IActionResult> HiteachUnlinkByClassId(JsonElement request)
  694. {
  695. // 必要檢查
  696. if (!request.TryGetProperty("school_code", out JsonElement code)) return BadRequest();
  697. if (!request.TryGetProperty("classId", out JsonElement id)) return BadRequest();
  698. try
  699. {
  700. // [變數宣告]
  701. string school_code = code.ToString(); // 學校簡碼
  702. string classId = id.ToString(); // 教室ID
  703. // [取得DB資料]
  704. var client = _azureCosmos.GetCosmosClient();
  705. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school_code, new PartitionKey("Product"));
  706. if (response.Status == 200)
  707. {
  708. var json = await JsonDocument.ParseAsync(response.ContentStream);
  709. //軟體
  710. SchoolProduct schoolProductItem = json.ToObject<SchoolProduct>();
  711. foreach (SerialInfoBaseWithdeviceBound updSerialInfo in schoolProductItem.serial)
  712. {
  713. if (updSerialInfo.deviceBound != null)
  714. {
  715. deviceBound updDeviceBound = updSerialInfo.deviceBound.Where(d => d.classId == classId).FirstOrDefault();
  716. if (updDeviceBound != null)
  717. {
  718. updDeviceBound.classId = null;
  719. }
  720. }
  721. }
  722. await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolProduct>(schoolProductItem, school_code, new PartitionKey("Product"));
  723. }
  724. return Ok(new { error = 0 });
  725. }
  726. catch (Exception ex)
  727. {
  728. return BadRequest();
  729. }
  730. }
  731. [ProducesDefaultResponseType]
  732. //[AuthToken(Roles = "Teacher")]
  733. [HttpPost("name")]
  734. public async Task<IActionResult> GetNameList(JsonElement request)
  735. {
  736. if (!request.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
  737. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  738. try
  739. {
  740. var client = _azureCosmos.GetCosmosClient();
  741. //List<string> id = ids.ToObject<List<string>>();
  742. string info = "";
  743. for (int i = 0; i < ids.GetArrayLength(); i++)
  744. {
  745. //ids.Add(id[i].ToJsonString());
  746. info += ids[i].ToJsonString() + ",";
  747. }
  748. List<object> ClassName = new List<object>();
  749. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(
  750. queryText: $"select c.id,c.name from c where c.id in ({info[0..^1]})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{code}") }))
  751. {
  752. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  753. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  754. {
  755. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  756. {
  757. ClassName.Add(obj.ToObject<object>());
  758. }
  759. }
  760. }
  761. return Ok(new { ClassName });
  762. }
  763. catch (Exception ex)
  764. {
  765. await _dingDing.SendBotMsg($"OS,{_option.Location},class/name()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  766. return BadRequest();
  767. }
  768. }
  769. }
  770. }