LessonRecordController.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. using Microsoft.Azure.Cosmos;
  2. using Azure.Messaging.ServiceBus;
  3. using Microsoft.AspNetCore.Authorization;
  4. using Microsoft.AspNetCore.Cors;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.AspNetCore.Mvc;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.Options;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Text;
  14. using System.Text.Json;
  15. using System.Text.Json.Nodes;
  16. using System.Threading.Tasks;
  17. using TEAMModelOS.Filter;
  18. using TEAMModelOS.Models;
  19. using TEAMModelOS.SDK;
  20. using TEAMModelOS.SDK.DI;
  21. using TEAMModelOS.SDK.Extension;
  22. using TEAMModelOS.SDK.Models;
  23. using TEAMModelOS.SDK.Models.Cosmos.OpenEntity;
  24. using TEAMModelOS.SDK.Models.Service;
  25. namespace TEAMModelOS.Controllers
  26. {
  27. /// <summary>
  28. /// 课堂记录
  29. /// </summary>
  30. [ProducesResponseType(StatusCodes.Status200OK)]
  31. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  32. [Route("common/lesson-record")]
  33. [ApiController]
  34. public class LessonRecordController : ControllerBase
  35. {
  36. private readonly AzureCosmosFactory _azureCosmos;
  37. private readonly SnowflakeId _snowflakeId;
  38. private readonly AzureServiceBusFactory _serviceBus;
  39. private readonly DingDing _dingDing;
  40. private readonly Option _option;
  41. private readonly AzureStorageFactory _azureStorage;
  42. private readonly AzureRedisFactory _azureRedis;
  43. public IConfiguration _configuration { get; set; }
  44. public LessonRecordController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
  45. IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration)
  46. {
  47. _azureCosmos = azureCosmos;
  48. _serviceBus = serviceBus;
  49. _snowflakeId = snowflakeId;
  50. _dingDing = dingDing;
  51. _option = option?.Value;
  52. _azureStorage = azureStorage;
  53. _azureRedis = azureRedis;
  54. _configuration = configuration;
  55. }
  56. /// <summary>
  57. /// 更新课堂记录
  58. /// </summary>
  59. /// <param name="request"></param>
  60. /// <returns></returns>
  61. [ProducesDefaultResponseType]
  62. [HttpPost("update-lesson-baseinfo")]
  63. #if !DEBUG
  64. [AuthToken(Roles = "teacher,admin")]
  65. [Authorize(Roles = "IES")]
  66. #endif
  67. public async Task<IActionResult> UpdateLessonBaseInfo(JsonElement request)
  68. {
  69. var client = _azureCosmos.GetCosmosClient();
  70. if (!request.TryGetProperty("lesson_id", out JsonElement _lessonId)) return BadRequest();
  71. if (!request.TryGetProperty("tmdid", out JsonElement _tmdid)) return BadRequest();
  72. request.TryGetProperty("school", out JsonElement _school);
  73. if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
  74. if (!request.TryGetProperty("grant_types", out JsonElement _grant_types)) return BadRequest();
  75. string tbname ;
  76. string code ;
  77. if (_scope.GetString().Equals("school") && !string.IsNullOrWhiteSpace(_school.GetString()))
  78. {
  79. code = $"LessonRecord-{_school}";
  80. tbname = "School";
  81. }
  82. else if ($"{_scope}".Equals("private"))
  83. {
  84. code = $"LessonRecord";
  85. tbname = "Teacher";
  86. }
  87. else
  88. {
  89. return BadRequest();
  90. }
  91. try
  92. {
  93. Dictionary<string, object> dict = new Dictionary<string, object>();
  94. if (_grant_types.ValueKind.Equals(JsonValueKind.Array)) {
  95. LessonRecord lessonRecord = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<LessonRecord>($"{_lessonId}", new PartitionKey(code));
  96. List<LessonUpdate> updates = _grant_types.ToObject<List<LessonUpdate>>();
  97. foreach (var item in updates) {
  98. if (item.grant_type.Equals("up-baseinfo")) {
  99. JsonElement element = item.data.ToJsonString().ToObject<JsonElement>();
  100. element.TryGetProperty("name", out JsonElement _name);
  101. element.TryGetProperty("subjectId", out JsonElement _subjectId);
  102. element.TryGetProperty("grade", out JsonElement _grade);
  103. element.TryGetProperty("category", out JsonElement _category);
  104. element.TryGetProperty("show", out JsonElement _show);
  105. if (_name.ValueKind.Equals(JsonValueKind.String) && !string.IsNullOrWhiteSpace($"{_name}"))
  106. {
  107. lessonRecord.name = $"{_name}";
  108. }
  109. if (_subjectId.ValueKind.Equals(JsonValueKind.String) && !string.IsNullOrWhiteSpace($"{_subjectId}"))
  110. {
  111. lessonRecord.subjectId = $"{_subjectId}";
  112. }
  113. if (_grade.ValueKind.Equals(JsonValueKind.Array))
  114. {
  115. lessonRecord.grade = _grade.ToObject<List<string>>();
  116. }
  117. if (_category.ValueKind.Equals(JsonValueKind.Array))
  118. {
  119. lessonRecord.category = _category.ToObject<List<string>>();
  120. }
  121. if (_show.ValueKind.Equals(JsonValueKind.Array))
  122. {
  123. lessonRecord.show = _show.ToObject<List<string>>();
  124. }
  125. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, $"{_lessonId}", new PartitionKey(code));
  126. dict["up-baseinfo"] = new { status= 1 ,code="ok"};
  127. }
  128. if (item.grant_type.Equals("up-expire")) {
  129. if (_scope.GetString().Equals("private"))
  130. {
  131. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{_tmdid}", new PartitionKey("Base"));
  132. HashSet<string> ids = new HashSet<string>();
  133. //未定义的 以及过期时间小于等于0 的 课例
  134. string private_count_sql = $"select value(c.id) from c where ( c.expire<=0 or IS_DEFINED(c.expire) = false ) and c.tmdid='{_tmdid}' ";
  135. await foreach (var lid in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<string>(
  136. queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
  137. {
  138. ids.Add(lid);
  139. }
  140. //包含收藏的本人的个人课例
  141. string favorite_count_sql = $"select value(c.id) from c where c.type='LessonRecord' and c.owner='{_tmdid}' and c.scope='private' ";
  142. await foreach (var lid in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<string>(
  143. queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{_tmdid}") }))
  144. {
  145. ids.Add(lid);
  146. }
  147. //教师个人预设的,可以通过设置的方式增加
  148. int limit = teacher.lessonLimit;
  149. if (teacher.lessonLimit == 0)
  150. {
  151. //未设置的的采用系统设置的默认值50
  152. limit = Constant.private_lesson_limit;
  153. }
  154. if (ids.Count < limit)
  155. {
  156. lessonRecord.expire = -1;
  157. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, $"{_lessonId}", new PartitionKey(code));
  158. dict["up-expire"] = new { status = 1, code = "ok" };
  159. }
  160. else
  161. {
  162. dict["up-expire"] = new { status = 0, code = "lessonLimit", data = limit };
  163. }
  164. }
  165. else if (_scope.GetString().Equals("school")) {
  166. lessonRecord.expire = -1;
  167. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, $"{_lessonId}", new PartitionKey(code));
  168. dict["up-expire"] = new { status = 1, code = "ok" };
  169. }
  170. }
  171. }
  172. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  173. var messageChange = new ServiceBusMessage(request.ToJsonString());
  174. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  175. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  176. return Ok(new { status = 200,updateInfo= dict });
  177. }
  178. return BadRequest();
  179. }
  180. catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
  181. {
  182. return BadRequest("课堂记录不存在");
  183. }
  184. catch (Exception ex)
  185. {
  186. return BadRequest();
  187. }
  188. }
  189. /*
  190. {
  191. "scope":"school/private",
  192. "tmdid":"1595321354",
  193. "delete_id":"asdeeeqq-adfghnlr-pfkcmsss-ssadffgtre",
  194. "opt":"delete",
  195. "school":"hbcn" //如果scope=school 这 school字段必须有值
  196. }
  197. */
  198. /// <summary>
  199. /// 删除课堂记录
  200. /// </summary>
  201. /// <param name="request"></param>
  202. /// <returns></returns>
  203. [ProducesDefaultResponseType]
  204. // [AuthToken(Roles = "teacher,admin")]
  205. [HttpPost("delete-lesson-record")]
  206. [Authorize(Roles = "IES")]
  207. [AuthToken(Roles = "admin,teacher")]
  208. public async Task<IActionResult> DeleteLessonRecord(JsonElement request)
  209. {
  210. string school;
  211. string tbname;
  212. string code;
  213. if (request.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
  214. // && request.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
  215. && request.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
  216. && request.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
  217. {
  218. request.TryGetProperty("school", out JsonElement _dschool);
  219. school = $"{_dschool}";
  220. var client = _azureCosmos.GetCosmosClient();
  221. if ($"{_opt}".Equals("delete"))
  222. {
  223. if ($"{_dscope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
  224. {
  225. code = $"LessonRecord-{school}";
  226. tbname = "School";
  227. }
  228. else if ($"{_dscope}".Equals("private"))
  229. {
  230. code = $"LessonRecord";
  231. tbname = "Teacher";
  232. }
  233. else
  234. {
  235. return BadRequest() ;
  236. }
  237. List<string> lessonIds = new List<string>();
  238. //string lessonId = $"{_delete_id}";
  239. if (_delete_id.ValueKind.Equals(JsonValueKind.Array))
  240. {
  241. lessonIds.AddRange(_delete_id.ToObject<List<string>>());
  242. }
  243. else {
  244. lessonIds.Add($"{_delete_id}");
  245. }
  246. if (lessonIds.IsNotEmpty())
  247. {
  248. foreach (var lessonId in lessonIds) {
  249. ResponseMessage response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
  250. if (response.StatusCode==System.Net.HttpStatusCode.OK)
  251. {
  252. LessonRecord lessonRecord;
  253. var doc = JsonDocument.Parse(response.Content);
  254. lessonRecord = doc.RootElement.ToObject<LessonRecord>();
  255. lessonRecord.status = 404;
  256. await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
  257. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  258. var messageChange = new ServiceBusMessage(request.ToJsonString());
  259. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  260. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  261. }
  262. }
  263. return Ok(new { status = 200 });
  264. }
  265. else { return BadRequest(); }
  266. }
  267. else { return BadRequest() ; }
  268. }
  269. else
  270. {
  271. return BadRequest();
  272. }
  273. }
  274. /// <summary>
  275. /// 获取开课记录 (c.status<>404 or IS_DEFINED(c.status)=false )
  276. /// </summary>
  277. /// <param name="request"></param>
  278. /// <returns></returns>
  279. [ProducesDefaultResponseType]
  280. //[AuthToken(Roles = "teacher,admin")]
  281. [HttpPost("get-lesson-record-count")]
  282. [Authorize(Roles = "IES")]
  283. [AuthToken(Roles = "admin,teacher,student")]
  284. public async Task<IActionResult> GetLessonRecordCont(JsonElement request)
  285. {
  286. object _roles = null;
  287. HttpContext?.Items.TryGetValue("Roles", out _roles);
  288. List<string> roles = new List<string>();
  289. if (_roles != null)
  290. {
  291. roles = _roles.ToJsonString().ToObject<List<string>>();
  292. }
  293. if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
  294. request.TryGetProperty("managePage", out JsonElement _managePage);
  295. bool managePage = false;
  296. if (_managePage.ValueKind.Equals(JsonValueKind.True)) {
  297. managePage = true;
  298. }
  299. StringBuilder sql = new StringBuilder();
  300. sql.Append("select c.id,c.groupIds,c.courseId from c ");
  301. Dictionary<string ,object> dict = LessonService.GetLessonCond(request);
  302. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  303. string tbname = "";
  304. string code = "";
  305. string school = null;
  306. List<string> autoTch = new List<string>();
  307. string sqlPrivate = "";
  308. if (_scope.GetString().Equals("school"))
  309. {
  310. if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
  311. if (!string.IsNullOrEmpty($"{_school}"))
  312. {
  313. school = $"{_school}";
  314. code = $"LessonRecord-{_school}";
  315. tbname = "School";
  316. List<string> ids = new List<string>();
  317. //只查询某个老师的课例
  318. if (request.TryGetProperty("tmdid", out JsonElement tmdid) && !string.IsNullOrWhiteSpace($"{tmdid}"))
  319. {
  320. ids.Add($"{tmdid}");
  321. }
  322. else
  323. {
  324. string sqltch = "select distinct value(c.id) from c ";
  325. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  326. .GetItemQueryIteratorSql<string>(queryText: sqltch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{_school}") }))
  327. {
  328. ids.Add(item);
  329. }
  330. }
  331. if (ids.Any())
  332. {
  333. string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
  334. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  335. .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  336. {
  337. autoTch.Add(item);
  338. }
  339. }
  340. }
  341. else {
  342. return BadRequest();
  343. }
  344. }
  345. else if ($"{_scope}".Equals("private"))
  346. {
  347. code = $"LessonRecord";
  348. tbname = "Teacher";
  349. request.TryGetProperty("tmdid", out JsonElement _tmdid);
  350. if (!string.IsNullOrEmpty($"{_tmdid}"))
  351. {
  352. sqlPrivate = $" and c.tmdid='{_tmdid}'";
  353. List<string> ids = new List<string>();
  354. ids.Add($"{_tmdid}");
  355. if (ids.Any())
  356. {
  357. string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
  358. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  359. .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  360. {
  361. autoTch.Add(item);
  362. }
  363. }
  364. }
  365. else
  366. {
  367. //如果不传tmdid, 则必须传递,课程id或者名单列表
  368. // 如果不传递tmdid
  369. if (!request.TryGetProperty("groupIds", out JsonElement groupIds))
  370. {
  371. return BadRequest("个人课例不传醍摩豆id则必传 groupIds");
  372. }
  373. }
  374. }
  375. else
  376. {
  377. return BadRequest();
  378. }
  379. int count=0;
  380. string sqlShow = "";
  381. if (roles.Count == 1 && roles.Contains("student"))
  382. {
  383. string autoSql = "";
  384. if (autoTch.Any())
  385. {
  386. autoSql = $" or c.tmdid in ({string.Join(",", autoTch.Select(x => $"'{x}'"))})";
  387. }
  388. sqlShow = $" and (array_contains(c.show,'student') or array_contains(c.show,'all') {autoSql} ) ";
  389. }
  390. long now = DateTimeOffset.Now.ToUnixTimeMilliseconds();
  391. string sql_status_managePage = " (c.status<>404 or IS_DEFINED(c.status) = false ) and ";
  392. if (managePage) {
  393. sql_status_managePage = "";
  394. }
  395. cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where {sql_status_managePage} array_length(c.groupIds)>0 {sqlPrivate} {sqlShow} and ");
  396. if (request.TryGetProperty("singleGreen", out JsonElement doubleGreen) && doubleGreen.GetBoolean())
  397. {
  398. cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where ((c.tLevel=2 and c.pLevel<2 )or(c.tLevel<2 and c.pLevel=2 )) and ");
  399. }
  400. if (request.TryGetProperty("expire", out JsonElement expire) && expire.ValueKind.Equals(JsonValueKind.True))
  401. {
  402. cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where c.expire>{now} and ");
  403. }
  404. List<LessonRecord> records = new List<LessonRecord>();
  405. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIteratorQuery<LessonRecord>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
  406. {
  407. records.Add(item);
  408. }
  409. if (records.Any()) {
  410. var groupIds= records.SelectMany(x => x.groupIds).ToHashSet();
  411. if (groupIds.Any()) {
  412. var groups = await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToList(), school," c.id ");
  413. //获取已经被删除的名单。
  414. var idsExp = groupIds.Except(groups.Select(x => x.id));
  415. if (idsExp.Any()) {
  416. foreach(var item in records)
  417. {
  418. int countRmv = item.groupIds.RemoveAll(x => idsExp.Contains(x));
  419. if (countRmv > 0)
  420. {
  421. try {
  422. LessonRecord record = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<LessonRecord>(item.id, new PartitionKey(code));
  423. record.groupIds = item.groupIds;
  424. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(record, item.id, new PartitionKey(code));
  425. } catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound) {
  426. continue;
  427. }
  428. }
  429. }
  430. }
  431. }
  432. }
  433. count = records.Count;
  434. return Ok(new { count=count, records });
  435. }
  436. /// <summary>
  437. /// 获取开课记录
  438. /// </summary>
  439. /// <param name="request"></param>
  440. /// <returns></returns>
  441. [ProducesDefaultResponseType]
  442. // [AuthToken(Roles = "teacher,admin")]
  443. [HttpPost("get-lesson-record-schorpvt")]
  444. [Authorize(Roles = "IES")]
  445. [AuthToken(Roles = "admin,teacher,student")]
  446. public async Task<IActionResult> GetLessonRecordSchOrPvt(JsonElement request) {
  447. object _roles = null;
  448. HttpContext?.Items.TryGetValue("Roles", out _roles);
  449. List<string> roles = new List<string>();
  450. if (_roles != null)
  451. {
  452. roles = _roles.ToJsonString().ToObject<List<string>>();
  453. }
  454. StringBuilder sql = new StringBuilder();
  455. sql.Append("select value(c) from c ");
  456. Dictionary<string, object> dict = LessonService.GetLessonCond(request);
  457. if (request.TryGetProperty("DESC", out JsonElement desc))
  458. {
  459. dict.Add("@DESC", desc.ToString());
  460. }
  461. if (request.TryGetProperty("ASC", out JsonElement asc))
  462. {
  463. dict.Add("@ASC", asc.ToString());
  464. }
  465. string school = null;
  466. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  467. List<LessonRecord> lessonRecords = new List<LessonRecord>();
  468. //获取学校的
  469. {
  470. string tbname = "School";
  471. string code = "";
  472. string sqlPrivate = "";
  473. List<string> autoTch = new List<string>();
  474. request.TryGetProperty("school", out JsonElement _school);
  475. if (!string.IsNullOrEmpty($"{_school}"))
  476. {
  477. code = $"LessonRecord-{_school}";
  478. tbname = "School";
  479. school = $"{_school}";
  480. List<string> ids = new List<string>();
  481. //只查询某个老师的课例
  482. if (request.TryGetProperty("tmdid", out JsonElement tmdid) && !string.IsNullOrWhiteSpace($"{tmdid}"))
  483. {
  484. ids.Add($"{tmdid}");
  485. }
  486. else
  487. {
  488. string sqltch = "select distinct value(c.id) from c ";
  489. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  490. .GetItemQueryIteratorSql<string>(queryText: sqltch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{_school}") }))
  491. {
  492. ids.Add(item);
  493. }
  494. }
  495. if (ids.Any())
  496. {
  497. string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
  498. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  499. .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  500. {
  501. autoTch.Add(item);
  502. }
  503. }
  504. string sqlShow = "";
  505. if (roles.Count == 1 && roles.Contains("student"))
  506. {
  507. string autoSql = "";
  508. if (autoTch.Any())
  509. {
  510. autoSql = $" or c.tmdid in ({string.Join(",", autoTch.Select(x => $"'{x}'"))})";
  511. }
  512. sqlShow = $" and (array_contains(c.show,'student') or array_contains(c.show,'all') {autoSql} ) ";
  513. }
  514. cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where (c.status<>404 or IS_DEFINED(c.status) = false ) and array_length(c.groupIds)>0 {sqlPrivate} {sqlShow} and ");
  515. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname)
  516. .GetItemQueryStreamIteratorQuery(queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
  517. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
  518. {
  519. using var json = await JsonDocument.ParseAsync(item.Content);
  520. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  521. {
  522. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  523. {
  524. lessonRecords.Add(obj.ToObject<LessonRecord>());
  525. }
  526. break;
  527. }
  528. }
  529. }
  530. }
  531. //获取个人的
  532. {
  533. string code = $"LessonRecord";
  534. string tbname = "Teacher";
  535. List<string> autoTch = new List<string>();
  536. request.TryGetProperty("tmdid", out JsonElement _tmdid);
  537. if (!string.IsNullOrEmpty($"{_tmdid}"))
  538. {
  539. string sqlPrivate = $" and c.tmdid='{_tmdid}'";
  540. List<string> ids = new List<string>();
  541. ids.Add($"{_tmdid}");
  542. if (ids.Any())
  543. {
  544. string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
  545. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  546. .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  547. {
  548. autoTch.Add(item);
  549. }
  550. }
  551. string sqlShow = "";
  552. if (roles.Count == 1 && roles.Contains("student"))
  553. {
  554. string autoSql = "";
  555. if (autoTch.Any())
  556. {
  557. autoSql = $" or c.tmdid in ({string.Join(",", autoTch.Select(x => $"'{x}'"))})";
  558. }
  559. sqlShow = $" and (array_contains(c.show,'student') or array_contains(c.show,'all') {autoSql} ) ";
  560. }
  561. cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where (c.status<>404 or IS_DEFINED(c.status) = false ) and array_length(c.groupIds)>0 {sqlPrivate} {sqlShow} and ");
  562. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname)
  563. .GetItemQueryStreamIteratorQuery(queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
  564. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
  565. {
  566. using var json = await JsonDocument.ParseAsync(item.Content);
  567. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  568. {
  569. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  570. {
  571. lessonRecords.Add(obj.ToObject<LessonRecord>());
  572. }
  573. break;
  574. }
  575. }
  576. }
  577. }
  578. var tmdids = lessonRecords.Select(x => x.tmdid).ToHashSet();
  579. if (tmdids != null && tmdids.Count > 0)
  580. {
  581. List<IdNameCode> codes = new List<IdNameCode>();
  582. string sqltmd = $"select c.id,c.name,c.picture from c where c.id in ({string.Join(",", tmdids.Select(x => $"'{x}'"))})";
  583. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<IdNameCode>(queryText: sqltmd, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  584. {
  585. codes.Add(item);
  586. }
  587. if (codes.IsNotEmpty())
  588. {
  589. lessonRecords.ForEach(x => {
  590. var tmd = codes.Find(z => z.id.Equals(x.tmdid));
  591. if (tmd != null)
  592. {
  593. x.tmdname = tmd.name;
  594. x.tmdpicture = tmd.picture;
  595. }
  596. });
  597. }
  598. }
  599. var groupIds = lessonRecords.SelectMany(x => x.groupIds);
  600. if (groupIds.Any())
  601. {
  602. List<GroupListDto> groupLists = await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToList(), school);
  603. lessonRecords.ForEach(x => {
  604. List<string> groupNmae = new List<string>();
  605. x.groupIds.ForEach(y => {
  606. var dto = groupLists.Find(z => z.id.Equals(y));
  607. string name = dto != null ? dto.name : "-";
  608. groupNmae.Add(name);
  609. });
  610. x.groupNames = groupNmae;
  611. });
  612. }
  613. if(request.TryGetProperty("top", out JsonElement _top) && lessonRecords.Any())
  614. {
  615. var rcords= lessonRecords.OrderByDescending(x => x.startTime).Take(int.Parse($"{_top}"));
  616. return Ok(new { currCount =rcords.Count(), lessonRecords =rcords});
  617. }
  618. return Ok(new { currCount = lessonRecords.Count, lessonRecords });
  619. }
  620. /// <summary>
  621. /// 获取开课记录
  622. /// </summary>
  623. /// <param name="request"></param>
  624. /// <returns></returns>
  625. [ProducesDefaultResponseType]
  626. // [AuthToken(Roles = "teacher,admin")]
  627. [HttpPost("get-lesson-record")]
  628. [Authorize(Roles = "IES")]
  629. [AuthToken(Roles ="admin,teacher,student")]
  630. public async Task<IActionResult> GetLessonRecord(JsonElement request)
  631. {
  632. object _roles = null;
  633. HttpContext?.Items.TryGetValue("Roles", out _roles);
  634. List<string> roles = new List<string>();
  635. if (_roles != null) {
  636. roles = _roles.ToJsonString().ToObject<List<string>>();
  637. }
  638. if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
  639. request.TryGetProperty("managePage", out JsonElement _managePage);
  640. bool managePage = false;
  641. if (_managePage.ValueKind.Equals(JsonValueKind.True))
  642. {
  643. managePage = true;
  644. }
  645. StringBuilder sql = new StringBuilder();
  646. sql.Append("select value(c) from c ");
  647. int pageCount = 10;
  648. Dictionary<string, object> dict = LessonService.GetLessonCond(request);
  649. if (request.TryGetProperty("pageCount", out JsonElement _pageCount))
  650. {
  651. int.TryParse($"{_pageCount}", out int pcount);
  652. if (pcount > 0)
  653. {
  654. pageCount = pcount;
  655. }
  656. }
  657. if (request.TryGetProperty("DESC", out JsonElement desc))
  658. {
  659. dict.Add("@DESC", desc.ToString());
  660. }
  661. if (request.TryGetProperty("ASC", out JsonElement asc))
  662. {
  663. dict.Add("@ASC", asc.ToString());
  664. }
  665. string continuationToken = null;
  666. if (request.TryGetProperty("continuationToken", out JsonElement _continuationToken))
  667. {
  668. if (!string.IsNullOrEmpty($"{_continuationToken}"))
  669. {
  670. continuationToken = $"{_continuationToken}";
  671. }
  672. }
  673. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  674. string tbname = "";
  675. string code = "";
  676. string school = null;
  677. string sqlPrivate = "";
  678. List<string> autoTch = new List<string>();
  679. if (_scope.GetString().Equals("school"))
  680. {
  681. if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
  682. if (!string.IsNullOrEmpty($"{_school}"))
  683. {
  684. code = $"LessonRecord-{_school}";
  685. tbname = "School";
  686. school = $"{_school}";
  687. List<string> ids = new List<string>();
  688. //只查询某个老师的课例
  689. if (request.TryGetProperty("tmdid", out JsonElement tmdid) && !string.IsNullOrWhiteSpace($"{tmdid}"))
  690. {
  691. ids.Add($"{tmdid}");
  692. }
  693. else {
  694. string sqltch = "select distinct value(c.id) from c ";
  695. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  696. .GetItemQueryIteratorSql<string>(queryText: sqltch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{_school}") }))
  697. {
  698. ids.Add(item);
  699. }
  700. }
  701. if (ids.Any()) {
  702. string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
  703. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  704. .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  705. {
  706. autoTch.Add(item);
  707. }
  708. }
  709. }
  710. else
  711. {
  712. return BadRequest();
  713. }
  714. }
  715. else if ($"{_scope}".Equals("private"))
  716. {
  717. code = $"LessonRecord";
  718. tbname = "Teacher";
  719. request.TryGetProperty("tmdid", out JsonElement _tmdid);
  720. if (!string.IsNullOrEmpty($"{_tmdid}"))
  721. {
  722. sqlPrivate = $" and c.tmdid='{_tmdid}'";
  723. List<string> ids = new List<string>();
  724. ids.Add($"{_tmdid}");
  725. if (ids.Any())
  726. {
  727. string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
  728. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  729. .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  730. {
  731. autoTch.Add(item);
  732. }
  733. }
  734. }
  735. else
  736. {
  737. //如果不传tmdid, 则必须传递,课程id或者名单列表
  738. // 如果不传递tmdid
  739. if (!request.TryGetProperty("groupIds", out JsonElement groupIds)) {
  740. return BadRequest("个人课例不传醍摩豆id则必传 groupIds");
  741. }
  742. }
  743. }
  744. else
  745. {
  746. return BadRequest();
  747. }
  748. List<LessonRecord> lessonRecords = new List<LessonRecord>();
  749. try
  750. {
  751. string sqlShow = "";
  752. if (roles.Count == 1 && roles.Contains("student"))
  753. {
  754. string autoSql = "";
  755. if (autoTch.Any()) {
  756. autoSql = $" or c.tmdid in ({string.Join(",",autoTch.Select(x=>$"'{x}'"))})";
  757. }
  758. sqlShow = $" and (array_contains(c.show,'student') or array_contains(c.show,'all') {autoSql} ) ";
  759. }
  760. string sql_status_managePage = "(c.status<>404 or IS_DEFINED(c.status) = false ) and ";
  761. if (managePage)
  762. {
  763. sql_status_managePage = "";
  764. }
  765. cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where {sql_status_managePage} array_length(c.groupIds)>0 {sqlPrivate} {sqlShow} and ");
  766. if (request.TryGetProperty("singleGreen", out JsonElement doubleGreen) && doubleGreen.GetBoolean())
  767. {
  768. cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where ((c.tLevel=2 and c.pLevel<2 )or(c.tLevel<2 and c.pLevel=2 )) and ");
  769. }
  770. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname)
  771. .GetItemQueryStreamIteratorQuery(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, continuationToken: continuationToken,
  772. requestOptions: new QueryRequestOptions() { MaxItemCount = pageCount, PartitionKey = new PartitionKey(code) }))
  773. {
  774. using var json = await JsonDocument.ParseAsync(item.Content);
  775. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  776. {
  777. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  778. {
  779. var rcd = obj.ToObject<LessonRecord>();
  780. if (rcd.hitaClientCmpCount <= 0 && rcd.collateTaskCount > 0) {
  781. rcd.hitaClientCmpCount= rcd.collateTaskCount;
  782. }
  783. if (rcd.learningCategory == null)
  784. {
  785. rcd.learningCategory = new LearningCategory();
  786. }
  787. if (rcd.hitaClientCmpCount > 0)
  788. {
  789. rcd.learningCategory.cooperation = 1;
  790. }
  791. lessonRecords.Add(rcd);
  792. }
  793. continuationToken = item.ContinuationToken;
  794. break;
  795. }
  796. }
  797. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  798. //查询时处理已经过期的课例。防止ServiceBus未触发的。
  799. var expireRecords= lessonRecords.Where(x=> x.expire > 0 && now > x.expire);
  800. try {
  801. foreach (var item in expireRecords)
  802. {
  803. //item.status = 404;
  804. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  805. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  806. var messageChange = new ServiceBusMessage(new { delete_id = item.id, tmdid = item.tmdid, scope = item.scope, opt = "delete", school = item.school }.ToJsonString());
  807. messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  808. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  809. }
  810. } catch (Exception ex) {
  811. await _dingDing.SendBotMsg($"{_option.Location},ServiceBus ,LessonRecordEvent 发送消息失败,检查是否配置正常。", GroupNames.成都开发測試群組);
  812. }
  813. var tmdids = lessonRecords.Select(x => x.tmdid).ToHashSet();
  814. if (tmdids != null && tmdids.Count > 0)
  815. {
  816. List<IdNameCode> codes = new List<IdNameCode>();
  817. string sqltmd = $"select c.id,c.name,c.picture from c where c.id in ({string.Join(",", tmdids.Select(x => $"'{x}'"))})";
  818. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<IdNameCode>(queryText: sqltmd, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  819. {
  820. codes.Add(item);
  821. }
  822. if (codes.IsNotEmpty())
  823. {
  824. lessonRecords.ForEach(x => {
  825. var tmd = codes.Find(z => z.id.Equals(x.tmdid));
  826. if (tmd != null)
  827. {
  828. x.tmdname = tmd.name;
  829. x.tmdpicture = tmd.picture;
  830. }
  831. });
  832. }
  833. }
  834. var groupIds = lessonRecords.SelectMany(x => x.groupIds);
  835. if (groupIds.Any()) {
  836. List<GroupListDto> groupLists= await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToList(), school);
  837. lessonRecords.ForEach(x => {
  838. List<string> groupNmae = new List<string>();
  839. x.groupIds.ForEach(y => {
  840. var dto= groupLists.Find(z => z.id.Equals(y));
  841. string name = dto != null ? dto.name : "-";
  842. groupNmae.Add(name);
  843. });
  844. x.groupNames = groupNmae;
  845. });
  846. }
  847. //已经过期的处理掉垃圾数据
  848. List<LessonRecord> lessonRecords404 = new List<LessonRecord>();
  849. foreach (var item in lessonRecords)
  850. {
  851. if (item.scope.Equals("school"))
  852. {
  853. if (item.expire>0 && item.expire<now && item.status!=404)
  854. {
  855. item.status=404;
  856. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, item.school, new List<string> { $"records/{item.id}" });
  857. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(item.id, new PartitionKey($"Bloblog-{item.school}"));
  858. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  859. lessonRecords404.Add(item);
  860. }
  861. }
  862. }
  863. if (lessonRecords404.IsNotEmpty()) {
  864. foreach (var item in lessonRecords404) {
  865. lessonRecords.Remove(item);
  866. }
  867. }
  868. return Ok(new { currCount = lessonRecords.Count, continuationToken, lessonRecords });
  869. }
  870. catch (Exception )
  871. {
  872. continuationToken = null;
  873. return Ok(new { currCount = 0, continuationToken = continuationToken, lessonRecords });
  874. }
  875. }
  876. /// <summary>
  877. /// 获取开课记录
  878. /// </summary>
  879. /// <param name="request"></param>
  880. /// <returns></returns>
  881. [ProducesDefaultResponseType]
  882. // [AuthToken(Roles = "teacher,admin")]
  883. [HttpPost("get-lesson-record-id")]
  884. [Authorize(Roles = "IES")]
  885. [AuthToken(Roles = "admin,teacher,student")]
  886. public async Task<IActionResult> GetLessonRecordId(JsonElement request)
  887. {
  888. if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
  889. if (!request.TryGetProperty("id", out JsonElement _id)) return BadRequest();
  890. string tbname = "";
  891. string code = "";
  892. if (_scope.GetString().Equals("school"))
  893. {
  894. if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
  895. if (!string.IsNullOrEmpty($"{_school}"))
  896. {
  897. code = $"LessonRecord-{_school}";
  898. tbname = "School";
  899. }
  900. else
  901. {
  902. return BadRequest();
  903. }
  904. }
  905. else if ($"{_scope}".Equals("private"))
  906. {
  907. if (!request.TryGetProperty("tmdid", out JsonElement _tmdid)) return BadRequest();
  908. if (!string.IsNullOrEmpty($"{_tmdid}"))
  909. {
  910. code = $"LessonRecord";
  911. tbname = "Teacher";
  912. }
  913. else
  914. {
  915. return BadRequest();
  916. }
  917. }
  918. else
  919. {
  920. return BadRequest();
  921. }
  922. try
  923. {
  924. LessonRecord lessonRecord = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<LessonRecord>($"{_id}", new PartitionKey(code));
  925. return Ok(new { lessonRecord });
  926. }
  927. catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
  928. {
  929. return Ok(new { status = 404 });
  930. }
  931. }
  932. /// <summary>
  933. /// 获取开课记录
  934. /// </summary>
  935. /// <param name="request"></param>
  936. /// <returns></returns>
  937. [ProducesDefaultResponseType]
  938. // [AuthToken(Roles = "teacher,admin")]
  939. [HttpPost("get-other-lesson-record")]
  940. [Authorize(Roles = "IES")]
  941. [AuthToken(Roles = "admin,teacher,student")]
  942. public async Task<IActionResult> GetOtherLessonRecord(JsonElement request)
  943. {
  944. if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
  945. string tbname = "";
  946. string code = "";
  947. string sqlPrivate = "";
  948. if (_scope.GetString().Equals("school") )
  949. {
  950. if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
  951. if (!string.IsNullOrEmpty($"{_school}"))
  952. {
  953. code = $"LessonRecord-{_school}";
  954. tbname = "School";
  955. }
  956. else
  957. {
  958. return BadRequest();
  959. }
  960. }
  961. else if ($"{_scope}".Equals("private"))
  962. {
  963. if (!request.TryGetProperty("tmdid", out JsonElement _tmdid)) return BadRequest();
  964. if (!string.IsNullOrEmpty($"{_tmdid}"))
  965. {
  966. sqlPrivate = $" and c.tmdid='{_tmdid}'";
  967. code = $"LessonRecord";
  968. tbname = "Teacher";
  969. }
  970. else {
  971. return BadRequest();
  972. }
  973. }
  974. else
  975. {
  976. return BadRequest();
  977. }
  978. request.TryGetProperty("periodId", out JsonElement _periodId);
  979. request.TryGetProperty("stime", out JsonElement _stime);
  980. request.TryGetProperty("etime", out JsonElement _etime);
  981. //优质课程
  982. var excellent = new JsonObject
  983. {
  984. ["excellent"] = true,
  985. ["periodId"] = $"{_periodId}",
  986. ["stime"] = $"{_stime}",
  987. ["etime"] = $"{_etime}",
  988. }.ToJsonString().ToObject<JsonElement>();
  989. //专家好客
  990. var doubleGreen = new JsonObject
  991. {
  992. ["doubleGreen"] = true,
  993. ["periodId"] = $"{_periodId}",
  994. ["stime"] = $"{_stime}",
  995. ["etime"] = $"{_etime}",
  996. }.ToJsonString().ToObject<JsonElement>();
  997. //今日课程
  998. var today = new JsonObject
  999. {
  1000. ["today"] = true,
  1001. ["periodId"] = $"{_periodId}",
  1002. }.ToJsonString().ToObject<JsonElement>();
  1003. List<LessonRecord> excellentRcd =await GetOtherLessonCond(excellent, code, tbname, sqlPrivate);
  1004. List<LessonRecord> doubleGreenRcd = await GetOtherLessonCond(doubleGreen, code, tbname, sqlPrivate);
  1005. List<LessonRecord> todayRcd = await GetOtherLessonCond(today, code, tbname, sqlPrivate);
  1006. try {
  1007. var tmdids_excellent = excellentRcd.Select(x => x.tmdid);
  1008. var tmdids_doubleGreen = excellentRcd.Select(x => x.tmdid);
  1009. var tmdids_today = excellentRcd.Select(x => x.tmdid);
  1010. List<string> tmdids=new List<string>();
  1011. tmdids.AddRange(tmdids_excellent);
  1012. tmdids.AddRange(tmdids_doubleGreen);
  1013. tmdids.AddRange(tmdids_today);
  1014. if (tmdids != null && tmdids.Count > 0) {
  1015. List< IdNameCode > codes= new List<IdNameCode> ();
  1016. string sqltmd = $"select c.id,c.name,c.picture from c where c.id in ({string.Join(",", tmdids.Select(x => $"'{x}'"))})";
  1017. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<IdNameCode>(queryText:sqltmd,requestOptions:new QueryRequestOptions { PartitionKey=new PartitionKey("Base") })){
  1018. codes.Add(item);
  1019. }
  1020. if (codes.IsNotEmpty()) {
  1021. excellentRcd.ForEach(x => {
  1022. var tmd= codes.Find(z => z.id.Equals(x.tmdid));
  1023. if (tmd != null) {
  1024. x.tmdname = tmd.name;
  1025. x.tmdpicture= tmd.picture;
  1026. }
  1027. });
  1028. doubleGreenRcd.ForEach(x => {
  1029. var tmd = codes.Find(z => z.id.Equals(x.tmdid));
  1030. if (tmd != null)
  1031. {
  1032. x.tmdname = tmd.name;
  1033. x.tmdpicture = tmd.picture;
  1034. }
  1035. });
  1036. todayRcd.ForEach(x => {
  1037. var tmd = codes.Find(z => z.id.Equals(x.tmdid));
  1038. if (tmd != null)
  1039. {
  1040. x.tmdname = tmd.name;
  1041. x.tmdpicture = tmd.picture;
  1042. }
  1043. });
  1044. }
  1045. }
  1046. return Ok(new { excellentRcd , doubleGreenRcd, todayRcd });
  1047. } catch (Exception ex) {
  1048. return Ok(new { excellentRcd, doubleGreenRcd, todayRcd });
  1049. }
  1050. }
  1051. private async Task<List<LessonRecord>> GetOtherLessonCond(JsonElement request,string code ,string tbname,string sqlPrivate) {
  1052. StringBuilder sql = new StringBuilder();
  1053. sql.Append("select value(c) from c ");
  1054. Dictionary<string, object> dict = LessonService.GetLessonCond(request);
  1055. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  1056. List<LessonRecord> lessonRecords = new List<LessonRecord>();
  1057. cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where (c.status<>404 or IS_DEFINED(c.status) = false ) and array_length(c.groupIds)>0 {sqlPrivate} and ");
  1058. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname)
  1059. .GetItemQueryStreamIteratorQuery(queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
  1060. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
  1061. {
  1062. using var json = await JsonDocument.ParseAsync(item.Content);
  1063. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1064. {
  1065. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1066. {
  1067. lessonRecords.Add(obj.ToObject<LessonRecord>());
  1068. }
  1069. }
  1070. }
  1071. return lessonRecords;
  1072. }
  1073. /// <summary>
  1074. /// 验证IES课例
  1075. /// </summary>
  1076. /// <param name="request"></param>
  1077. /// <returns></returns>
  1078. [HttpGet("lesson-record-verify")]
  1079. [Authorize(Roles = "IES")]
  1080. [AuthToken(Roles = "teacher")]
  1081. [EnableCors("AllowSpecificOrigin")]//跨域
  1082. public async Task<IActionResult> LessonRecordVerify([FromQuery] string id , [FromQuery] string owner, [FromQuery] string scope, [FromQuery] string token )
  1083. {
  1084. (string tmdid, _, _, string school) = HttpContext.GetAuthTokenInfo();
  1085. if (!string.IsNullOrWhiteSpace(id)) { return Ok(new { code=4001,msg="id不能为空" }); }
  1086. if (!string.IsNullOrWhiteSpace(scope)) { return Ok(new { code = 4002, msg = "scope不能为空" }); }
  1087. if (!string.IsNullOrWhiteSpace(owner)) { return Ok(new { code = 4003, msg = "owner不能为空" }); }
  1088. if (!string.IsNullOrWhiteSpace(token)) { return Ok(new { code = 4004, msg = "token不能为空" }); }
  1089. string tbname;
  1090. string code;
  1091. if (scope.Equals("school") && !string.IsNullOrWhiteSpace(owner))
  1092. {
  1093. code = $"LessonRecord-{owner}";
  1094. tbname = "School";
  1095. }
  1096. else if ($"{scope}".Equals("private") && owner.Equals(tmdid))
  1097. {
  1098. code = $"LessonRecord";
  1099. tbname = "Teacher";
  1100. }
  1101. else
  1102. {
  1103. { return Ok(new { code = 400, msg = "参数错误" }); }
  1104. }
  1105. ResponseMessage response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(id, new PartitionKey(code));
  1106. if (response.StatusCode==System.Net.HttpStatusCode.OK)
  1107. {
  1108. LessonRecord lessonRecord = JsonDocument.Parse(response.Content).RootElement.ToObject<LessonRecord>();
  1109. if (lessonRecord.scope.Equals("school"))
  1110. {
  1111. if (lessonRecord.school.Equals(school))
  1112. {
  1113. if (lessonRecord.tmdid.Equals(tmdid))
  1114. {
  1115. return Ok(new { code = 200, lessonRecord });
  1116. }
  1117. else
  1118. {
  1119. ///不是本人的课例
  1120. ///(非授权信息) 服务器已成功处理了请求,但返回的信息可能来自另一来源。
  1121. return Ok(new { code = 2031, lessonRecord });
  1122. }
  1123. }
  1124. else
  1125. {
  1126. //不是同一个学校的课例
  1127. ///(非授权信息) 服务器已成功处理了请求,但返回的信息可能来自另一来源。
  1128. return Ok(new { code = 2032, lessonRecord });
  1129. }
  1130. }
  1131. else {
  1132. if (lessonRecord.tmdid.Equals(tmdid))
  1133. {
  1134. return Ok(new { code = 200, lessonRecord });
  1135. }
  1136. else
  1137. {
  1138. ///不是本人的课例
  1139. ///(非授权信息) 服务器已成功处理了请求,但返回的信息可能来自另一来源。
  1140. return Ok(new { code = 2031, lessonRecord });
  1141. }
  1142. }
  1143. }
  1144. else {
  1145. return Ok(new { code = 404, msg = "课例不存在" });
  1146. }
  1147. }
  1148. }
  1149. }