瀏覽代碼

Merge branch 'PL/develop-BI' into develop

Li 2 年之前
父節點
當前提交
9bde88c34f

+ 328 - 0
TEAMModelBI/Controllers/BINormal/BusinessController.cs

@@ -0,0 +1,328 @@
+using 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 BusinessController : ControllerBase
+    {
+        public readonly AzureCosmosFactory _azureCosmos;
+        public readonly AzureStorageFactory _azureStorage;
+        public readonly DingDing _dingDing;
+        public readonly Option _option;
+        public BusinessController(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 = "Business";
+                bizConfig.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+                var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, bizConfig.id, _option.JwtSecretKey, "business");
+                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").GetItemQueryIterator<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.Status == 200)
+                {
+                    using var json = await JsonDocument.ParseAsync(response.ContentStream);
+                    BizConfig tempBizConfig = json.ToObject<BizConfig>();
+
+                    bizConfig.pk = "Business";
+                    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]
+        [HttpPost("get-infos")]
+        public async Task<IActionResult> GetInfos(JsonElement jsonElement) 
+        {
+            jsonElement.TryGetProperty("id", out JsonElement id);
+            jsonElement.TryGetProperty("site", out JsonElement site);
+            var cosmosClient = _azureCosmos.GetCosmosClient();
+            if ($"{site}".Equals(BIConst.Global))
+                cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
+            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").GetItemQueryIterator<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("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.Status == 200)
+            {
+                using var json = await JsonDocument.ParseAsync(response.ContentStream);
+                bizConfig = json.ToObject<BizConfig>();
+                var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, bizConfig.id, _option.JwtSecretKey, "business");
+                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();
+            if (string.IsNullOrEmpty("add"))
+            {
+                strMsg.Append($"关联企业ID:{id},学校列表:");
+            }
+            else if (string.IsNullOrEmpty("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.Status == RespondCode.Ok)
+            {
+                using var json = await JsonDocument.ParseAsync(response.ContentStream);
+                bizConfig = json.ToObject<BizConfig>();
+                foreach (var item in bizSchool)
+                {
+                    var temp = bizConfig.schools.Find(f => f.id.Equals(item.id));
+                    if (string.IsNullOrEmpty("add"))
+                    {
+                        if (temp == null)
+                        {
+                            bizConfig.schools.Add(item);
+                            strMsg.Append($"{item.name}[{item.id}]|");
+                        }
+                        else
+                            noBizSc.Add(temp);
+                    }
+                    else if (string.IsNullOrEmpty("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>
+        /// 删除企业关联学校
+        /// </summary>
+        /// <param name="jsonElement"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [AuthToken(Roles = "admin,rdc,assist")]
+        [HttpPost("del-school")]
+        public async Task<IActionResult> DelSchool(JsonElement jsonElement)
+        {
+            if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
+            if (!jsonElement.TryGetProperty("schools", out JsonElement _schools)) 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}]关联企业ID:{id},学校列表:");
+
+            BizConfig bizConfig = new();
+            var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
+            if (response.Status == RespondCode.Ok)
+            {
+                using var json = await JsonDocument.ParseAsync(response.ContentStream);
+                bizConfig = json.ToObject<BizConfig>();
+                foreach (var item in bizSchool)
+                {
+                    var temp = bizConfig.schools.Find(f => f.id.Equals(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-addSchool", strMsg.ToString(), _dingDing, httpContext: HttpContext);
+
+            return Ok(new { state = RespondCode.Ok, bizConfig });
+        }
+
+
+    }
+}

+ 280 - 0
TEAMModelBI/Controllers/BINormal/BusinessUsersController.cs

@@ -0,0 +1,280 @@
+using 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("bizuser")]
+    [ApiController]
+    public class BusinessUsersController : ControllerBase
+    {
+        public readonly AzureCosmosFactory _azureCosmos;
+        public readonly AzureStorageFactory _azureStorage;
+        public readonly DingDing _dingDing;
+        public readonly Option _option;
+        public BusinessUsersController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option)
+        {
+            _azureCosmos = azureCosmos;
+            _azureStorage = azureStorage;
+            _dingDing = dingDing;
+            _option = option?.Value;
+        }
+
+        /// <summary>
+        /// 获取第三方用户信息
+        /// </summary>
+        /// <param name="jsonElement"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("get-infos")]
+        public async Task<IActionResult> GetInfos(JsonElement jsonElement) 
+        {
+            jsonElement.TryGetProperty("id", out JsonElement id);
+            jsonElement.TryGetProperty("site", out JsonElement site);
+            var cosmosClient = _azureCosmos.GetCosmosClient();
+            if ($"{site}".Equals(BIConst.Global))
+                cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
+            StringBuilder sqlTxt = new("select value(c) from c");
+            if (!string.IsNullOrEmpty($"{id}"))
+            {
+                sqlTxt.Append($" where c.id='{id}'");
+            }
+
+            List<BusinessUsers> bizUsers = new();
+            await foreach (var items in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BusinessUsers>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
+            {
+                bizUsers.Add(items);
+            }
+
+            return Ok(new { state = RespondCode.Ok, bizUsers });
+        }
+
+        /// <summary>
+        /// 用户信息企业信息
+        /// </summary>
+        /// <param name="bizUsers"></param>
+        /// <param name="site"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [AuthToken(Roles = "admin,rdc,assist")]
+        [HttpPost("set-info")]
+        public async Task<IActionResult> SetInfos([FromBody] BizUsers bizUsers, [FromHeader] string 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 (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
+            StringBuilder strMsg = new($"{tmdName}[{tmdId}]操作:");
+            string salt = Utils.CreatSaltString(8);
+            string type = "";
+            if (string.IsNullOrEmpty(bizUsers.id))
+            {
+                bizUsers.id = Guid.NewGuid().ToString();
+                bizUsers.code = "BizUsers";
+                bizUsers.name = string.IsNullOrEmpty(bizUsers.name)? bizUsers.mobile.ToString(): bizUsers.name;
+
+                bizUsers.salt = salt;
+                bizUsers.pwd = string.IsNullOrEmpty(bizUsers.pwd) ? Utils.HashedPassword(bizUsers.mobile.ToString(), salt) : Utils.HashedPassword(bizUsers.pwd, salt);
+
+                bizUsers = await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<BizUsers>(bizUsers, new PartitionKey("BizUsers"));
+                strMsg.Append($"{bizUsers.name}【{bizUsers.id}】新增第三方用户信息基础信息。");
+                type = "bizuser-add";
+            }
+            else 
+            {
+                var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync(bizUsers.id, new PartitionKey("BizUsers"));
+                if (response.Status == RespondCode.Ok)
+                {
+                    using var json = await JsonDocument.ParseAsync(response.ContentStream);
+                    BizUsers tempbizUsers = json.ToObject<BizUsers>();
+
+                    bizUsers.pk = "Business";
+                    bizUsers.code = "BizUsers";
+                    bizUsers.ttl = -1;
+
+                    bizUsers.salt = tempbizUsers.salt;
+                    bizUsers.pwd = tempbizUsers.pwd;
+                    bizUsers = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizUsers>(bizUsers, bizUsers.id, new PartitionKey("BizUsers"));
+
+                    strMsg.Append($"{bizUsers.name}【{bizUsers.id}】修改第三方用户信息基础信息。");
+                    type = "bizuser-add";
+                }
+                else Ok(new { state = RespondCode.NotFound ,msg="未找到id用户。"});
+            }
+
+            //保存操作记录
+            await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
+            return Ok(new { state = RespondCode.Ok, bizUsers });
+        }
+
+        /// <summary>
+        /// 重置密码
+        /// </summary>
+        /// <param name="jsonElement"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [AuthToken(Roles = "admin,rdc,assist")]
+        [HttpPost("reset-pwd")]
+        public async Task<IActionResult> ResetPassWord(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);
+            }
+            BizUsers bizUsers = new();
+            StringBuilder strMsg = new($"{tmdName}[{tmdId}]操作:");
+            string salt = Utils.CreatSaltString(8);
+            var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
+            if (response.Status == 200)
+            {
+                using var json = await JsonDocument.ParseAsync(response.ContentStream);
+                bizUsers = json.ToObject<BizUsers>();
+                bizUsers.salt = salt;
+                bizUsers.pwd = Utils.HashedPassword(bizUsers.mobile.ToString(), salt);
+
+                strMsg.Append($"重置{bizUsers.name}【{bizUsers.id}】的密码,重置成功!");
+                bizUsers = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizUsers>(bizUsers, bizUsers.id, new PartitionKey("BizUsers"));
+            }
+
+            //保存操作记录
+            await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "bizuser-reset", strMsg.ToString(), _dingDing, httpContext: HttpContext);
+            return Ok(new { state = RespondCode.Ok, bizUsers });
+        }
+
+        /// <summary>
+        /// 用户关联/移除企业信息
+        /// </summary>
+        /// <param name="jsonElement"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [AuthToken(Roles = "admin,rdc,assist")]
+        [HttpPost("rel-biz")]
+        public async Task<ActionResult> RelationBusiness(JsonElement jsonElement) 
+        {
+            if(!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
+            if (!jsonElement.TryGetProperty("bizs", out JsonElement _bizs)) return BadRequest();
+            jsonElement.TryGetProperty("site", out JsonElement site);
+            var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
+
+            List<BizRel> bizRels = _bizs.ToObject<List<BizRel>>();
+
+            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 (string.IsNullOrEmpty("add"))
+            {
+                strMsg.Append($"关联企业ID:{id},学校列表:");
+            }
+            else if (string.IsNullOrEmpty("del"))
+            {
+                strMsg.Append("移除企业学校信息,学校列表:");
+            }
+            else { return Ok(new { state = RespondCode.ParamsError, msg = "类型错误" }); }
+
+            List<BizRel> noBizRel = new();
+            BizUsers bizUsers = new();
+
+            var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizUsers"));
+            if (response.Status == RespondCode.Ok)
+            {
+                using var json = await JsonDocument.ParseAsync(response.ContentStream);
+                bizUsers = json.ToObject<BizUsers>();
+                foreach (var item in bizRels)
+                {
+                    var temp = bizUsers.relation.Find(f => f.bizId.Equals(item.bizId));
+                    if (string.IsNullOrEmpty("add"))
+                    {
+                        if (temp == null)
+                        {
+                            bizUsers.relation.Add(item);
+                            strMsg.Append($"{item.name}[{item.bizId}]|");
+                        }
+                        else
+                            noBizRel.Add(temp);
+                    }
+                    else if (string.IsNullOrEmpty("del"))
+                    {
+                        if (temp != null)
+                        {
+                            bizUsers.relation.Remove(temp);
+                            strMsg.Append($"{item.name}[{item.bizId}]|");
+                        }
+                    }
+                }
+
+                bizUsers = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizUsers>(bizUsers, bizUsers.id, new PartitionKey("BizUsers"));
+            }
+            else return Ok(new { state = RespondCode.NotFound, msg = "未找到该用户" });
+
+            //保存操作记录
+            await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "bizconfig-addSchool", strMsg.ToString(), _dingDing, httpContext: HttpContext);
+            if (noBizRel.Count > 0)
+                return Ok(new { state = RespondCode.Created, bizUsers, noBizRel });
+            return Ok(new { state = RespondCode.Ok, bizUsers });
+        }
+
+        /// <summary>
+        /// 通过企业Id查询用户信息
+        /// </summary>
+        /// <param name="jsonElement"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("get-bizid")]
+        public async Task<IActionResult> GetBizIdUsers(JsonElement jsonElement)
+        {
+
+            if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
+            jsonElement.TryGetProperty("site", out JsonElement site);
+            var cosmosClient = _azureCosmos.GetCosmosClient();
+            if ($"{site}".Equals(BIConst.Global))
+                cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
+
+            List<BusinessUsers> businessUsers = new();
+            string sql = $"select value(c) from c join s in c.relation  where c.code='BizUsers' and s.bizId = '80e1bb6c-acba-46ab-9939-4851c4ef2158'";
+            await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BusinessUsers>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
+            {
+                businessUsers.Add(item);
+            }
+
+            return Ok(new { state = RespondCode.Ok, businessUsers });
+        }
+
+    }
+}

+ 1 - 1
TEAMModelBI/Controllers/BITable/CompanyUserController.cs

@@ -16,7 +16,7 @@ using TEAMModelOS.SDK.Models.Table;
 
 namespace TEAMModelBI.Controllers.BITable
 {
-    [Route("bizuser")]
+    [Route("bizusertable")]
     [ApiController]
     public class CompanyUserController : ControllerBase
     {

+ 126 - 0
TEAMModelBI/Controllers/LoginController.cs

@@ -39,6 +39,7 @@ using TEAMModelOS.SDK.Models.Table;
 using TEAMModelOS.SDK.Context.Constant;
 using TEAMModelBI.Models;
 using TEAMModelOS.SDK.Context.BI;
+using TEAMModelOS.SDK.Models.Cosmos.BI.BINormal;
 //using static DingTalk.Api.Response.OapiV2UserGetResponse;
 
 namespace TEAMModelBI.Controllers
@@ -743,6 +744,131 @@ namespace TEAMModelBI.Controllers
             else return Ok(new { state = RespondCode.Conflict, msg = "该手机号已注册开放平台,请直接登录" });
         }
 
+        /// <summary>
+        /// 登录 第三方用户数据在CosmosDB 
+        /// </summary>
+        /// <param name="jsonElement"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("get-bizuser")]
+        public async Task<IActionResult> GetBizUserLogin(JsonElement jsonElement) 
+        {
+            jsonElement.TryGetProperty("mobile", out JsonElement mobile);
+            jsonElement.TryGetProperty("mail", out JsonElement mail);
+            if (!jsonElement.TryGetProperty("pwd", out JsonElement password)) 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);
+            }
+            
+            string loginSql = null;
+            if (!string.IsNullOrEmpty($"{mobile}"))
+                loginSql = $"select value(c) from c where c.mobile ={mobile}";
+            else if (!string.IsNullOrEmpty($"{mail}"))
+                loginSql = $"select value(c) from c where c.mail ={mail}";
+            else return Ok(new { state = RespondCode.ParamsError, msg = "手机号/和邮箱为空" });
+
+            List<BusinessUsers> bizUsers = new();
+            await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BusinessUsers>(queryText:loginSql,requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
+            {
+                bizUsers.Add(item);
+            }
+            BusinessUsers businessUsers = new(); string openid_token = null;
+            if (bizUsers.Count > 0)
+            {
+                foreach (var item in bizUsers)
+                {
+                    var hashedPw = Utils.HashedPassword(password.ToString(), item.salt.ToString());
+                    if (hashedPw.Equals(item.pwd))
+                    {
+                        businessUsers = item;
+                        //string id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, bizUser.RowKey?.ToString(), bizUser.name?.ToString(), bizUser.picture?.ToString(), _option.JwtSecretKey, scope: "company", webSite: Website, expire: 3);
+                        openid_token = JwtAuthExtension.CreateBizLoginAuthToken(_option.HostName, businessUsers.id?.ToString(), businessUsers.name?.ToString(), businessUsers.picture?.ToString(), $"{_option.Location}-Open", _option.JwtSecretKey, expire: 3);
+
+                        await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{businessUsers.name}【{businessUsers.id}】登录开放平台", _dingDing, tid: businessUsers.id, tname: businessUsers.name, twebsite: "Open", httpContext: HttpContext);
+                    };
+                }
+            }
+            else return Ok(new { state = RespondCode.NotFound, msg = "未找到该用户!" });
+
+            if (businessUsers.id != null)
+                return Ok(new { state = RespondCode.Ok, openid_token, businessUsers });
+            else
+                return Ok(new { state = RespondCode.ForbiddenPwd, msg = "密码错误" });
+        }
+
+        /// <summary>
+        /// 注册 第三方用户数据在CosmosDB
+        /// </summary>
+        /// <param name="jsonElement"></param>
+        /// <returns></returns>
+        [HttpPost("set-bizuser")]
+        public async Task<IActionResult> SetBizUserLogin(JsonElement jsonElement)
+        {
+            jsonElement.TryGetProperty("name", out JsonElement name);
+            if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
+            jsonElement.TryGetProperty("mail", out JsonElement mail);
+            jsonElement.TryGetProperty("pwd", out JsonElement pwd);
+            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);
+            }
+
+            string loginSql = null;
+            if (!string.IsNullOrEmpty($"{mobile}"))
+                loginSql = $"select value(c) from c where c.mobile ={mobile}";
+            else if (!string.IsNullOrEmpty($"{mail}"))
+                loginSql = $"select value(c) from c where c.mail ={mail}";
+            else return Ok(new { state = RespondCode.ParamsError, msg = "手机号/和邮箱为空" });
+
+            List<BizUsers> tempBizUsers = new();
+            await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BizUsers>(queryText: loginSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
+            {
+                tempBizUsers.Add(item);
+            }
+
+            if (tempBizUsers.Count > 0)
+                return Ok(new { state = RespondCode.Conflict, msg = "已存在" });
+            else
+            {
+                string salt = Utils.CreatSaltString(8);
+                BizUsers bizUsers = new()
+                {
+                    id = Guid.NewGuid().ToString(),
+                    code = "BizUsers",
+                    name = string.IsNullOrEmpty($"{name}") ? $"{mobile}" : $"{name}",
+                    mobile = mobile.GetInt32(),
+                    salt = salt,
+                    pwd = string.IsNullOrEmpty($"{pwd}") ? Utils.HashedPassword($"{mobile}", salt) : Utils.HashedPassword($"{pwd}", salt),
+                };
+
+                bizUsers = await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<BizUsers>(bizUsers, new PartitionKey("BizUsers"));
+                string log = $"{bizUsers.name}【{bizUsers.id}】注册第三方用户信息基础信息。";
+
+                //保存操作记录
+                await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "login-login", log, _dingDing, httpContext: HttpContext);
+
+                var openid_token = JwtAuthExtension.CreateBizLoginAuthToken(_option.HostName, bizUsers.id?.ToString(), bizUsers.name?.ToString(), bizUsers.picture?.ToString(), $"{_option.Location}-Open", _option.JwtSecretKey, expire: 3);
+
+                return Ok(new { state = RespondCode.Ok, openid_token, bizUsers });
+            }
+        }
+
+
         public record DingDingbinds
         {
             public string type { get; set; }

+ 272 - 0
TEAMModelOS.SDK/Models/Cosmos/BI/BINormal/BizConfig.cs

@@ -0,0 +1,272 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TEAMModelOS.SDK.Models.Cosmos.BI.BINormal
+{
+    /// <summary>
+    /// 企业基础信息
+    /// </summary>
+    public class BizConfig:CosmosEntity
+    {
+        public BizConfig()
+        {
+            pk = "Business";
+        }
+        /// <summary>
+        /// 合作方名称
+        /// </summary>
+        [Required(ErrorMessage = "合作方名称 必须填写")]
+        public string name { get; set; }
+
+        /// <summary>
+        /// 统一社会信用代码
+        /// </summary>
+        [Required(ErrorMessage = "合作方统一社会信用代码 必须填写")]
+        public string credit { get; set; }
+
+        /// <summary>
+        /// 企业log
+        /// </summary>
+        public string picture { get; set; }
+
+        /// <summary>
+        /// 联系人手机号
+        /// </summary>
+        [Required(ErrorMessage = "合作方联系人手机号 必须填写")]
+        public long mobile { get; set; }
+
+        /// <summary>
+        /// 企业开放的学校列表
+        /// </summary>
+        public List<BizSchool> schools { get; set; }
+
+        /// <summary>
+        /// 企业邮箱
+        /// </summary>
+        public string email { get; set; }
+
+        /// <summary>
+        /// 官网地址
+        /// </summary>
+
+        public string domain { get; set; }
+
+        /// <summary>
+        /// webhook  支持多个域名, 逗号隔开 。
+        /// </summary>
+
+        public string webhook { get; set; }
+
+        /// <summary>
+        /// 是否https 0 否,1 是 
+        /// </summary>
+        public int https { get; set; } = 0;
+
+        /// <summary>
+        /// 授权的token ,存放 scope="business",Sub="合作方id",  9e40e436-f958-498d-93cf-4242b77a17ab
+        /// </summary>
+        public string token { get; set; }
+
+        public string jti { get; set; }
+        /// <summary>
+        /// 创建时间
+        /// </summary>
+        public long createTime { get; set; }
+
+    }
+
+    /// <summary>
+    /// 用户信息基础信息
+    /// </summary>
+    public class BizUsers : CosmosEntity 
+    {
+        public BizUsers() 
+        {
+            pk = "Business";
+        }
+
+        /// <summary>
+        /// 人员名称
+        /// </summary>
+        public string name { get; set; }
+
+        /// <summary>
+        /// 头像
+        /// </summary>
+        public string picture { get; set; }
+
+        ///// <summary>
+        ///// 醍摩豆账户
+        ///// </summary>
+        //public string tmdId { get; set; }
+
+        /// <summary>
+        /// 手机号
+        /// </summary>
+        [Required(ErrorMessage = "第三方账户手机号 必须填写")]
+        public long mobile { get; set; }
+
+        /// <summary>
+        /// 邮箱
+        /// </summary>
+        public string mail { get; set; }
+
+        /// <summary>
+        /// 企业关联信息
+        /// </summary>
+        public List<BizRel> relation { get; set; }
+
+        /// <summary>
+        /// 密码生成秘钥
+        /// </summary>
+        public string salt { get; set; }
+
+        /// <summary>
+        /// 密码
+        /// </summary>
+        public string pwd { get; set; }
+    }
+
+
+    /// <summary>
+    /// 关联企业角色
+    /// </summary>
+    public class BizRel
+    {
+        public string bizId { get; set; }
+        public string name { get; set; }
+        public string picture { get; set; }
+        public List<string> role { get; set; }
+    }
+
+    /// <summary>
+    /// 企业学校
+    /// </summary>
+    public class BizSchool
+    {
+        public string id { get; set; }
+        public string name { get; set; }
+        public string picture { get; set; }
+    }
+
+    /// <summary>
+    /// 前端显示用户
+    /// </summary>
+    public record BusinessUsers
+    {
+        public string id { get; set; }
+
+        public string code { get; set; }
+        /// <summary>
+        /// 人员名称
+        /// </summary>
+        public string name { get; set; }
+
+        /// <summary>
+        /// 头像
+        /// </summary>
+        public string picture { get; set; }
+
+        ///// <summary>
+        ///// 醍摩豆账户
+        ///// </summary>
+        //public string tmdId { get; set; }
+
+        /// <summary>
+        /// 手机号
+        /// </summary>
+        public long mobile { get; set; }
+
+        /// <summary>
+        /// 邮箱
+        /// </summary>
+        public string mail { get; set; }
+
+        /// <summary>
+        /// 密码生成秘钥
+        /// </summary>
+        public string salt { get; set; }
+
+        /// <summary>
+        /// 密码
+        /// </summary>
+        public string pwd { get; set; }
+        /// <summary>
+        /// 企业关联信息
+        /// </summary>
+        public List<BizRel> relation { get; set; }
+    }
+
+
+    /// <summary>
+    /// 前端显示企业信息
+    /// </summary>
+    public record Business
+    {
+        /// <summary>
+        /// 企业id
+        /// </summary>
+        public string id { get; set; }
+
+        public string code { get; set; }
+
+        /// <summary>
+        /// 合作方名称
+        /// </summary>
+        public string name { get; set; }
+
+        /// <summary>
+        /// 统一社会信用代码
+        /// </summary>
+        public string credit { get; set; }
+
+        /// <summary>
+        /// 企业log
+        /// </summary>
+        public string picture { get; set; }
+
+        /// <summary>
+        /// 联系人手机号
+        /// </summary>
+        public long mobile { get; set; }
+
+        /// <summary>
+        /// 企业开放的学校列表
+        /// </summary>
+        public List<BizSchool> schools { get; set; }
+
+        /// <summary>
+        /// 企业邮箱
+        /// </summary>
+        public string email { get; set; }
+
+        /// <summary>
+        /// 官网地址
+        /// </summary>
+
+        public string domain { get; set; }
+
+        /// <summary>
+        /// webhook  支持多个域名, 逗号隔开 。
+        /// </summary>
+
+        public string webhook { get; set; }
+
+        /// <summary>
+        /// 是否https 0 否,1 是 
+        /// </summary>
+        public int https { get; set; } = 0;
+
+        /// <summary>
+        /// 授权的token ,存放 scope="business",Sub="合作方id",  9e40e436-f958-498d-93cf-4242b77a17ab
+        /// </summary>
+        public string token { get; set; }
+
+        public string jti { get; set; }
+    }
+
+}

+ 116 - 131
TEAMModelOS/Controllers/OpenApi/Init/BizUsersController.cs

@@ -1,4 +1,5 @@
-using Microsoft.AspNetCore.Http;
+using Azure.Cosmos;
+using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.Options;
@@ -12,6 +13,7 @@ using TEAMModelOS.SDK.Context.Constant;
 using TEAMModelOS.SDK.DI;
 using TEAMModelOS.SDK.Extension;
 using TEAMModelOS.SDK.Models;
+using TEAMModelOS.SDK.Models.Cosmos.BI.BINormal;
 using TEAMModelOS.SDK.Models.Table;
 
 namespace TEAMModelOS.Controllers
@@ -40,144 +42,117 @@ namespace TEAMModelOS.Controllers
             _coreAPIHttpService = coreAPIHttpService;
         }
 
+
         /// <summary>
-        /// 开放平台用户登录
+        /// 登录 第三方用户数据在CosmosDB 
         /// </summary>
         /// <param name="jsonElement"></param>
         /// <returns></returns>
         [ProducesDefaultResponseType]
-        [HttpPost("get-bizuserlogin")]
-        public async Task<IActionResult> GetCommpanyLogin(JsonElement jsonElement) 
+        [HttpPost("get-loginuser")]
+        public async Task<IActionResult> GetBizUserLogin(JsonElement jsonElement)
         {
             jsonElement.TryGetProperty("mobile", out JsonElement mobile);
-            jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
             jsonElement.TryGetProperty("mail", out JsonElement mail);
             if (!jsonElement.TryGetProperty("pwd", out JsonElement password)) return BadRequest();
 
+            var cosmosClient = _azureCosmos.GetCosmosClient();
             var tableClient = _azureStorage.GetCloudTableClient();
             var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
-            Dictionary<string, object> tableDic = new();
-            string tableSql = null;
-            if (!string.IsNullOrEmpty($"{mail}"))
-            {
-                tableSql = $" PartitionKey eq 'BusinessUser' and mail eq '{mail}'";
-                //tableDic = new Dictionary<string, object>() { { "PartitionKey", "BizRelUser" }, { "mail", $"{mail}" } };
-            }
-            if (!string.IsNullOrEmpty($"{tmdId}"))
-            {
-                tableSql = $" PartitionKey eq 'BusinessUser' and tmdId eq '{tmdId}'";
-                //tableDic = new Dictionary<string, object>() { { "PartitionKey", "BizRelUser" }, { "tmdId", $"{tmdId}" } };
-            }
+
+            string loginSql = null;
             if (!string.IsNullOrEmpty($"{mobile}"))
+                loginSql = $"select value(c) from c where c.mobile ={mobile}";
+            else if (!string.IsNullOrEmpty($"{mail}"))
+                loginSql = $"select value(c) from c where c.mail ={mail}";
+            else return Ok(new { state = RespondCode.ParamsError, msg = "手机号/和邮箱为空" });
+
+            List<BusinessUsers> bizUsers = new();
+            await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BusinessUsers>(queryText: loginSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
             {
-                tableSql = $" PartitionKey eq 'BusinessUser' and mobile eq '{mobile}'";
-                //tableDic = new Dictionary<string, object>() { { "PartitionKey", "BizRelUser" }, { "mobile", $"{mobile}" } };
+                bizUsers.Add(item);
             }
-
-            if (!string.IsNullOrEmpty(tableSql))
+            BusinessUsers businessUsers = new(); string openid_token = null;
+            if (bizUsers.Count > 0)
             {
-                var table = tableClient.GetTableReference("IESOpenApi");
-                List<BusinessUser> findBizUsers = await table.QueryWhereString<BusinessUser>(tableSql);
-                //List<BusinessUser> findBizUsers = await table.FindListByDict<BusinessUser>(tableDic);
-                if (findBizUsers.Count > 0)
+                foreach (var item in bizUsers)
                 {
-                    BusinessUser bizUser = new();
-                    foreach (var item in findBizUsers)
+                    var hashedPw = Utils.HashedPassword(password.ToString(), item.salt.ToString());
+                    if (hashedPw.Equals(item.pwd))
                     {
-                        bizUser.PartitionKey = item.PartitionKey;
-                        bizUser.RowKey = item.RowKey;
-                        bizUser.name = item.name;
-                        bizUser.picture = item.picture;
-                        bizUser.tmdId = item.tmdId;
-                        bizUser.mobile = item.mobile;
-                        bizUser.mail = item.mail;
-                        bizUser.salt = item.salt;
-                        bizUser.pwd = item.pwd;
-                    }
-                    List<BizRelUser> bizRelUsers = new();
-
-                    List<RelBizInfo> relBizInfos = new();
-                    if (bizUser != null)
-                    {
-                        string tableSqlUser = $"PartitionKey eq 'BizRelUser' and userId eq '{bizUser.RowKey}'";
-                        bizRelUsers = await table.QueryWhereString<BizRelUser>(tableSqlUser);
-                        if (bizRelUsers.Count > 0)
-                        {
-                            foreach (var item in bizRelUsers)
-                            {
-                                BusinessConfig businessConfig = table.Get<BusinessConfig>("BusinessConfig", item.bizId);
-                                RelBizInfo relBizInfo = new()
-                                {
-                                    userRowKey = item.userId,
-                                    relId = item.RowKey,
-                                    bizRowKey = item.bizId,
-                                    roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(',')) : new List<string>()
-                                };
-                                if (businessConfig != null)
-                                {
-                                    relBizInfo.bizName = businessConfig.name;
-                                    relBizInfo.bizCredit = businessConfig.credit;
-                                    relBizInfo.bizPicture = businessConfig.picture;
-                                    relBizInfos.Add(relBizInfo);
-                                }
-                            }
-                        }
-                    }
-                    var hashedPw = Utils.HashedPassword(password.ToString(), bizUser.salt.ToString());
-                    if (hashedPw.Equals(bizUser.pwd))
-                    {
-                        string openid_token = JwtAuthExtension.CreateBizLoginAuthToken(_option.HostName, bizUser.RowKey?.ToString(), bizUser.name?.ToString(), bizUser.picture?.ToString(), $"{_option.Location}-Open", _option.JwtSecretKey, expire: 3);
+                        businessUsers = item;
+                        //string id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, bizUser.RowKey?.ToString(), bizUser.name?.ToString(), bizUser.picture?.ToString(), _option.JwtSecretKey, scope: "company", webSite: Website, expire: 3);
+                        openid_token = JwtAuthExtension.CreateBizLoginAuthToken(_option.HostName, businessUsers.id?.ToString(), businessUsers.name?.ToString(), businessUsers.picture?.ToString(), $"{_option.Location}-Open", _option.JwtSecretKey, expire: 3);
 
-                        await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{bizUser.name}【{bizUser.RowKey}】登录商务智能开放平台", _dingDing, tid: bizUser.RowKey, tname: bizUser.name, twebsite: _option.Location, httpContext: HttpContext);
-                        return Ok(new { state = RespondCode.Ok, openid_token, bizUser, relBizInfos });
-                    }
-                    else return Ok(new { state = RespondCode.ForbiddenPwd, msg = "密码错误!" });
+                        await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{businessUsers.name}【{businessUsers.id}】登录开放平台", _dingDing, tid: businessUsers.id, tname: businessUsers.name, twebsite: "Open", httpContext: HttpContext);
+                    };
                 }
-                else return Ok(new { state = RespondCode.NotFound, msg = "该账户不存在" });
             }
-            else return Ok(new { state = RespondCode.ParamsError, msg = "参数错误" });
-        }
+            else return Ok(new { state = RespondCode.NotFound, msg = "未找到该用户!" });
 
