ElegantController.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Dynamic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Net.Http.Json;
  10. using System.Text;
  11. using System.Text.Json;
  12. using System.Text.Json.Serialization;
  13. using System.Threading.Tasks;
  14. using Azure;
  15. using Azure.Cosmos;
  16. using Azure.Storage.Sas;
  17. using DocumentFormat.OpenXml.Drawing.Charts;
  18. using HTEXLib.COMM.Helpers;
  19. using Microsoft.AspNetCore.Authorization;
  20. using Microsoft.AspNetCore.Cryptography.KeyDerivation;
  21. using Microsoft.AspNetCore.Mvc;
  22. using Microsoft.Extensions.Options;
  23. using Newtonsoft.Json;
  24. using OpenXmlPowerTools;
  25. using TEAMModelOS.Filter;
  26. using TEAMModelOS.Models;
  27. using TEAMModelOS.SDK.DI;
  28. using TEAMModelOS.SDK.Extension;
  29. using TEAMModelOS.SDK.Models;
  30. using TEAMModelOS.SDK.Models.Cosmos;
  31. using TEAMModelOS.SDK.Models.Cosmos.Common;
  32. using TEAMModelOS.SDK.Models.Dtos;
  33. using TEAMModelOS.SDK.Models.Service;
  34. namespace TEAMModelOS.Controllers
  35. {
  36. [Route("school/elegant")]
  37. [ApiController]
  38. public class ElegantController : ControllerBase
  39. {
  40. private readonly AzureCosmosFactory _azureCosmos;
  41. private readonly AzureStorageFactory _azureStorage;
  42. private readonly DingDing _dingDing;
  43. private readonly Option _option;
  44. private IHttpClientFactory _httpClientFactory;
  45. public ElegantController(
  46. AzureCosmosFactory azureCosmos,
  47. AzureStorageFactory azureStorage,
  48. DingDing dingDing,
  49. IOptionsSnapshot<Option> option,IHttpClientFactory httpClientFactory
  50. )
  51. {
  52. _azureCosmos = azureCosmos;
  53. _azureStorage = azureStorage;
  54. _dingDing = dingDing;
  55. _option = option?.Value;
  56. _httpClientFactory = httpClientFactory;
  57. }
  58. /// <summary>
  59. /// 新增 或 修改
  60. /// </summary>
  61. /// <param name="request"></param>
  62. /// <returns></returns>
  63. [ProducesDefaultResponseType]
  64. [HttpPost("statistics")]
  65. #if !DEBUG
  66. [Authorize(Roles = "IES")]
  67. [AuthToken(Roles = "teacher,admin,area")]
  68. #endif
  69. public async Task<IActionResult> Statistics(JsonElement json)
  70. {
  71. json.TryGetProperty("periodId", out JsonElement _periodId);
  72. json.TryGetProperty("periodType", out JsonElement _periodType);
  73. if (!json.TryGetProperty("scope", out JsonElement _scope))
  74. {
  75. return BadRequest();
  76. }
  77. if (!json.TryGetProperty("code", out JsonElement _code))
  78. {
  79. return BadRequest();
  80. }
  81. List<School> schools= new List<School>();
  82. List<Elegant> elegants = new List<Elegant>();
  83. IEnumerable<string> periodIds = new List<string>();
  84. if ($"{_scope}".Equals("area"))
  85. {
  86. string sql = $"select value c from c where c.areaId ='{_code}'";
  87. var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<School>(sql, "Base");
  88. if (result.list.IsNotEmpty())
  89. {
  90. string sqlPeriod = string.Empty;
  91. if (!string.IsNullOrWhiteSpace($"{_periodType}")) {
  92. periodIds = result.list.SelectMany(x => x.period).Where(z => !string.IsNullOrWhiteSpace(z.periodType) && z.periodType.Equals($"{_periodType}")).Select(x => x.id);
  93. if (periodIds!=null && periodIds.Count()>0)
  94. {
  95. sqlPeriod=$" and c.periodId in ({string.Join(",",periodIds.Select(x=>$"'{x}'"))})";
  96. }
  97. }
  98. schools.AddRange(result.list);
  99. string sqlE = $"select value c from c where c.school in ({string.Join(",", result.list.Select(z => $"'{z.id}'"))}) {sqlPeriod} and c.pk='Elegant' and contains(c.code,'Elegant-')";
  100. var resultE = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<Elegant>(sqlE);
  101. if (resultE.list.IsNotEmpty())
  102. {
  103. elegants.AddRange(resultE.list);
  104. }
  105. }
  106. }
  107. else if ($"{_scope}".Equals("school"))
  108. {
  109. string sqlE = $"select value c from c ";
  110. if (!string.IsNullOrWhiteSpace($"{_periodId}"))
  111. {
  112. sqlE=$"{sqlE} where c.periodId='{_periodId}'";
  113. }
  114. else if (!string.IsNullOrWhiteSpace($"{_periodType}"))
  115. {
  116. School school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(_code.GetString(),new PartitionKey("Base"));
  117. var periods= school.period.FindAll(z => !string.IsNullOrWhiteSpace(z.periodType) && z.periodType.Equals($"{_periodType}"));
  118. if (periods.IsNotEmpty()) {
  119. sqlE=$"{sqlE} where c.periodId='{periods.First().id}'";
  120. }
  121. }
  122. var resultE = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<Elegant>(sqlE,$"Elegant-{_code}");
  123. if (resultE.list.IsNotEmpty())
  124. {
  125. elegants.AddRange(resultE.list);
  126. }
  127. }
  128. List<ClassifiedItemSchool > schoolDatas= new List<ClassifiedItemSchool>();
  129. if (schools.IsNotEmpty()) {
  130. foreach (var school in schools) {
  131. if (periodIds.Count()>0) {
  132. bool has = false;
  133. foreach (var period in school.period) {
  134. if (periodIds.Contains(period.id)) {
  135. has=true;
  136. }
  137. }
  138. if (!has) {
  139. continue;
  140. }
  141. }
  142. var esSchool = elegants.FindAll(z => z.school.Equals(school.id));
  143. List<ClassifiedItem> itemschool = ClassifyHierarchy(esSchool);
  144. if (!itemschool.Select(z => z.id).Contains("德育风采"))
  145. {
  146. itemschool.Add(new ClassifiedItem()
  147. {
  148. videoCount = 0,
  149. imageCount = 0,
  150. docCount = 0,
  151. otherCount = 0,
  152. count= 0,
  153. id="德育风采"
  154. });
  155. }
  156. if (!itemschool.Select(z => z.id).Contains("艺术特色"))
  157. {
  158. itemschool.Add(new ClassifiedItem()
  159. {
  160. videoCount = 0,
  161. imageCount = 0,
  162. docCount = 0,
  163. otherCount = 0,
  164. count= 0,
  165. id="艺术特色"
  166. });
  167. }
  168. List<ClassifiedItem> schoolItems= new List<ClassifiedItem>();
  169. foreach (var item in itemschool)
  170. {
  171. if (item.pid== null) {
  172. var es = elegants.FindAll(z => item.sid.Contains(z.id));
  173. if (es.IsNotEmpty())
  174. {
  175. var video = es.SelectMany(z => z.attachments).Where(a => !string.IsNullOrWhiteSpace(a.type) && a.type.Equals("video"));
  176. if (video.Any())
  177. {
  178. item.videoCount = video.Count();
  179. }
  180. var image = es.SelectMany(z => z.attachments).Where(a => !string.IsNullOrWhiteSpace(a.type) &&a.type.Equals("image"));
  181. if (image.Any())
  182. {
  183. item.imageCount = image.Count();
  184. }
  185. var doc = es.SelectMany(z => z.attachments).Where(a => !string.IsNullOrWhiteSpace(a.type) && a.type.Equals("doc"));
  186. if (doc.Any())
  187. {
  188. item.docCount = doc.Count();
  189. }
  190. var other = es.SelectMany(z => z.attachments).Where(a => string.IsNullOrWhiteSpace(a.type) || (!a.type.Equals("doc") && !a.type.Equals("video") && !a.type.Equals("image") && !a.type.Equals("doc")));
  191. if (other.Any())
  192. {
  193. item.otherCount = other.Count();
  194. }
  195. }
  196. schoolItems.Add(item);
  197. }
  198. }
  199. schoolDatas.Add(new ClassifiedItemSchool { id= school.id, name = school.name, picture= school.picture, items =schoolItems });
  200. }
  201. }
  202. List<ClassifiedItem> items = ClassifyHierarchy(elegants);
  203. int videoCount = 0;
  204. int imageCount = 0;
  205. int docCount = 0;
  206. int otherCount = 0;
  207. if (!items.Select(z=>z.id).Contains("德育风采")) {
  208. items.Add(new ClassifiedItem()
  209. {
  210. videoCount = 0,
  211. imageCount = 0,
  212. docCount = 0,
  213. otherCount = 0,
  214. count= 0,
  215. id="德育风采"
  216. });
  217. }
  218. if (!items.Select(z => z.id).Contains("艺术特色"))
  219. {
  220. items.Add(new ClassifiedItem()
  221. {
  222. videoCount = 0,
  223. imageCount = 0,
  224. docCount = 0,
  225. otherCount = 0,
  226. count= 0,
  227. id="艺术特色"
  228. });
  229. }
  230. List<ItemCommentKeyCount> itemKeys = new List<ItemCommentKeyCount>();
  231. foreach (var item in items)
  232. {
  233. var es = elegants.FindAll(z => item.sid.Contains(z.id));
  234. if (es.IsNotEmpty()) {
  235. var video = es.SelectMany(z => z.attachments).Where(a =>!string.IsNullOrWhiteSpace(a.type) && a.type.Equals("video"));
  236. if (video.Any()) {
  237. item.videoCount = video.Count();
  238. }
  239. var image = es.SelectMany(z => z.attachments).Where(a => !string.IsNullOrWhiteSpace(a.type) &&a.type.Equals("image"));
  240. if (image.Any())
  241. {
  242. item.imageCount = image.Count();
  243. }
  244. var doc = es.SelectMany(z => z.attachments).Where(a => !string.IsNullOrWhiteSpace(a.type) && a.type.Equals("doc"));
  245. if (doc.Any())
  246. {
  247. item.docCount = doc.Count();
  248. }
  249. var other = es.SelectMany(z => z.attachments).Where(a => string.IsNullOrWhiteSpace(a.type) || (!a.type.Equals("doc") && !a.type.Equals("video") && !a.type.Equals("image") && !a.type.Equals("doc")));
  250. if (other.Any())
  251. {
  252. item.otherCount = other.Count();
  253. }
  254. }
  255. if (item.pid==null) {
  256. videoCount+=item.videoCount;
  257. imageCount+=item.imageCount;
  258. docCount += item.docCount;
  259. otherCount += item.otherCount;
  260. List<dynamic> comments = new List<dynamic>();
  261. foreach (var e in es)
  262. {
  263. comments.Add(new { comment = $"{e.title},{e.content}" });
  264. }
  265. string rs = string.Empty;
  266. if (comments.IsNotEmpty())
  267. {
  268. rs= comments.ToJsonString();
  269. }
  270. List<CommentKeyCount> keyCounts = new List<CommentKeyCount>();
  271. if (!string.IsNullOrWhiteSpace(rs))
  272. {
  273. var httpClient = _httpClientFactory.CreateClient();
  274. if (!httpClient.DefaultRequestHeaders.Contains("x-functions-key"))
  275. {
  276. httpClient.DefaultRequestHeaders.Add("x-functions-key", "2BcXFR_hvzG1pZjqIkaM7Dx74Hcu6m0PwwOacFpDpq44AzFuHJBRXA==");
  277. }
  278. string paramJson = JsonConvert.SerializeObject(new { rs = $"{rs}", fmt = "0" });
  279. var content = new StringContent(paramJson, Encoding.UTF8, "application/json");
  280. HttpResponseMessage httpResponse = await httpClient.PostAsync("https://malearn.teammodel.cn/api/txtwc", content);
  281. if (httpResponse.IsSuccessStatusCode)
  282. {
  283. string str = await httpResponse.Content.ReadAsStringAsync();
  284. if (str.Contains("freq"))
  285. { keyCounts= str.ToObject<List<CommentKeyCount>>(); }
  286. }
  287. }
  288. itemKeys.Add(new ItemCommentKeyCount { id= item.id, keyCounts=keyCounts});
  289. }
  290. }
  291. /*List<string> clds = elegants.SelectMany(c => c.classes).ToList();
  292. string classSql = $"select c.id, c.name from c where c.pk = 'Class' and c.id in ({string.Join(",", clds.Select(o => $"'{o}'"))})";
  293. List<(string id, string name)> classInfos = new();
  294. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  295. .GetItemQueryStreamIterator(queryText: classSql))
  296. {
  297. using var sc_json = await JsonDocument.ParseAsync(item.ContentStream);
  298. if (sc_json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  299. {
  300. var accounts = sc_json.RootElement.GetProperty("Documents").EnumerateArray();
  301. while (accounts.MoveNext())
  302. {
  303. JsonElement account = accounts.Current;
  304. classInfos.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
  305. }
  306. }
  307. }
  308. var lel = elegants.Select(c => new {
  309. c.title,
  310. c.content,
  311. type = string.Join("-", c.bizType.Select(o => $"'{o}'")),
  312. schoolName = schools.Where(z => z.id.Equals(c.school)).FirstOrDefault().name,
  313. classId = c.classes,
  314. className = c.classes.Count > 0 ? classInfos.Where(z => z.id.Equals(c.classes[0])).FirstOrDefault().name : "",
  315. });*/
  316. return Ok(new {schoolDatas, videoCount, imageCount,otherCount,docCount , itemKeys, items = items.Select(z=>new {z.id ,z.pid,z.count,z.videoCount,z.docCount,z.imageCount,z.otherCount })});
  317. }
  318. private List<ClassifiedItem> ClassifyHierarchy(List<Elegant> inputArray)
  319. {
  320. Dictionary<string, int> hierarchyCount = new Dictionary<string, int>();
  321. List<ClassifiedItem> result = new List<ClassifiedItem>();
  322. foreach (var list in inputArray)
  323. {
  324. if (list.bizType.IsEmpty()) {
  325. list.bizType.Add("德育风采");
  326. }
  327. for (int i = 0; i < list.bizType.Count; i++)
  328. {
  329. string currentId = list.bizType[i];
  330. string parentId = (i > 0) ? list.bizType[i - 1] : null;
  331. string hierarchyKey = $"{currentId}|{parentId}";
  332. if (hierarchyCount.ContainsKey(hierarchyKey))
  333. {
  334. hierarchyCount[hierarchyKey]++;
  335. }
  336. else
  337. {
  338. hierarchyCount[hierarchyKey] = 1;
  339. }
  340. var item = result.Find(item => item.id == currentId && item.pid == parentId);
  341. if (item== null)
  342. {
  343. result.Add(new ClassifiedItem
  344. {
  345. id = currentId,
  346. pid = parentId,
  347. count = 0,
  348. sid= new List<string> {list.id }
  349. });
  350. }
  351. else {
  352. item.sid.Add(list.id);
  353. }
  354. }
  355. }
  356. foreach (var item in result)
  357. {
  358. string hierarchyKey = $"{item.id}|{item.pid}";
  359. item.count = hierarchyCount.ContainsKey(hierarchyKey) ? hierarchyCount[hierarchyKey] : 0;
  360. }
  361. return result;
  362. }
  363. class ItemCommentKeyCount {
  364. public string id { get; set; }
  365. public List<CommentKeyCount> keyCounts { get; set; } = new List<CommentKeyCount>();
  366. }
  367. class CommentKeyCount
  368. {
  369. public int id { get; set; }
  370. public string word { get; set; }
  371. public int freq { get; set; }
  372. }
  373. class ClassifiedItemSchool {
  374. public string id { get; set; }
  375. public string name { get; set; }
  376. public string picture { get; set; }
  377. public List<ClassifiedItem> items { get; set; } = new List<ClassifiedItem>();
  378. }
  379. class ClassifiedItem
  380. {
  381. [System.Text.Json.Serialization.JsonIgnoreAttribute]
  382. public List<string> sid { get; set; } = new List<string>();
  383. public string id { get; set; }
  384. public int count { get; set; }
  385. public string pid { get; set; }
  386. public int videoCount { get; set; }
  387. public int imageCount { get; set; }
  388. public int docCount { get; set; }
  389. public int otherCount { get; set; }
  390. }
  391. /// <summary>
  392. /// 新增 或 修改
  393. /// </summary>
  394. /// <param name="request"></param>
  395. /// <returns></returns>
  396. [ProducesDefaultResponseType]
  397. [HttpPost("upsert")]
  398. [Authorize(Roles = "IES")]
  399. [AuthToken(Roles = "teacher,admin")]
  400. public async Task<IActionResult> Upsert(Elegant request)
  401. {
  402. try
  403. {
  404. var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
  405. //新增
  406. var client = _azureCosmos.GetCosmosClient();
  407. request.school = school;
  408. request.code = $"Elegant-{school}";
  409. request.pk = "Elegant";
  410. request.ttl = -1;
  411. request.scope = "school";
  412. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  413. if (request.autoDelete)
  414. {
  415. int time = (int)(request.endTime - now) / 1000;
  416. if (time > 0)
  417. {
  418. request.ttl = time;
  419. }
  420. }
  421. request.createTime = now;
  422. request.creatorId = userid;
  423. //如果设置的时间是小于当前时间则立即发布
  424. if (request.startTime <= 0)
  425. {
  426. request.startTime = now;
  427. }
  428. if (request.publish == 1)
  429. {
  430. if (request.endTime <= request.startTime)
  431. {
  432. return BadRequest("结束时间必须大于开始时间");
  433. }
  434. }
  435. if (string.IsNullOrEmpty(request.id))
  436. {
  437. request.id = Guid.NewGuid().ToString();
  438. request = await client.GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(request, new PartitionKey($"{request.code}"));
  439. }
  440. else
  441. {
  442. var response = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
  443. if (response.Status == 200)
  444. {
  445. request = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
  446. }
  447. else
  448. {
  449. request = await client.GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(request, new PartitionKey($"{request.code}"));
  450. }
  451. }
  452. return Ok(new { elegant = request });
  453. }
  454. catch (Exception e)
  455. {
  456. await _dingDing.SendBotMsg($"OS,{_option.Location},school/Elegant/upsert()\n{e.Message}\n{e.StackTrace}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  457. return BadRequest(e.StackTrace);
  458. }
  459. }
  460. /// <summary>
  461. ///
  462. /// </summary>
  463. /// <param name="request"></param>
  464. /// <returns></returns>
  465. [ProducesDefaultResponseType]
  466. [HttpPost("find")]
  467. #if !DEBUG
  468. [Authorize(Roles = "IES")]
  469. #endif
  470. [AuthToken(Roles = "teacher,admin,student")]
  471. public async Task<IActionResult> Find(JsonElement request)
  472. {
  473. try
  474. {
  475. var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
  476. //必须有学校或者教师编码
  477. request.TryGetProperty("admin", out JsonElement admin);
  478. string stimestampsql = "";
  479. string etimestampsql = "";
  480. if (!$"{admin}".Equals("1"))
  481. {
  482. var stimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  483. if (request.TryGetProperty("stime", out JsonElement stime))
  484. {
  485. if (long.TryParse($"{stime}", out long data))
  486. {
  487. stimestamp = data;
  488. }
  489. }
  490. stimestampsql = $" and c.startTime <= {stimestamp} ";
  491. //默认当前时间
  492. var etimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  493. if (request.TryGetProperty("etime", out JsonElement etime))
  494. {
  495. if (long.TryParse($"{etime}", out long data))
  496. {
  497. etimestamp = data;
  498. }
  499. }
  500. etimestampsql = $" and c.endTime >= {etimestamp} ";
  501. }
  502. var publishsql = "";
  503. if (request.TryGetProperty("publish", out JsonElement publish))
  504. {
  505. if (!publish.ValueKind.Equals(JsonValueKind.Undefined) && !publish.ValueKind.Equals(JsonValueKind.Null) && publish.ValueKind.Equals(JsonValueKind.Number))
  506. {
  507. publishsql = $" and c.publish={publish} ";
  508. }
  509. }
  510. var creatorIdSql = "";
  511. if (request.TryGetProperty("creatorId", out JsonElement creatorId))
  512. {
  513. if (!publish.ValueKind.Equals(JsonValueKind.Undefined) && !publish.ValueKind.Equals(JsonValueKind.Null) && publish.ValueKind.Equals(JsonValueKind.String))
  514. {
  515. publishsql = $" and c.creatorId='{creatorId}' ";
  516. }
  517. }
  518. var typesql = "";
  519. if (request.TryGetProperty("type", out JsonElement type))
  520. {
  521. if (!type.ValueKind.Equals(JsonValueKind.Undefined) && !type.ValueKind.Equals(JsonValueKind.Null) && type.ValueKind.Equals(JsonValueKind.String))
  522. {
  523. typesql = $" and c.type='{type}' ";
  524. }
  525. }
  526. string joinSqlClasses = "";
  527. string andSqlClasses = "";
  528. if (request.TryGetProperty("classes", out JsonElement _classes))
  529. {
  530. if (_classes.ValueKind is JsonValueKind.Array)
  531. {
  532. List<string> subjects = _classes.ToObject<List<string>>();
  533. if (subjects.IsNotEmpty())
  534. {
  535. joinSqlClasses = " join A2 in c.classes ";
  536. List<string> sqlList = new List<string>();
  537. subjects.ForEach(x => { sqlList.Add($" '{x}' "); });
  538. string sql = string.Join(" , ", sqlList);
  539. andSqlClasses = $" and A2 in ({sql}) ";
  540. }
  541. }
  542. }
  543. List<Elegant> elegants = new List<Elegant>();
  544. var client = _azureCosmos.GetCosmosClient();
  545. var query = $"select distinct value(c) from c {joinSqlClasses} where 1=1 {etimestampsql} {stimestampsql} {publishsql} {typesql} {andSqlClasses} {creatorIdSql} ";
  546. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIterator<Elegant>(queryText: query,
  547. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Elegant-{school}") }))
  548. {
  549. elegants.Add(item);
  550. }
  551. return Ok(new { elegants });
  552. }
  553. catch (Exception ex)
  554. {
  555. await _dingDing.SendBotMsg($"OS,{_option.Location},school/Elegant/find()\n", GroupNames.醍摩豆服務運維群組);
  556. return BadRequest(ex.StackTrace);
  557. }
  558. }
  559. /// <summary>
  560. ///
  561. /// </summary>
  562. /// <param name="request"></param>
  563. /// <returns></returns>
  564. [ProducesDefaultResponseType]
  565. [HttpPost("find-by-student")]
  566. [Authorize(Roles = "IES")]
  567. [AuthToken(Roles = "teacher,admin,student")]
  568. public async Task<IActionResult> FindByStudent(JsonElement request)
  569. {
  570. try
  571. {
  572. var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
  573. var publishsql = $" and c.publish=1 ";
  574. string joinSqlClasses = "";
  575. string andSqlClasses = "";
  576. if (request.TryGetProperty("classes", out JsonElement _classes))
  577. {
  578. if (_classes.ValueKind is JsonValueKind.Array)
  579. {
  580. List<string> subjects = _classes.ToObject<List<string>>();
  581. if (subjects.IsNotEmpty())
  582. {
  583. joinSqlClasses = " join A2 in c.classes ";
  584. List<string> sqlList = new List<string>();
  585. subjects.ForEach(x => { sqlList.Add($" '{x}' "); });
  586. string sql = string.Join(" , ", sqlList);
  587. andSqlClasses = $" and A2 in ({sql}) ";
  588. }
  589. }
  590. }
  591. else
  592. {
  593. return BadRequest();
  594. }
  595. List<Elegant> elegants = new List<Elegant>();
  596. var client = _azureCosmos.GetCosmosClient();
  597. var query = $"select distinct value(c) from c {joinSqlClasses} where 1=1 {publishsql} {andSqlClasses} ";
  598. if (!string.IsNullOrWhiteSpace(school))
  599. {
  600. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIterator<Elegant>(queryText: query,
  601. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Elegant-{school}") }))
  602. {
  603. elegants.Add(item);
  604. }
  605. }
  606. return Ok(new { elegants });
  607. }
  608. catch (Exception ex)
  609. {
  610. await _dingDing.SendBotMsg($"OS,{_option.Location},school/Elegant/find()\n", GroupNames.醍摩豆服務運維群組);
  611. return BadRequest(ex.StackTrace);
  612. }
  613. }
  614. /// <summary>
  615. /// 删除
  616. /// </summary>
  617. /// <param name="request"></param>
  618. /// <returns></returns>
  619. [ProducesDefaultResponseType]
  620. [HttpPost("delete")]
  621. [Authorize(Roles = "IES")]
  622. [AuthToken(Roles = "admin",Permissions = "teacher-upd")]
  623. public async Task<IActionResult> Delete(JsonElement request)
  624. {
  625. try
  626. {
  627. var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
  628. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  629. var client = _azureCosmos.GetCosmosClient();
  630. await client.GetContainer(Constant.TEAMModelOS, Constant.School).DeleteItemStreamAsync(id.GetString(), new PartitionKey($"Elegant-{school}"));
  631. return Ok(new { status = 200 });
  632. }
  633. catch (Exception e)
  634. {
  635. return BadRequest(e.StackTrace);
  636. }
  637. }
  638. }
  639. }