CourseController.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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.IdentityModel.Tokens.Jwt;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Text.Json;
  12. using System.Threading.Tasks;
  13. using TEAMModelOS.Models;
  14. using TEAMModelOS.Models.Dto;
  15. using TEAMModelOS.SDK.Models;
  16. using TEAMModelOS.SDK;
  17. using TEAMModelOS.SDK.DI;
  18. using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
  19. using TEAMModelOS.SDK.Extension;
  20. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  21. using TEAMModelOS.SDK.Helper.Common.StringHelper;
  22. using System.Dynamic;
  23. using Azure;
  24. namespace TEAMModelOS.Controllers
  25. {
  26. [ProducesResponseType(StatusCodes.Status200OK)]
  27. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  28. //[Authorize(Roles = "IES5")]
  29. [Route("school/course")]
  30. [ApiController]
  31. public class CourseController : ControllerBase
  32. {
  33. private AzureCosmosFactory _azureCosmos;
  34. private readonly DingDing _dingDing;
  35. private readonly Option _option;
  36. public CourseController(AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option)
  37. {
  38. _azureCosmos = azureCosmos;
  39. _dingDing = dingDing;
  40. _option = option?.Value;
  41. }
  42. /// <summary>
  43. /// 更新保存课程
  44. /// </summary>
  45. /// <param name="request"></param>
  46. /// <returns></returns>
  47. [ProducesDefaultResponseType]
  48. //[AuthToken(Roles = "Teacher")]
  49. [HttpPost("upsert")]
  50. public async Task<IActionResult> upsert(JsonElement requert)
  51. {
  52. try {
  53. /*//ResponseBuilder builder = ResponseBuilder.custom();
  54. if (!string.IsNullOrEmpty(requert.id))
  55. {
  56. List<int> count = await _azureCosmos.FindCountByDict<Course>(new Dictionary<string, object> { { "courseCode", requert.courseCode }, { "code", requert.code } });
  57. if (count.IsNotEmpty() && count[0] > 0)
  58. {
  59. // return builder.Error(ResponseCode.DATA_EXIST, "课程编码已经存在!").build();
  60. }
  61. requert.id = requert.code.Replace("#", "") + "-" + requert.courseCode;
  62. }
  63. Course response = await _azureCosmos.SaveOrUpdate<Course>(requert);
  64. return Ok(new { requert });*/
  65. Course course = new Course();
  66. if (!requert.TryGetProperty("course", out JsonElement room)) return BadRequest();
  67. if (!requert.TryGetProperty("option", out JsonElement option)) return BadRequest();
  68. course = room.ToObject<Course>();
  69. var client = _azureCosmos.GetCosmosClient();
  70. course.pk = typeof(Course).Name;
  71. string code = course.code;
  72. course.code = typeof(Course).Name + "-" + course.code;
  73. if (option.ToString().Equals("insert"))
  74. {
  75. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(course.id, new PartitionKey($"Course-{code}"));
  76. if (response.Status == 200)
  77. {
  78. return Ok(new { error = ResponseCode.DATA_EXIST, V = "课程编码已经存在!" });
  79. }
  80. else
  81. {
  82. course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync(course, new PartitionKey($"Course-{code}"));
  83. }
  84. }
  85. else
  86. {
  87. course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").UpsertItemAsync(course, new PartitionKey($"Course-{code}"));
  88. }
  89. return Ok(new { course });
  90. }
  91. catch (Exception ex) {
  92. await _dingDing.SendBotMsg($"OS,{_option.Location},course/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  93. return BadRequest();
  94. }
  95. }
  96. /// <summary>
  97. /// 查询课程
  98. /// </summary>
  99. /// <param name="request"></param>
  100. /// <returns></returns>
  101. [ProducesDefaultResponseType]
  102. //[AuthToken(Roles = "Teacher")]
  103. [HttpPost("find")]
  104. public async Task<IActionResult> Find(JsonElement requert)
  105. {
  106. //ResponseBuilder builder = ResponseBuilder.custom();
  107. //if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
  108. if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  109. //var jwt = new JwtSecurityToken(id_token.GetString());
  110. //if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
  111. //var id = jwt.Payload.Sub;
  112. //var id = "TBLCOURSE700";
  113. try {
  114. var client = _azureCosmos.GetCosmosClient();
  115. List<object> courses = new List<object>();
  116. var query = $"select c.code,c.id,c.name,c.period,c.subject,c.teachers from c";
  117. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_code.GetString()}") }))
  118. {
  119. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  120. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  121. {
  122. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  123. {
  124. courses.Add(obj.ToObject<object>());
  125. }
  126. }
  127. }
  128. return Ok(new { courses, courses.Count });
  129. } catch (Exception ex) {
  130. await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},course/find()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  131. return BadRequest();
  132. }
  133. /* List<Course> data = new List<Course>();
  134. if (StringHelper.getKeyCount(request) > 0) {
  135. data = await _azureCosmos.FindByDict<Course>(request);
  136. }
  137. return builder.Data(data).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();*/
  138. }
  139. /// <summary>
  140. /// 删除课程
  141. /// </summary>
  142. /// <param name="request"></param>
  143. /// <returns></returns>
  144. [ProducesDefaultResponseType]
  145. //[AuthToken(Roles = "Teacher")]
  146. [HttpPost("delete")]
  147. public async Task<IActionResult> Delete(JsonElement request)
  148. {
  149. try {
  150. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  151. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  152. if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  153. //string school_code = code.ToString().Substring(typeof(Course).Name.Length + 1);
  154. var client = _azureCosmos.GetCosmosClient();
  155. if (scope.ToString().Equals("school")){
  156. List<CourseManagement> managements = new List<CourseManagement>();
  157. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"select value(c) from c join A0 in c.courses where A0.course.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{code}") }))
  158. {
  159. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  160. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  161. {
  162. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  163. {
  164. managements.Add(obj.ToObject<CourseManagement>());
  165. }
  166. }
  167. }
  168. for (int i = 0; i < managements.Count; i++)
  169. {
  170. bool flag = false;
  171. for (int j = 0; j < managements[i].courses.Count; j++)
  172. {
  173. if (!managements[i].courses[j].course.id.Equals(id.ToString()))
  174. {
  175. flag = true;
  176. managements[i].courses.Remove(managements[i].courses[j]);
  177. break;
  178. }
  179. }
  180. if (flag)
  181. {
  182. await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(managements[i], managements[i].id, new PartitionKey($"{managements[i].code}"));
  183. }
  184. }
  185. } else {
  186. await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Course-{code}"));
  187. }
  188. //IdPk idPk= await _azureCosmos.DeleteAsync<Course>(request);
  189. return Ok(new { id });
  190. }
  191. catch (Exception ex)
  192. {
  193. await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},course/delete()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  194. return BadRequest();
  195. }
  196. }
  197. /// <summary>
  198. /// 删除课程
  199. /// </summary>
  200. /// <param name="request"></param>
  201. /// <returns></returns>
  202. [ProducesDefaultResponseType]
  203. //[AuthToken(Roles = "Teacher")]
  204. [HttpPost("delete-all")]
  205. public async Task<IActionResult> DeleteAll(BatchOption request)
  206. {
  207. try
  208. {
  209. /*if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  210. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();*/
  211. var client = _azureCosmos.GetCosmosClient();
  212. if (request == null) return BadRequest();
  213. StringBuilder sql = new StringBuilder();
  214. sql.Append("select value(c) from c ");
  215. /*Dictionary<string, object> dict = new Dictionary<string, object>();
  216. //处理id
  217. if (request.ids.IsNotEmpty())
  218. {
  219. dict.Add("id", request.ids.ToArray());
  220. }*/
  221. string school_code = request.code;
  222. /*AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  223. List<Course> courses = new List<Course>();
  224. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_code}") }))
  225. {
  226. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  227. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  228. {
  229. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  230. {
  231. courses.Add(obj.ToObject<Course>());
  232. }
  233. }
  234. }*/
  235. List<Response> res = await client.GetContainer("TEAMModelOS", "School").DeleteItemsStreamAsync(request.ids, $"Course-{school_code}");
  236. // TODO JJ调整批量删除
  237. //await _azureCosmos.DeleteAll(courses);
  238. //List<IdPk> idPk = await _azureCosmos.DeleteAll<Course>(request);
  239. //await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Class-{code}"));
  240. //[Jeff] CourseManagement表廢除 刪除預定:以下CourseManagement更新程序
  241. StringBuilder sqlM = new StringBuilder();
  242. sqlM.Append("select value(c) from c ");
  243. Dictionary<string, object> dict_management = new Dictionary<string, object>();
  244. //处理ID
  245. if (request.ids.IsNotEmpty())
  246. {
  247. dict_management.Add("courses[*].course.id", request.ids.ToArray());
  248. }
  249. List<CourseManagement> managements = new List<CourseManagement>();
  250. AzureCosmosQuery cosmosDbQuery_1 = SQLHelper.GetSQL(dict_management, sqlM);
  251. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery_1.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{school_code}") }))
  252. {
  253. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  254. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  255. {
  256. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  257. {
  258. managements.Add(obj.ToObject<CourseManagement>());
  259. }
  260. }
  261. }
  262. for (int i = 0; i < managements.Count; i++)
  263. {
  264. bool flag = false;
  265. for (int k = 0; k < request.ids.Count; k++)
  266. {
  267. for (int j = 0; j < managements[i].courses.Count; j++)
  268. {
  269. if (managements[i].courses[j].course.id.Equals(request.ids[k].ToString()))
  270. {
  271. managements[i].courses.Remove(managements[i].courses[j]);
  272. flag = true;
  273. }
  274. }
  275. }
  276. if (flag)
  277. {
  278. await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(managements[i], managements[i].id, new PartitionKey($"{managements[i].code}"));
  279. }
  280. }
  281. ////[Jeff] CourseManagement表廢除 刪除預定:以下CourseManagement更新程序
  282. //IdPk idPk= await _azureCosmos.DeleteAsync<Course>(request);
  283. return Ok(new { ids = request.ids });
  284. }
  285. catch (Exception ex)
  286. {
  287. await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},course/delete()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  288. return BadRequest();
  289. }
  290. //ResponseBuilder builder = ResponseBuilder.custom();
  291. //return builder.Data(idPk).build();
  292. //return Ok(new { idPk });
  293. }
  294. /// <summary>
  295. /// 更新保存排课管理
  296. /// </summary>
  297. /// <param name="request"></param>
  298. /// <returns></returns>
  299. [ProducesDefaultResponseType]
  300. //[AuthToken(Roles = "Teacher")]
  301. [HttpPost("upsert-management")]
  302. public async Task<IActionResult> upsertCourseManagement(CourseManagement requert)
  303. {
  304. try
  305. {
  306. CourseManagement course = new CourseManagement();
  307. //course = room.ToObject<CourseManagement>();
  308. var client = _azureCosmos.GetCosmosClient();
  309. string code = requert.code;
  310. requert.code = "CourseManagement-" + requert.code;
  311. /* if (requert.scope.Equals) {
  312. }*/
  313. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(requert.id, new PartitionKey($"CourseManagement-{code}"));
  314. if (response.Status == 200)
  315. {
  316. /* using var json = await JsonDocument.ParseAsync(response.ContentStream);
  317. CourseManagement courseManagement = json.ToObject<CourseManagement>();
  318. courseManagement.courses = requert.courses;*/
  319. //return Ok(new { error = ResponseCode.DATA_EXIST, V = "课程编码已经存在!" });
  320. course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync(requert, requert.id, new PartitionKey($"CourseManagement-{code}"));
  321. }
  322. else
  323. {
  324. course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync(requert, new PartitionKey($"CourseManagement-{code}"));
  325. }
  326. return Ok(new { course });
  327. }
  328. catch (Exception ex)
  329. {
  330. await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},management/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  331. return BadRequest();
  332. }
  333. }
  334. /// <summary>
  335. /// 查询排课管理
  336. /// </summary>
  337. /// <param name="request"></param>
  338. /// <returns></returns>
  339. [ProducesDefaultResponseType]
  340. //[AuthToken(Roles = "Teacher")]
  341. [HttpPost("find-management")]
  342. public async Task<IActionResult> FindManagement(JsonElement requert)
  343. {
  344. //if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  345. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  346. var client = _azureCosmos.GetCosmosClient();
  347. List<object> courses = new List<object>();
  348. StringBuilder sql = new StringBuilder();
  349. sql.Append("select c.code,c.id,c.name,c.courses,c.scope,c.teacher from c ");
  350. Dictionary<string, object> dict = new Dictionary<string, object>();
  351. var emobj = requert.EnumerateObject();
  352. while (emobj.MoveNext())
  353. {
  354. dict[emobj.Current.Name] = emobj.Current.Value;
  355. }
  356. //处理code
  357. if (dict.TryGetValue("code", out object _))
  358. {
  359. dict.Remove("code");
  360. }
  361. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  362. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{code}") }))
  363. {
  364. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  365. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  366. {
  367. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  368. {
  369. courses.Add(obj.ToObject<object>());
  370. }
  371. }
  372. }
  373. /* List<object> courses = new List<object>();
  374. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(id.ToString(), new PartitionKey($"CourseManagement-{code}"));
  375. if (response.Status == 200)
  376. {
  377. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  378. foreach (var obj in json.RootElement.GetProperty("courseSimples").EnumerateArray())
  379. {
  380. courses.Add(obj.ToObject<object>());
  381. }
  382. *//*if (json.RootElement.TryGetProperty("courseSimples", out JsonElement value))
  383. {
  384. courses = (List<object>)value.ToObject<object>();
  385. }*//*
  386. }
  387. else {
  388. return Ok(new { error = ResponseCode.UNDEFINED, V = "数据未找到!" });
  389. }*/
  390. return Ok(new { courses });
  391. /* var query = $"select c.code,c.id,c.name,c.period,c.subject,c.teachers from c";
  392. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_code.GetString()}") }))
  393. {
  394. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  395. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  396. {
  397. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  398. {
  399. courses.Add(obj.ToObject<object>());
  400. }
  401. }
  402. }*/
  403. //return Ok(new { courses, courses.Count });
  404. /* List<Course> data = new List<Course>();
  405. if (StringHelper.getKeyCount(request) > 0) {
  406. data = await _azureCosmos.FindByDict<Course>(request);
  407. }
  408. return builder.Data(data).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();*/
  409. }
  410. [ProducesDefaultResponseType]
  411. //[AuthToken(Roles = "Teacher")]
  412. [HttpPost("find-course")]
  413. public async Task<IActionResult> FindCourse(JsonElement requert)
  414. {
  415. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  416. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  417. var client = _azureCosmos.GetCosmosClient();
  418. List<object> courses = new List<object>();
  419. var query = $"select c.code,c.id,c.name,A0.course.id courseId,A0.course.name courseName ,A0.course.notice notice ,A1,c.scope,c.teacher from c join A0 in c.courses join A1 in A0.teachers where A1.id = '{id}' ";
  420. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{code}") }))
  421. {
  422. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  423. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  424. {
  425. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  426. {
  427. courses.Add(obj.ToObject<object>());
  428. }
  429. }
  430. }
  431. return Ok(new { courses });
  432. }
  433. [ProducesDefaultResponseType]
  434. //[AuthToken(Roles = "Teacher")]
  435. [HttpPost("upsert-notice")]
  436. public async Task<IActionResult> upsertNotice(JsonElement requert)
  437. {
  438. if (!requert.TryGetProperty("courseId", out JsonElement courseId)) return BadRequest();
  439. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  440. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  441. if (!requert.TryGetProperty("notice", out JsonElement notice)) return BadRequest();
  442. if (!requert.TryGetProperty("A1", out JsonElement teacherInfo)) return BadRequest();
  443. Teachers teachers = teacherInfo.ToObject<Teachers>();
  444. var client = _azureCosmos.GetCosmosClient();
  445. List<CourseManagement> courseManagements = new List<CourseManagement>();
  446. /*var sresponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{code}"));
  447. if (sresponse.Status == 200)
  448. {
  449. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  450. CourseManagement course = json.ToObject<CourseManagement>();
  451. for (int i =0; i < course.courses.Count;i++) {
  452. if (course.courses[i].course.id.Equals(courseId.ToString())) {
  453. course.courses[i].course.notice = notice.ToString();
  454. await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(course, course.id, new PartitionKey($"{course.code}"));
  455. break;
  456. }
  457. }
  458. }*/
  459. StringBuilder sql = new StringBuilder();
  460. sql.Append("select value(c) from c");
  461. Dictionary<string, object> dict = new Dictionary<string, object>();
  462. //dict.Add("id", id);
  463. dict.Add("courses[*].course.id", courseId);
  464. dict.Add("courses[*].teachers[*].id", teachers.id);
  465. //dict.Add("id", classroom.id);
  466. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  467. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{code}") }))
  468. {
  469. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  470. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  471. {
  472. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  473. {
  474. courseManagements.Add(obj.ToObject<CourseManagement>());
  475. }
  476. }
  477. }
  478. for (int i = 0; i < courseManagements.Count; i++)
  479. {
  480. for (int j = 0;j < courseManagements[i].courses.Count;j++) {
  481. if (courseManagements[i].courses[j].course.id.Equals(courseId.ToString()))
  482. {
  483. courseManagements[i].courses[j].course.notice = notice.ToString();
  484. await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(courseManagements[i], courseManagements[i].id, new PartitionKey($"{courseManagements[i].code}"));
  485. break;
  486. }
  487. }
  488. }
  489. return Ok(new { id });
  490. }
  491. internal class valitime {
  492. public string code { get; set; }
  493. public string courseId { get; set; }
  494. public string classroomCode { get; set; }
  495. public string time { get; set; }
  496. public string day { get; set; }
  497. public string notice { get; set; }
  498. public CourseTime courseTime { get; set; }
  499. /// <summary>
  500. /// 学生分组
  501. /// </summary>
  502. public List<GroupStudent> groups { get; set; }
  503. /// <summary>
  504. /// 助教
  505. /// </summary>
  506. public List<Assistant> assistant { get; set; }
  507. /// <summary>
  508. /// 学期代码
  509. /// </summary>
  510. public string semesterCode { get; set; }
  511. }
  512. // TODO 前端没在用
  513. /// <summary>
  514. /// 教师更新副属信息,助教,分组等。
  515. /// </summary>
  516. /// <param name="request"></param>
  517. /// <returns></returns>
  518. //[ProducesDefaultResponseType]
  519. ////[AuthToken(Roles = "Teacher")]
  520. //[HttpPost("upsert-plan")]
  521. //public async Task<BaseResponse> UpsertPlan(CoursePlan request) {
  522. // ResponseBuilder builder = ResponseBuilder.custom();
  523. // CoursePlan datas = await _azureCosmos.FindByIdPk<CoursePlan>(request.id,request.code);
  524. // if (datas!=null) {
  525. // request.semesterCode = datas.semesterCode;
  526. // request.classes.ForEach(x => {
  527. // datas.classes.ForEach(m => {
  528. // if (m.classroomCode == x.classroomCode) {
  529. // x.courseTimes = m.courseTimes;
  530. // } });
  531. // });
  532. // await _azureCosmos.Update(request);
  533. // }
  534. // return builder.Data(request).build();
  535. //}
  536. [ProducesDefaultResponseType]
  537. //[AuthToken(Roles = "Teacher")]
  538. [HttpPost("upsert-teacher-course")]
  539. public async Task<IActionResult> upsertCourse(JsonElement requert)
  540. {
  541. try
  542. {
  543. TeacherCourse course = new TeacherCourse();
  544. if (!requert.TryGetProperty("course", out JsonElement room)) return BadRequest();
  545. if (!requert.TryGetProperty("option", out JsonElement option)) return BadRequest();
  546. course = room.ToObject<TeacherCourse>();
  547. var client = _azureCosmos.GetCosmosClient();
  548. course.pk = typeof(Course).Name;
  549. string code = course.code;
  550. course.code = typeof(Course).Name + "-" + course.code;
  551. if (option.ToString().Equals("insert"))
  552. {
  553. var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(course.id, new PartitionKey($"Course-{code}"));
  554. if (response.Status == 200)
  555. {
  556. return Ok(new { error = ResponseCode.DATA_EXIST, V = "课程编码已经存在!" });
  557. }
  558. else
  559. {
  560. course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(course, new PartitionKey($"Course-{code}"));
  561. }
  562. }
  563. else
  564. {
  565. if (course.classes.Count > 0) {
  566. //TODO 教师创建的个人的校本班级待处理冗余数据
  567. foreach (ClassSimple classSimple in course.classes) {
  568. if (classSimple.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  569. {
  570. Class cla = new Class();
  571. cla.id = classSimple.id;
  572. cla.code = cla.pk + "-" + code;
  573. cla.name = classSimple.name;
  574. cla.scope = classSimple.scope;
  575. cla.teacher.id = classSimple.teacher.id;
  576. cla.teacher.name = classSimple.teacher.name;
  577. await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync(cla, new PartitionKey($"Class-{code}"));
  578. }
  579. else {
  580. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(classSimple.id, new PartitionKey($"Class-{classSimple.code}"));
  581. if (response.Status == 200)
  582. {
  583. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  584. Class cla = json.ToObject<Class>();
  585. Class newCla = new Class();
  586. newCla.id = cla.id;
  587. newCla.code = cla.pk + "-" + code;
  588. newCla.name = classSimple.name;
  589. newCla.scope = classSimple.scope;
  590. /*foreach (StudentSimple student in cla.students)
  591. {
  592. StudentSimple studentSimple = new StudentSimple();
  593. studentSimple.id = student.id;
  594. studentSimple.name = student.name;
  595. studentSimple.no = student.no;
  596. newCla.students.Add(studentSimple);
  597. }*/
  598. newCla.teacher.id = classSimple.teacher.id;
  599. newCla.teacher.name = classSimple.teacher.name;
  600. await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync(newCla, new PartitionKey($"Class-{code}"));
  601. classSimple.code = code;
  602. }
  603. else
  604. {
  605. Class cla = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Class>(classSimple.id, new PartitionKey($"Class-{classSimple.code}"));
  606. Class newCla = new Class();
  607. newCla.id = cla.id;
  608. newCla.code = cla.pk + "-" + code;
  609. newCla.name = classSimple.name;
  610. newCla.scope = classSimple.scope;
  611. //newCla.students = cla.students;
  612. newCla.teacher.id = classSimple.teacher.id;
  613. newCla.teacher.name = classSimple.teacher.name;
  614. await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync(newCla, new PartitionKey($"Class-{code}"));
  615. }
  616. }
  617. }
  618. }
  619. course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(course,course.id, new PartitionKey($"Course-{code}"));
  620. }
  621. return Ok(new { course });
  622. }
  623. catch (Exception ex)
  624. {
  625. await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},teacherCourse/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  626. return BadRequest();
  627. }
  628. }
  629. [ProducesDefaultResponseType]
  630. //[AuthToken(Roles = "Teacher")]
  631. [HttpPost("find-teacher-course")]
  632. public async Task<IActionResult> FindTeacherCourse(JsonElement requert)
  633. {
  634. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  635. //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  636. var client = _azureCosmos.GetCosmosClient();
  637. List<object> courses = new List<object>();
  638. var query = $"select c.code,c.id,c.name,c.subjectId,c.periodId,c.scope,c.notice,c.classes from c ";
  639. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{id}") }))
  640. {
  641. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  642. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  643. {
  644. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  645. {
  646. courses.Add(obj.ToObject<object>());
  647. }
  648. }
  649. }
  650. return Ok(new { courses });
  651. }
  652. /// <summary>
  653. /// 查询执教助教的课程班级
  654. /// </summary>
  655. /// <param name="request"></param>
  656. /// <returns></returns>
  657. [ProducesDefaultResponseType]
  658. //[AuthToken(Roles = "Teacher")]
  659. [HttpPost("find-teach-class")]
  660. public async Task<IActionResult> FindPlanClass(JsonElement request)
  661. {
  662. ResponseBuilder builder = ResponseBuilder.custom();
  663. HashSet<string> data = new HashSet<string>();
  664. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  665. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  666. var client = _azureCosmos.GetCosmosClient();
  667. List<Student> courses = new List<Student>();
  668. var query = $"select A0.id,A0.name,A0.scope from c join A0 in c.classes";
  669. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{id}") }))
  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. courses.Add(obj.ToObject<Student>());
  677. }
  678. }
  679. }
  680. //List<object> coursesBySchool = new List<object>();
  681. var queryBySchool = $"select distinct c.id,c.name,c.scope from c join A0 in c.courses join A1 in A0.teachers where A1.id = '{id}' ";
  682. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: queryBySchool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{code}") }))
  683. {
  684. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  685. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  686. {
  687. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  688. {
  689. courses.Add(obj.ToObject<Student>());
  690. }
  691. }
  692. }
  693. courses = courses.Distinct(new ListDistinct()).ToList();
  694. //courses = courses.Distinct().ToList();
  695. return Ok(new { courses ,courses.Count});
  696. //request.TryGetProperty("assistant[*]", out JsonElement element);
  697. /*List<dynamic> room = new List<dynamic>();
  698. var prop = new List<string> { "classes" };
  699. if (request.TryGetProperty("code", out JsonElement code))
  700. {
  701. var teachers = await _azureCosmos.FindByDict<CoursePlan>(new Dictionary<string, object> { { "code", code.ToString() } }, prop);
  702. if (teachers.IsNotEmpty()) {
  703. teachers.Select(x => x.classes).ToList().ForEach(x => { x.ForEach(y => { data.Add(y.classroomCode); }); });
  704. }
  705. }
  706. if (request.TryGetProperty("assistant[*]", out JsonElement element)) {
  707. var assistant = await _azureCosmos.FindByDict<CoursePlan>(new Dictionary<string, object> { { "assistant[*]", element.ToString() } }, prop);
  708. if (assistant.IsNotEmpty()) {
  709. assistant.Select(x => x.classes).ToList().ForEach(x => { x.ForEach(y => { data.Add(y.classroomCode); }); });
  710. }
  711. }
  712. if (data.Count > 0) {
  713. var classRoom= await _azureCosmos.FindByDict<Classroom>(new Dictionary<string, object> { { "id",data.ToArray() } } );
  714. if (classRoom.IsNotEmpty()) {
  715. classRoom.ForEach(x => {
  716. room.Add(x);
  717. });
  718. }
  719. }*/
  720. //return builder.Data(room).Extend(new Dictionary<string, object> { { "count", room.Count } }).build();
  721. }
  722. // TODO 前端没在用
  723. /// <summary>
  724. /// 删除课程安排
  725. /// </summary>
  726. /// <param name="request"></param>
  727. /// <returns></returns>
  728. //[ProducesDefaultResponseType]
  729. ////[AuthToken(Roles = "Teacher")]
  730. //[HttpPost("delete-time")]
  731. //public async Task<BaseResponse> DeletePlan(JsonElement request)
  732. //{
  733. // ResponseBuilder builder = ResponseBuilder.custom();
  734. // if (request.TryGetProperty("id",out JsonElement id) && request.TryGetProperty("code",out JsonElement code) && request.TryGetProperty("classroomCode",out JsonElement classroomCode)
  735. // && request.TryGetProperty("time",out JsonElement time) && request.TryGetProperty("day",out JsonElement day)) {
  736. // CoursePlan coursePlan = await _azureCosmos.FindByIdPk<CoursePlan>(id.ToString(), code.ToString());
  737. // List<CourseTime> courseTimes = new List<CourseTime>();
  738. // coursePlan.classes.ForEach(x=> {
  739. // if (x.classroomCode == classroomCode.ToString()) {
  740. // x.courseTimes.ForEach(y => {
  741. // if (y.time == time.ToString() && y.day == day.ToString())
  742. // {
  743. // courseTimes.Add(y);
  744. // }
  745. // });
  746. // }
  747. // });
  748. // coursePlan.classes.ForEach(x => { if (x.classroomCode == classroomCode.ToString()) {
  749. // courseTimes.ForEach(y => { x.courseTimes.Remove(y); });
  750. // } });
  751. // await _azureCosmos.Update(coursePlan);
  752. // return builder.Data(coursePlan).build();
  753. // }
  754. // return builder.Data(null).build();
  755. //}
  756. public class Student
  757. {
  758. public string id { get; set; }
  759. public string name { get; set; }
  760. public string scope { get; set; }
  761. }
  762. public class ListDistinct : IEqualityComparer<Student>
  763. {
  764. public bool Equals(Student s1, Student s2)
  765. {
  766. return (s1.id == s2.id);
  767. }
  768. public int GetHashCode(Student s)
  769. {
  770. return s==null?0:s.ToString().GetHashCode();
  771. }
  772. }
  773. }
  774. public class BatchOption {
  775. public List<string> ids { get; set; }
  776. public string code { get; set; }
  777. }
  778. }