+            if (businessUsers.id != null)
+                return Ok(new { state = RespondCode.Ok, openid_token, businessUsers });
+            else
+                return Ok(new { state = RespondCode.ForbiddenPwd, msg = "密码错误" });
+        }
 
         /// <summary>
-        /// 注册开放平台用户
+        /// 注册 第三方用户数据在CosmosDB
         /// </summary>
         /// <param name="jsonElement"></param>
         /// <returns></returns>
-        [HttpPost("set-ropen")]
-        public async Task<IActionResult> SetRegistered(JsonElement jsonElement)
+        [HttpPost("set-bizuser")]
+        public async Task<IActionResult> SetBizUserLogin(JsonElement jsonElement)
         {
-            if (!jsonElement.TryGetProperty("name", out JsonElement name)) return BadRequest();
+            jsonElement.TryGetProperty("name", out JsonElement name);
             if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
-            jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
             jsonElement.TryGetProperty("mail", out JsonElement mail);
             jsonElement.TryGetProperty("pwd", out JsonElement pwd);
 
-            string Website = "China";
+            long set1 = mobile.GetInt64();
+
+            var cosmosClient = _azureCosmos.GetCosmosClient();
             var tableClient = _azureStorage.GetCloudTableClient();
             var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
 
-            var table = tableClient.GetTableReference("IESOpenApi");
+            string loginSql = null;
+            if (!string.IsNullOrEmpty($"{mobile}"))
+                loginSql = $"select value(c) from c where c.mobile ={mobile}";
+            else if (!string.IsNullOrEmpty($"{mail}"))
+                loginSql = $"select value(c) from c where c.mail ={mail}";
+            else return Ok(new { state = RespondCode.ParamsError, msg = "手机号/和邮箱为空" });
 
-            string salt = Utils.CreatSaltString(8);
+            List<BizUsers> tempBizUsers = new();
+            await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BizUsers>(queryText: loginSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
+            {
+                tempBizUsers.Add(item);
+            }
 
-            BusinessUser bizUser = null;
-            List<BusinessUser> findBizUsers = await table.QueryWhereString<BusinessUser>($" PartitionKey eq 'BusinessUser' and mobile eq '{mobile}'");
-            if (findBizUsers.Count <= 0)
+            if (tempBizUsers.Count > 0)
+                return Ok(new { state = RespondCode.Conflict, msg = "已存在" });
+            else
             {
-                var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{mobile}" } }, _option.Location, _configuration);
+                string salt = Utils.CreatSaltString(8);
+                BizUsers bizUsers = new()
+                {
+                    id = Guid.NewGuid().ToString(),
+                    code = "BizUsers",
+                    name = string.IsNullOrEmpty($"{name}") ? $"{mobile}" : $"{name}",
+                    mobile = mobile.GetInt64(),
+                    salt = salt,
+                    pwd = string.IsNullOrEmpty($"{pwd}") ? Utils.HashedPassword($"{mobile}", salt) : Utils.HashedPassword($"{pwd}", salt),
+                };
 
-                if (coreUser != null)
-                    bizUser = new() { RowKey = Guid.NewGuid().ToString(), name = coreUser.name, tmdId = coreUser.id, mobile = coreUser.mobile, mail = coreUser.mail, salt = salt, pwd = string.IsNullOrEmpty($"{pwd}") ? Utils.HashedPassword($"{mobile}", salt) : Utils.HashedPassword($"{pwd}", salt) };
-                else
-                    bizUser = new() { RowKey = Guid.NewGuid().ToString(), name = $"{name}", mobile = $"{mobile}", salt = salt, pwd = string.IsNullOrEmpty($"{pwd}") ? Utils.HashedPassword($"{mobile}", salt) : Utils.HashedPassword($"{pwd}", salt) };
+                bizUsers = await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<BizUsers>(bizUsers, new PartitionKey("BizUsers"));
+                string log = $"{bizUsers.name}【{bizUsers.id}】注册第三方用户信息基础信息。";
 
-                bizUser = await table.Save<BusinessUser>(bizUser);
+                //保存操作记录
+                await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "login-login", log, _dingDing, httpContext: HttpContext);
 
-                await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "bizUser-update", $"{bizUser.name}【{bizUser.RowKey}】注册开放平台用户", _dingDing, tid: bizUser.RowKey, tname: bizUser.name, twebsite: Website?.ToString(), httpContext: HttpContext);
-                return Ok(new { state = RespondCode.Ok, bizUser });
+                var openid_token = JwtAuthExtension.CreateBizLoginAuthToken(_option.HostName, bizUsers.id?.ToString(), bizUsers.name?.ToString(), bizUsers.picture?.ToString(), $"{_option.Location}-Open", _option.JwtSecretKey, expire: 3);
+
+                return Ok(new { state = RespondCode.Ok, openid_token, bizUsers });
             }
