123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515 |
- using Azure.Cosmos;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelBI.Filter;
- using TEAMModelBI.Models;
- using TEAMModelBI.Tool.Extension;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.Context.BI;
- using TEAMModelOS.SDK.Context.Constant;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos.BI;
- namespace TEAMModelBI.Controllers.BISchool
- {
- [Route("area")]
- [ApiController]
- public class AreaRelevantController : ControllerBase
- {
- //数据容器
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly AzureStorageFactory _azureStorage;
- //钉钉提示信息
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly IConfiguration _configuration;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- public AreaRelevantController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration, CoreAPIHttpService coreAPIHttpService)
- {
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _dingDing = dingDing;
- _option = option?.Value;
- }
- /// <summary>
- /// 查询区域已经有的学校
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-areaschools")]
- public async Task<IActionResult> GetAreaSchools(JsonElement jsonElement)
- {
- try
- {
- jsonElement.TryGetProperty("areaId", out JsonElement _areaId);
- jsonElement.TryGetProperty("isDefault", out JsonElement _isDefalue);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- var isManyArea = false;
- if (!string.IsNullOrEmpty($"{_isDefalue}"))
- {
- isManyArea = true;
- }
- List<JoinAreaSchool> joinAreaSchools = new();
- 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}'";
- if (isManyArea)
- {
- 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}'";
- //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}'";
- }
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: sqltxt, requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("Base")}))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach(var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- JoinAreaSchool joinAreaSchool = new JoinAreaSchool
- {
- id = obj.GetProperty("id").GetString(),
- name = obj.GetProperty("name").GetString(),
- schoolCode = obj.GetProperty("schoolCode").GetString(),
- province = obj.GetProperty("province").GetString(),
- city = obj.GetProperty("city").GetString(),
- dist = obj.GetProperty("dist").GetString(),
- picture = obj.GetProperty("picture").GetString(),
- period = obj.GetProperty("period").ToObject<List<Period>>().Select(x => x.name).ToList(),
- areaId = obj.GetProperty("areaId").GetString(),
- standard = obj.GetProperty("standard").GetString()
- };
- try
- {
- joinAreaSchool.areas = obj.GetProperty("areas").ToObject<List<SchoolArea>>();
- }
- catch { }
- joinAreaSchools.Add(joinAreaSchool);
- }
- }
- }
- return Ok(new { state = 200, joinAreaSchools });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI, {_option.Location} /area/get-areaschools \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 学校移出区域
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("set-areashiftschool")]
- public async Task<IActionResult> SetAreaShiftSchool(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
- jsonElement.TryGetProperty("areaId", out JsonElement areaId);
- jsonElement.TryGetProperty("standard", out JsonElement standard);
- jsonElement.TryGetProperty("isDefault", out JsonElement isDefault);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{areaId}", new PartitionKey("AreaSetting"));
- if (responseSet.Status == 200)
- {
- using var fileJson = await JsonDocument.ParseAsync(responseSet.ContentStream);
- AreaSetting delSet = fileJson.ToObject<AreaSetting>();
- if (!string.IsNullOrEmpty(delSet.accessConfig))
- return Ok(new { state = 401, msg = "区域已经规定了,不能切换能能力" });
- }
- School tempSchool = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base"));
- if (bool.Parse($"{isDefault}") == true)
- {
- tempSchool.areaId = null;
- tempSchool.standard = null;
- List<Teacher> teachers = new();
- 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") }))
- {
- teachers.Add(item);
- }
- foreach (var item in teachers)
- {
- var tchSchool = item.schools.Find(f => f.schoolId.Equals($"{schoolId}") && f.areaId.Equals($"{areaId}"));
- if (tchSchool != null)
- {
- item.schools.Remove(tchSchool);
- await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(item, item.id, new PartitionKey("Base"));
- }
- }
- }
- if (tempSchool.areas != null)
- {
- if (bool.Parse($"{isDefault}") == true)
- {
- tempSchool.areaId = "";
- tempSchool.standard = "";
- }
- if (tempSchool.areas != null)
- {
- if (!string.IsNullOrEmpty($"{areaId}"))
- {
- var temp = tempSchool.areas.Find(ma => ma.areaId == $"{areaId}");
- if (temp != null)
- tempSchool.areas.Remove(temp);
- }
- }
- }
- School school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(tempSchool, tempSchool.id, new PartitionKey("Base"));
- //保存操作记录
- //await _azureStorage.SaveBILog("school-update", $"{_tmdName}【{_tmdId}】已操作学校({schoolId})移除该区域", _dingDing, httpContext: HttpContext);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", $"{_tmdName}【{_tmdId}】已操作学校(ID:{schoolId})移除已区域(ID:{areaId})", _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200, school });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI, {_option.Location} /area/set-areashiftschool \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 设置区级管理员
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("set-manage")]
- public async Task<IActionResult> SetAreaManage(JsonElement jsonElement)
- {
- var (_tmdId, _tmdName, _, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
- if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
- jsonElement.TryGetProperty("tmdPic", out JsonElement tmdPic);
- if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
- if (!jsonElement.TryGetProperty("areaName", out JsonElement areaName)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- Teacher teacher = null;
- var response = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Base"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- teacher = json.ToObject<Teacher>();
- var existArea = teacher.areas.Find(f => f.areaId.Equals($"{areaId}"));
- if (existArea == null)
- {
- teacher.areas.Add(new Teacher.TeacherArea() { areaId = $"{areaId}", name = $"{areaName}", status = "join" });
- teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
- }
- else
- return Ok(new { state = RespondCode.Conflict, msg = "该账户已是管理员" });
- }
- else
- {
- teacher.id = $"{tmdId}";
- teacher.name = $"{tmdName}";
- teacher.picture = string.IsNullOrEmpty($"{tmdPic}") ? "" : $"{tmdPic}";
- teacher.pk = "Base";
- teacher.code = "Base";
- teacher.size = 1;
- teacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- //教师存在,在该教师信息中添加要管理的学校信息
- teacher.areas.Add(new Teacher.TeacherArea { areaId = $"{areaId}", name = $"{areaName}", status = "join" });
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
- }
- return Ok(new { state = RespondCode.Ok, teacher });
- }
- /// <summary>
- /// 获取区域的管理员
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-manage")]
- public async Task<IActionResult> GetAreaManages(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- }
-
- List<BaseInfo> areaManages = new();
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<BaseInfo>(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")}))
- {
- areaManages.Add(item);
- }
- return Ok(new { state = RespondCode.Ok, areaManages });
- }
- /// <summary>
- /// 删除区域管理员
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("del-manage")]
- public async Task<IActionResult> DelAreaManage(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
- if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- }
- Teacher teacher = null;
- var response = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Base"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- teacher = json.ToObject<Teacher>();
- var existArea = teacher.areas.Find(f => f.areaId.Equals($"{areaId}"));
- if (existArea != null)
- {
- teacher.areas.RemoveAll((stt)=>stt.areaId.Equals($"{areaId}"));
- teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
- }
- else
- return Ok(new { state = RespondCode.NotFound, msg = "该账户不是该区的管理员" });
- }
- else
- return Ok(new { state = RespondCode.NotFound, msg = "未找到该教师信息" });
- return Ok(new { state = RespondCode.Ok, teacher });
- }
- /// <summary>
- /// 通过区域ID查询学校列表
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-schools")]
- public async Task<IActionResult> GetSchools(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- }
- List<AreaSchool> areaSchool = new();
- string areaScSql = $"select c.id,c.name,c.picture,c.size,c.areaId from c where c.areaId='{areaId}'";
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<AreaSchool>(queryText: areaScSql,requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("Base")}))
- {
- areaSchool.Add(item);
- }
- areaSchool.ForEach(async areaSc =>
- {
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(areaSc.id, new PartitionKey("ProductSum"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
- {
- areaSc.serial = serial.ToObject<List<SchoolProductSumData>>().Count;//.Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
- {
- areaSc.service = service.ToObject<List<SchoolProductSumData>>().Count;//.Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
- {
- areaSc.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Count;//.Select(x => x.prodCode).ToList();
- }
- }
- });
- return Ok(new { state = RespondCode.Ok, areaSchool });
- }
- /// <summary>
- /// 依据区域id查询该区域的顾问信息
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-assists")]
- public async Task<IActionResult> GetAssists(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- var table = tableClient.GetTableReference("BIDDUserInfo");
- List<string> scIds = new();
- HashSet<string> tchIds = new();
- string scIdsSql = $"select value(c.id) from c where c.areaId='{areaId}'";
- await foreach (var itemId in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scIdsSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- scIds.Add(itemId);
- }
- foreach (var scId in scIds)
- {
- string tchIdSql = $"select value(c.id) from c where array_contains(c.roles,'assist',true) and c.pk='Teacher'";
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: tchIdSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{scId}") }))
- {
- tchIds.Add(item);
- }
- }
- List<AreaAssist> areaAssists = new();
- List<string> noIds = new();
- foreach (var item in tchIds)
- {
- List<DingDingUserInfo> ddUsers = await table.QueryWhereString<DingDingUserInfo>($"PartitionKey eq '{_option.Location}' and tmdId eq '{item}'");
- if (ddUsers.Count > 0)
- {
- foreach (var dduser in ddUsers)
- {
- AreaAssist areaAssist = new()
- {
- userId = dduser.userId,
- unionId = dduser.unionId,
- name = dduser.name,
- mobile = dduser.mobile,
- avatar = dduser.avatar,
- tmdId = dduser.tmdId,
- tmdName = dduser.tmdName,
- tmdMobile = dduser.tmdMobile,
- picture = dduser.picture,
- roles = dduser.roles,
- schoolIds = dduser.schoolIds
- };
- areaAssists.Add(areaAssist);
- }
- }
- else { noIds.Add(item); }
- }
- return Ok(new { state = 200, areaAssists, noIds });
- }
- public record AreaAssist
- {
- public string userId { get; set; }
- public string unionId { get; set; }
- public string name { get; set; }
- public string mobile { get; set; }
- public string avatar { get; set; }
- public string tmdId { get; set; }
- public string tmdName { get; set; }
- public string tmdMobile { get; set; }
- public string picture { get; set; }
- public string roles { get; set; }
- public string schoolIds { get; set; }
- }
- /// <summary>
- /// 通过区域ID查询学校前端暂时
- /// </summary>
- public record AreaSchool
- {
- public string id{ get; set; }
- public string name{ get; set; }
- public string picture { get; set; }
- public int size { get; set; }
- public string areaId { get; set; }
- public int serial { get; set; }
- public int service { get; set; }
- public int hard { get; set; }
- }
- /// <summary>
- /// 已加入区域的学校
- /// </summary>
- public record JoinAreaSchool
- {
- public string id { get; set; }
- public string name { get; set; }
- public string schoolCode { get; set; }
- public string picture { get; set; }
- public string areaId{ get; set; }
- public string standard { get; set; }
- public List<string> period { get; set; }
- public string province { get; set; }
- public string city { get; set; }
- public string dist { get; set; }
- public List<SchoolArea> areas { get; set; } = new List<SchoolArea>();
- }
- }
- }
|