LessonRecordController.cs 76 KB

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