-            else return Ok(new { state = RespondCode.Conflict, msg = "该手机号已注册开放平台,请直接登录" });
         }
 
         /// <summary>
@@ -191,7 +166,7 @@ namespace TEAMModelOS.Controllers
         {
             try
             {
-                if(!jsonElenent.TryGetProperty("id", out JsonElement id)) return BadRequest();
+                if (!jsonElenent.TryGetProperty("id", out JsonElement id)) return BadRequest();
                 var cosmosClient = _azureCosmos.GetCosmosClient();
                 var tableClient = _azureStorage.GetCloudTableClient();
 
@@ -202,9 +177,16 @@ namespace TEAMModelOS.Controllers
                     keyValue.Add("RowKey", $"{id}");
                 }
 
-                List<BusinessConfig> companys = table.FindListByDictSync<BusinessConfig>(keyValue);
+                Business business = new();
+                var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
+                if (response.Status == RespondCode.Ok)
+                {
+                    using var json = await JsonDocument.ParseAsync(response.ContentStream);
+                    business = json.ToObject<Business>();
+                }
+                else return Ok(new { state = RespondCode.NotFound, msg = "该企业信息" });
 
-                return Ok(new { state = RespondCode.Ok, companys });
+                return Ok(new { state = RespondCode.Ok, business });
             }
             catch (Exception e)
             {
@@ -213,74 +195,77 @@ namespace TEAMModelOS.Controllers
             }
         }
 
