123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788 |
- 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;
- using Microsoft.Azure.Cosmos.Table;
- 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>();
- }
- }
- }
|