ClassController.cs 40 KB

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