+
+
         /// <summary>
-        /// 重新秘钥token
+        /// 重置秘钥
         /// </summary>
         /// <param name="jsonElement"></param>
         /// <returns></returns>
         [ProducesDefaultResponseType]
-        [HttpPost("reset-bus")]
-        public async Task<IActionResult> ResetBus(JsonElement jsonElement)
+        [HttpPost("reset-secretkey")]
+        public async Task<IActionResult> ResetSecretKey(JsonElement jsonElement)
         {
             try
             {
                 if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
-                var table = _azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
 
-                List<BusinessConfig> busConfigs = await table.FindListByDict<BusinessConfig>(new Dictionary<string, object>() { { "PartitionKey", "BusinessConfig" }, { "RowKey", $"{id}" } });
-                if (busConfigs.Count > 0)
+                var cosmosClient = _azureCosmos.GetCosmosClient();
+                var tableClient = _azureStorage.GetCloudTableClient();
+                var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
+                BizConfig bizConfig = new();
+
+                var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
+                if (response.Status == 200)
                 {
-                    foreach (var busConfig in busConfigs)
-                    {
-                        var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, busConfig.RowKey, _option.JwtSecretKey, "business");
-                        busConfig.jti = auth_token.jti;
-                        busConfig.token = auth_token.jwt;
-                    }
-                    await table.SaveOrUpdateAll(busConfigs);
-                    return Ok(new { state = RespondCode.Ok, busConfigs });
+                    using var json = await JsonDocument.ParseAsync(response.ContentStream);
+                    bizConfig = json.ToObject<BizConfig>();
+                    var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, bizConfig.id, _option.JwtSecretKey, "business");
+                    bizConfig.jti = auth_token.jti;
+                    bizConfig.token = auth_token.jwt;
+
+                    bizConfig = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizConfig>(bizConfig, bizConfig.id, new PartitionKey("BizConfig"));
                 }
