1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348 |
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.DI;
- using Microsoft.Extensions.Options;
- using System.Net.Http;
- using Microsoft.Extensions.Configuration;
- using DingTalk.Api;
- using DingTalk.Api.Request;
- using DingTalk.Api.Response;
- using System.Text.Json;
- using System.Net.Http.Json;
- using TEAMModelOS.SDK.Models.Cosmos.BI;
- using System.Net;
- using TEAMModelOS.SDK.Extension;
- using OpenXmlPowerTools;
- using System.Text;
- using Azure.Cosmos;
- using Microsoft.Azure.Cosmos.Table;
- using TEAMModelBI.Filter;
- using TEAMModelBI.Tool.Extension;
- using TEAMModelBI.Models;
- using TEAMModelBI.Tool.CosmosBank;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.Context.BI;
- using TEAMModelOS.SDK.Models;
- namespace TEAMModelBI.Controllers.BITable
- {
- [Route("tabledd")]
- [ApiController]
- public class TableDingDingInfoController : ControllerBase
- {
- //读取配置文件
- private readonly IConfiguration _configuration;
- //数据容器
- private readonly AzureCosmosFactory _azureCosmos;
- //blob和table容器
- private readonly AzureStorageFactory _azureStorage;
- //钉钉提示信息
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly IHttpClientFactory _http;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- public TableDingDingInfoController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IConfiguration configuration, IHttpClientFactory http, CoreAPIHttpService coreAPIHttpService)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _azureStorage = azureStorage;
- _option = option?.Value;
- _http = http;
- _configuration = configuration;
- _coreAPIHttpService = coreAPIHttpService;
- }
- /// <summary>
- /// 从钉钉的组织架构中人员信息数据,并保存或者更新至Blob中 已对接
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "admin,rdc")]
- [HttpPost("get-dingdingusers")]
- public async Task<IActionResult> GetDingDingUser(JsonElement jsonElement)
- {
- try
- {
- 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("BIDDUserInfo");
- string appKey = _configuration["DingDingAuth:appKey"];
- string appSecret = _configuration["DingDingAuth:appSecret"];
- //string divide = _configuration["CustomParam:SiteScope"];
- string divide = _option.Location;
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- //HttpClient httpClient = _http.CreateClient();
- //string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
- //获取access_token
- IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest tokenRequest = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
- tokenRequest.SetHttpMethod("Get");
- OapiGettokenResponse tokenRespone = tokenClient.Execute(tokenRequest);
- if (tokenRespone.IsError)
- {
- return BadRequest();
- }
- //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
- string access_token = tokenRespone.AccessToken;
- //获取部门接口
- IDingTalkClient deptListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
- //一级部门
- OapiV2DepartmentListsubRequest reqDeptList1 = new OapiV2DepartmentListsubRequest() { DeptId = 1L, Language = "zh_CN" };
- OapiV2DepartmentListsubResponse rspDeptList1 = deptListClient.Execute(reqDeptList1, access_token);
- List<DingDingUserInfo> ddUserInfos = new();
- if (rspDeptList1.Result != null)
- {
- foreach (var tempDept1 in rspDeptList1.Result)
- {
- //获取一级部门用户信息
- List<DingDingUserInfo> dingDingUserInfos1 = await GetDingDingUserInfo(divide, tempDept1.DeptId, tempDept1.ParentId, tempDept1.Name, access_token);
- //if (dingDingUserInfos1.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos1.ToList()));
- if (dingDingUserInfos1.Count > 0) ddUserInfos.AddRange(dingDingUserInfos1);
- //获取二级部门
- OapiV2DepartmentListsubRequest reqDeptList2 = new OapiV2DepartmentListsubRequest() { DeptId = tempDept1.DeptId, Language = "zh_CN" };
- OapiV2DepartmentListsubResponse rspDeptList2 = deptListClient.Execute(reqDeptList2, access_token);
- if (rspDeptList2.Result != null)
- {
- foreach (var tempDept2 in rspDeptList2.Result)
- {
- //获取二级部门用户信息
- List<DingDingUserInfo> dingDingUserInfos2 = await GetDingDingUserInfo(divide, tempDept2.DeptId, tempDept2.ParentId, tempDept2.Name, access_token);
- //if (dingDingUserInfos2.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos2.ToList()));
- if (dingDingUserInfos2.Count > 0) ddUserInfos.AddRange(dingDingUserInfos2);
- //获取三级部门
- OapiV2DepartmentListsubRequest reqDeptList3 = new OapiV2DepartmentListsubRequest() { DeptId = tempDept2.DeptId, Language = "zh_CN" };
- OapiV2DepartmentListsubResponse rspDeptList3 = deptListClient.Execute(reqDeptList3, access_token);
- if (rspDeptList3.Result != null)
- {
- foreach (var tempDept3 in rspDeptList3.Result)
- {
- //获取三级部门用户信息
- List<DingDingUserInfo> dingDingUserInfos3 = await GetDingDingUserInfo(divide, tempDept3.DeptId, tempDept3.ParentId, tempDept3.Name, access_token);
- //if (dingDingUserInfos3.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos3.ToList()));
- if (dingDingUserInfos3.Count > 0) ddUserInfos.AddRange(dingDingUserInfos3);
- //获取四级部门
- OapiV2DepartmentListsubRequest reqDeptList4 = new OapiV2DepartmentListsubRequest() { DeptId = tempDept3.DeptId, Language = "zh_CN" };
- OapiV2DepartmentListsubResponse rspDeptList4 = deptListClient.Execute(reqDeptList4, access_token);
- if (rspDeptList4.Result != null)
- {
- foreach (var tempDept4 in rspDeptList4.Result)
- {
- //获取四级部门用户信息
- List<DingDingUserInfo> dingDingUserInfos4 = await GetDingDingUserInfo(divide, tempDept4.DeptId, tempDept4.ParentId, tempDept4.Name, access_token);
- //if (dingDingUserInfos4.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos4.ToList()));
- if (dingDingUserInfos4.Count > 0) ddUserInfos.AddRange(dingDingUserInfos4);
- //获取五级部门
- OapiV2DepartmentListsubRequest reqDeptList5 = new OapiV2DepartmentListsubRequest() { DeptId = tempDept4.DeptId, Language = "zh_CN" };
- OapiV2DepartmentListsubResponse rspDeptList5 = deptListClient.Execute(reqDeptList5, access_token);
- if (rspDeptList5.Result != null)
- {
- foreach (var tempDept5 in rspDeptList5.Result)
- {
- //获取五级部门用户信息
- List<DingDingUserInfo> dingDingUserInfos5 = await GetDingDingUserInfo(divide, tempDept5.DeptId, tempDept5.ParentId, tempDept5.Name, access_token);
- //if (dingDingUserInfos5.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos5).ToList());
- if (dingDingUserInfos5.Count > 0) ddUserInfos.AddRange(dingDingUserInfos5);
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- //保存操作记录
- //await _azureStorage.SaveBILog("tabledd-update", $"{_tmdName}【{_tmdId}】从钉钉组织结构更新至Azure Table表【DDUserInfo】中。", _dingDing, httpContext: HttpContext);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{_tmdName}【{_tmdId}】从钉钉组织结构更新至Azure Table表【DDUserInfo】中。", _dingDing, httpContext: HttpContext);
- var tempddUserInfos = ddUserInfos.GroupBy(c => c.userId).Select(c => c.First()).ToList();//去重
- //List<DingDingUserInfo> TempdingDingUserInfos = await _azureStorage.SaveOrUpdateAll(dingDingUserInfos); //只是保存至Table
- //查询数据的数据 并和钉钉查询的数据对比,找出不同的数据,并删除 待后期测试
- var users = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{divide}" } });
- List<DingDingUserInfo> noExisits = new();
- if (users.Count > 0)
- {
- //var temps = users.Union(tempddUserInfos).Except(users.Intersect(tempddUserInfos));
- List<DingDingUserInfo> existsUserInfo = users.Where(u => !tempddUserInfos.Exists(e => u.userId.Equals(e.userId) && u.PartitionKey.Equals(e.PartitionKey))).ToList();
- if (users.Count >= tempddUserInfos.Count)
- {
- existsUserInfo.AddRange(tempddUserInfos.Where(e => !users.Exists(u => e.userId.Equals(u.userId) && e.PartitionKey.Equals(u.PartitionKey))).ToList());
- }
- ////List<DingDingUserInfo> existsUserInfo = users.Where((x, i) => users.FindIndex(z => z.userId.Equals(x.userId) && x.PartitionKey.Equals(divide)) == i).Select(x => x).ToList();
- if (existsUserInfo.Count > 0)
- {
- noExisits = await table.DeleteAll(existsUserInfo);
- }
- }
- List<DingDingUserInfo> UserInfo = await table.SaveOrUpdateAll(tempddUserInfos); //保存和修改至Table
- return Ok(new { state = 200, UserInfo, noExisits });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/get-dingdingusers \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 查询钉钉信息和醍摩豆信息 //已对接
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-ddusers")]
- public async Task<IActionResult> GetDingDingUsers(JsonElement jsonElement)
- {
- try
- {
- jsonElement.TryGetProperty("busy", out JsonElement busy);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosCliet = _azureCosmos.GetCosmosClient();
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
- if ($"{site}".Equals(BIConst.Global))
- {
- table = _azureStorage.GetCloudTableClient(BIConst.Global).GetTableReference("BIDDUserInfo");
- }
- //string divide = _configuration["CustomParam:SiteScope"];
- string divide = _option.Location;
- List<DDUserInfo> ddUserInfos = new();
- Dictionary<string, object> dic = new() { { "PartitionKey", $"{divide}" } };
- List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
- switch ($"{busy}")
- {
- case "admin":
- foreach (var item in ddUserInfoList)
- {
- if (item.roles.Contains("admin"))
- {
- DDUserInfo ddUserInfo = new()
- {
- partitionKey = item.PartitionKey,
- rowKey = item.RowKey,
- userId = item.userId,
- unionId = item.unionId,
- name = item.name,
- title = item.title,
- stateCode = item.stateCode,
- mobile = item.mobile,
- jobNumber = item.jobNumber,
- pid = item.pid,
- deptId = item.deptId,
- deptName = item.deptName,
- depts = item.depts,
- avatar = item.avatar,
- isAdmin = item.isAdmin,
- tmdId = item.tmdId,
- tmdName = item.tmdName,
- tmdMobile = item.tmdMobile,
- mail = item.mail,
- picture = item.picture,
- roles = item.roles,
- joinTime = item.joinTime,
- permissions = item.permissions,
- handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
- handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
-
- };
- if (!string.IsNullOrEmpty(item.schoolIds))
- {
- List<string> tempSchoolIds = new(item.schoolIds.Split("|"));
- ddUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
- }
- ddUserInfos.Add(ddUserInfo);
- }
- }
- break;
- default:
- foreach (var item in ddUserInfoList)
- {
- DDUserInfo ddUserInfo = new()
- {
- partitionKey = item.PartitionKey,
- rowKey = item.RowKey,
- userId = item.userId,
- unionId = item.unionId,
- name = item.name,
- title = item.title,
- stateCode = item.stateCode,
- mobile = item.mobile,
- jobNumber = item.jobNumber,
- pid = item.pid,
- deptId = item.deptId,
- deptName = item.deptName,
- depts = item.depts,
- avatar = item.avatar,
- isAdmin = item.isAdmin,
- tmdId = item.tmdId,
- tmdName = item.tmdName,
- tmdMobile = item.tmdMobile,
- mail = item.mail,
- picture = item.picture,
- roles = item.roles,
- joinTime = item.joinTime,
- permissions = item.permissions,
- handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
- handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
- };
- if (!string.IsNullOrEmpty(item.schoolIds))
- {
- List<string> tempSchoolIds = new(item.schoolIds.Split("|"));
- ddUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
- }
- ddUserInfos.Add(ddUserInfo);
- }
- break;
- }
- return Ok(new { state = 200, ddUserInfos = ddUserInfos });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/get-ddusers \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 查询钉钉待入职人员的ID添加至Table数据表中
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("set-ddinductionuser")]
- public async Task<IActionResult> SetDingDingInductionUser(JsonElement jsonElement)
- {
- try
- {
- 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("BIDDUserInfo");
- string appKey = _configuration["DingDingAuth:appKey"];
- string appSecret = _configuration["DingDingAuth:appSecret"];
- //string divide = _configuration["CustomParam:SiteScope"];
- string divide = _option.Location;
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- //获取access_token
- IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
- request.SetHttpMethod("Get");
- OapiGettokenResponse response = client.Execute(request);
- if (response.IsError)
- {
- return BadRequest();
- }
- //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
- string access_token = response.AccessToken;
- IDingTalkClient InductionClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querypreentry");
- OapiSmartworkHrmEmployeeQuerypreentryRequest reqInduction = new OapiSmartworkHrmEmployeeQuerypreentryRequest() { Offset = 0L, Size = 50 };
- reqInduction.SetHttpMethod("GET");
- OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
- if (rspInduction.Result.DataList != null)
- {
- List<DingDingUserInfo> ddUserInfos = new List<DingDingUserInfo>();
- foreach (var itemId in rspInduction.Result.DataList)
- {
- DingDingUserInfo ddUserInfo = new DingDingUserInfo();
- ddUserInfo.PartitionKey = divide;
- ddUserInfo.RowKey = itemId;
- ddUserInfos.Add(ddUserInfo);
- }
- List<DingDingUserInfo> tempddUserInfos = await table.SaveAll(ddUserInfos);
- //保存操作记录
- //await _azureStorage.SaveBILog("tabledd-add", $"{_tmdName}【{_tmdId}】添加待入职员工至table数据表中", _dingDing, httpContext: HttpContext);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-add", $"{_tmdName}【{_tmdId}】添加待入职员工至table数据表中", _dingDing, httpContext: HttpContext);
- if (ddUserInfos.Count == tempddUserInfos.Count)
- {
- return Ok(new { state = 200, UserInfo = tempddUserInfos });
- }
- else
- {
- var diffArr = tempddUserInfos.Where(c => !ddUserInfos.Contains(c)).ToList();
- return Ok(new { state = 201, notUserInfo = diffArr });
- }
- }
- else
- {
- return Ok(new { state = 400, rspInduction.SubErrCode, rspInduction.SubErrMsg });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-ddinductionuser \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 获取钉钉离职人员ID并删除Table表中的数据
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("del-ddquituser")]
- public async Task<IActionResult> DeleteDDQuitUser(JsonElement jsonElement)
- {
- try
- {
- 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("BIDDUserInfo");
- string appKey = _configuration["DingDingAuth:appKey"];
- string appSecret = _configuration["DingDingAuth:appSecret"];
- //string divide = _configuration["CustomParam:SiteScope"];
- string divide = _option.Location;
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- //获取access_token
- IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest request = new() { Appkey = appKey, Appsecret = appSecret };
- request.SetHttpMethod("Get");
- OapiGettokenResponse response = client.Execute(request);
- if (response.IsError)
- {
- return BadRequest();
- }
- //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
- string access_token = response.AccessToken;
- IDingTalkClient quitStaffClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
- OapiSmartworkHrmEmployeeQuerydimissionRequest reqDimission = new OapiSmartworkHrmEmployeeQuerydimissionRequest() { Offset = 0L, Size = 50L };
- OapiSmartworkHrmEmployeeQuerydimissionResponse rspDimission = quitStaffClient.Execute(reqDimission, access_token);
- if (rspDimission.Result != null)
- {
- List<DingDingUserInfo> ddUserInfos = new();
- foreach (var itemId in rspDimission.Result.DataList)
- {
- await table.DeleteSingle<DingDingUserInfo>(divide, $"{itemId}");
- }
- //保存操作记录
- //await _azureStorage.SaveBILog("tabledd-del", $"{_tmdName}【{_tmdId}】从table数据表中删除离职员工", _dingDing, httpContext: HttpContext);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-del", $"{_tmdName}【{_tmdId}】从table数据表中删除离职员工", _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200 });
- }
- else
- {
- return Ok(new { state = rspDimission.SubErrCode });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/del-ddquituser \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 更新钉钉和醍摩豆的BI权限 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("set-rolesper")]
- public async Task<IActionResult> SetPermissions(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
- jsonElement.TryGetProperty("userId", out JsonElement userId);
- jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
- if (!jsonElement.TryGetProperty("permissions", out JsonElement _permissions)) return BadRequest();
- if (!jsonElement.TryGetProperty("roles", out JsonElement _roles)) return BadRequest();
- 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("BIDDUserInfo");
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- List<DingDingUserInfo> ddUserInfo = new();
- List<string> listper = _permissions.ToObject<List<string>>();
- List<string> listroles = _roles.ToObject<List<string>>();
- List<string> roles = new();//角色列表
- List<string> permissions = new();//权限列表
- StringBuilder stringBuilder = new($"{_tmdName}【{_tmdId}】醍摩豆账号");
- Dictionary<string, object> dic = new() { { "PartitionKey", $"{partitionKey}" } };
- if (!string.IsNullOrEmpty($"{userId}"))
- {
- dic.Add("userId", $"{userId}");
- }
- if (!string.IsNullOrEmpty($"{tmdId}"))
- {
- dic.Add("tmdId", $"{tmdId}");
- }
- if (string.IsNullOrEmpty($"{userId}") && string.IsNullOrEmpty($"{tmdId}"))
- {
- return BadRequest();
- }
- var tempUser = await table.FindListByDict<DingDingUserInfo>(dic);
- foreach (var item in tempUser)
- {
- stringBuilder.Append($"操作醍摩豆账户{item.tmdName}【{item.tmdId}】修改权限:{string.Join("|", listper.ToArray())}");
-
- item.roles = listroles.Count > 0 ? string.Join(",", listroles) : "assist";
- item.permissions = string.Join(",", listper);
- ddUserInfo.Add(item);
- roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
- permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
- }
- ddUserInfo = await table.UpdateAll<DingDingUserInfo>(ddUserInfo);
- //保存操作记录
- //await _azureStorage.SaveBILog("tabledd-update", stringBuilder?.ToString(), _dingDing, httpContext: HttpContext);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", stringBuilder?.ToString(), _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200, ddUserInfo, roles, permissions });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-rolesper \n {ex.Message}\n{ex.StackTrace} ", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 依据部门ID获取部门列表 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-dddeptiduser")]
- public async Task<IActionResult> GetDDDeptIdUser(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("deptId", out JsonElement deptId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosCliet = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosCliet = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- };
- var table = tableClient.GetTableReference("BIDDUserInfo");
- //string divide = _configuration["CustomParam:SiteScope"];
- string divide = _option.Location;
- Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
- List<DingDingUserInfo> tempUserInfos = await table.FindListByDict<DingDingUserInfo>(dic);
- List<DingDingUserInfo> userInfo = new();
- tempUserInfos.ForEach(x => {
- if (x.depts.Contains($"{deptId}"))
- {
- userInfo.Add(x);
- }
- if (x.pid.Equals(long.Parse($"{deptId}")))
- {
- userInfo.Add(x);
- }
- });
- //userInfo.Distinct().ToList(); //Equals实现去重
- userInfo.Where((x, i) => userInfo.FindIndex(z => z.RowKey.Equals(x.RowKey)) == i);//Lambda表达式去重
- //userInfo.GroupBy(p => p).Select(p => p.Key).ToList();//去重复
- //List<DingDingUserInfo> ddUserInfo = new();
- //List<DingDingUserInfo> tempUser = new();
- //tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "deptId", $"{deptId}" } });
- //if (tempUser.Count == 0)
- //{
- // tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{deptId}" } });
- //}
- //foreach (var itemUser in tempUser)
- //{
- // var tempUser1 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{deptId}" } });
- // foreach (var itemUser1 in tempUser1)
- // {
- // if (!long.Parse($"{deptId}").Equals(itemUser1.pid))
- // {
- // var tempUser2 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{itemUser1.pid}" } });
- // foreach (var itemUser2 in tempUser2)
- // {
- // if (!itemUser1.pid.Equals(itemUser2.pid))
- // {
- // var tempUser3 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{itemUser2.pid}" } });
- // foreach (var itemUser3 in tempUser3)
- // {
- // if (!itemUser2.pid.Equals(itemUser3.pid))
- // {
- // var tempUser4 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{itemUser3.pid}" } });
- // foreach (var itemUser4 in tempUser4)
- // {
- // if (!itemUser3.pid.Equals(itemUser4.pid)) { }
- // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser4.RowKey)) == null)
- // {
- // ddUserInfo.Add(itemUser4);
- // }
- // }
- // }
- // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser3.RowKey)) == null)
- // {
- // ddUserInfo.Add(itemUser3);
- // }
- // }
- // }
- // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser2.RowKey)) == null)
- // {
- // ddUserInfo.Add(itemUser2);
- // }
- // }
- // }
- // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser1.RowKey)) == null)
- // {
- // ddUserInfo.Add(itemUser1);
- // }
- // }
- // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser.RowKey)) == null)
- // {
- // ddUserInfo.Add(itemUser);
- // }
- //}
- List<DDUserInfo> ddUserInfos = new();
- foreach (var item in userInfo)
- {
- DDUserInfo tempUserInfo = new DDUserInfo()
- {
- partitionKey = item.PartitionKey,
- rowKey = item.RowKey,
- userId = item.userId,
- unionId = item.unionId,
- name = item.name,
- title = item.title,
- stateCode = item.stateCode,
- mobile = item.mobile,
- jobNumber = item.jobNumber,
- pid = item.pid,
- deptId = item.deptId,
- deptName = item.deptName,
- depts = item.depts,
- avatar = item.avatar,
- isAdmin = item.isAdmin,
- tmdId = item.tmdId,
- tmdName = item.tmdName,
- tmdMobile = item.tmdMobile,
- mail = item.mail,
- picture = item.picture,
- roles = item.roles,
- joinTime = item.joinTime,
- permissions = item.permissions,
- handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
- handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
- };
- if (!string.IsNullOrEmpty(item.schoolIds))
- {
- List<string> tempSchoolIds = new List<string>(item.schoolIds.Split("|"));
- tempUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
- }
- ddUserInfos.Add(tempUserInfo);
- }
- return Ok(new { state = 200, ddUserInfos });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/get-dddeptiduser \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
-
- /// <summary>
- /// 后端钉钉账户和醍摩豆账户进行绑定
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("set-backenbind")]
- public async Task<IActionResult> SetBackenBind(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
- if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var (_tmdId, _tmdName, pic, did, dname, dpic) = 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("BIDDUserInfo");
- List<DingDingUserInfo> tempddUsers = null;
- List<DingDingUserInfo> ddUsers = new();
- StringBuilder tableSql = new();
- if (!string.IsNullOrEmpty($"{rowKey}"))
- tableSql.Append($"RowKey {QueryComparisons.Equal} '{rowKey}'");
- string tmdId = null;
- string tmdName = null;
- string tmdMobile = null;
- string mail = null;
- string picture = null;
- var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{mobile}" } }, _option.Location, _configuration);
- if (coreUser != null && coreUser.id != null)
- {
- tmdId = coreUser.id;
- tmdName = coreUser.name;
- tmdMobile = coreUser.mobile;
- mail = coreUser.mail;
- picture = coreUser.picture;
- }else return Ok(new { state = 1, message = "该手机号未找到醍摩豆账户" });
- //HttpClient httpClient = _http.CreateClient();
- //string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
- //List<string> mobiles = new List<string>() { $"{mobile}" };
- //HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
- //if (responseMessage.StatusCode == HttpStatusCode.OK)
- //{
- // string temp = responseMessage.Content.ReadAsStringAsync().Result;
- // List<JsonElement> json_id = temp.ToObject<List<JsonElement>>();
- // if (json_id.Count > 0)
- // {
- // foreach (var item in json_id)
- // {
- // tmdId = item.GetProperty("id").ToString();
- // tmdName = item.GetProperty("name").ToString();
- // tmdMobile = item.GetProperty("mobile").ToString();
- // mail = item.GetProperty("mail").ToString();
- // picture = item.GetProperty("picture").ToString();
- // }
- // }
- // else return Ok(new { state = 1, message = "该手机号未找到醍摩豆账户" });
- //}
- tempddUsers = await table.QueryWhereString<DingDingUserInfo>(tableSql.ToString());
- if (tempddUsers.Count > 0)
- {
- foreach (var item in tempddUsers)
- {
- if (item.RowKey.Equals($"{rowKey}"))
- {
- item.tmdId = tmdId;
- item.tmdName = tmdName;
- item.tmdMobile = tmdMobile;
- item.mail = mail;
- item.picture = picture;
- ddUsers.Add(item);
- }
- }
- }
- else return Ok(new { state = 2, message = "钉钉ID错误请检查钉钉ID" });
- if (ddUsers.Count > 0) ddUsers = await table.SaveOrUpdateAll(ddUsers);
- //保存操作记录
- //await _azureStorage.SaveBILog("tabledd-update", $"{_tmdName}【{_tmdId}】操作:绑定钉钉账户[{rowKey}]和醍摩豆账户[{tmdId}]", _dingDing, httpContext: HttpContext);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{_tmdName}【{_tmdId}】操作:绑定钉钉账户[{rowKey}]和醍摩豆账户[{tmdId}]", _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200, ddUsers });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backenbind \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 设置系统管理员 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("set-backend")]
- public async Task<IActionResult> SetBackendAdmin(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
- if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
- if (!jsonElement.TryGetProperty("isAdmin", out JsonElement isAdmin)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var (_tmdId, _tmdName, pic, did, dname, dpic) = 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("BIDDUserInfo");
- var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{rowKey}" } });
-
- List<DDUserInfo> ddUserInfos = new();
- List<string> roles = new();//角色列表
- List<string> permissions = new();//权限列表
- StringBuilder msg = new($"{_tmdName}【{_tmdId}】");
- if (bool.Parse($"{isAdmin}") == true)
- {
- foreach (var user in tempUser)
- {
- if (string.IsNullOrEmpty(user.roles))
- {
- user.roles = "admin,assist";
- }
- List<string> tempRoles = new(user.roles.Split(","));
- if (!tempRoles.Contains("admin"))
- {
- tempRoles.Add("admin");
- }
- user.roles = string.Join(",", tempRoles);
- user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
- if (respUser != null)
- {
- roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
- }
- msg.Append($"添加{respUser.name}【{respUser.RowKey}】账号的BI管理员");
- }
- }
- else
- {
- var userInfos = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" } });
- var adminInfos = userInfos.FindAll(x => x.roles.Contains("admin"));
- if (adminInfos.Count == 1)
- {
- return Ok(new { state = 403, msg = "已经是最后一个管理员了" });
- }
- else
- {
- foreach (var user in tempUser)
- {
- if (!user.userId.Equals($"{did}"))
- {
- List<string> tempRoles = new(user.roles.Split(","));
- if (tempRoles.Contains("admin"))
- {
- tempRoles.Remove("admin");
- }
- user.roles = string.Join(",", tempRoles);
- DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
- if (respUser != null)
- {
- roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
- msg.Append($"取消{respUser.name}【{respUser.RowKey}】账号的BI管理员");
- }
- }
- else return Ok(new { state = 1, msg = "不能删除自己" });
- }
- }
- }
- //保存操作记录
- //await _azureStorage.SaveBILog("tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200, roles });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backend \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 后端初始化管理员
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("set-apiphoneadmin")]
- public async Task<IActionResult> SetPhoneAdmin(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey);
- if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- var partKey = _option.Location;
- if (string.IsNullOrEmpty($"{partitionKey}"))
- {
- partKey = $"{partitionKey}";
- };
- 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("BIDDUserInfo");
- var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partKey}" }, { "mobile", $"{mobile}" } });
- List<string> roles = new();//角色列表
- List<string> permissions = new();//权限列表
- StringBuilder msg = new();
- foreach (var user in tempUser)
- {
- if (string.IsNullOrEmpty(user.roles))
- {
- user.roles = "admin,assist";
- }
- List<string> tempRoles = new(user.roles.Split(","));
- if (!tempRoles.Contains("admin"))
- {
- tempRoles.Add("admin");
- }
- user.roles = string.Join(",", tempRoles);
- user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
- if (respUser != null)
- {
- roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
- }
- msg.Append($"初始将{respUser.name}【{respUser.RowKey}】账号的BI管理员");
- }
- //保存操作记录
- //await _azureStorage.SaveBILog("tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200, roles });
- }
- /// <summary>
- /// 通过醍摩豆账户信息 设置BI后台管理员 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("set-tmdadmin")]
- public async Task<IActionResult> SetTmdBackendAdmin(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
- if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
- if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
- jsonElement.TryGetProperty("picture ", out JsonElement picture);
- jsonElement.TryGetProperty("mail ", out JsonElement mail);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- var cosmosCliet = _azureCosmos.GetCosmosClient();
-
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosCliet = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- var table = tableClient.GetTableReference("BIDDUserInfo");
- List<DDUserInfo> ddUserInfos = new();
- List<string> roles = new();//角色列表
- List<string> permissions = new();//权限列表
- StringBuilder msg = new($"{_tmdName}【{_tmdId}】");
- //string divide = _configuration["CustomParam:SiteScope"];
- string divide = _option.Location;
- Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" }, { "mobile", $"{mobile}" } };
- List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
- if (ddUserInfoList.Count > 0)
- {
- foreach (var user in ddUserInfoList)
- {
- List<string> tempRoles = new(user.roles.Split(","));
- if (tempRoles.Count > 0)
- {
- if (!tempRoles.Contains("admin"))
- {
- tempRoles.Add("admin");
- }
- }
- else
- tempRoles.Add("admin");
- user.roles = string.Join(",", tempRoles);
- user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- user.tmdId = $"{tmdId}";
- user.tmdName = $"{tmdName}";
- user.tmdMobile = $"{mobile}";
- if (!string.IsNullOrEmpty($"{picture}"))
- {
- user.picture = $"{picture}";
- }
- if (!string.IsNullOrEmpty($"{mail}"))
- {
- user.mail = $"{mail}";
- }
- msg.Append($" 将:{tmdName}【{tmdId}】醍摩豆账号和({user.name}【{user.unionId}】) 钉钉账户绑定,并设置管理员");
- DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
-
- if (respUser != null)
- {
- roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
- }
- DDUserInfo dDUserInfo = new()
- {
- partitionKey = respUser.PartitionKey,
- rowKey = respUser.RowKey,
- userId = respUser.userId,
- unionId = respUser.unionId,
- name = respUser.name,
- title = respUser.title,
- stateCode = respUser.stateCode,
- mobile = respUser.mobile,
- jobNumber = respUser.jobNumber,
- pid = respUser.pid,
- deptId = respUser.deptId,
- deptName = respUser.deptName,
- depts = respUser.depts,
- avatar = respUser.avatar,
- isAdmin = respUser.isAdmin,
- tmdId = respUser.tmdId,
- tmdName = respUser.tmdName,
- tmdMobile = respUser.tmdMobile,
- mail = respUser.mail,
- picture = respUser.picture,
- roles = respUser.roles,
- joinTime = respUser.joinTime,
- permissions = respUser.permissions,
- handleRoles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>(),
- handlePermissions = !string.IsNullOrEmpty($"{respUser.permissions}") ? new List<string>(respUser.permissions.Split(",")) : new List<string>()
- };
- if (!string.IsNullOrEmpty(respUser.schoolIds))
- {
- List<string> tempSchoolIds = new List<string>(respUser.schoolIds.Split("|"));
- dDUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
- }
- ddUserInfos.Add(dDUserInfo);
- }
- }
- else
- {
- DingDingUserInfo dingDingUserInfo = new()
- {
- PartitionKey = divide,
- RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
- roles = "admin",
- tmdId = $"{tmdId}",
- tmdName = $"{tmdName}",
- tmdMobile = $"{mobile}",
- };
- if (!string.IsNullOrEmpty($"{picture}"))
- {
- dingDingUserInfo.picture = $"{picture}";
- }
- if (!string.IsNullOrEmpty($"{mail}"))
- {
- dingDingUserInfo.mail = $"{mail}";
- }
- DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(dingDingUserInfo);
- return Ok(new { state = 201, msg = "新生成的BIadmin", respUser });
- }
- //保存操作记录
- //await _azureStorage.SaveBILog("tabledd-update",msg.ToString(), _dingDing, httpContext: HttpContext);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200, ddUserInfos });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-tmdadmin \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 解除钉钉和醍摩豆的绑定
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("set-unbind")]
- public async Task<IActionResult> SetUnbind(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("mobile", out JsonElement mobile);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
- if ($"{site}".Equals(BIConst.Global))
- {
- table = _azureStorage.GetCloudTableClient(BIConst.Global).GetTableReference("BIDDUserInfo");
- }
- //string divide = _configuration["CustomParam:SiteScope"];
- string divide = _option.Location;
- Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
- if (!string.IsNullOrEmpty($"{mobile}"))
- dic.Add("tmdMobile", $"{mobile}");
- else
- dic.Add("tmdMobile", "18281911681");
- List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
- List<DingDingUserInfo> tempDDUI = new();
- if (ddUserInfoList.Count > 0)
- {
- foreach (var item in ddUserInfoList)
- {
- item.tmdId = null;
- item.tmdName = null;
- item.tmdMobile = null;
- item.picture = null;
- tempDDUI.Add(item);
- }
- }
- else return Ok(new { state = 404, msg = "未找到手机号匹配的绑定号码!,请检查手机号" });
- var userInfos = await table.SaveOrUpdateAll(tempDDUI); //保存和修改至Table
- return Ok(new { state = 200, userInfos });
- }
- /// <summary>
- /// 获取钉钉用户信息
- /// 并查询本地Table数据表中是否存在
- /// </summary>
- /// <param name="deptId"></param>
- /// <param name="parentId"></param>
- /// <param name="name"></param>
- /// <param name="access_token"></param>
- /// <returns></returns>
- public async Task<List<DingDingUserInfo>> GetDingDingUserInfo(string partitionKey, long deptId, long parentId, string name, string access_token)
- {
- List<DingDingUserInfo> ddUserInfos = new();
- //获取部门人员信息
- IDingTalkClient userListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
- //获取部门用户
- OapiV2UserListRequest reqUserList = new()
- {
- DeptId = deptId,
- Cursor = 0L,
- Size = 50L,
- OrderField = "custom",
- Language = "zh_CN"
- };
- reqUserList.SetHttpMethod("GET");
- OapiV2UserListResponse rspV2UserList = userListClient.Execute(reqUserList, access_token);
- if (rspV2UserList.Result.List != null)
- {
- foreach (var itemUser in rspV2UserList.Result.List)
- {
- var tempInfo = ddUserInfos.Find(x => x.RowKey.Equals(itemUser.Unionid));
- if (string.IsNullOrEmpty($"{tempInfo}"))
- {
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
- var users = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "userId", $"{itemUser.Userid}" }, { "unionId", $"{itemUser.Unionid}" } });
- if (users.Count > 0)
- {
- foreach (var user in users)
- {
- DingDingUserInfo ddUserInfo = new()
- {
- PartitionKey = user.PartitionKey,
- RowKey = user.RowKey,
- userId = itemUser.Userid,
- unionId = itemUser.Unionid,
- name = itemUser.Name,
- email = itemUser.Email,
- title = itemUser.Title,
- stateCode = itemUser.StateCode,
- mobile = itemUser.Mobile,
- jobNumber = itemUser.JobNumber,
- pid = parentId,
- deptId = deptId,
- deptName = name,
- depts = string.Join(",", itemUser.DeptIdList.ToArray()),
- avatar = itemUser.Avatar,
- isAdmin = itemUser.Admin,
- tmdId = user.tmdId,
- tmdName = user.tmdName,
- tmdMobile = user.tmdMobile,
- mail = user.mail,
- picture = user.picture,
- roles = user.roles,
- joinTime = user.joinTime,
- permissions = user.permissions,
- schoolIds = user.schoolIds
- };
- ddUserInfos.Add(ddUserInfo);
- }
- }
- else
- {
- DingDingUserInfo ddUserInfo = new()
- {
- RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
- userId = itemUser.Userid,
- unionId = itemUser.Unionid,
- name = itemUser.Name,
- email = itemUser.Email,
- title = itemUser.Title,
- stateCode = itemUser.StateCode,
- mobile = itemUser.Mobile,
- jobNumber = itemUser.JobNumber,
- pid = parentId,
- deptId = deptId,
- deptName = name,
- depts = string.Join(",", itemUser.DeptIdList.ToArray()),
- avatar = itemUser.Avatar,
- isAdmin = itemUser.Admin,
- PartitionKey = partitionKey,
- tmdId = "",
- tmdName = "",
- tmdMobile = "",
- mail = "",
- picture = "",
- roles = "",
- joinTime = 0,
- permissions = "areadata-read,areadata-upd,schooldata-read,schooldata-upd",
- schoolIds = ""
- };
- ddUserInfos.Add(ddUserInfo);
- }
- }
- }
- }
- return ddUserInfos;
- }
- public record DDUserInfo
- {
- public string partitionKey { get; set; }
- public string rowKey { get; set; }
- public string userId { get; set; }
- public string unionId { get; set; }
- public string name { get; set; }
- public string title { get; set; }
- public string stateCode { get; set; }
- public string mobile { get; set; }
- public string jobNumber { get; set; }
- public long pid { get; set; }
- public long deptId { get; set; }
- public string deptName { get; set; }
- public string depts { get; set; }
- public string avatar { get; set; }
- public bool isAdmin { get; set; }
- public string tmdId { get; set; }
- public string tmdName { get; set; }
- public string tmdMobile { get; set; }
- public string mail { get; set; }
- public string picture { get; set; }
- public string roles { get; set; }
- public long joinTime { get; set; }
- public string permissions { get; set; }
- public List<string> handleRoles { get; set; }
- public List<string> handlePermissions { get; set; }
- public List<BaseInfo> handleSchools { get; set; } = new List<BaseInfo>();
- }
- }
- }
|