12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787 |
- 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 System.Text;
- using Microsoft.Azure.Cosmos;
- 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;
- using TEAMModelOS.SDK.Context.Constant;
- using TEAMModelOS.SDK.Models.Dtos;
- using TEAMModelOS.SDK.Models.Cosmos.BI.BISchool;
- 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);
- //获取access_token
- IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest tokenRequest = new() { 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() { 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() { 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() { 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() { 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() { 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);
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- 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);
- }
- }
- //保存和修改至Table
- List<DingDingUserInfo> UserInfo = await table.SaveOrUpdateAll(tempddUserInfos);
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{_tmdName}【{_tmdId}】从钉钉组织结构更新至Azure Table表【DDUserInfo】中。", _dingDing, httpContext: HttpContext);
- 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,
- isDisable = item.isDisable,
- 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,
- isDisable = item.isDisable,
- 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>
- /// 更新钉钉和醍摩豆的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();
- if (!jsonElement.TryGetProperty("isDisable", out JsonElement _isDisable)) return BadRequest();
- var cosmosCliet = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- long isDisable = 0;
- try
- {
- isDisable = long.Parse($"{_isDisable}");
- if (isDisable != 1 && isDisable != 0)
- return Ok(new { state = RespondCode.ParamsError, msg = "账户禁用参数错误!" });
- }
- catch
- {
- return Ok(new { state = RespondCode.ParamsError, msg = "账户禁用参数错误!" });
- }
- var table = tableClient.GetTableReference("BIDDUserInfo");
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- List<DingDingUserInfo> ddUserInfos = 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);
- List<string> oldRoles = new();
- List<Task<ItemResponse<BIRelation>>> upBIRel = new();
- //List<Task<ItemResponse<SchoolTeacher>>> upScTch = new();
- foreach (var item in tempUser)
- {
- oldRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
- stringBuilder.Append($"操作醍摩豆账户{item.tmdName}【{item.tmdId}】修改权限:{string.Join("|", listper.ToArray())}");
-
- item.roles = listroles.Count > 0 ? string.Join(",", listroles) : "assist";
- item.permissions = string.Join(",", listper);
- item.isDisable = isDisable;
- ddUserInfos.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>();
- foreach (var itemR in listroles)
- {
- if(itemR.Equals("assist"))
- {
- string tempSql = $"select value(c) from c join a in c.sales where a.id='{itemR}'";
- await foreach (var itemRel in cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<BIRelation>(queryText: tempSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
- {
- var tempRel = itemRel.sales.Find(f => f.id.Equals(itemR));
- itemRel.sales.Remove(tempRel);
- itemRel.assists.Add(tempRel);
- itemRel.upDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- upBIRel.Add(cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<BIRelation>(itemRel, itemRel.id, new PartitionKey("BIRel")));
- }
- //string sql = $"select value(c) from c where c.pk='Teacher' and c.id='{item.tmdId}'";
- //await foreach (var scTch in cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<SchoolTeacher>(queryText: sql, requestOptions: new QueryRequestOptions() { }))
- //{
- // if (scTch.roles.Contains("sales"))
- // {
- // //int index = scTch.roles.FindIndex(fi => fi.Equals("sales"));
- // //scTch.roles[index]= "assist";
- // //scTch.job = "顾问";
- // //upScTch.Add(cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(scTch, scTch.id, new PartitionKey($"{scTch.code}")));
- // int index = scTch.roles.FindIndex(fi => fi.Equals("sales"));
- // if (index >= 0)
- // {
- // scTch.roles[index] = "assist";
- // scTch.job = "顾问";
- // upScTch.Add(cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(scTch, scTch.id, new PartitionKey($"{scTch.code}")));
- // }
- // }
- //}
- }
- if (itemR.Equals("sales"))
- {
- string tempSql = $"select value(c) from c join a in c.assists where a.id='{itemR}'";
- await foreach (var itemRel in cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<BIRelation>(queryText: tempSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
- {
- var tempRel = itemRel.sales.Find(f => f.id.Equals(itemR));
- itemRel.assists.Remove(tempRel);
- itemRel.sales.Add(tempRel);
- itemRel.upDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- upBIRel.Add(cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<BIRelation>(itemRel, itemRel.id, new PartitionKey("BIRel")));
- }
- //string sql = $"select value(c) from c where c.pk='Teacher' and c.id='{item.tmdId}'";
- //await foreach (var scTch in cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<SchoolTeacher>(queryText: sql, requestOptions: new QueryRequestOptions() { }))
- //{
- // if (scTch.roles.Contains("assist"))
- // {
- // int index = scTch.roles.FindIndex(fi => fi.Equals("assist"));
- // if (index >= 0)
- // {
- // scTch.roles[index] = "sales";
- // scTch.job = "销售";
- // upScTch.Add(cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(scTch, scTch.id, new PartitionKey($"{scTch.code}")));
- // }
- // }
- //}
- }
- }
- }
- if (upBIRel.Count < 256)
- {
- await Task.WhenAll(upBIRel);
- }
- else
- {
- int pages = (upBIRel.Count + 255) / 256;
- for (int i = 0; i < pages; i++)
- {
- List<Task<ItemResponse<BIRelation>>> tempRel = upBIRel.Skip((i) * 256).Take(256).ToList();
- await Task.WhenAll(tempRel);
- }
- }
- ddUserInfos = await table.UpdateAll<DingDingUserInfo>(ddUserInfos);
- List<DDUserInfo> ddUserInfo = new();
- foreach (var item in ddUserInfos)
- {
- DDUserInfo tempInfo = 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,
- isDisable = item.isDisable,
- 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("|"));
- tempInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
- }
- ddUserInfo.Add(tempInfo);
- }
- //保存操作记录
- 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/tabledd-update \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() { { "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<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,
- isDisable = item.isDisable,
- 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("|"));
- 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>
- /// 通过醍摩豆账户信息 设置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() { { "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,
- isDisable = respUser.isDisable,
- 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(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 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]
- [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";
- }
- 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 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>
- /// 从钉钉的组织架构中人员信息数据,并保存或者更新至Blob中 初始化使用该接口
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-dduserinitial")]
- public async Task<IActionResult> GetddUserInitial(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 tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest tokenRequest = new() { 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() { 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() { 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() { 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() { 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() { 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 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>
- /// <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 = "该手机号未找到醍摩豆账户" });
- 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 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]
- [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";
- }
- 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 AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200, roles });
- }
- /// <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>
- /// 查询钉钉待入职人员的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() { 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() { Offset = 0L, Size = 50 };
- reqInduction.SetHttpMethod("GET");
- OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
- if (rspInduction.Result.DataList != null)
- {
- List<DingDingUserInfo> ddUserInfos = new();
- foreach (var itemId in rspInduction.Result.DataList)
- {
- DingDingUserInfo ddUserInfo = new();
- ddUserInfo.PartitionKey = divide;
- ddUserInfo.RowKey = itemId;
- ddUserInfos.Add(ddUserInfo);
- }
- List<DingDingUserInfo> tempddUserInfos = await table.SaveAll(ddUserInfos);
- //保存操作记录
- 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() { 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 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>
- /// 依据人员信息唯一编码修改人员信息表中的醍摩豆id信息相关的事情。
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin")]
- [HttpPost("set-usettmdinfo")]
- public async Task<IActionResult> UpUserTmdInfo(JsonElement jsonElement)
- {
- try
- {
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partKey)) return BadRequest();
- if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
- if (!jsonElement.TryGetProperty("role", out JsonElement role)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- var table = tableClient.GetTableReference("BIDDUserInfo");
- StringBuilder msg = new($"{_tmdName}[{_tmdId}]将");
- List<DingDingUserInfo> upUserInfos = new();
- List<DDUserInfo> upUserInfo = new();
- CoreUser coreUser = new();
- string oldTmdId = null;
- string reole = null;
- var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partKey}" }, { "RowKey", $"{rowKey}" } });
- if (tempUser.Count > 0)
- {
- foreach (var item in tempUser)
- {
- oldTmdId = item.tmdId;
- reole = item.roles;
- coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{item.mobile}" } }, _option.Location, _configuration);
- if (!string.IsNullOrEmpty(coreUser.id))
- {
- item.tmdId = coreUser.id;
- item.tmdName = coreUser.name;
- item.tmdMobile = coreUser.mobile;
- item.picture = coreUser.picture;
- item.mail = coreUser.mail;
- msg.Append($"{item.name}的{item.tmdId}账号改为新的{coreUser.id}账号;");
- upUserInfos.Add(item);
- }
- else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
- }
- }
- if (!string.IsNullOrEmpty(coreUser.id))
- {
- msg.Append("并将学校就的学校信息移植到新的账号,移植的学校:");
- Teacher teacher = new();
- var respone = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(coreUser.id, new PartitionKey("Base"));
- if (respone.StatusCode == HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(respone.Content);
- teacher = json.ToObject<Teacher>();
- }
- else
- {
- teacher = new Teacher()
- {
- id = coreUser.id,
- code = "Base",
- name = coreUser.name,
- picture = coreUser.picture,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- }
- List<Task<ItemResponse<BIRelation>>> scRole = new();
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<BIRelation>(queryText: $"select value(c) from c join a in c.assists join s in c.sales where c.code='BIRel' and s.id='{oldTmdId}' or a.id='{oldTmdId}'", requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
- {
- var tempAss = item.assists.Find(f => f.id.Equals($"{oldTmdId}"));
- if (tempAss != null)
- item.assists.Remove(tempAss);
- var tempSa = item.sales.Find(f => f.id.Equals($"{oldTmdId}"));
- if (tempSa != null)
- item.sales.Remove(tempAss);
- switch ($"{role}")
- {
- case "assist":
- item.assists.Add(new IdInfo() { id = coreUser.id, name = coreUser.name, picture = coreUser.picture });
- break;
- case "sales":
- item.sales.Add(new IdInfo() { id = coreUser.id, name = coreUser.name, picture = coreUser.picture });
- break;
- }
- item.upDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- scRole.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<BIRelation>(item, item.id, new PartitionKey("BIRel")));
- }
- if (scRole.Count < 256)
- await Task.WhenAll(scRole);
- else
- {
- int pages = (scRole.Count + 255) / 256;
- for (int i = 0; i < pages; i++)
- {
- List<Task<ItemResponse<BIRelation>>> tempScRole = scRole.Skip((i) * 256).Take(256).ToList();
- await Task.WhenAll(tempScRole);
- }
- }
- //List<Task<ItemResponse<SchoolTeacher>>> schoolTeachers = new();
- //await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<SchoolTeacher>($"select value(c) from c where c.pk='Teacher' and c.id='{oldTmdId}'"))
- //{
- // item.id = coreUser.id;
- // var resp = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{coreUser.id}", new PartitionKey($"{item.code}"));
- // if (resp.Status == 200)
- // {
- // using var json = await JsonDocument.ParseAsync(resp.Content);
- // SchoolTeacher scTeacher = json.ToObject<SchoolTeacher>();
- // if (scTeacher.roles.Contains("sales"))
- // scTeacher.roles.Remove("sales");
- // if (scTeacher.roles.Contains("assist"))
- // scTeacher.roles.Remove("assist");
- // string scId = scTeacher.code.Substring(scTeacher.code.IndexOf("-") + 1);
- // Teacher.TeacherSchool isExitId = null;
- // isExitId = teacher.schools.Find(s => s.schoolId.Equals(scId));
- // if (isExitId == null)
- // {
- // ScEasyInfo school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<ScEasyInfo>(scId, new PartitionKey("Base"));
- // msg.Append($"{school.name}[{school.id}],");
- // teacher.schools.Add(new Teacher.TeacherSchool() { schoolId = school.id, name = school.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = school.picture, areaId = school.areaId });
- // }
- // scTeacher.roles.Add(reole);
- // schoolTeachers.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(scTeacher, scTeacher.id, new PartitionKey($"{scTeacher.code}")));
- // }
- // else
- // {
- // item.name = coreUser.name;
- // string scId = item.code.Substring(item.code.IndexOf("-") + 1);
- // Teacher.TeacherSchool isExitId = null;
- // isExitId = teacher.schools.Find(s => s.schoolId.Equals(scId));
- // if (isExitId == null)
- // {
- // ScEasyInfo school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<ScEasyInfo>(scId, new PartitionKey("Base"));
- // msg.Append($"{school.name}[{school.id}],");
- // teacher.schools.Add(new Teacher.TeacherSchool() { schoolId = school.id, name = school.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = school.picture, areaId = school.areaId });
- // }
- // schoolTeachers.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(item, new PartitionKey($"{item.code}")));
- // }
- //}
- //if (schoolTeachers.Count < 256)
- // await Task.WhenAll(schoolTeachers);
- //else
- //{
- // int pages = (schoolTeachers.Count + 255) / 256;
- // for (int i = 0; i < pages; i++)
- // {
- // List<Task<ItemResponse<SchoolTeacher>>> tempScTeachers = schoolTeachers.Skip((i) * 256).Take(256).ToList();
- // await Task.WhenAll(tempScTeachers);
- // }
- //}
- if (respone.StatusCode == HttpStatusCode.OK)
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
- else
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
- upUserInfos = await table.SaveOrUpdateAll<DingDingUserInfo>(upUserInfos);
- }
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update-tmdinfo", msg.ToString(), _dingDing, httpContext: HttpContext);
- foreach (var item in upUserInfos)
- {
- DDUserInfo tempUserInfo = 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,
- isDisable = item.isDisable,
- 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("|"));
- tempUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosClient, tempSchoolIds);
- }
- upUserInfo.Add(tempUserInfo);
- }
- return Ok(new { state = RespondCode.Ok, upUserInfo });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-usettmdinfo \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <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");
- //long joinDate = DateTimeOffset.UtcNow.AddDays(-91).ToUnixTimeMilliseconds();
- //获取部门用户
- 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)
- {
- //long isDisble = 0;
- //if (!string.IsNullOrEmpty($"{itemUser.HiredDate}"))
- //{
- // if (itemUser.HiredDate < joinDate)
- // isDisble = 1;
- // else
- // isDisble = 0;
- //}
- 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,
- isDisable = 1,
- };
- 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 = "",
- isDisable = 0,
- };
- 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 long isDisable { 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>();
- }
- }
- }
|