AreaRelevantController.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. using Azure.Cosmos;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.Options;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text.Json;
  10. using System.Threading.Tasks;
  11. using TEAMModelBI.DI.BIAzureStorage;
  12. using TEAMModelBI.Filter;
  13. using TEAMModelBI.Models;
  14. using TEAMModelBI.Tool.Extension;
  15. using TEAMModelOS.Models;
  16. using TEAMModelOS.SDK;
  17. using TEAMModelOS.SDK.Context.BI;
  18. using TEAMModelOS.SDK.Context.Constant;
  19. using TEAMModelOS.SDK.DI;
  20. using TEAMModelOS.SDK.Extension;
  21. using TEAMModelOS.SDK.Models;
  22. using TEAMModelOS.SDK.Models.Cosmos.BI;
  23. namespace TEAMModelBI.Controllers.BISchool
  24. {
  25. [Route("area")]
  26. [ApiController]
  27. public class AreaRelevantController : ControllerBase
  28. {
  29. //数据容器
  30. private readonly AzureCosmosFactory _azureCosmos;
  31. private readonly AzureStorageFactory _azureStorage;
  32. //钉钉提示信息
  33. private readonly DingDing _dingDing;
  34. private readonly Option _option;
  35. private readonly IConfiguration _configuration;
  36. private readonly CoreAPIHttpService _coreAPIHttpService;
  37. public AreaRelevantController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration, CoreAPIHttpService coreAPIHttpService)
  38. {
  39. _azureCosmos = azureCosmos;
  40. _azureStorage = azureStorage;
  41. _dingDing = dingDing;
  42. _option = option?.Value;
  43. }
  44. /// <summary>
  45. /// 查询区域已经有的学校
  46. /// </summary>
  47. /// <param name="jsonElement"></param>
  48. /// <returns></returns>
  49. [ProducesDefaultResponseType]
  50. [HttpPost("get-areaschools")]
  51. public async Task<IActionResult> GetAreaSchools(JsonElement jsonElement)
  52. {
  53. try
  54. {
  55. jsonElement.TryGetProperty("areaId", out JsonElement _areaId);
  56. jsonElement.TryGetProperty("isDefault", out JsonElement _isDefalue);
  57. jsonElement.TryGetProperty("site", out JsonElement site);
  58. var cosmosClient = _azureCosmos.GetCosmosClient();
  59. if ($"{site}".Equals(BIConst.Global))
  60. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  61. var isManyArea = false;
  62. if (!string.IsNullOrEmpty($"{_isDefalue}"))
  63. {
  64. isManyArea = true;
  65. }
  66. List<JoinAreaSchool> joinAreaSchools = new();
  67. string sqltxt = $"SELECT c.id,c.name,c.schoolCode,c.province,c.city,c.dist,c.picture,c.period,c.areaId,c.standard,c.manyAreas FROM c WHERE c.areaId='{_areaId}'";
  68. if (isManyArea)
  69. {
  70. sqltxt = $"SELECT c.id,c.name,c.schoolCode,c.province,c.city,c.dist,c.picture,c.period,c.areaId,c.standard,c.manyAreas FROM c join m in c.manyAreas WHERE c.areaId ='{_areaId}' or m.areaId='{_areaId}'";
  71. //sqltxt = $"SELECT c.id,c.name,c.schoolCode,c.province,c.city,c.dist,c.picture,c.period FROM c join m in c.manyAreas where m.areaId='{_areaId}' or c.areaId='{_areaId}'";
  72. }
  73. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: sqltxt, requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("Base")}))
  74. {
  75. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  76. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  77. {
  78. foreach(var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  79. {
  80. JoinAreaSchool joinAreaSchool = new JoinAreaSchool
  81. {
  82. id = obj.GetProperty("id").GetString(),
  83. name = obj.GetProperty("name").GetString(),
  84. schoolCode = obj.GetProperty("schoolCode").GetString(),
  85. province = obj.GetProperty("province").GetString(),
  86. city = obj.GetProperty("city").GetString(),
  87. dist = obj.GetProperty("dist").GetString(),
  88. picture = obj.GetProperty("picture").GetString(),
  89. period = obj.GetProperty("period").ToObject<List<Period>>().Select(x => x.name).ToList(),
  90. areaId = obj.GetProperty("areaId").GetString(),
  91. standard = obj.GetProperty("standard").GetString()
  92. };
  93. try
  94. {
  95. joinAreaSchool.areas = obj.GetProperty("areas").ToObject<List<SchoolArea>>();
  96. }
  97. catch { }
  98. joinAreaSchools.Add(joinAreaSchool);
  99. }
  100. }
  101. }
  102. return Ok(new { state = 200, joinAreaSchools });
  103. }
  104. catch (Exception ex)
  105. {
  106. await _dingDing.SendBotMsg($"BI, {_option.Location} /area/get-areaschools \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  107. return BadRequest();
  108. }
  109. }
  110. /// <summary>
  111. /// 学校移出区域
  112. /// </summary>
  113. /// <param name="jsonElement"></param>
  114. /// <returns></returns>
  115. [ProducesDefaultResponseType]
  116. [AuthToken(Roles = "admin,rdc")]
  117. [HttpPost("set-areashiftschool")]
  118. public async Task<IActionResult> SetAreaShiftSchool(JsonElement jsonElement)
  119. {
  120. try
  121. {
  122. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  123. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  124. jsonElement.TryGetProperty("standard", out JsonElement standard);
  125. jsonElement.TryGetProperty("isDefault", out JsonElement isDefault);
  126. jsonElement.TryGetProperty("site", out JsonElement site);
  127. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  128. var cosmosClient = _azureCosmos.GetCosmosClient();
  129. var tableClient = _azureStorage.GetCloudTableClient();
  130. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  131. if ($"{site}".Equals(BIConst.Global))
  132. {
  133. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  134. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  135. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  136. }
  137. var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{areaId}", new PartitionKey("AreaSetting"));
  138. if (responseSet.Status == 200)
  139. {
  140. using var fileJson = await JsonDocument.ParseAsync(responseSet.ContentStream);
  141. AreaSetting delSet = fileJson.ToObject<AreaSetting>();
  142. if (!string.IsNullOrEmpty(delSet.accessConfig))
  143. return Ok(new { state = 401, msg = "区域已经规定了,不能切换能能力" });
  144. }
  145. School tempSchool = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base"));
  146. if (bool.Parse($"{isDefault}") == true)
  147. {
  148. tempSchool.areaId = null;
  149. tempSchool.standard = null;
  150. List<Teacher> teachers = new();
  151. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Teacher>(queryText: $"SELECT value(c) FROM c join s in c.schools where s.schoolId ='{schoolId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  152. {
  153. teachers.Add(item);
  154. }
  155. foreach (var item in teachers)
  156. {
  157. var tchSchool = item.schools.Find(f => f.schoolId.Equals($"{schoolId}") && f.areaId.Equals($"{areaId}"));
  158. if (tchSchool != null)
  159. {
  160. item.schools.Remove(tchSchool);
  161. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(item, item.id, new PartitionKey("Base"));
  162. }
  163. }
  164. }
  165. if (tempSchool.areas != null)
  166. {
  167. if (bool.Parse($"{isDefault}") == true)
  168. {
  169. tempSchool.areaId = "";
  170. tempSchool.standard = "";
  171. }
  172. if (tempSchool.areas != null)
  173. {
  174. if (!string.IsNullOrEmpty($"{areaId}"))
  175. {
  176. var temp = tempSchool.areas.Find(ma => ma.areaId == $"{areaId}");
  177. if (temp != null)
  178. tempSchool.areas.Remove(temp);
  179. }
  180. }
  181. }
  182. School school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(tempSchool, tempSchool.id, new PartitionKey("Base"));
  183. //保存操作记录
  184. //await _azureStorage.SaveBILog("school-update", $"{_tmdName}【{_tmdId}】已操作学校({schoolId})移除该区域", _dingDing, httpContext: HttpContext);
  185. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", $"{_tmdName}【{_tmdId}】已操作学校(ID:{schoolId})移除已区域(ID:{areaId})", _dingDing, httpContext: HttpContext);
  186. return Ok(new { state = 200, school });
  187. }
  188. catch (Exception ex)
  189. {
  190. await _dingDing.SendBotMsg($"BI, {_option.Location} /area/set-areashiftschool \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  191. return BadRequest();
  192. }
  193. }
  194. /// <summary>
  195. /// 设置区级管理员
  196. /// </summary>
  197. /// <param name="jsonElement"></param>
  198. /// <returns></returns>
  199. [ProducesDefaultResponseType]
  200. [AuthToken(Roles = "admin,rdc")]
  201. [HttpPost("set-manage")]
  202. public async Task<IActionResult> SetAreaManage(JsonElement jsonElement)
  203. {
  204. var (_tmdId, _tmdName, _, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  205. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  206. if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
  207. jsonElement.TryGetProperty("tmdPic", out JsonElement tmdPic);
  208. if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
  209. if (!jsonElement.TryGetProperty("areaName", out JsonElement areaName)) return BadRequest();
  210. jsonElement.TryGetProperty("site", out JsonElement site);
  211. var cosmosClient = _azureCosmos.GetCosmosClient();
  212. var tableClient = _azureStorage.GetCloudTableClient();
  213. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  214. if ($"{site}".Equals(BIConst.Global))
  215. {
  216. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  217. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  218. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  219. }
  220. Teacher teacher = null;
  221. var response = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Base"));
  222. if (response.Status == 200)
  223. {
  224. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  225. teacher = json.ToObject<Teacher>();
  226. var existArea = teacher.areas.Find(f => f.areaId.Equals($"{areaId}"));
  227. if (existArea == null)
  228. {
  229. teacher.areas.Add(new Teacher.TeacherArea() { areaId = $"{areaId}", name = $"{areaName}", status = "join" });
  230. teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  231. }
  232. else
  233. return Ok(new { state = RespondCode.Conflict, msg = "该账户已是管理员" });
  234. }
  235. else
  236. {
  237. teacher.id = $"{tmdId}";
  238. teacher.name = $"{tmdName}";
  239. teacher.picture = string.IsNullOrEmpty($"{tmdPic}") ? "" : $"{tmdPic}";
  240. teacher.pk = "Base";
  241. teacher.code = "Base";
  242. teacher.size = 1;
  243. teacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  244. //教师存在,在该教师信息中添加要管理的学校信息
  245. teacher.areas.Add(new Teacher.TeacherArea { areaId = $"{areaId}", name = $"{areaName}", status = "join" });
  246. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  247. }
  248. return Ok(new { state = RespondCode.Ok, teacher });
  249. }
  250. /// <summary>
  251. /// 获取区域的管理员
  252. /// </summary>
  253. /// <param name="jsonElement"></param>
  254. /// <returns></returns>
  255. [ProducesDefaultResponseType]
  256. [HttpPost("get-manage")]
  257. public async Task<IActionResult> GetAreaManages(JsonElement jsonElement)
  258. {
  259. if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
  260. jsonElement.TryGetProperty("site", out JsonElement site);
  261. var cosmosClient = _azureCosmos.GetCosmosClient();
  262. if ($"{site}".Equals(BIConst.Global))
  263. {
  264. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  265. }
  266. List<ManageMember> areaManages = new();
  267. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<ManageMember>(queryText:$"select c.id,c.name,c.picture from c join a in c.areas where a.areaId ='{areaId}' and c.code='Base'",requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("Base")}))
  268. {
  269. areaManages.Add(item);
  270. }
  271. return Ok(new { state = RespondCode.Ok, areaManages });
  272. }
  273. /// <summary>
  274. /// 删除区域管理员
  275. /// </summary>
  276. /// <param name="jsonElement"></param>
  277. /// <returns></returns>
  278. [ProducesDefaultResponseType]
  279. [AuthToken(Roles = "admin,rdc")]
  280. [HttpPost("del-manage")]
  281. public async Task<ActionResult> DelAreaManage(JsonElement jsonElement)
  282. {
  283. if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
  284. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  285. jsonElement.TryGetProperty("site", out JsonElement site);
  286. var cosmosClient = _azureCosmos.GetCosmosClient();
  287. if ($"{site}".Equals(BIConst.Global))
  288. {
  289. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  290. }
  291. Teacher teacher = null;
  292. var response = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Base"));
  293. if (response.Status == 200)
  294. {
  295. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  296. teacher = json.ToObject<Teacher>();
  297. var existArea = teacher.areas.Find(f => f.areaId.Equals($"{areaId}"));
  298. if (existArea != null)
  299. {
  300. teacher.areas.RemoveAll((stt)=>stt.areaId.Equals($"{areaId}"));
  301. teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  302. }
  303. else
  304. return Ok(new { state = RespondCode.NotFound, msg = "该账户不是该区的管理员" });
  305. }
  306. else
  307. return Ok(new { state = RespondCode.NotFound, msg = "未找到该教师信息" });
  308. return Ok(new { state = RespondCode.Ok, teacher });
  309. }
  310. /// <summary>
  311. /// 已加入区域的学校
  312. /// </summary>
  313. public record JoinAreaSchool
  314. {
  315. public string id { get; set; }
  316. public string name { get; set; }
  317. public string schoolCode { get; set; }
  318. public string picture { get; set; }
  319. public string areaId{ get; set; }
  320. public string standard { get; set; }
  321. public List<string> period { get; set; }
  322. public string province { get; set; }
  323. public string city { get; set; }
  324. public string dist { get; set; }
  325. public List<SchoolArea> areas { get; set; } = new List<SchoolArea>();
  326. }
  327. }
  328. }