SchoolTeacherController.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. using Microsoft.AspNetCore.Mvc;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using TEAMModelOS.Models;
  7. using TEAMModelOS.SDK;
  8. using TEAMModelOS.SDK.DI;
  9. using System.Text.Json;
  10. using TEAMModelOS.SDK.Models;
  11. using Microsoft.AspNetCore.Http;
  12. using Azure.Cosmos;
  13. using TEAMModelOS.SDK.Extension;
  14. using System.IdentityModel.Tokens.Jwt;
  15. using System.IO;
  16. using System.Linq;
  17. using Microsoft.Extensions.Options;
  18. using System.Net.Http;
  19. using System.Net;
  20. using Microsoft.Extensions.Configuration;
  21. using TEAMModelOS.Filter;
  22. using HTEXLib.COMM.Helpers;
  23. using Microsoft.AspNetCore.Authorization;
  24. using TEAMModelOS.SDK.DI.CoreAPI;
  25. using DocumentFormat.OpenXml.Wordprocessing;
  26. using static TEAMModelOS.Controllers.FixDataController;
  27. using Microsoft.Extensions.Hosting;
  28. using Microsoft.AspNetCore.Hosting;
  29. using DocumentFormat.OpenXml.Office2010.Excel;
  30. namespace TEAMModelOS.Controllers
  31. {
  32. [ProducesResponseType(StatusCodes.Status200OK)]
  33. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  34. [Route("school/teacher")]
  35. [ApiController]
  36. public class SchoolTeacherController : Controller
  37. {
  38. private readonly AzureCosmosFactory _azureCosmos;
  39. private readonly AzureStorageFactory _azureStorage;
  40. private readonly Option _option;
  41. private readonly IConfiguration _configuration;
  42. private readonly NotificationService _notificationService;
  43. private readonly AzureServiceBusFactory _azureServiceBus;
  44. private readonly CoreAPIHttpService _coreAPIHttpService;
  45. private readonly IWebHostEnvironment _environment;
  46. private readonly DingDing _dingDing;
  47. public SchoolTeacherController(IWebHostEnvironment environment,DingDing dingDing, CoreAPIHttpService coreAPIHttpService, AzureServiceBusFactory azureServiceBus, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IConfiguration configuration, NotificationService notificationService)
  48. {
  49. _dingDing = dingDing;
  50. _azureCosmos = azureCosmos;
  51. _azureStorage = azureStorage;
  52. _option = option?.Value;
  53. _configuration = configuration;
  54. _notificationService = notificationService;
  55. _azureServiceBus = azureServiceBus;
  56. _coreAPIHttpService = coreAPIHttpService;
  57. _environment = environment;
  58. }
  59. /// <summary>
  60. /// 取得學校所有老師(不論加入狀態)
  61. /// </summary>
  62. /// <param name="request"></param>
  63. /// <returns></returns>
  64. [ProducesDefaultResponseType]
  65. [HttpPost("get-teacher-all")]
  66. #if !DEBUG
  67. [Authorize(Roles = "IES")]
  68. #endif
  69. public async Task<IActionResult> GetSchoolTeacherAll(JsonElement request)
  70. {
  71. var client = _azureCosmos.GetCosmosClient();
  72. //參數取得
  73. if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  74. //string status_str = (request.TryGetProperty("join_status", out JsonElement status_json)) ? status_json.ToString() : "join";
  75. //資料取得
  76. List<ScTeacher> teachers = new List<ScTeacher>();
  77. try
  78. {
  79. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ScTeacher>
  80. (queryText: $"SELECT c.subjectIds, c.id, c.name, c.picture ,c.status, c.job, c.createTime, ARRAY_LENGTH(c.permissions) as permissionCount,c.permissions,c.roles , c.size FROM c",
  81. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school_code}") }))
  82. {
  83. if ($"{item.createTime}".Length > 10)
  84. {
  85. item.createTime = item.createTime / 1000;
  86. }
  87. teachers.Add(item);
  88. }
  89. if (teachers.IsNotEmpty())
  90. {
  91. List<IdNameCode> groupLists = new List<IdNameCode>();
  92. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<IdNameCode>
  93. (queryText: $"SELECT c.id, c.name, m.id as code FROM c join m in c.members where c.type='research' and m.id in ({string.Join(",", teachers.Select(x => $"'{x.id}'"))}) ",
  94. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school_code}") }))
  95. {
  96. groupLists.Add(item);
  97. }
  98. if (groupLists.IsNotEmpty())
  99. {
  100. teachers.ForEach(x => {
  101. List<IdNameCode> codes = groupLists.FindAll(g => g.code.Equals(x.id));
  102. if (codes.IsNotEmpty())
  103. {
  104. x.groups = codes;
  105. }
  106. });
  107. }
  108. }
  109. Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync($"{school_code}", new PartitionKey("TeacherImport"));
  110. IEnumerable<string> ids = null;
  111. List<CoreUser> coreUsers = new List<CoreUser>();
  112. if (response.Status == 200)
  113. {
  114. TeacherImport teacherImport = JsonDocument.Parse(response.Content).RootElement.ToObject<TeacherImport>();
  115. var idsIn = teacherImport.teachers.Where(x => !string.IsNullOrWhiteSpace(x.id));
  116. //id是空 其他不是空的
  117. var tmdidsi = teacherImport.teachers.Where(x => string.IsNullOrWhiteSpace(x.id) && !string.IsNullOrWhiteSpace(x.tmdid)).Select(z => z.tmdid);
  118. var phonesi = teacherImport.teachers.Where(x => string.IsNullOrWhiteSpace(x.id) && !string.IsNullOrWhiteSpace(x.phone)).Select(z => z.phone);
  119. var emailsi = teacherImport.teachers.Where(x => string.IsNullOrWhiteSpace(x.id) && !string.IsNullOrWhiteSpace(x.email)).Select(z => z.email);
  120. List<string> skeys = new List<string>();
  121. if (idsIn.Any())
  122. {
  123. skeys.AddRange(idsIn.Select(x => x.id));
  124. }
  125. if (tmdidsi.Any())
  126. {
  127. skeys.AddRange(tmdidsi);
  128. }
  129. if (phonesi.Any())
  130. {
  131. skeys.AddRange(phonesi);
  132. }
  133. if (emailsi.Any())
  134. {
  135. skeys.AddRange(emailsi);
  136. }
  137. if (skeys.Any())
  138. {
  139. try
  140. {
  141. var content = new StringContent(skeys.ToJsonString(), Encoding.UTF8, "application/json");
  142. string json = await _coreAPIHttpService.GetUserInfos(content);
  143. if (!string.IsNullOrWhiteSpace(json))
  144. {
  145. coreUsers = json.ToObject<List<CoreUser>>();
  146. ids = coreUsers.Select(x => x.id);
  147. }
  148. }
  149. catch (Exception ex)
  150. {
  151. //await _dingDing.SendBotMsg($"{_option.Location},导入名单时,查验key信息错误{ex.Message}\n{ex.StackTrace}\n\n{skeys.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  152. }
  153. }
  154. if (coreUsers.Any())
  155. {
  156. teacherImport.teachers.ForEach(t =>
  157. {
  158. if (!string.IsNullOrWhiteSpace(t.id))
  159. {
  160. CoreUser coreUser = coreUsers.Find(x => x.searchKey.Equals(t.id) || x.id.Equals(t.id));
  161. if (coreUser != null)
  162. {
  163. t.id = coreUser.id;
  164. t.name = coreUser.name;
  165. t.picture = coreUser.picture;
  166. t.tmdid = coreUser.id;
  167. if (!string.IsNullOrWhiteSpace(coreUser.mobile))
  168. {
  169. t.phone = coreUser.mobile;
  170. }
  171. if (!string.IsNullOrWhiteSpace(coreUser.mail))
  172. {
  173. t.email = coreUser.mail;
  174. }
  175. }
  176. else
  177. {
  178. t.id = null;
  179. }
  180. }
  181. if (string.IsNullOrWhiteSpace(t.id))
  182. {
  183. if (!string.IsNullOrWhiteSpace(t.tmdid))
  184. {
  185. CoreUser coreUser = coreUsers.Find(x => x.id.Equals(t.tmdid));
  186. if (coreUser != null)
  187. {
  188. t.id = coreUser.id;
  189. t.name = coreUser.name;
  190. t.picture = coreUser.picture;
  191. t.tmdid = coreUser.id;
  192. if (!string.IsNullOrWhiteSpace(coreUser.mobile))
  193. {
  194. t.phone = coreUser.mobile;
  195. }
  196. if (!string.IsNullOrWhiteSpace(coreUser.mail))
  197. {
  198. t.email = coreUser.mail;
  199. }
  200. }
  201. }
  202. if (string.IsNullOrWhiteSpace(t.id))
  203. {
  204. if (!string.IsNullOrWhiteSpace(t.phone))
  205. {
  206. CoreUser coreUser = coreUsers.Find(x => !string.IsNullOrWhiteSpace(x.mobile) && x.mobile.Equals(t.phone));
  207. if (coreUser != null)
  208. {
  209. t.id = coreUser.id;
  210. t.name = coreUser.name;
  211. t.picture = coreUser.picture;
  212. t.tmdid = coreUser.id;
  213. if (!string.IsNullOrWhiteSpace(coreUser.mobile))
  214. {
  215. t.phone = coreUser.mobile;
  216. }
  217. if (!string.IsNullOrWhiteSpace(coreUser.mail))
  218. {
  219. t.email = coreUser.mail;
  220. }
  221. }
  222. }
  223. }
  224. if (string.IsNullOrWhiteSpace(t.id))
  225. {
  226. if (!string.IsNullOrWhiteSpace(t.email))
  227. {
  228. CoreUser coreUser = coreUsers.Find(x => !string.IsNullOrWhiteSpace(x.mail) && x.mail.Equals(t.email));
  229. if (coreUser != null)
  230. {
  231. t.id = coreUser.id;
  232. t.name = coreUser.name;
  233. t.picture = coreUser.picture;
  234. t.tmdid = coreUser.id;
  235. if (!string.IsNullOrWhiteSpace(coreUser.mobile))
  236. {
  237. t.phone = coreUser.mobile;
  238. }
  239. if (!string.IsNullOrWhiteSpace(coreUser.mail))
  240. {
  241. t.email = coreUser.mail;
  242. }
  243. }
  244. }
  245. }
  246. }
  247. if (!string.IsNullOrWhiteSpace(t.id))
  248. {
  249. var tch = teachers.Find(x => !string.IsNullOrWhiteSpace(x.id) && x.id.Equals(t.id));
  250. if (tch == null)
  251. {
  252. tch = new ScTeacher
  253. {
  254. id = t.id,
  255. iname = t.iname,
  256. name = t.name,
  257. picture = t.picture,
  258. status = "import",
  259. createTime = t.time,
  260. permissionCount = 0,
  261. size = 0,
  262. permissions = new List<string>(),
  263. roles = new List<string>(),
  264. subjectIds = new List<string>(),
  265. groups = new List<IdNameCode>(),
  266. note = t.note,
  267. phone = t.phone,
  268. email = t.email,
  269. };
  270. teachers.Add(tch);
  271. }
  272. else
  273. {
  274. tch.iname = t.iname;
  275. tch.note = t.note;
  276. tch.phone = t.phone;
  277. tch.email = t.email;
  278. }
  279. }
  280. else
  281. {
  282. //teachers.Add();
  283. var tch = new ScTeacher
  284. {
  285. id = t.id,
  286. picture = t.picture,
  287. iname = t.iname,
  288. name = t.name,
  289. status = "import",
  290. createTime = t.time,
  291. permissionCount = 0,
  292. size = 0,
  293. permissions = new List<string>(),
  294. roles = new List<string>(),
  295. subjectIds = new List<string>(),
  296. groups = new List<IdNameCode>(),
  297. note = t.note,
  298. phone = t.phone,
  299. email = t.email,
  300. };
  301. teachers.Add(tch);
  302. }
  303. });
  304. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(teacherImport, $"{school_code}", new PartitionKey("TeacherImport"));
  305. }
  306. else
  307. {
  308. var noids = teacherImport.teachers.Where(x => string.IsNullOrWhiteSpace(x.id));
  309. foreach (var t in noids)
  310. {
  311. teachers.Add(new ScTeacher
  312. {
  313. id = t.id,
  314. picture = t.picture,
  315. iname = t.iname,
  316. name = t.name,
  317. status = "import",
  318. createTime = t.time,
  319. permissionCount = 0,
  320. size = 0,
  321. permissions = new List<string>(),
  322. roles = new List<string>(),
  323. subjectIds = new List<string>(),
  324. groups = new List<IdNameCode>(),
  325. note = t.note,
  326. phone = t.phone,
  327. email = t.email,
  328. });
  329. }
  330. }
  331. }
  332. IEnumerable<string> coreids = null;
  333. coreids = teachers.Where(z => !string.IsNullOrWhiteSpace(z.id)).Select(x => x.id);
  334. List<CoreUser> users = new List<CoreUser>();
  335. if (coreids != null && coreids.Any())
  336. {
  337. try
  338. {
  339. var content = new StringContent(coreids.ToJsonString(), Encoding.UTF8, "application/json");
  340. string json = await _coreAPIHttpService.GetUserInfos(content);
  341. if (!string.IsNullOrWhiteSpace(json))
  342. {
  343. users = json.ToObject<List<CoreUser>>();
  344. }
  345. }
  346. catch (Exception ex)
  347. {
  348. //await _dingDing.SendBotMsg($"{_option.Location},导入名单时,查验key信息错误{ex.Message}\n{ex.StackTrace}\n\n{skeys.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  349. }
  350. }
  351. if (users.Any())
  352. {
  353. teachers.ForEach(x => {
  354. if (!string.IsNullOrWhiteSpace(x.id))
  355. {
  356. CoreUser coreUser = users.Find(u => u.id.Equals(x.id));
  357. if (coreUser != null)
  358. {
  359. x.phone = coreUser.mobile;
  360. x.email = coreUser.mail;
  361. }
  362. else
  363. {
  364. x.status = "delete";
  365. }
  366. }
  367. });
  368. }
  369. }
  370. catch (Exception ex)
  371. {
  372. await _dingDing.SendBotMsg($"{_option.Location},{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  373. }
  374. //Azure.Response responseSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync($"{school_code}", new PartitionKey("Base"));
  375. //if (responseSchool.Status == 200) {
  376. // School school = JsonDocument.Parse(responseSchool.Content).RootElement.Deserialize<School>();
  377. //}
  378. //处理区级权限数据
  379. HashSet<string> teacherIds = teachers.Where(x => !string.IsNullOrWhiteSpace(x.id)).Select(z => z.id).ToHashSet();
  380. if (teacherIds.Any()) {
  381. string sql = $"select distinct value c from c where array_length(c.areas)>0 and c.id in ({string.Join(",",teacherIds.Select(c=>$"'{c}'"))})";
  382. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  383. .GetItemQueryIterator<Teacher>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") })) {
  384. var teach= teachers.Find(x => !string.IsNullOrWhiteSpace(x.id) && x.id.Equals(item.id));
  385. if (teach != null) { teach.areas = item.areas; }
  386. }
  387. }
  388. return Ok(new { teachers });
  389. }
  390. public class ScTeacher
  391. {
  392. public string id { get; set; }
  393. public string name { get; set; }
  394. public string iname { get; set; }
  395. public string picture { get; set; }
  396. public string status { get; set; }
  397. public string job { get; set; }
  398. public long createTime { get; set; }
  399. public int permissionCount { get; set; }
  400. public int size { get; set; }
  401. public List<string> permissions { get; set; }
  402. public List<string> roles { get; set; }
  403. public List<string> subjectIds { get; set; }
  404. public List<IdNameCode> groups { get; set; } = new List<IdNameCode>();
  405. public string note { get; set; }
  406. public string phone { get; set; }
  407. public string email { get; set; }
  408. public List<TEAMModelOS.SDK.Models.Teacher.TeacherArea> areas { get; set; } = new List<TEAMModelOS.SDK.Models.Teacher.TeacherArea>();
  409. }
  410. /// <summary>
  411. /// 取得某位老師的權限
  412. /// </summary>
  413. /// <param name="request"></param>
  414. /// <returns></returns>
  415. [ProducesDefaultResponseType]
  416. [HttpPost("get-teacher-permission")]
  417. [Authorize(Roles = "IES")]
  418. public async Task<IActionResult> GetPermissionById(JsonElement request)
  419. {
  420. var client = _azureCosmos.GetCosmosClient();
  421. //參數取得
  422. if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  423. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  424. //老師權限資料取得
  425. object permissions = null;
  426. var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Teacher-{school_code}"));
  427. if (response.Status == 200)
  428. {
  429. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  430. if (json.RootElement.TryGetProperty("permissions", out JsonElement value))
  431. {
  432. permissions = value.ToObject<object>();
  433. }
  434. }
  435. return Ok(new { permissions });
  436. }
  437. /// <summary>
  438. /// 取得權限總列表
  439. /// </summary>
  440. [ProducesDefaultResponseType]
  441. [HttpPost("get-teacher-authoritylist")]
  442. [Authorize(Roles = "IES")]
  443. public async Task<IActionResult> GetSchoolAuthorityList()
  444. {
  445. Dictionary<string, object> dict = new Dictionary<string, object>
  446. {
  447. { "PartitionKey", "authority"}
  448. };
  449. var table = _azureStorage.GetCloudTableClient().GetTableReference("SchoolSetting");
  450. List<Authority> authoritylist = await table.FindListByDict<Authority>(dict);
  451. return Ok(new { authoritylist });
  452. }
  453. /// <summary>
  454. /// 更新老師的權限(可複數)
  455. /// </summary>
  456. /// <param name="request"></param>
  457. /// <returns></returns>
  458. [ProducesDefaultResponseType]
  459. [HttpPost("upd-teacher-permission")]
  460. [Authorize(Roles = "IES")]
  461. public async Task<IActionResult> UpdSchoolTeacherPermission(JsonElement request)
  462. {
  463. try
  464. {
  465. var client = _azureCosmos.GetCosmosClient();
  466. //參數取得
  467. if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  468. request.TryGetProperty("ids", out JsonElement _ids);
  469. request.TryGetProperty("job", out JsonElement _job);
  470. request.TryGetProperty("permission", out JsonElement _permission);
  471. request.TryGetProperty("pmClean", out JsonElement _pmClean);
  472. request.TryGetProperty("pmAdd", out JsonElement _pmAdd);
  473. request.TryGetProperty("pmRmv", out JsonElement _pmRmv);
  474. List<string> rmvPm = null;
  475. if (_pmRmv.ValueKind.Equals(JsonValueKind.Array))
  476. {
  477. rmvPm = _pmRmv.ToObject<List<string>>();
  478. }
  479. List<string> addPm = null;
  480. if (_pmAdd.ValueKind.Equals(JsonValueKind.Array))
  481. {
  482. addPm = _pmAdd.ToObject<List<string>>();
  483. }
  484. List<string> permission = null;
  485. if (_permission.ValueKind.Equals(JsonValueKind.Array))
  486. {
  487. permission = _permission.ToObject<List<string>>();
  488. }
  489. if (!_ids.ValueKind.Equals(JsonValueKind.Array))
  490. {
  491. return BadRequest();
  492. }
  493. List<string> ids = _ids.ToObject<List<string>>();
  494. //更新權限
  495. List<SchoolTeacher> schoolTeachers = new List<SchoolTeacher>();
  496. bool hasjob = false;
  497. if (ids.Count > 1 && !string.IsNullOrWhiteSpace($"{_job}"))
  498. {
  499. hasjob = true;
  500. }
  501. else if (ids.Count == 1 && permission.IsNotEmpty())
  502. {
  503. hasjob = true;
  504. }
  505. foreach (var id in ids)
  506. {
  507. SchoolTeacher st = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolTeacher>(id, new PartitionKey($"Teacher-{school_code}"));
  508. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(id, new PartitionKey($"Base"));
  509. if (permission.IsNotEmpty())
  510. {
  511. st.permissions = permission;
  512. }
  513. if (addPm.IsNotEmpty())
  514. {
  515. st.permissions.AddRange(addPm);
  516. }
  517. if (rmvPm.IsNotEmpty())
  518. {
  519. st.permissions.RemoveAll(x => rmvPm.Contains(x));
  520. }
  521. if (hasjob)
  522. {
  523. st.job = $"{_job}";
  524. }
  525. //清除权限标记。
  526. if (_pmClean.ValueKind.Equals(JsonValueKind.True)) {
  527. st.permissions = new List<string>();
  528. }
  529. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
  530. new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  531. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(st, id, new PartitionKey($"Teacher-{school_code}"));
  532. schoolTeachers.Add(st);
  533. }
  534. return Ok(new { teachers = schoolTeachers });
  535. }
  536. catch (Exception)
  537. {
  538. return BadRequest();
  539. }
  540. }
  541. /// <summary>
  542. /// 追加老師及學校加入狀態
  543. /// </summary>
  544. /// <param name="request"></param>
  545. /// <returns></returns>
  546. [ProducesDefaultResponseType]
  547. [HttpPost("add-teacher-status")]
  548. [Authorize(Roles = "IES")]
  549. [AuthToken(Roles = "teacher,admin")]
  550. public async Task<IActionResult> AddSchoolTeacher(JsonElement request)
  551. {
  552. var (tid, tname, _, tschool) = HttpContext.GetAuthTokenInfo();
  553. var client = _azureCosmos.GetCosmosClient();
  554. //參數取得
  555. if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  556. if (!request.TryGetProperty("user_list", out JsonElement user_list)) return BadRequest();
  557. if (!request.TryGetProperty("grant_type", out JsonElement grant_type)) return BadRequest();
  558. //取得學校資訊
  559. var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey("Base"));
  560. string schname = string.Empty;
  561. string schareaId = string.Empty;
  562. string schpic = string.Empty;
  563. if (schresponse.Status == 200)
  564. {
  565. using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
  566. schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
  567. schname = jsonschname.ToString();
  568. schjson.RootElement.TryGetProperty("areaId", out JsonElement areaId);
  569. schareaId = $"{areaId}";
  570. schjson.RootElement.TryGetProperty("picture", out JsonElement picture);
  571. schpic = $"{picture}";
  572. }
  573. else
  574. {
  575. return BadRequest();
  576. }
  577. try
  578. {
  579. List<KeyValuePair<string, int>> keys = new List<KeyValuePair<string, int>>();
  580. List<IdNameCode> ids = new List<IdNameCode>();
  581. foreach (var obj in user_list.EnumerateArray())
  582. {
  583. obj.TryGetProperty("id", out JsonElement id);
  584. obj.TryGetProperty("name", out JsonElement name);
  585. obj.TryGetProperty("picture", out JsonElement picture);
  586. IdNameCode tmd = new IdNameCode { id = $"{id}", name = $"{name}" };
  587. ids.Add(tmd);
  588. //老師個人資料
  589. var tresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(id.ToString(), new PartitionKey("Base"));
  590. if (tresponse.Status == 200)
  591. {
  592. using var json = await JsonDocument.ParseAsync(tresponse.ContentStream);
  593. Teacher teacher = json.ToObject<Teacher>();
  594. tmd.code = teacher.lang;
  595. var school = teacher.schools.FirstOrDefault(x => x.schoolId.Equals(school_code.GetString(), StringComparison.OrdinalIgnoreCase));
  596. if (school != null)
  597. {
  598. school.time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  599. if (school.status.Equals("invite") && grant_type.ToString().Equals("invite"))
  600. {
  601. keys.Add(new KeyValuePair<string, int>($"{id}", 1));
  602. //移除不能发送通知的部分
  603. ids.Remove(tmd);
  604. continue;
  605. }
  606. if (school.status.Equals("join") && grant_type.ToString().Equals("invite"))
  607. {
  608. keys.Add(new KeyValuePair<string, int>($"{id}", 2));
  609. //移除不能发送通知的部分
  610. ids.Remove(tmd);
  611. continue;
  612. }
  613. school.status = grant_type.GetString();
  614. }
  615. else
  616. teacher.schools.Add(new Teacher.TeacherSchool() { areaId = schareaId, picture = schpic, schoolId = school_code.GetString(), name = schname, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), status = grant_type.GetString() });
  617. if (teacher.schools.Count > 0 && teacher.size <= 1)
  618. {
  619. teacher.size = 2;
  620. }
  621. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, id.ToString(), new PartitionKey("Base"));
  622. }
  623. else
  624. {
  625. using var stream = new MemoryStream();
  626. using var writer = new Utf8JsonWriter(stream);
  627. writer.WriteStartObject();
  628. writer.WriteString("pk", "Base");
  629. writer.WriteString("code", "Base");
  630. writer.WriteString("id", id.ToString());
  631. writer.WriteString("name", name.ToString());
  632. writer.WriteString("picture", picture.ToString());
  633. writer.WriteNumber("size", 1);
  634. writer.WriteString("groupId", "default");
  635. writer.WriteString("groupName", "默认组别");
  636. writer.WriteNull("defaultSchool");
  637. writer.WriteStartArray("schools");
  638. writer.WriteStartObject();
  639. writer.WriteString("schoolId", school_code.ToString());
  640. writer.WriteString("name", schname);
  641. writer.WriteString("status", grant_type.ToString());
  642. writer.WriteEndObject();
  643. writer.WriteEndArray();
  644. writer.WriteEndObject();
  645. writer.Flush();
  646. await client.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemStreamAsync(stream, new PartitionKey("Base"));
  647. }
  648. //學校老師資料
  649. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Teacher-{school_code}"));
  650. //SchoolTeacher schteacher = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolTeacher>(id.ToString(), new PartitionKey($"Teacher-{school_code}"));
  651. if (sresponse.Status == 200)
  652. {
  653. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  654. SchoolTeacher schteacher = json.ToObject<SchoolTeacher>();
  655. if (schteacher.status.Equals("invite") && grant_type.ToString().Equals("invite"))
  656. {
  657. keys.Add(new KeyValuePair<string, int>($"{id}", 1));
  658. continue;
  659. }
  660. if (schteacher.status.Equals("join") && grant_type.ToString().Equals("invite"))
  661. {
  662. keys.Add(new KeyValuePair<string, int>($"{id}", 2));
  663. continue;
  664. }
  665. schteacher.status = grant_type.ToString();
  666. schteacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  667. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(schteacher, id.ToString(), new PartitionKey($"Teacher-{school_code}"));
  668. }
  669. else
  670. {
  671. using var stream = new MemoryStream();
  672. using var writer = new Utf8JsonWriter(stream);
  673. writer.WriteStartObject();
  674. writer.WriteString("pk", "Teacher");
  675. writer.WriteString("code", $"Teacher-{school_code}");
  676. writer.WriteString("id", id.ToString());
  677. writer.WriteString("name", name.ToString());
  678. writer.WriteString("groupId", "default");
  679. writer.WriteString("groupName", "默认组别");
  680. writer.WriteString("picture", picture.ToString());
  681. writer.WriteNull("job");
  682. writer.WriteNumber("size", 0);
  683. writer.WriteStartArray("roles");
  684. writer.WriteStringValue("teacher");
  685. writer.WriteEndArray();
  686. writer.WriteStartArray("permissions");
  687. if (grant_type.ToString().Equals("join"))
  688. {
  689. writer.WriteStringValue("content-read");
  690. writer.WriteStringValue("exercise-read");
  691. writer.WriteStringValue("knowledge-read");
  692. writer.WriteStringValue("syllabus-read");
  693. }
  694. writer.WriteEndArray();
  695. writer.WriteString("status", grant_type.ToString());
  696. writer.WriteNumber("createTime", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
  697. writer.WriteEndObject();
  698. writer.Flush();
  699. await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemStreamAsync(stream, new PartitionKey($"Teacher-{school_code}"));
  700. }
  701. if (grant_type.ToString().Equals("join"))
  702. {
  703. await TmdUserService.JoinSchool(client, $"{id}", $"{picture}", $"{name}", $"{school_code}", $"{schname}");
  704. }
  705. }
  706. string bizcode = grant_type.GetString();
  707. if (grant_type.GetString().Equals("join"))
  708. {
  709. bizcode = "request-join";
  710. }
  711. Notification notification = new Notification
  712. {
  713. hubName = "hita",
  714. type = "msg",
  715. from = $"ies5:{_option.Location}:private",
  716. to = ids.Select(x => x.id).ToList(),
  717. label = $"{bizcode}_school",
  718. body = new {
  719. location = _option.Location,
  720. biz = bizcode,
  721. tmdid = tid,
  722. tmdname = tname.ToString(),
  723. schoolcode = $"{school_code}",
  724. schoolname = $"{schname}",
  725. status = 1,
  726. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  727. }.ToJsonString(),
  728. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  729. };
  730. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  731. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  732. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  733. var location = _option.Location;
  734. var code = await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);
  735. _coreAPIHttpService.PushNotify(ids, $"{bizcode}_school", Constant.NotifyType_IES5_Management,
  736. new Dictionary<string, object> { { "tmdname", tname }, { "schoolName", schname }, { "schoolId", $"{school_code}" } , { "tmdid",tid} }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  737. return Ok(new { exist = keys });
  738. }
  739. catch (Exception ex)
  740. {
  741. return BadRequest();
  742. }
  743. }
  744. /// <summary>
  745. /// 學校變更老師加入狀態
  746. /// </summary>
  747. /// <param name="request"></param>
  748. /// <returns></returns>
  749. [ProducesDefaultResponseType]
  750. [AuthToken(Roles = "admin", Permissions = "schoolSetting-upd,auth-upd,schoolAc-upd,teacher-upd")]
  751. [HttpPost("upd-teacher-status")]
  752. [Authorize(Roles = "IES")]
  753. public async Task<IActionResult> UpdSchoolTeacherStatus(JsonElement request)
  754. {
  755. try
  756. {
  757. var (tid, tname, _, tschool) = HttpContext.GetAuthTokenInfo();
  758. if (!request.TryGetProperty("grant_type", out JsonElement grant_type)) return BadRequest();
  759. if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  760. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  761. request.TryGetProperty("importName", out JsonElement _importName);
  762. var client = _azureCosmos.GetCosmosClient();
  763. //取得學校資訊
  764. var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey("Base"));
  765. string schname = string.Empty;
  766. string schareaId = string.Empty;
  767. string schpic = string.Empty;
  768. if (schresponse.Status == 200)
  769. {
  770. using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
  771. schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
  772. schname = jsonschname.ToString();
  773. schjson.RootElement.TryGetProperty("areaId", out JsonElement areaId);
  774. schareaId = $"{areaId}";
  775. schjson.RootElement.TryGetProperty("picture", out JsonElement picture);
  776. schpic = $"{picture}";
  777. }
  778. else
  779. {
  780. return BadRequest();
  781. }
  782. //在老師表找出老師,處理該學校狀態 (老師基本資料應該要存在)
  783. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id.ToString(), new PartitionKey("Base"));
  784. if (teacher.schools == null)
  785. teacher.schools = new List<Teacher.TeacherSchool>();
  786. var school = teacher.schools?.FirstOrDefault(x => x.schoolId.Equals(school_code.GetString(), StringComparison.OrdinalIgnoreCase));
  787. if (school != null)
  788. {
  789. school.status = grant_type.GetString();
  790. school.time = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  791. }
  792. else
  793. teacher.schools.Add(new Teacher.TeacherSchool() { areaId = schareaId, picture = schpic, schoolId = school_code.GetString(), name = schname, time = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), status = grant_type.GetString() });
  794. var dft = new List<string>() { "content-read", "exercise-read", "knowledge-read", "syllabus-read" };
  795. if (teacher.schools.Count > 0 && teacher.size <= 1)
  796. {
  797. teacher.size = 2;
  798. }
  799. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, id.ToString(), new PartitionKey("Base"));
  800. //在學校表處理該學校教師帳號的狀態
  801. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Teacher-{school_code}"));
  802. if (sresponse.Status == 200)
  803. {
  804. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  805. SchoolTeacher steacher = json.ToObject<SchoolTeacher>();
  806. steacher.status = grant_type.GetString();
  807. if (grant_type.ToString().Equals("join"))
  808. {
  809. if (steacher.permissions.IsNotEmpty())
  810. {
  811. foreach (var d in dft)
  812. {
  813. if (!steacher.permissions.Contains(d))
  814. {
  815. steacher.permissions.Add(d);
  816. }
  817. }
  818. }
  819. else
  820. {
  821. steacher.permissions = dft;
  822. }
  823. }
  824. var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(steacher, id.GetString(), new PartitionKey($"Teacher-{school_code}"));
  825. }
  826. else
  827. {
  828. SchoolTeacher st = new SchoolTeacher()
  829. {
  830. pk = "Teacher",
  831. code = $"Teacher-{school_code}",
  832. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  833. id = teacher.id,
  834. name = teacher.name,
  835. picture = teacher.picture,
  836. roles = new List<string>(new string[] { "teacher" }),
  837. /// 只是申请加入就需要开放 这几个权限吗
  838. permissions = grant_type.GetString().Equals("join") ? dft : null,
  839. size = 0,
  840. status = grant_type.GetString()
  841. };
  842. var response = await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(st, new PartitionKey($"Teacher-{school_code}"));
  843. }
  844. if (grant_type.ToString().Equals("join"))
  845. {
  846. await TmdUserService.JoinSchool(client, $"{teacher.id}", $"{teacher.picture}", $"{teacher.name}", $"{school_code}", $"{schname}");
  847. }
  848. string bizcode = grant_type.GetString();
  849. if (grant_type.GetString().Equals("join"))
  850. {
  851. bizcode = "request-join";
  852. if (!string.IsNullOrWhiteSpace($"{_importName}"))
  853. {
  854. Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync($"{school_code}", new PartitionKey("TeacherImport"));
  855. TeacherImport teacherImport = null;
  856. if (response.Status == 200)
  857. {
  858. teacherImport = JsonDocument.Parse(response.Content).RootElement.Deserialize<TeacherImport>();
  859. var tchs = teacherImport.teachers.FindAll(x => x.iname.Equals($"{_importName}") && string.IsNullOrWhiteSpace(x.id));
  860. if (tchs.IsNotEmpty())
  861. {
  862. var tch = tchs[0];
  863. string ujson = null;
  864. var content = new StringContent(new List<string> { $"{id}" }.ToJsonString(), Encoding.UTF8, "application/json");
  865. ujson = await _coreAPIHttpService.GetUserInfos(content);
  866. List<CoreUser> coreUsers = new List<CoreUser>();
  867. if (!string.IsNullOrWhiteSpace(ujson))
  868. {
  869. coreUsers = ujson.ToObject<List<CoreUser>>();
  870. }
  871. if (coreUsers.IsNotEmpty())
  872. {
  873. tch.phone = coreUsers[0].mobile;
  874. tch.email = coreUsers[0].mail;
  875. }
  876. tch.id = $"{teacher.id}";
  877. tch.picture = $"{teacher.picture}";
  878. tch.status = $"{grant_type}";
  879. tch.time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  880. tch.tmdid = teacher.id;
  881. tch.name = teacher.name;
  882. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(teacherImport, $"{school_code}", new PartitionKey("TeacherImport"));
  883. }
  884. }
  885. }
  886. }
  887. Notification notification = new Notification
  888. {
  889. hubName = "hita",
  890. type = "msg",
  891. from = $"ies5:{_option.Location}:private",
  892. to = new List<string> { teacher.id },
  893. label = $"{bizcode}_school",
  894. body = new { location = _option.Location, biz = bizcode, tmdid = tid, tmdname = tname, schoolcode = $"{school_code}", schoolname = $"{schname}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  895. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  896. };
  897. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  898. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  899. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  900. var location = _option.Location;
  901. var code = await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);
  902. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name=teacher.name, code= teacher.lang} }, $"{bizcode}_school", Constant.NotifyType_IES5_Management,
  903. new Dictionary<string, object> { { "tmdname", tname }, { "schoolName", schname }, { "schoolId", $"{school_code}" }, { "tmdid", tid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  904. return Ok(new { });
  905. }
  906. catch (Exception ex)
  907. {
  908. return BadRequest();
  909. }
  910. }
  911. /// <summary>
  912. /// 學校移除老師跟學校關聯
  913. /// </summary>
  914. /// <param name="request"></param>
  915. /// <returns></returns>
  916. [ProducesDefaultResponseType]
  917. //[AuthToken(Roles = "admin")]
  918. [HttpPost("rmv-teacher")]
  919. [Authorize(Roles = "IES")]
  920. public async Task<IActionResult> RmvSchoolTeacher(JsonElement request)
  921. {
  922. if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  923. try
  924. {
  925. var (tid, tname, _, tschool) = HttpContext.GetAuthTokenInfo();
  926. request.TryGetProperty("id", out JsonElement id);
  927. request.TryGetProperty("name", out JsonElement name);
  928. var client = _azureCosmos.GetCosmosClient();
  929. //在老師表找出老師,刪除該學校 (老師基本資料應該要存在)
  930. Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync($"{school_code}", new PartitionKey("TeacherImport"));
  931. TeacherImport teacherImport = null;
  932. if (response.Status == 200)
  933. {
  934. teacherImport = JsonDocument.Parse(response.Content).RootElement.Deserialize<TeacherImport>();
  935. }
  936. if (!string.IsNullOrWhiteSpace($"{name}") && teacherImport != null)
  937. {
  938. //移除同名的、其中一个
  939. var ts = teacherImport.teachers.FindAll(x => string.IsNullOrWhiteSpace(x.id) && !string.IsNullOrWhiteSpace(x.iname) && x.iname.Equals($"{name}"));
  940. if (ts.IsNotEmpty())
  941. {
  942. teacherImport.teachers.Remove(ts.First());
  943. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(teacherImport, $"{school_code}", new PartitionKey("TeacherImport"));
  944. }
  945. }
  946. if (!string.IsNullOrWhiteSpace($"{id}"))
  947. {
  948. if (teacherImport != null)
  949. {
  950. int count = teacherImport.teachers.RemoveAll(x => !string.IsNullOrWhiteSpace(x.id) && x.id.Equals($"{id}"));
  951. if (count > 0)
  952. {
  953. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(teacherImport, $"{school_code}", new PartitionKey("TeacherImport"));
  954. }
  955. }
  956. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id.ToString(), new PartitionKey("Base"));
  957. //教师还未加入,就被移除,则不通知。
  958. bool needNotify = false;
  959. var sc= teacher.schools.FindAll(x => x.schoolId.Equals($"{school_code}"));
  960. if (sc.IsNotEmpty()) {
  961. sc.ForEach(z => {
  962. if (z.status.Equals("join")) {
  963. needNotify = true;
  964. }
  965. });
  966. }
  967. var school = teacher.schools.RemoveAll(x => x.schoolId.Equals(school_code.GetString(), StringComparison.OrdinalIgnoreCase));
  968. if (!string.IsNullOrEmpty(teacher.defaultSchool) && teacher.defaultSchool.Equals($"{school_code}"))
  969. {
  970. if (teacher.schools.IsNotEmpty())
  971. {
  972. teacher.defaultSchool = teacher.schools[0].schoolId;
  973. }
  974. else
  975. {
  976. teacher.defaultSchool = null;
  977. }
  978. }
  979. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, id.ToString(), new PartitionKey("Base"));
  980. //移除學校表中的老師document
  981. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemStreamAsync(id.GetString(), new PartitionKey($"Teacher-{school_code}"));
  982. //将教师移除学校,同时也移除研修名单,教研组。
  983. StringBuilder queryText = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain' or c.type='research' ");
  984. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: queryText.ToString(),
  985. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school_code.GetString()}") }))
  986. {
  987. bool exists = item.members.Exists(x => x.id.Equals(id.ToString()));
  988. if (exists)
  989. {
  990. item.members.RemoveAll(x => x.id.Equals(id.ToString()));
  991. await GroupListService.UpsertList(item, _azureCosmos, _configuration, _azureServiceBus);
  992. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(item,item.id,new PartitionKey(item.code));
  993. }
  994. }
  995. //await TmdUserService.LeaveSchool(client, $"{teacher.id}", $"{school_code}" );
  996. //取得學校資訊
  997. var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey("Base"));
  998. string schname = string.Empty;
  999. if (schresponse.Status == 200)
  1000. {
  1001. using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
  1002. schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
  1003. schname = jsonschname.ToString();
  1004. }
  1005. else
  1006. {
  1007. return BadRequest();
  1008. }
  1009. Notification notification = new Notification
  1010. {
  1011. hubName = "hita",
  1012. type = "msg",
  1013. from = $"ies5:{_option.Location}:private",
  1014. to = new List<string> { teacher.id },
  1015. label = $"remove_school",
  1016. body = new { location = _option.Location, biz = "remove", tmdid = tid, tmdname = tname, schoolcode = $"{school_code}", schoolname = $"{schname}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  1017. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1018. };
  1019. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1020. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1021. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1022. var location = _option.Location;
  1023. var code = await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);
  1024. if (needNotify) {
  1025. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, $"remove_school", Constant.NotifyType_IES5_Management,
  1026. new Dictionary<string, object> { { "tmdname", tname }, { "schoolName", schname }, { "schoolId", $"{school_code}" }, { "tmdid", tid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  1027. }
  1028. }
  1029. return Ok(new { });
  1030. }
  1031. catch (Exception ex)
  1032. {
  1033. return BadRequest();
  1034. }
  1035. finally {
  1036. Azure.Response schoolRes = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{school_code}", new PartitionKey("Base"));
  1037. if (schoolRes.Status==200)
  1038. {
  1039. School school = JsonDocument.Parse(schoolRes.Content).RootElement.Deserialize<School>();
  1040. string sql = "select value sum(c.size ) from c ";
  1041. int teachSize = 0;
  1042. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<int>(queryText: sql,
  1043. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school_code}") }))
  1044. {
  1045. teachSize += item;
  1046. }
  1047. school.tsize = teachSize;
  1048. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, school.id, new PartitionKey("Base"));
  1049. }
  1050. }
  1051. }
  1052. /// <summary>
  1053. /// 取得CoreID資訊
  1054. /// </summary>
  1055. /// <param name="request"></param>
  1056. /// <returns></returns>
  1057. [ProducesDefaultResponseType]
  1058. //[AuthToken(Roles = "admin")]
  1059. [HttpPost("get-coreuser")]
  1060. [Authorize(Roles = "IES")]
  1061. public async Task<IActionResult> GetUserFromCoreID(JsonElement request)
  1062. {
  1063. var content = new StringContent(request.ToString(), Encoding.UTF8, "application/json");
  1064. string json = await _coreAPIHttpService.GetUserInfos(content);
  1065. return Ok(json.ToObject<JsonElement>());
  1066. }
  1067. }
  1068. }