AreaRelevantController.cs 15 KB

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