123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383 |
- using Microsoft.Azure.Cosmos;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelBI.Filter;
- using TEAMModelBI.Tool.Extension;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.Context.BI;
- using TEAMModelOS.SDK.Context.Constant;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models.Cosmos.BI.BINormal;
- namespace TEAMModelBI.Controllers.BINormal
- {
- [Route("bizconfig")]
- [ApiController]
- public class BusinessConfigController : ControllerBase
- {
- public readonly AzureCosmosFactory _azureCosmos;
- public readonly AzureStorageFactory _azureStorage;
- public readonly DingDing _dingDing;
- public readonly Option _option;
- public BusinessConfigController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option)
- {
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _dingDing = dingDing;
- _option = option?.Value;
- }
- /// <summary>
- /// 新增企业信息和修改企业信息 //已对接
- /// </summary>
- /// <param name="bizConfig"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc,assist")]
- [HttpPost("set-info")]
- public async Task<IActionResult> SetInfo([FromBody] BizConfig bizConfig, [FromHeader] string site)
- {
- StringBuilder strMsg = new();
- 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);
- //}
- string salt = Utils.CreatSaltString(8);
- List<BizUsers> bizUsers = new();
- string type = "";
- //新增企业信息
- if (string.IsNullOrEmpty(bizConfig.id))
- {
- bizConfig.id = Guid.NewGuid().ToString();
- bizConfig.code = "BizConfig";
- bizConfig.pk = "BizConfig";
- bizConfig.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, bizConfig.id, _option.JwtSecretKey, bizConfig.isCustomize);
- bizConfig.jti = auth_token.jti;
- bizConfig.token = auth_token.jwt;
- await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<BizConfig>(bizConfig, new PartitionKey("BizConfig"));
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIteratorSql<BizUsers>(queryText: $"select value(c) from c where c.mobile ={bizConfig.mobile}", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
- {
- bizUsers.Add(item);
- }
- BizRel bizRel = new() { bizId = bizConfig.id, role = new List<string>() { "admin" } };
- if (bizUsers.Count > 0)
- {
- foreach (var item in bizUsers)
- {
- BizRel temp = item.relation.Find(f => f.bizId.Equals(bizConfig.id));
- if (temp == null)
- {
- item.relation.Add(bizRel);
- await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizUsers>(item, item.id, new PartitionKey("BizUsers"));
- }
- }
- }
- else
- {
- BizUsers tBizUsers = new() { id = Guid.NewGuid().ToString(), code= "BizUsers", name = bizConfig.mobile.ToString(), mobile = bizConfig.mobile, salt = salt, pwd = Utils.HashedPassword($"{bizConfig.mobile}", salt),relation= new List<BizRel>() { { bizRel } } };
- await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<BizUsers>(tBizUsers, new PartitionKey("BizUsers"));
- }
- strMsg.Append($"{bizConfig.name}【{bizConfig.id}】新增企业基础信息。");
- type = "bizconfig-add";
- }
- //修改企业信息
- else
- {
- var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync(bizConfig.id, new PartitionKey("BizConfig"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- BizConfig tempBizConfig = json.ToObject<BizConfig>();
- bizConfig.pk = "BizConfig";
- bizConfig.code = "BizConfig";
- bizConfig.ttl = -1;
- bizConfig.createTime = tempBizConfig.createTime;
- bizConfig.jti = tempBizConfig.jti;
- bizConfig.token = tempBizConfig.token;
- bizConfig = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizConfig>(bizConfig, bizConfig.id, new PartitionKey("BizConfig"));
- strMsg.Append($"{bizConfig.name}【{bizConfig.id}】修改企业基础信息。");
- type = "bizconfig-update";
- }
- }
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
- return Ok(new { state = RespondCode.Ok, bizConfig });
- }
- /// <summary>
- /// 获取企业信息列表 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc,assist")]
- [HttpPost("get-infos")]
- public async Task<IActionResult> GetInfos(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("id", out JsonElement id);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- StringBuilder sqlTxt = new("select value(c) from c");
- if (!string.IsNullOrEmpty($"{id}"))
- {
- sqlTxt.Append($" where c.id='{id}'");
- }
- List<Business> businesses = new();
- await foreach (var items in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIteratorSql<Business>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizConfig") }))
- {
- businesses.Add(items);
- }
- return Ok(new { state = RespondCode.Ok, businesses });
- }
- /// <summary>
- /// 刪除企业信息列表
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc,assist")]
- [HttpPost("del-info")]
- public async Task<IActionResult> DelInfo(JsonElement jsonElement)
- {
- try
- {
- if(!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- //企業聯絡人 刪除該企業聯絡資訊
- List<string> bizUsersIdList = new List<string>();
- StringBuilder sql = new($"SELECT VALUE c.id FROM c JOIN r IN c.relation WHERE r.bizId = '{id}'");
- await foreach (var items in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIteratorSql<string>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") })) {
- bizUsersIdList.Add(items);
- }
- if(bizUsersIdList.Count > 0)
- {
- string bizUsersIdListStr = JsonSerializer.Serialize(bizUsersIdList);
- sql = new($"SELECT * FROM c WHERE ARRAY_CONTAINS({bizUsersIdListStr}, c.id, true)");
- await foreach (BizUsers item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIteratorSql<BizUsers>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
- {
- item.relation.RemoveAll(r => r.bizId == $"{id}");
- await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizUsers>(item, item.id, new PartitionKey("BizUsers"));
- }
- }
- //刪除企業
- await cosmosClient.GetContainer("TEAMModelOS", "Normal").DeleteItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
- //Log
- StringBuilder strMsg = new();
- strMsg.Append($"删除企业基础信息。删除ID:{id}");
- string type = "bizconfig-del";
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
- return Ok(new { state = RespondCode.Ok, id = id });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} bizconfig/del-info \n {ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 重置秘钥 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc,assist")]
- [HttpPost("reset-secretkey")]
- public async Task<IActionResult> ResetSecretKey(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
- var (tmdId, tmdName, pic, _, _, _) = 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(BIConst.Global);
- // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- //}
- BizConfig bizConfig = new();
- var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- bizConfig = json.ToObject<BizConfig>();
- var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, bizConfig.id, _option.JwtSecretKey, bizConfig.isCustomize);
- bizConfig.jti = auth_token.jti;
- bizConfig.token = auth_token.jwt;
- bizConfig = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizConfig>(bizConfig, bizConfig.id, new PartitionKey("BizConfig"));
- }
- return Ok(new { state =RespondCode.Ok, bizConfig });
- }
- /// <summary>
- /// 关联企业学校 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc,assist")]
- [HttpPost("rel-school")]
- public async Task<IActionResult> RelationSchool(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!jsonElement.TryGetProperty("schools", out JsonElement _schools)) return BadRequest();
- if (!jsonElement.TryGetProperty("type", out JsonElement type)) return BadRequest();
- //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
- var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- List<BizSchool> bizSchool = _schools.ToObject<List<BizSchool>>();
- 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);
- //}
- StringBuilder strMsg = new($"{tmdName}[{tmdId}]给");
- if ($"{type}".Equals("add"))
- {
- strMsg.Append($"企业关联学校;学校信息列表:");
- }
- else if ($"{type}".Equals("del"))
- {
- strMsg.Append("企业移除学校,学校信息列表:");
- }
- else { return Ok(new { state = RespondCode.ParamsError, msg = "类型错误" }); }
- List<BizSchool> noBizSc = new();
- BizConfig bizConfig = new();
- var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- bizConfig = json.ToObject<BizConfig>();
- foreach (var item in bizSchool)
- {
- var temp = bizConfig.schools.Find(f => f.id.Equals(item.id));
- if ($"{type}".Equals("add"))
- {
- if (temp == null)
- {
- bizConfig.schools.Add(item);
- strMsg.Append($"{item.name}[{item.id}]|");
- }
- else
- noBizSc.Add(temp);
- }
- else if ($"{type}".Equals("del"))
- {
- if (temp != null)
- {
- bizConfig.schools.Remove(temp);
- strMsg.Append($"{item.name}[{item.id}]|");
- }
- }
- }
- bizConfig = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizConfig>(bizConfig, bizConfig.id, new PartitionKey("BizConfig"));
- }
- else return Ok(new { state = RespondCode.NotFound, msg = "未找到该企业" });
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, $"bizconfig-{type}School", strMsg.ToString(), _dingDing, httpContext: HttpContext);
- if (noBizSc.Count > 0)
- return Ok(new { state = RespondCode.Created, bizConfig , noBizSc });
- return Ok(new { state = RespondCode.Ok, bizConfig });
- }
- /// <summary>
- /// 查询所有学校 如果传企业ID则查询与企业没有关联的学校 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-schools")]
- public async Task<IActionResult> GetSchools(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("id", out JsonElement id);
- //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);
- //}
- List<OpenSchool> openSchools = new();
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<OpenSchool>(queryText: "select c.id,c.code,c.name,c.picture from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- openSchools.Add(item);
- }
- BizConfig bizConfig = new();
- if (!string.IsNullOrEmpty($"id"))
- {
- var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- bizConfig = json.ToObject<BizConfig>();
- if (bizConfig.schools.Count > 0)
- {
- foreach (var item in bizConfig.schools)
- {
- var temp = openSchools.Find(f => f.id.Equals(item.id));
- if (temp != null)
- openSchools.Remove(temp);
- }
- }
- }
- }
- return Ok(new { state = RespondCode.Ok , openSchools });
- }
- public record OpenSchool
- {
- public string id { get; set; }
- public string code { get; set; }
- public string name { get; set; }
- public string picture { get; set; }
- }
- }
- }
|