12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268 |
- 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 TEAMModelBI.Tool.Context;
- using TEAMModelBI.DI.BIAzureStorage;
- namespace TEAMModelBI.Controllers.DingDingStruc
- {
- [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;
- public TableDingDingInfoController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IConfiguration configuration, IHttpClientFactory http)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _azureStorage = azureStorage;
- _option = option?.Value;
- _http = http;
- _configuration = configuration;
- }
- /// <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.GlobalSite))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
- }
- 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();
- 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.GlobalSite))
- {
- table = _azureStorage.GetCloudTableClient(BIConst.GlobalSite).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.GlobalSite))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
- }
- 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.GlobalSite))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
- }
- 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.GlobalSite))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
- }
- 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-permissions \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.GlobalSite))
- {
- cosmosCliet = _azureCosmos.GetCosmosClient(name: BIConst.GlobalSite);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
- };
- 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.GlobalSite))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
- }
- 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;
- 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.GlobalSite))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
- }
- 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>
- /// 通过醍摩豆账户信息 设置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.GlobalSite))
- {
- cosmosCliet = _azureCosmos.GetCosmosClient(name: BIConst.GlobalSite);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
- }
- 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.GlobalSite))
- {
- table = _azureStorage.GetCloudTableClient(BIConst.GlobalSite).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> { { "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<AdvSchool> handleSchools { get; set; } = new List<AdvSchool>();
- }
- }
- }
|