-                else
-                    return Ok(new { state = RespondCode.ParamsError, msg = "未找到企业信息" });
+
+                return Ok(new { state = RespondCode.Ok, bizConfig });
             }
             catch (Exception e)
             {
-                await _dingDing.SendBotMsg($"OS,{_option.Location} , /biz/reset-bus  \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
+                await _dingDing.SendBotMsg($"OS,{_option.Location} , /biz/reset-secretkey   \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
                 return BadRequest();
             }
         }
 
+
         /// <summary>
-        /// 依据企业ID查询关联的学校
+        /// 通过企业Id查询用户信息
         /// </summary>
         /// <param name="jsonElement"></param>
         /// <returns></returns>
         [ProducesDefaultResponseType]
-        [HttpPost("get-companyschool")]
-        public async Task<IActionResult> GetCompanySc(JsonElement jsonElement)
+        [HttpPost("get-bizid")]
+        public async Task<IActionResult> GetBizIdUsers(JsonElement jsonElement)
         {
             try
             {
-                if(!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
-
-                var table = _azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
-                Dictionary<string, object> keyValue = new() { { "PartitionKey", $"BusinessSchool" } };
+                if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
+                var cosmosClient = _azureCosmos.GetCosmosClient();
 
-                if (!string.IsNullOrEmpty($"{id}"))
+                List<BusinessUsers> businessUsers = new();
+                string sql = $"select value(c) from c join s in c.relation  where c.code='BizUsers' and s.bizId = '80e1bb6c-acba-46ab-9939-4851c4ef2158'";
+                await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BusinessUsers>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
                 {
-                    keyValue.Add("bizid", $"{id}");
+                    businessUsers.Add(item);
                 }
 
-                List<BusinessSchool> busSchools = await table.FindListByDict<BusinessSchool>(keyValue);
-
-                return Ok(new { state = 200, busSchools });
+                return Ok(new { state = RespondCode.Ok, businessUsers });
             }
             catch (Exception e)
             {
-                await _dingDing.SendBotMsg($"OS,{_option.Location} , /biz/get-companyschool   \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
+                await _dingDing.SendBotMsg($"OS,{_option.Location} , /biz/get-bizid   \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
                 return BadRequest();
             }
         }
 
-
     }
 }