SchoolTeacherController.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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. if (permission.IsNotEmpty())
  509. {
  510. st.permissions = permission;
  511. }
  512. if (addPm.IsNotEmpty())
  513. {
  514. st.permissions.AddRange(addPm);
  515. }
  516. if (rmvPm.IsNotEmpty())
  517. {
  518. st.permissions.RemoveAll(x => rmvPm.Contains(x));
  519. }
  520. if (hasjob)
  521. {
  522. st.job = $"{_job}";
  523. }
  524. //清除权限标记。
  525. if (_pmClean.ValueKind.Equals(JsonValueKind.True)) {
  526. st.permissions = new List<string>();
  527. }
  528. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(st, id, new PartitionKey($"Teacher-{school_code}"));
  529. schoolTeachers.Add(st);
  530. }
  531. return Ok(new { teachers = schoolTeachers });
  532. }
  533. catch (Exception)
  534. {
  535. return BadRequest();
  536. }
  537. }
  538. /// <summary>
  539. /// 追加老師及學校加入狀態
  540. /// </summary>
  541. /// <param name="request"></param>
  542. /// <returns></returns>
  543. [ProducesDefaultResponseType]
  544. [HttpPost("add-teacher-status")]
  545. [Authorize(Roles = "IES")]
  546. [AuthToken(Roles = "teacher,admin")]
  547. public async Task<IActionResult> AddSchoolTeacher(JsonElement request)
  548. {
  549. var (tid, tname, _, tschool) = HttpContext.GetAuthTokenInfo();
  550. var client = _azureCosmos.GetCosmosClient();
  551. //參數取得
  552. if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  553. if (!request.TryGetProperty("user_list", out JsonElement user_list)) return BadRequest();
  554. if (!request.TryGetProperty("grant_type", out JsonElement grant_type)) return BadRequest();
  555. //取得學校資訊
  556. var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey("Base"));
  557. string schname = string.Empty;
  558. string schareaId = string.Empty;
  559. string schpic = string.Empty;
  560. if (schresponse.Status == 200)
  561. {
  562. using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
  563. schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
  564. schname = jsonschname.ToString();
  565. schjson.RootElement.TryGetProperty("areaId", out JsonElement areaId);
  566. schareaId = $"{areaId}";
  567. schjson.RootElement.TryGetProperty("picture", out JsonElement picture);
  568. schpic = $"{picture}";
  569. }
  570. else
  571. {
  572. return BadRequest();
  573. }
  574. try
  575. {
  576. List<KeyValuePair<string, int>> keys = new List<KeyValuePair<string, int>>();
  577. List<IdNameCode> ids = new List<IdNameCode>();
  578. foreach (var obj in user_list.EnumerateArray())
  579. {
  580. obj.TryGetProperty("id", out JsonElement id);
  581. obj.TryGetProperty("name", out JsonElement name);
  582. obj.TryGetProperty("picture", out JsonElement picture);
  583. IdNameCode tmd = new IdNameCode { id = $"{id}", name = $"{name}" };
  584. ids.Add(tmd);
  585. //老師個人資料
  586. var tresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(id.ToString(), new PartitionKey("Base"));
  587. if (tresponse.Status == 200)
  588. {
  589. using var json = await JsonDocument.ParseAsync(tresponse.ContentStream);
  590. Teacher teacher = json.ToObject<Teacher>();
  591. tmd.code = teacher.lang;
  592. var school = teacher.schools.FirstOrDefault(x => x.schoolId.Equals(school_code.GetString(), StringComparison.OrdinalIgnoreCase));
  593. if (school != null)
  594. {
  595. school.time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  596. if (school.status.Equals("invite") && grant_type.ToString().Equals("invite"))
  597. {
  598. keys.Add(new KeyValuePair<string, int>($"{id}", 1));
  599. //移除不能发送通知的部分
  600. ids.Remove(tmd);
  601. continue;
  602. }
  603. if (school.status.Equals("join") && grant_type.ToString().Equals("invite"))
  604. {
  605. keys.Add(new KeyValuePair<string, int>($"{id}", 2));
  606. //移除不能发送通知的部分
  607. ids.Remove(tmd);
  608. continue;
  609. }
  610. school.status = grant_type.GetString();
  611. }
  612. else
  613. teacher.schools.Add(new Teacher.TeacherSchool() { areaId = schareaId, picture = schpic, schoolId = school_code.GetString(), name = schname, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), status = grant_type.GetString() });
  614. if (teacher.schools.Count > 0 && teacher.size <= 1)
  615. {
  616. teacher.size = 2;
  617. }
  618. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, id.ToString(), new PartitionKey("Base"));
  619. }
  620. else
  621. {
  622. using var stream = new MemoryStream();
  623. using var writer = new Utf8JsonWriter(stream);
  624. writer.WriteStartObject();
  625. writer.WriteString("pk", "Base");
  626. writer.WriteString("code", "Base");
  627. writer.WriteString("id", id.ToString());
  628. writer.WriteString("name", name.ToString());
  629. writer.WriteString("picture", picture.ToString());
  630. writer.WriteNumber("size", 1);
  631. writer.WriteString("groupId", "default");
  632. writer.WriteString("groupName", "默认组别");
  633. writer.WriteNull("defaultSchool");
  634. writer.WriteStartArray("schools");
  635. writer.WriteStartObject();
  636. writer.WriteString("schoolId", school_code.ToString());
  637. writer.WriteString("name", schname);
  638. writer.WriteString("status", grant_type.ToString());
  639. writer.WriteEndObject();
  640. writer.WriteEndArray();
  641. writer.WriteEndObject();
  642. writer.Flush();
  643. await client.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemStreamAsync(stream, new PartitionKey("Base"));
  644. }
  645. //學校老師資料
  646. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Teacher-{school_code}"));
  647. //SchoolTeacher schteacher = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolTeacher>(id.ToString(), new PartitionKey($"Teacher-{school_code}"));
  648. if (sresponse.Status == 200)
  649. {
  650. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  651. SchoolTeacher schteacher = json.ToObject<SchoolTeacher>();
  652. if (schteacher.status.Equals("invite") && grant_type.ToString().Equals("invite"))
  653. {
  654. keys.Add(new KeyValuePair<string, int>($"{id}", 1));
  655. continue;
  656. }
  657. if (schteacher.status.Equals("join") && grant_type.ToString().Equals("invite"))
  658. {
  659. keys.Add(new KeyValuePair<string, int>($"{id}", 2));
  660. continue;
  661. }
  662. schteacher.status = grant_type.ToString();
  663. schteacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  664. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(schteacher, id.ToString(), new PartitionKey($"Teacher-{school_code}"));
  665. }
  666. else
  667. {
  668. using var stream = new MemoryStream();
  669. using var writer = new Utf8JsonWriter(stream);
  670. writer.WriteStartObject();
  671. writer.WriteString("pk", "Teacher");
  672. writer.WriteString("code", $"Teacher-{school_code}");
  673. writer.WriteString("id", id.ToString());
  674. writer.WriteString("name", name.ToString());
  675. writer.WriteString("groupId", "default");
  676. writer.WriteString("groupName", "默认组别");
  677. writer.WriteString("picture", picture.ToString());
  678. writer.WriteNull("job");
  679. writer.WriteNumber("size", 0);
  680. writer.WriteStartArray("roles");
  681. writer.WriteStringValue("teacher");
  682. writer.WriteEndArray();
  683. writer.WriteStartArray("permissions");
  684. if (grant_type.ToString().Equals("join"))
  685. {
  686. writer.WriteStringValue("content-read");
  687. writer.WriteStringValue("exercise-read");
  688. writer.WriteStringValue("knowledge-read");
  689. writer.WriteStringValue("syllabus-read");
  690. }
  691. writer.WriteEndArray();
  692. writer.WriteString("status", grant_type.ToString());
  693. writer.WriteNumber("createTime", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
  694. writer.WriteEndObject();
  695. writer.Flush();
  696. await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemStreamAsync(stream, new PartitionKey($"Teacher-{school_code}"));
  697. }
  698. if (grant_type.ToString().Equals("join"))
  699. {
  700. await TmdUserService.JoinSchool(client, $"{id}", $"{picture}", $"{name}", $"{school_code}", $"{schname}");
  701. }
  702. }
  703. string bizcode = grant_type.GetString();
  704. if (grant_type.GetString().Equals("join"))
  705. {
  706. bizcode = "request-join";
  707. }
  708. Notification notification = new Notification
  709. {
  710. hubName = "hita",
  711. type = "msg",
  712. from = $"ies5:{_option.Location}:private",
  713. to = ids.Select(x => x.id).ToList(),
  714. label = $"{bizcode}_school",
  715. body = new {
  716. location = _option.Location,
  717. biz = bizcode,
  718. tmdid = tid,
  719. tmdname = tname.ToString(),
  720. schoolcode = $"{school_code}",
  721. schoolname = $"{schname}",
  722. status = 1,
  723. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  724. }.ToJsonString(),
  725. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  726. };
  727. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  728. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  729. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  730. var location = _option.Location;
  731. var code = await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);
  732. _coreAPIHttpService.PushNotify(ids, $"{bizcode}_school", Constant.NotifyType_IES5_Management,
  733. new Dictionary<string, object> { { "tmdname", tname }, { "schoolName", schname }, { "schoolId", $"{school_code}" } , { "tmdid",tid} }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  734. return Ok(new { exist = keys });
  735. }
  736. catch (Exception ex)
  737. {
  738. return BadRequest();
  739. }
  740. }
  741. /// <summary>
  742. /// 學校變更老師加入狀態
  743. /// </summary>
  744. /// <param name="request"></param>
  745. /// <returns></returns>
  746. [ProducesDefaultResponseType]
  747. [AuthToken(Roles = "admin", Permissions = "schoolSetting-upd,auth-upd,schoolAc-upd,teacher-upd")]
  748. [HttpPost("upd-teacher-status")]
  749. [Authorize(Roles = "IES")]
  750. public async Task<IActionResult> UpdSchoolTeacherStatus(JsonElement request)
  751. {
  752. try
  753. {
  754. var (tid, tname, _, tschool) = HttpContext.GetAuthTokenInfo();
  755. if (!request.TryGetProperty("grant_type", out JsonElement grant_type)) return BadRequest();
  756. if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  757. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  758. request.TryGetProperty("importName", out JsonElement _importName);
  759. var client = _azureCosmos.GetCosmosClient();
  760. //取得學校資訊
  761. var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey("Base"));
  762. string schname = string.Empty;
  763. string schareaId = string.Empty;
  764. string schpic = string.Empty;
  765. if (schresponse.Status == 200)
  766. {
  767. using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
  768. schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
  769. schname = jsonschname.ToString();
  770. schjson.RootElement.TryGetProperty("areaId", out JsonElement areaId);
  771. schareaId = $"{areaId}";
  772. schjson.RootElement.TryGetProperty("picture", out JsonElement picture);
  773. schpic = $"{picture}";
  774. }
  775. else
  776. {
  777. return BadRequest();
  778. }
  779. //在老師表找出老師,處理該學校狀態 (老師基本資料應該要存在)
  780. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id.ToString(), new PartitionKey("Base"));
  781. if (teacher.schools == null)
  782. teacher.schools = new List<Teacher.TeacherSchool>();
  783. var school = teacher.schools?.FirstOrDefault(x => x.schoolId.Equals(school_code.GetString(), StringComparison.OrdinalIgnoreCase));
  784. if (school != null)
  785. {
  786. school.status = grant_type.GetString();
  787. school.time = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  788. }
  789. else
  790. teacher.schools.Add(new Teacher.TeacherSchool() { areaId = schareaId, picture = schpic, schoolId = school_code.GetString(), name = schname, time = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), status = grant_type.GetString() });
  791. var dft = new List<string>() { "content-read", "exercise-read", "knowledge-read", "syllabus-read" };
  792. if (teacher.schools.Count > 0 && teacher.size <= 1)
  793. {
  794. teacher.size = 2;
  795. }
  796. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, id.ToString(), new PartitionKey("Base"));
  797. //在學校表處理該學校教師帳號的狀態
  798. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Teacher-{school_code}"));
  799. if (sresponse.Status == 200)
  800. {
  801. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  802. SchoolTeacher steacher = json.ToObject<SchoolTeacher>();
  803. steacher.status = grant_type.GetString();
  804. if (grant_type.ToString().Equals("join"))
  805. {
  806. if (steacher.permissions.IsNotEmpty())
  807. {
  808. foreach (var d in dft)
  809. {
  810. if (!steacher.permissions.Contains(d))
  811. {
  812. steacher.permissions.Add(d);
  813. }
  814. }
  815. }
  816. else
  817. {
  818. steacher.permissions = dft;
  819. }
  820. }
  821. var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(steacher, id.GetString(), new PartitionKey($"Teacher-{school_code}"));
  822. }
  823. else
  824. {
  825. SchoolTeacher st = new SchoolTeacher()
  826. {
  827. pk = "Teacher",
  828. code = $"Teacher-{school_code}",
  829. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  830. id = teacher.id,
  831. name = teacher.name,
  832. picture = teacher.picture,
  833. roles = new List<string>(new string[] { "teacher" }),
  834. /// 只是申请加入就需要开放 这几个权限吗
  835. permissions = grant_type.GetString().Equals("join") ? dft : null,
  836. size = 0,
  837. status = grant_type.GetString()
  838. };
  839. var response = await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(st, new PartitionKey($"Teacher-{school_code}"));
  840. }
  841. if (grant_type.ToString().Equals("join"))
  842. {
  843. await TmdUserService.JoinSchool(client, $"{teacher.id}", $"{teacher.picture}", $"{teacher.name}", $"{school_code}", $"{schname}");
  844. }
  845. string bizcode = grant_type.GetString();
  846. if (grant_type.GetString().Equals("join"))
  847. {
  848. bizcode = "request-join";
  849. if (!string.IsNullOrWhiteSpace($"{_importName}"))
  850. {
  851. Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync($"{school_code}", new PartitionKey("TeacherImport"));
  852. TeacherImport teacherImport = null;
  853. if (response.Status == 200)
  854. {
  855. teacherImport = JsonDocument.Parse(response.Content).RootElement.Deserialize<TeacherImport>();
  856. var tchs = teacherImport.teachers.FindAll(x => x.iname.Equals($"{_importName}") && string.IsNullOrWhiteSpace(x.id));
  857. if (tchs.IsNotEmpty())
  858. {
  859. var tch = tchs[0];
  860. string ujson = null;
  861. var content = new StringContent(new List<string> { $"{id}" }.ToJsonString(), Encoding.UTF8, "application/json");
  862. ujson = await _coreAPIHttpService.GetUserInfos(content);
  863. List<CoreUser> coreUsers = new List<CoreUser>();
  864. if (!string.IsNullOrWhiteSpace(ujson))
  865. {
  866. coreUsers = ujson.ToObject<List<CoreUser>>();
  867. }
  868. if (coreUsers.IsNotEmpty())
  869. {
  870. tch.phone = coreUsers[0].mobile;
  871. tch.email = coreUsers[0].mail;
  872. }
  873. tch.id = $"{teacher.id}";
  874. tch.picture = $"{teacher.picture}";
  875. tch.status = $"{grant_type}";
  876. tch.time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  877. tch.tmdid = teacher.id;
  878. tch.name = teacher.name;
  879. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(teacherImport, $"{school_code}", new PartitionKey("TeacherImport"));
  880. }
  881. }
  882. }
  883. }
  884. Notification notification = new Notification
  885. {
  886. hubName = "hita",
  887. type = "msg",
  888. from = $"ies5:{_option.Location}:private",
  889. to = new List<string> { teacher.id },
  890. label = $"{bizcode}_school",
  891. body = new { location = _option.Location, biz = bizcode, tmdid = tid, tmdname = tname, schoolcode = $"{school_code}", schoolname = $"{schname}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  892. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  893. };
  894. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  895. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  896. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  897. var location = _option.Location;
  898. var code = await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);
  899. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name=teacher.name, code= teacher.lang} }, $"{bizcode}_school", Constant.NotifyType_IES5_Management,
  900. new Dictionary<string, object> { { "tmdname", tname }, { "schoolName", schname }, { "schoolId", $"{school_code}" }, { "tmdid", tid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  901. return Ok(new { });
  902. }
  903. catch (Exception ex)
  904. {
  905. return BadRequest();
  906. }
  907. }
  908. /// <summary>
  909. /// 學校移除老師跟學校關聯
  910. /// </summary>
  911. /// <param name="request"></param>
  912. /// <returns></returns>
  913. [ProducesDefaultResponseType]
  914. //[AuthToken(Roles = "admin")]
  915. [HttpPost("rmv-teacher")]
  916. [Authorize(Roles = "IES")]
  917. public async Task<IActionResult> RmvSchoolTeacher(JsonElement request)
  918. {
  919. if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  920. try
  921. {
  922. var (tid, tname, _, tschool) = HttpContext.GetAuthTokenInfo();
  923. request.TryGetProperty("id", out JsonElement id);
  924. request.TryGetProperty("name", out JsonElement name);
  925. var client = _azureCosmos.GetCosmosClient();
  926. //在老師表找出老師,刪除該學校 (老師基本資料應該要存在)
  927. Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync($"{school_code}", new PartitionKey("TeacherImport"));
  928. TeacherImport teacherImport = null;
  929. if (response.Status == 200)
  930. {
  931. teacherImport = JsonDocument.Parse(response.Content).RootElement.Deserialize<TeacherImport>();
  932. }
  933. if (!string.IsNullOrWhiteSpace($"{name}") && teacherImport != null)
  934. {
  935. //移除同名的、其中一个
  936. var ts = teacherImport.teachers.FindAll(x => string.IsNullOrWhiteSpace(x.id) && !string.IsNullOrWhiteSpace(x.iname) && x.iname.Equals($"{name}"));
  937. if (ts.IsNotEmpty())
  938. {
  939. teacherImport.teachers.Remove(ts.First());
  940. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(teacherImport, $"{school_code}", new PartitionKey("TeacherImport"));
  941. }
  942. }
  943. if (!string.IsNullOrWhiteSpace($"{id}"))
  944. {
  945. if (teacherImport != null)
  946. {
  947. int count = teacherImport.teachers.RemoveAll(x => !string.IsNullOrWhiteSpace(x.id) && x.id.Equals($"{id}"));
  948. if (count > 0)
  949. {
  950. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(teacherImport, $"{school_code}", new PartitionKey("TeacherImport"));
  951. }
  952. }
  953. Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id.ToString(), new PartitionKey("Base"));
  954. //教师还未加入,就被移除,则不通知。
  955. bool needNotify = false;
  956. var sc= teacher.schools.FindAll(x => x.schoolId.Equals($"{school_code}"));
  957. if (sc.IsNotEmpty()) {
  958. sc.ForEach(z => {
  959. if (z.status.Equals("join")) {
  960. needNotify = true;
  961. }
  962. });
  963. }
  964. var school = teacher.schools.RemoveAll(x => x.schoolId.Equals(school_code.GetString(), StringComparison.OrdinalIgnoreCase));
  965. if (!string.IsNullOrEmpty(teacher.defaultSchool) && teacher.defaultSchool.Equals($"{school_code}"))
  966. {
  967. if (teacher.schools.IsNotEmpty())
  968. {
  969. teacher.defaultSchool = teacher.schools[0].schoolId;
  970. }
  971. else
  972. {
  973. teacher.defaultSchool = null;
  974. }
  975. }
  976. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, id.ToString(), new PartitionKey("Base"));
  977. //移除學校表中的老師document
  978. var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemStreamAsync(id.GetString(), new PartitionKey($"Teacher-{school_code}"));
  979. //将教师移除学校,同时也移除研修名单,教研组。
  980. StringBuilder queryText = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain' or c.type='research' ");
  981. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: queryText.ToString(),
  982. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school_code.GetString()}") }))
  983. {
  984. bool exists = item.members.Exists(x => x.id.Equals(id.ToString()));
  985. if (exists)
  986. {
  987. item.members.RemoveAll(x => x.id.Equals(id.ToString()));
  988. await GroupListService.UpsertList(item, _azureCosmos, _configuration, _azureServiceBus);
  989. //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(item,item.id,new PartitionKey(item.code));
  990. }
  991. }
  992. //await TmdUserService.LeaveSchool(client, $"{teacher.id}", $"{school_code}" );
  993. //取得學校資訊
  994. var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey("Base"));
  995. string schname = string.Empty;
  996. if (schresponse.Status == 200)
  997. {
  998. using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
  999. schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
  1000. schname = jsonschname.ToString();
  1001. }
  1002. else
  1003. {
  1004. return BadRequest();
  1005. }
  1006. Notification notification = new Notification
  1007. {
  1008. hubName = "hita",
  1009. type = "msg",
  1010. from = $"ies5:{_option.Location}:private",
  1011. to = new List<string> { teacher.id },
  1012. label = $"remove_school",
  1013. body = new { location = _option.Location, biz = "remove", tmdid = tid, tmdname = tname, schoolcode = $"{school_code}", schoolname = $"{schname}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  1014. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1015. };
  1016. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1017. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1018. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1019. var location = _option.Location;
  1020. var code = await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);
  1021. if (needNotify) {
  1022. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, $"remove_school", Constant.NotifyType_IES5_Management,
  1023. new Dictionary<string, object> { { "tmdname", tname }, { "schoolName", schname }, { "schoolId", $"{school_code}" }, { "tmdid", tid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  1024. }
  1025. }
  1026. return Ok(new { });
  1027. }
  1028. catch (Exception ex)
  1029. {
  1030. return BadRequest();
  1031. }
  1032. finally {
  1033. Azure.Response schoolRes = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{school_code}", new PartitionKey("Base"));
  1034. if (schoolRes.Status==200)
  1035. {
  1036. School school = JsonDocument.Parse(schoolRes.Content).RootElement.Deserialize<School>();
  1037. string sql = "select value sum(c.size ) from c ";
  1038. int teachSize = 0;
  1039. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<int>(queryText: sql,
  1040. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school_code}") }))
  1041. {
  1042. teachSize += item;
  1043. }
  1044. school.tsize = teachSize;
  1045. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, school.id, new PartitionKey("Base"));
  1046. }
  1047. }
  1048. }
  1049. /// <summary>
  1050. /// 取得CoreID資訊
  1051. /// </summary>
  1052. /// <param name="request"></param>
  1053. /// <returns></returns>
  1054. [ProducesDefaultResponseType]
  1055. //[AuthToken(Roles = "admin")]
  1056. [HttpPost("get-coreuser")]
  1057. [Authorize(Roles = "IES")]
  1058. public async Task<IActionResult> GetUserFromCoreID(JsonElement request)
  1059. {
  1060. var content = new StringContent(request.ToString(), Encoding.UTF8, "application/json");
  1061. string json = await _coreAPIHttpService.GetUserInfos(content);
  1062. return Ok(json.ToObject<JsonElement>());
  1063. }
  1064. }
  1065. }