123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430 |
- using Azure.Cosmos;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.Net.Http;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelBI.DI.BIAzureStorage;
- using TEAMModelBI.Filter;
- using TEAMModelBI.Models.Extension;
- using TEAMModelBI.Tool.Extension;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.Context.BI;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models.Cosmos.BI;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Models.Table;
- namespace TEAMModelBI.Controllers.BITable
- {
- [Route("business")]
- [ApiController]
- public class CompanyController : ControllerBase
- {
- public readonly AzureCosmosFactory _azureCosmos;
- public readonly AzureStorageFactory _azureStorage;
- public readonly DingDing _dingDing;
- public readonly Option _option;
- private readonly IWebHostEnvironment _environment; //读取文件
- public CompanyController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, IWebHostEnvironment environment)
- {
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _dingDing = dingDing;
- _option = option?.Value;
- _environment = environment;
- }
- /// <summary>
- /// 查询企业信息结集合 若传ID查查询该账户的企业信息
- /// </summary>
- /// <param name="jsonElenent"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "admin,rdc,assist,sales,company")]
- [HttpPost("get-info")]
- public async Task<IActionResult> GetInfo(JsonElement jsonElenent)
- {
- try
- {
- jsonElenent.TryGetProperty("id", out JsonElement id);
- jsonElenent.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- }
- var table = tableClient.GetTableReference("IESOpenApi");
- Dictionary<string, object> keyValue = new Dictionary<string, object>() { { "PartitionKey", "BusinessConfig" } };
- if (!string.IsNullOrEmpty($"{id}"))
- {
- keyValue.Add("RowKey", $"{id}");
- }
- List<BusinessConfig> companys = table.FindListByDictSync<BusinessConfig>(keyValue);
- //cosmosDB数据库
- //List<ReadCompany> companys = new();
- //StringBuilder sqlTxt = new("select c.id,c.pk,c.code,c.name,c.credit,c.picture,c.jti,c.secretKey,c.emall,c.mobile,c.password,c.webhookDomain,c.salt,c.createTime from c");
- //if (!string.IsNullOrEmpty($"{id}"))
- //{
- // sqlTxt.Append($" where c.id='{id}'");
- //}
- //await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<ReadCompany>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Company") }))
- //{
- // companys.Add(item);
- //}
- return Ok(new { state = 200, companys });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} , /business/get-info \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 新增企业信息和修改企业信息
- /// </summary>
- /// <param name="appCompany"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc,assist,sales,company")]
- [HttpPost("set-info")]
- public async Task<IActionResult> SetCompany([FromBody] BusinessConfig company, [FromHeader] string site)
- {
- try
- {
- //var (loginId, loginName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- 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);
- }
- List<BusinessConfig> companys = new();
- BusinessUser businessUser = new();
- BizRelUser bizRelUser = new();
- var table = tableClient.GetTableReference("IESOpenApi");
- string salt = Utils.CreatSaltString(8);
- string type = "";
- if (string.IsNullOrEmpty(company.RowKey))
- {
- company.RowKey = Guid.NewGuid().ToString();
- company.PartitionKey = "BusinessConfig";
- company.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, company.RowKey, _option.JwtSecretKey, "business");
- company.jti = auth_token.jti;
- company.token = auth_token.jwt;
- company = await table.SaveOrUpdate<BusinessConfig>(company);
-
- businessUser = new() { RowKey = Guid.NewGuid().ToString(), name = $"{company.mobile}", mobile = company.mobile, salt = salt, pwd = Utils.HashedPassword($"{company.mobile}", salt) };
- businessUser = await table.SaveOrUpdate<BusinessUser>(businessUser);
- bizRelUser = new() { RowKey = $"{businessUser.RowKey}-{company.RowKey}",userId= $"{company.RowKey}", bizId = $"{company.RowKey}",bizName = company.name ,roles = "admin" };
- bizRelUser = await table.SaveOrUpdate<BizRelUser>(bizRelUser);
- companys.Add(company);
- strMsg.Append($"{company.name}【{company.RowKey}】新增企业基础信息。新增该企业管理员信息{businessUser.name}【{businessUser.RowKey}】。");
- type = "business-add";
- }
- else
- {
- //List<BusinessConfig> companyTables = table.FindListByDictSync<BusinessConfig>(new Dictionary<string, object> { { "PartitionKey", "BusinessConfig" }, { "RowKey", $"{company.RowKey}" } });
- BusinessConfig businessConfig = table.Get<BusinessConfig>("BusinessConfig", $"{company.RowKey}");
- if (businessConfig != null)
- {
- company.PartitionKey = businessConfig.PartitionKey;
- company.RowKey = businessConfig.RowKey;
- company.credit = businessConfig.credit;
- company.jti = businessConfig.jti;
- company.token = businessConfig.token;
- businessConfig = await table.SaveOrUpdate<BusinessConfig>(company);
- companys.Add(businessConfig);
- strMsg.Append($"{company.name}【{company.RowKey}】修改企业基础信息:{company}。");
- type = "business-add";
- }
- else
- {
- company.RowKey = Guid.NewGuid().ToString();
- company.PartitionKey = "BusinessConfig";
- company.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, company.RowKey, _option.JwtSecretKey, "business");
- company.jti = auth_token.jti;
- company.token = auth_token.jwt;
- company = await table.SaveOrUpdate<BusinessConfig>(company);
- businessUser = new() { RowKey = Guid.NewGuid().ToString(), name = $"{company.mobile}", mobile = company.mobile, salt = salt, pwd = Utils.HashedPassword($"{company.mobile}", salt) };
- businessUser = await table.SaveOrUpdate<BusinessUser>(businessUser);
- bizRelUser = new() { RowKey = $"{businessUser.RowKey}-{company.RowKey}", userId = $"{company.RowKey}", bizId = $"{company.RowKey}", bizName = company.name, roles = "admin" };
- bizRelUser = await table.SaveOrUpdate<BizRelUser>(bizRelUser);
- companys.Add(company);
- strMsg.Append($"{company.name}【{company.RowKey}】新增企业基础信息:{company}。新增该企业管理员信息{businessUser.name}【{businessUser.RowKey}】。");
- type = "business-add";
- }
- }
-
- //保存操作记录
- //await _azureStorage.SaveBILog(type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200, companys, businessUser });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} , /business/set-info \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 关联企业学校
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc,assist,sales,company")]
- [HttpPost("set-companyschool")]
- public async Task<IActionResult> SetCompanySc(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("schools", out JsonElement _schools)) return BadRequest();
- if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
- var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- jsonElement.TryGetProperty("site", out JsonElement site);
- List<RecSc> recScs = _schools.ToObject<List<RecSc>>();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- var table = tableClient.GetTableReference("IESOpenApi");
- StringBuilder strMsg = new($"{tmdName}[{tmdId}]关联企业ID:{id},学校列表:");
- List<BusinessSchool> busSchools = new();
- foreach (var item in recScs)
- {
- BusinessSchool businessSchool = new() { PartitionKey = $"BusinessSchool", RowKey = Guid.NewGuid().ToString(), school = $"{item.id}", bizid = $"{id}", name = $"{item.name}", picture = $"{item.picture}" };
- busSchools.Add(businessSchool);
- strMsg.Append($"{item.name}[{item.id}]|");
- }
- busSchools = await table.SaveOrUpdateAll<BusinessSchool>(busSchools);
- //保存操作记录
- //await _azureStorage.SaveBILog(type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "BusinessSchool-add", strMsg.ToString(), _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200, busSchools });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} , /business/set-companyschool \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 依据企业ID查询关联的学校
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-companyschool")]
- public async Task<IActionResult> GetCompanySc(JsonElement jsonElement)
- {
- try
- {
- jsonElement.TryGetProperty("id", out JsonElement id);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- var table = tableClient.GetTableReference("IESOpenApi");
- Dictionary<string, object> keyValue = new() { { "PartitionKey", $"BusinessSchool" } };
- if (!string.IsNullOrEmpty($"{id}"))
- {
- keyValue.Add("bizid", $"{id}");
- }
- List<BusinessSchool> busSchools = await table.FindListByDict<BusinessSchool>(keyValue);
- return Ok(new { state = 200, busSchools });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} , /business/get-companyschool \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 删除企业关联学校
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc,assist,sales,company")]
- [HttpPost("del-companysc")]
- public async Task<IActionResult> DelCompanySc(JsonElement jsonElement)
- {
- if(!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!jsonElement.TryGetProperty("schools", out JsonElement _schools)) return BadRequest();
- var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- jsonElement.TryGetProperty("site", out JsonElement site);
- List<string> schools = _schools.ToObject<List<string>>();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- var table = tableClient.GetTableReference("IESOpenApi");
- StringBuilder strMsg = new($"{tmdName}[{tmdId}]删除企业关联学校,企业ID:{id},学校列表:");
- List<string> noSc = new();
- foreach (var school in schools)
- {
- string sqlTxt = $"PartitionKey eq 'BusinessSchool' and bizid eq '{id}' and school eq '{school}'";
- List<BusinessSchool> busSc = await table.QueryWhereString<BusinessSchool>(sqlTxt);
- if (busSc.Count > 0)
- {
- strMsg.Append($"{school}|");
- await table.DeleteAll(busSc);
- }
- else
- noSc.Add(school);
- }
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "BusinessSchool-del", strMsg.ToString(), _dingDing, httpContext: HttpContext);
- if (noSc.Count > 0)
- return Ok(new { state = 201, noSc });
- else
- return Ok(new { state = 200 });
- }
- /// <summary>
- /// 重置密码和token
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc,assist,sales,company")]
- [HttpPost("reset-bus")]
- public async Task<IActionResult> ResetBus(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!jsonElement.TryGetProperty("resetType", out JsonElement resetType)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- var table = tableClient.GetTableReference("IESOpenApi");
- List<BusinessConfig> busConfigs = await table.FindListByDict<BusinessConfig>(new Dictionary<string, object>() { { "PartitionKey", "BusinessConfig" }, { "RowKey", $"{id}" } });
- if (busConfigs.Count > 0)
- {
- foreach (var busConfig in busConfigs)
- {
- if ($"{resetType}".Equals("token"))
- {
- var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, busConfig.RowKey, _option.JwtSecretKey, "business");
- busConfig.jti = auth_token.jti;
- busConfig.token = auth_token.jwt;
- }
- }
- if ($"{resetType}".Equals("token"))
- {
- await table.SaveOrUpdateAll(busConfigs);
- return Ok(new { state = 200, busConfigs });
- }
- else
- return Ok(new { state = 400, msg = "重置类型错误!" });
- }
- else
- return Ok(new { state = 404, msg = "未找到企业信息" });
- }
- /// <summary>
- /// 关联时传入的学校信息
- /// </summary>
- public record RecSc
- {
- public string id { get; set; }
- public string name { get; set; }
- public string picture { get; set; }
- }
- /// <summary>
- /// 显示第三方信息
- /// </summary>
- public record ReadCompany
- {
- public string id { get; set; }
- public string code { get; set; }
- public string name { get; set; }
- public string credit { get; set; }
- public string picture { get; set; }
- public string jti { get; set; }
- public string secretKey { get; set; }
- public string emall { get; set; }
- public string mobile { get; set; }
- public string salt { get; set; }
- public string password { get; set; }
- public string webhookDomain { get; set; }
- public long createTime { get; set; }
- }
- }
- }
|