TableDingDingInfoController.cs 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using TEAMModelOS.Models;
  8. using TEAMModelOS.SDK.DI;
  9. using Microsoft.Extensions.Options;
  10. using System.Net.Http;
  11. using Microsoft.Extensions.Configuration;
  12. using DingTalk.Api;
  13. using DingTalk.Api.Request;
  14. using DingTalk.Api.Response;
  15. using System.Text.Json;
  16. using System.Net.Http.Json;
  17. using TEAMModelOS.SDK.Models.Cosmos.BI;
  18. using System.Net;
  19. using TEAMModelOS.SDK.Extension;
  20. using OpenXmlPowerTools;
  21. using System.Text;
  22. using Azure.Cosmos;
  23. using Microsoft.Azure.Cosmos.Table;
  24. using TEAMModelBI.Filter;
  25. using TEAMModelBI.Tool.Extension;
  26. using TEAMModelBI.Models;
  27. using TEAMModelBI.Tool.CosmosBank;
  28. using TEAMModelOS.SDK;
  29. using TEAMModelOS.SDK.Context.BI;
  30. using TEAMModelOS.SDK.Models;
  31. using TEAMModelOS.SDK.Context.Constant;
  32. namespace TEAMModelBI.Controllers.BITable
  33. {
  34. [Route("tabledd")]
  35. [ApiController]
  36. public class TableDingDingInfoController : ControllerBase
  37. {
  38. //读取配置文件
  39. private readonly IConfiguration _configuration;
  40. //数据容器
  41. private readonly AzureCosmosFactory _azureCosmos;
  42. //blob和table容器
  43. private readonly AzureStorageFactory _azureStorage;
  44. //钉钉提示信息
  45. private readonly DingDing _dingDing;
  46. private readonly Option _option;
  47. private readonly IHttpClientFactory _http;
  48. private readonly CoreAPIHttpService _coreAPIHttpService;
  49. public TableDingDingInfoController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IConfiguration configuration, IHttpClientFactory http, CoreAPIHttpService coreAPIHttpService)
  50. {
  51. _azureCosmos = azureCosmos;
  52. _dingDing = dingDing;
  53. _azureStorage = azureStorage;
  54. _option = option?.Value;
  55. _http = http;
  56. _configuration = configuration;
  57. _coreAPIHttpService = coreAPIHttpService;
  58. }
  59. /// <summary>
  60. /// 从钉钉的组织架构中人员信息数据,并保存或者更新至Blob中 已对接
  61. /// </summary>
  62. /// <returns></returns>
  63. [ProducesDefaultResponseType]
  64. [AuthToken(Roles = "admin,rdc")]
  65. [HttpPost("get-dingdingusers")]
  66. public async Task<IActionResult> GetDingDingUser(JsonElement jsonElement)
  67. {
  68. try
  69. {
  70. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  71. var tableClient = _azureStorage.GetCloudTableClient();
  72. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  73. ////分开部署,就不需要,一站多用时,取消注释
  74. //if ($"{site}".Equals(BIConst.Global))
  75. //{
  76. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  77. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  78. //}
  79. var table = tableClient.GetTableReference("BIDDUserInfo");
  80. string appKey = _configuration["DingDingAuth:appKey"];
  81. string appSecret = _configuration["DingDingAuth:appSecret"];
  82. //string divide = _configuration["CustomParam:SiteScope"];
  83. string divide = _option.Location;
  84. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  85. //HttpClient httpClient = _http.CreateClient();
  86. //string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  87. //获取access_token
  88. IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  89. OapiGettokenRequest tokenRequest = new() { Appkey = appKey, Appsecret = appSecret };
  90. tokenRequest.SetHttpMethod("Get");
  91. OapiGettokenResponse tokenRespone = tokenClient.Execute(tokenRequest);
  92. if (tokenRespone.IsError)
  93. {
  94. return BadRequest();
  95. }
  96. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  97. string access_token = tokenRespone.AccessToken;
  98. //获取部门接口
  99. IDingTalkClient deptListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
  100. //一级部门
  101. OapiV2DepartmentListsubRequest reqDeptList1 = new() { DeptId = 1L, Language = "zh_CN" };
  102. OapiV2DepartmentListsubResponse rspDeptList1 = deptListClient.Execute(reqDeptList1, access_token);
  103. List<DingDingUserInfo> ddUserInfos = new();
  104. if (rspDeptList1.Result != null)
  105. {
  106. foreach (var tempDept1 in rspDeptList1.Result)
  107. {
  108. //获取一级部门用户信息
  109. List<DingDingUserInfo> dingDingUserInfos1 = await GetDingDingUserInfo(divide, tempDept1.DeptId, tempDept1.ParentId, tempDept1.Name, access_token);
  110. //if (dingDingUserInfos1.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos1.ToList()));
  111. if (dingDingUserInfos1.Count > 0) ddUserInfos.AddRange(dingDingUserInfos1);
  112. //获取二级部门
  113. OapiV2DepartmentListsubRequest reqDeptList2 = new() { DeptId = tempDept1.DeptId, Language = "zh_CN" };
  114. OapiV2DepartmentListsubResponse rspDeptList2 = deptListClient.Execute(reqDeptList2, access_token);
  115. if (rspDeptList2.Result != null)
  116. {
  117. foreach (var tempDept2 in rspDeptList2.Result)
  118. {
  119. //获取二级部门用户信息
  120. List<DingDingUserInfo> dingDingUserInfos2 = await GetDingDingUserInfo(divide, tempDept2.DeptId, tempDept2.ParentId, tempDept2.Name, access_token);
  121. //if (dingDingUserInfos2.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos2.ToList()));
  122. if (dingDingUserInfos2.Count > 0) ddUserInfos.AddRange(dingDingUserInfos2);
  123. //获取三级部门
  124. OapiV2DepartmentListsubRequest reqDeptList3 = new() { DeptId = tempDept2.DeptId, Language = "zh_CN" };
  125. OapiV2DepartmentListsubResponse rspDeptList3 = deptListClient.Execute(reqDeptList3, access_token);
  126. if (rspDeptList3.Result != null)
  127. {
  128. foreach (var tempDept3 in rspDeptList3.Result)
  129. {
  130. //获取三级部门用户信息
  131. List<DingDingUserInfo> dingDingUserInfos3 = await GetDingDingUserInfo(divide, tempDept3.DeptId, tempDept3.ParentId, tempDept3.Name, access_token);
  132. //if (dingDingUserInfos3.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos3.ToList()));
  133. if (dingDingUserInfos3.Count > 0) ddUserInfos.AddRange(dingDingUserInfos3);
  134. //获取四级部门
  135. OapiV2DepartmentListsubRequest reqDeptList4 = new() { DeptId = tempDept3.DeptId, Language = "zh_CN" };
  136. OapiV2DepartmentListsubResponse rspDeptList4 = deptListClient.Execute(reqDeptList4, access_token);
  137. if (rspDeptList4.Result != null)
  138. {
  139. foreach (var tempDept4 in rspDeptList4.Result)
  140. {
  141. //获取四级部门用户信息
  142. List<DingDingUserInfo> dingDingUserInfos4 = await GetDingDingUserInfo(divide, tempDept4.DeptId, tempDept4.ParentId, tempDept4.Name, access_token);
  143. //if (dingDingUserInfos4.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos4.ToList()));
  144. if (dingDingUserInfos4.Count > 0) ddUserInfos.AddRange(dingDingUserInfos4);
  145. //获取五级部门
  146. OapiV2DepartmentListsubRequest reqDeptList5 = new() { DeptId = tempDept4.DeptId, Language = "zh_CN" };
  147. OapiV2DepartmentListsubResponse rspDeptList5 = deptListClient.Execute(reqDeptList5, access_token);
  148. if (rspDeptList5.Result != null)
  149. {
  150. foreach (var tempDept5 in rspDeptList5.Result)
  151. {
  152. //获取五级部门用户信息
  153. List<DingDingUserInfo> dingDingUserInfos5 = await GetDingDingUserInfo(divide, tempDept5.DeptId, tempDept5.ParentId, tempDept5.Name, access_token);
  154. //if (dingDingUserInfos5.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos5).ToList());
  155. if (dingDingUserInfos5.Count > 0) ddUserInfos.AddRange(dingDingUserInfos5);
  156. }
  157. }
  158. }
  159. }
  160. }
  161. }
  162. }
  163. }
  164. }
  165. }
  166. //保存操作记录
  167. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{_tmdName}【{_tmdId}】从钉钉组织结构更新至Azure Table表【DDUserInfo】中。", _dingDing, httpContext: HttpContext);
  168. var tempddUserInfos = ddUserInfos.GroupBy(c => c.userId).Select(c => c.First()).ToList();//去重
  169. //List<DingDingUserInfo> TempdingDingUserInfos = await _azureStorage.SaveOrUpdateAll(dingDingUserInfos); //只是保存至Table
  170. //查询数据的数据 并和钉钉查询的数据对比,找出不同的数据,并删除 待后期测试
  171. var users = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{divide}" } });
  172. List<DingDingUserInfo> noExisits = new();
  173. if (users.Count > 0)
  174. {
  175. //var temps = users.Union(tempddUserInfos).Except(users.Intersect(tempddUserInfos));
  176. List<DingDingUserInfo> existsUserInfo = users.Where(u => !tempddUserInfos.Exists(e => u.userId.Equals(e.userId) && u.PartitionKey.Equals(e.PartitionKey))).ToList();
  177. if (users.Count > tempddUserInfos.Count)
  178. {
  179. existsUserInfo.AddRange(tempddUserInfos.Where(e => !users.Exists(u => e.userId.Equals(u.userId) && e.PartitionKey.Equals(u.PartitionKey))).ToList());
  180. }
  181. ////List<DingDingUserInfo> existsUserInfo = users.Where((x, i) => users.FindIndex(z => z.userId.Equals(x.userId) && x.PartitionKey.Equals(divide)) == i).Select(x => x).ToList();
  182. if (existsUserInfo.Count > 0)
  183. {
  184. noExisits = await table.DeleteAll(existsUserInfo);
  185. }
  186. }
  187. List<DingDingUserInfo> UserInfo = await table.SaveOrUpdateAll(tempddUserInfos); //保存和修改至Table
  188. return Ok(new { state = 200, UserInfo, noExisits });
  189. }
  190. catch (Exception ex)
  191. {
  192. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/get-dingdingusers \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  193. return BadRequest();
  194. }
  195. }
  196. /// <summary>
  197. /// 查询钉钉信息和醍摩豆信息 //已对接
  198. /// </summary>
  199. /// <returns></returns>
  200. [ProducesDefaultResponseType]
  201. [HttpPost("get-ddusers")]
  202. public async Task<IActionResult> GetDingDingUsers(JsonElement jsonElement)
  203. {
  204. try
  205. {
  206. jsonElement.TryGetProperty("busy", out JsonElement busy);
  207. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  208. var cosmosCliet = _azureCosmos.GetCosmosClient();
  209. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  210. ////分开部署,就不需要,一站多用时,取消注释
  211. //if ($"{site}".Equals(BIConst.Global))
  212. // table = _azureStorage.GetCloudTableClient(BIConst.Global).GetTableReference("BIDDUserInfo");
  213. //string divide = _configuration["CustomParam:SiteScope"];
  214. string divide = _option.Location;
  215. List<DDUserInfo> ddUserInfos = new();
  216. Dictionary<string, object> dic = new() { { "PartitionKey", $"{divide}" } };
  217. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  218. switch ($"{busy}")
  219. {
  220. case "admin":
  221. foreach (var item in ddUserInfoList)
  222. {
  223. if (item.roles.Contains("admin"))
  224. {
  225. DDUserInfo ddUserInfo = new()
  226. {
  227. partitionKey = item.PartitionKey,
  228. rowKey = item.RowKey,
  229. userId = item.userId,
  230. unionId = item.unionId,
  231. name = item.name,
  232. title = item.title,
  233. stateCode = item.stateCode,
  234. mobile = item.mobile,
  235. jobNumber = item.jobNumber,
  236. pid = item.pid,
  237. deptId = item.deptId,
  238. deptName = item.deptName,
  239. depts = item.depts,
  240. avatar = item.avatar,
  241. isAdmin = item.isAdmin,
  242. tmdId = item.tmdId,
  243. tmdName = item.tmdName,
  244. tmdMobile = item.tmdMobile,
  245. mail = item.mail,
  246. picture = item.picture,
  247. roles = item.roles,
  248. joinTime = item.joinTime,
  249. isDisable = item.isDisable,
  250. permissions = item.permissions,
  251. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  252. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  253. };
  254. if (!string.IsNullOrEmpty(item.schoolIds))
  255. {
  256. List<string> tempSchoolIds = new(item.schoolIds.Split("|"));
  257. ddUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  258. }
  259. ddUserInfos.Add(ddUserInfo);
  260. }
  261. }
  262. break;
  263. default:
  264. foreach (var item in ddUserInfoList)
  265. {
  266. DDUserInfo ddUserInfo = new()
  267. {
  268. partitionKey = item.PartitionKey,
  269. rowKey = item.RowKey,
  270. userId = item.userId,
  271. unionId = item.unionId,
  272. name = item.name,
  273. title = item.title,
  274. stateCode = item.stateCode,
  275. mobile = item.mobile,
  276. jobNumber = item.jobNumber,
  277. pid = item.pid,
  278. deptId = item.deptId,
  279. deptName = item.deptName,
  280. depts = item.depts,
  281. avatar = item.avatar,
  282. isAdmin = item.isAdmin,
  283. tmdId = item.tmdId,
  284. tmdName = item.tmdName,
  285. tmdMobile = item.tmdMobile,
  286. mail = item.mail,
  287. picture = item.picture,
  288. roles = item.roles,
  289. joinTime = item.joinTime,
  290. isDisable = item.isDisable,
  291. permissions = item.permissions,
  292. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  293. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  294. };
  295. if (!string.IsNullOrEmpty(item.schoolIds))
  296. {
  297. List<string> tempSchoolIds = new(item.schoolIds.Split("|"));
  298. ddUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  299. }
  300. ddUserInfos.Add(ddUserInfo);
  301. }
  302. break;
  303. }
  304. return Ok(new { state = 200, ddUserInfos = ddUserInfos });
  305. }
  306. catch (Exception ex)
  307. {
  308. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/get-ddusers \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  309. return BadRequest();
  310. }
  311. }
  312. /// <summary>
  313. /// 更新钉钉和醍摩豆的BI权限 //已对接
  314. /// </summary>
  315. /// <param name="jsonElement"></param>
  316. /// <returns></returns>
  317. [ProducesDefaultResponseType]
  318. [AuthToken(Roles = "admin,rdc")]
  319. [HttpPost("set-rolesper")]
  320. public async Task<IActionResult> SetPermissions(JsonElement jsonElement)
  321. {
  322. try
  323. {
  324. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  325. jsonElement.TryGetProperty("userId", out JsonElement userId);
  326. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  327. if (!jsonElement.TryGetProperty("permissions", out JsonElement _permissions)) return BadRequest();
  328. if (!jsonElement.TryGetProperty("roles", out JsonElement _roles)) return BadRequest();
  329. if (!jsonElement.TryGetProperty("isDisable", out JsonElement _isDisable)) return BadRequest();
  330. var cosmosCliet = _azureCosmos.GetCosmosClient();
  331. var tableClient = _azureStorage.GetCloudTableClient();
  332. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  333. long isDisable = 0;
  334. try
  335. {
  336. isDisable = long.Parse($"{_isDisable}");
  337. if (isDisable != 1 && isDisable != 0)
  338. return Ok(new { state = RespondCode.ParamsError, msg = "账户禁用参数错误!" });
  339. }
  340. catch
  341. {
  342. return Ok(new { state = RespondCode.ParamsError, msg = "账户禁用参数错误!" });
  343. }
  344. var table = tableClient.GetTableReference("BIDDUserInfo");
  345. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  346. List<DingDingUserInfo> ddUserInfos = new();
  347. List<string> listper = _permissions.ToObject<List<string>>();
  348. List<string> listroles = _roles.ToObject<List<string>>();
  349. List<string> roles = new();//角色列表
  350. List<string> permissions = new();//权限列表
  351. StringBuilder stringBuilder = new($"{_tmdName}【{_tmdId}】醍摩豆账号");
  352. Dictionary<string, object> dic = new() { { "PartitionKey", $"{partitionKey}" } };
  353. if (!string.IsNullOrEmpty($"{userId}"))
  354. dic.Add("userId", $"{userId}");
  355. if (!string.IsNullOrEmpty($"{tmdId}"))
  356. dic.Add("tmdId", $"{tmdId}");
  357. if (string.IsNullOrEmpty($"{userId}") && string.IsNullOrEmpty($"{tmdId}"))
  358. {
  359. return BadRequest();
  360. }
  361. var tempUser = await table.FindListByDict<DingDingUserInfo>(dic);
  362. List<string> oldRoles = new();
  363. List<Task<ItemResponse<SchoolTeacher>>> upScTch = new();
  364. foreach (var item in tempUser)
  365. {
  366. oldRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  367. stringBuilder.Append($"操作醍摩豆账户{item.tmdName}【{item.tmdId}】修改权限:{string.Join("|", listper.ToArray())}");
  368. item.roles = listroles.Count > 0 ? string.Join(",", listroles) : "assist";
  369. item.permissions = string.Join(",", listper);
  370. item.isDisable = isDisable;
  371. ddUserInfos.Add(item);
  372. roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  373. permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
  374. foreach (var itemR in listroles)
  375. {
  376. if(itemR.Equals("assist"))
  377. {
  378. string sql = $"select value(c) from c where c.pk='Teacher' and c.id='{item.tmdId}'";
  379. await foreach (var scTch in cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<SchoolTeacher>(queryText: sql, requestOptions: new QueryRequestOptions() { }))
  380. {
  381. if (scTch.roles.Contains("sales"))
  382. {
  383. int index = scTch.roles.FindIndex(fi => fi.Contains("sales"));
  384. if (index >= 0)
  385. {
  386. scTch.roles[index] = "assist";
  387. scTch.job = "顾问";
  388. upScTch.Add(cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(scTch, scTch.id, new PartitionKey($"{scTch.code}")));
  389. }
  390. }
  391. }
  392. }
  393. if (itemR.Equals("sales"))
  394. {
  395. string sql = $"select value(c) from c where c.pk='Teacher' and c.id='{item.tmdId}'";
  396. await foreach (var scTch in cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<SchoolTeacher>(queryText: sql, requestOptions: new QueryRequestOptions() { }))
  397. {
  398. if (scTch.roles.Contains("assist"))
  399. {
  400. int index = scTch.roles.FindIndex(fi => fi.Contains("assist"));
  401. if (index >= 0)
  402. {
  403. scTch.roles[index] = "sales";
  404. scTch.job = "销售";
  405. upScTch.Add(cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(scTch, scTch.id, new PartitionKey($"{scTch.code}")));
  406. }
  407. }
  408. }
  409. }
  410. }
  411. }
  412. if (upScTch.Count < 256)
  413. {
  414. await Task.WhenAll(upScTch);
  415. }
  416. else
  417. {
  418. int pages = (upScTch.Count + 255) / 256;
  419. for (int i = 0; i < pages; i++)
  420. {
  421. List<Task<ItemResponse<SchoolTeacher>>> temScTch = upScTch.Skip((i) * 256).Take(256).ToList();
  422. await Task.WhenAll(temScTch);
  423. }
  424. }
  425. ddUserInfos = await table.UpdateAll<DingDingUserInfo>(ddUserInfos);
  426. List<DDUserInfo> ddUserInfo = new();
  427. foreach (var item in ddUserInfos)
  428. {
  429. DDUserInfo tempInfo = new()
  430. {
  431. partitionKey = item.PartitionKey,
  432. rowKey = item.RowKey,
  433. userId = item.userId,
  434. unionId = item.unionId,
  435. name = item.name,
  436. title = item.title,
  437. stateCode = item.stateCode,
  438. mobile = item.mobile,
  439. jobNumber = item.jobNumber,
  440. pid = item.pid,
  441. deptId = item.deptId,
  442. deptName = item.deptName,
  443. depts = item.depts,
  444. avatar = item.avatar,
  445. isAdmin = item.isAdmin,
  446. tmdId = item.tmdId,
  447. tmdName = item.tmdName,
  448. tmdMobile = item.tmdMobile,
  449. mail = item.mail,
  450. picture = item.picture,
  451. roles = item.roles,
  452. joinTime = item.joinTime,
  453. isDisable = item.isDisable,
  454. permissions = item.permissions,
  455. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  456. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  457. };
  458. if (!string.IsNullOrEmpty(item.schoolIds))
  459. {
  460. List<string> tempSchoolIds = new(item.schoolIds.Split("|"));
  461. tempInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  462. }
  463. ddUserInfo.Add(tempInfo);
  464. }
  465. //保存操作记录
  466. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", stringBuilder?.ToString(), _dingDing, httpContext: HttpContext);
  467. return Ok(new { state = 200, ddUserInfo, roles, permissions });
  468. }
  469. catch (Exception ex)
  470. {
  471. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/tabledd-update \n {ex.Message}\n{ex.StackTrace} ", GroupNames.成都开发測試群組);
  472. return BadRequest();
  473. }
  474. }
  475. /// <summary>
  476. /// 依据部门ID获取部门列表 //已对接
  477. /// </summary>
  478. /// <param name="jsonElement"></param>
  479. /// <returns></returns>
  480. [ProducesDefaultResponseType]
  481. [HttpPost("get-dddeptiduser")]
  482. public async Task<IActionResult> GetDDDeptIdUser(JsonElement jsonElement)
  483. {
  484. try
  485. {
  486. if (!jsonElement.TryGetProperty("deptId", out JsonElement deptId)) return BadRequest();
  487. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  488. var cosmosCliet = _azureCosmos.GetCosmosClient();
  489. var tableClient = _azureStorage.GetCloudTableClient();
  490. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  491. ////分开部署,就不需要,一站多用时,取消注释
  492. //if ($"{site}".Equals(BIConst.Global))
  493. //{
  494. // cosmosCliet = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  495. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  496. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  497. //};
  498. var table = tableClient.GetTableReference("BIDDUserInfo");
  499. //string divide = _configuration["CustomParam:SiteScope"];
  500. string divide = _option.Location;
  501. Dictionary<string, object> dic = new() { { "PartitionKey", $"{divide}" } };
  502. List<DingDingUserInfo> tempUserInfos = await table.FindListByDict<DingDingUserInfo>(dic);
  503. List<DingDingUserInfo> userInfo = new();
  504. tempUserInfos.ForEach(x => {
  505. if (x.depts.Contains($"{deptId}"))
  506. {
  507. userInfo.Add(x);
  508. }
  509. if (x.pid.Equals(long.Parse($"{deptId}")))
  510. {
  511. userInfo.Add(x);
  512. }
  513. });
  514. //userInfo.Distinct().ToList(); //Equals实现去重
  515. userInfo.Where((x, i) => userInfo.FindIndex(z => z.RowKey.Equals(x.RowKey)) == i);//Lambda表达式去重
  516. //userInfo.GroupBy(p => p).Select(p => p.Key).ToList();//去重复
  517. List<DDUserInfo> ddUserInfos = new();
  518. foreach (var item in userInfo)
  519. {
  520. DDUserInfo tempUserInfo = new DDUserInfo()
  521. {
  522. partitionKey = item.PartitionKey,
  523. rowKey = item.RowKey,
  524. userId = item.userId,
  525. unionId = item.unionId,
  526. name = item.name,
  527. title = item.title,
  528. stateCode = item.stateCode,
  529. mobile = item.mobile,
  530. jobNumber = item.jobNumber,
  531. pid = item.pid,
  532. deptId = item.deptId,
  533. deptName = item.deptName,
  534. depts = item.depts,
  535. avatar = item.avatar,
  536. isAdmin = item.isAdmin,
  537. tmdId = item.tmdId,
  538. tmdName = item.tmdName,
  539. tmdMobile = item.tmdMobile,
  540. mail = item.mail,
  541. picture = item.picture,
  542. roles = item.roles,
  543. joinTime = item.joinTime,
  544. isDisable = item.isDisable,
  545. permissions = item.permissions,
  546. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  547. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  548. };
  549. if (!string.IsNullOrEmpty(item.schoolIds))
  550. {
  551. List<string> tempSchoolIds = new(item.schoolIds.Split("|"));
  552. tempUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  553. }
  554. ddUserInfos.Add(tempUserInfo);
  555. }
  556. return Ok(new { state = 200, ddUserInfos });
  557. }
  558. catch (Exception ex)
  559. {
  560. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/get-dddeptiduser \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  561. return BadRequest();
  562. }
  563. }
  564. /// <summary>
  565. /// 通过醍摩豆账户信息 设置BI后台管理员 //已对接
  566. /// </summary>
  567. /// <param name="jsonElement"></param>
  568. /// <returns></returns>
  569. [ProducesDefaultResponseType]
  570. [AuthToken(Roles = "admin,rdc")]
  571. [HttpPost("set-tmdadmin")]
  572. public async Task<IActionResult> SetTmdBackendAdmin(JsonElement jsonElement)
  573. {
  574. try
  575. {
  576. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  577. if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
  578. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  579. jsonElement.TryGetProperty("picture ", out JsonElement picture);
  580. jsonElement.TryGetProperty("mail ", out JsonElement mail);
  581. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  582. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  583. var cosmosCliet = _azureCosmos.GetCosmosClient();
  584. var tableClient = _azureStorage.GetCloudTableClient();
  585. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  586. ////分开部署,就不需要,一站多用时,取消注释
  587. //if ($"{site}".Equals(BIConst.Global))
  588. //{
  589. // cosmosCliet = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  590. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  591. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  592. //}
  593. var table = tableClient.GetTableReference("BIDDUserInfo");
  594. List<DDUserInfo> ddUserInfos = new();
  595. List<string> roles = new();//角色列表
  596. List<string> permissions = new();//权限列表
  597. StringBuilder msg = new($"{_tmdName}【{_tmdId}】");
  598. //string divide = _configuration["CustomParam:SiteScope"];
  599. string divide = _option.Location;
  600. Dictionary<string, object> dic = new() { { "PartitionKey", $"{divide}" }, { "mobile", $"{mobile}" } };
  601. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  602. if (ddUserInfoList.Count > 0)
  603. {
  604. foreach (var user in ddUserInfoList)
  605. {
  606. List<string> tempRoles = new(user.roles.Split(","));
  607. if (tempRoles.Count > 0)
  608. {
  609. if (!tempRoles.Contains("admin"))
  610. {
  611. tempRoles.Add("admin");
  612. }
  613. }
  614. else
  615. tempRoles.Add("admin");
  616. user.roles = string.Join(",", tempRoles);
  617. user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  618. user.tmdId = $"{tmdId}";
  619. user.tmdName = $"{tmdName}";
  620. user.tmdMobile = $"{mobile}";
  621. if (!string.IsNullOrEmpty($"{picture}"))
  622. {
  623. user.picture = $"{picture}";
  624. }
  625. if (!string.IsNullOrEmpty($"{mail}"))
  626. {
  627. user.mail = $"{mail}";
  628. }
  629. msg.Append($" 将:{tmdName}【{tmdId}】醍摩豆账号和({user.name}【{user.unionId}】) 钉钉账户绑定,并设置管理员");
  630. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  631. if (respUser != null)
  632. {
  633. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  634. }
  635. DDUserInfo dDUserInfo = new()
  636. {
  637. partitionKey = respUser.PartitionKey,
  638. rowKey = respUser.RowKey,
  639. userId = respUser.userId,
  640. unionId = respUser.unionId,
  641. name = respUser.name,
  642. title = respUser.title,
  643. stateCode = respUser.stateCode,
  644. mobile = respUser.mobile,
  645. jobNumber = respUser.jobNumber,
  646. pid = respUser.pid,
  647. deptId = respUser.deptId,
  648. deptName = respUser.deptName,
  649. depts = respUser.depts,
  650. avatar = respUser.avatar,
  651. isAdmin = respUser.isAdmin,
  652. tmdId = respUser.tmdId,
  653. tmdName = respUser.tmdName,
  654. tmdMobile = respUser.tmdMobile,
  655. mail = respUser.mail,
  656. picture = respUser.picture,
  657. roles = respUser.roles,
  658. joinTime = respUser.joinTime,
  659. isDisable = respUser.isDisable,
  660. permissions = respUser.permissions,
  661. handleRoles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>(),
  662. handlePermissions = !string.IsNullOrEmpty($"{respUser.permissions}") ? new List<string>(respUser.permissions.Split(",")) : new List<string>()
  663. };
  664. if (!string.IsNullOrEmpty(respUser.schoolIds))
  665. {
  666. List<string> tempSchoolIds = new(respUser.schoolIds.Split("|"));
  667. dDUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  668. }
  669. ddUserInfos.Add(dDUserInfo);
  670. }
  671. }
  672. else
  673. {
  674. DingDingUserInfo dingDingUserInfo = new()
  675. {
  676. PartitionKey = divide,
  677. RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
  678. roles = "admin",
  679. tmdId = $"{tmdId}",
  680. tmdName = $"{tmdName}",
  681. tmdMobile = $"{mobile}",
  682. };
  683. if (!string.IsNullOrEmpty($"{picture}"))
  684. {
  685. dingDingUserInfo.picture = $"{picture}";
  686. }
  687. if (!string.IsNullOrEmpty($"{mail}"))
  688. {
  689. dingDingUserInfo.mail = $"{mail}";
  690. }
  691. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(dingDingUserInfo);
  692. return Ok(new { state = 201, msg = "新生成的BIadmin", respUser });
  693. }
  694. //保存操作记录
  695. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
  696. return Ok(new { state = 200, ddUserInfos });
  697. }
  698. catch (Exception ex)
  699. {
  700. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-tmdadmin \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  701. return BadRequest();
  702. }
  703. }
  704. /// <summary>
  705. /// 设置系统管理员 //已对接
  706. /// </summary>
  707. /// <param name="jsonElement"></param>
  708. /// <returns></returns>
  709. [ProducesDefaultResponseType]
  710. [AuthToken(Roles = "admin,rdc")]
  711. [HttpPost("set-backend")]
  712. public async Task<IActionResult> SetBackendAdmin(JsonElement jsonElement)
  713. {
  714. try
  715. {
  716. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  717. if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
  718. if (!jsonElement.TryGetProperty("isAdmin", out JsonElement isAdmin)) return BadRequest();
  719. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  720. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  721. var tableClient = _azureStorage.GetCloudTableClient();
  722. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  723. ////分开部署,就不需要,一站多用时,取消注释
  724. //if ($"{site}".Equals(BIConst.Global))
  725. //{
  726. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  727. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  728. //}
  729. var table = tableClient.GetTableReference("BIDDUserInfo");
  730. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{rowKey}" } });
  731. List<DDUserInfo> ddUserInfos = new();
  732. List<string> roles = new();//角色列表
  733. List<string> permissions = new();//权限列表
  734. StringBuilder msg = new($"{_tmdName}【{_tmdId}】");
  735. if (bool.Parse($"{isAdmin}") == true)
  736. {
  737. foreach (var user in tempUser)
  738. {
  739. if (string.IsNullOrEmpty(user.roles))
  740. {
  741. user.roles = "admin,assist";
  742. }
  743. List<string> tempRoles = new(user.roles.Split(","));
  744. if (!tempRoles.Contains("admin"))
  745. {
  746. tempRoles.Add("admin");
  747. }
  748. user.roles = string.Join(",", tempRoles);
  749. user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  750. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  751. if (respUser != null)
  752. {
  753. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  754. }
  755. msg.Append($"添加{respUser.name}【{respUser.RowKey}】账号的BI管理员");
  756. }
  757. }
  758. else
  759. {
  760. var userInfos = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" } });
  761. var adminInfos = userInfos.FindAll(x => x.roles.Contains("admin"));
  762. if (adminInfos.Count == 1)
  763. {
  764. return Ok(new { state = 403, msg = "已经是最后一个管理员了" });
  765. }
  766. else
  767. {
  768. foreach (var user in tempUser)
  769. {
  770. if (!user.userId.Equals($"{did}"))
  771. {
  772. List<string> tempRoles = new(user.roles.Split(","));
  773. if (tempRoles.Contains("admin"))
  774. {
  775. tempRoles.Remove("admin");
  776. }
  777. user.roles = string.Join(",", tempRoles);
  778. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  779. if (respUser != null)
  780. {
  781. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  782. msg.Append($"取消{respUser.name}【{respUser.RowKey}】账号的BI管理员");
  783. }
  784. }
  785. else return Ok(new { state = 1, msg = "不能删除自己" });
  786. }
  787. }
  788. }
  789. //保存操作记录
  790. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
  791. return Ok(new { state = 200, roles });
  792. }
  793. catch (Exception ex)
  794. {
  795. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backend \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  796. return BadRequest();
  797. }
  798. }
  799. /// <summary>
  800. /// 从钉钉的组织架构中人员信息数据,并保存或者更新至Blob中 初始化使用该接口
  801. /// </summary>
  802. /// <returns></returns>
  803. [ProducesDefaultResponseType]
  804. [HttpPost("get-dduserinitial")]
  805. public async Task<IActionResult> GetddUserInitial(JsonElement jsonElement)
  806. {
  807. try
  808. {
  809. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  810. var tableClient = _azureStorage.GetCloudTableClient();
  811. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  812. ////分开部署,就不需要,一站多用时,取消注释
  813. //if ($"{site}".Equals(BIConst.Global))
  814. //{
  815. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  816. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  817. //}
  818. var table = tableClient.GetTableReference("BIDDUserInfo");
  819. string appKey = _configuration["DingDingAuth:appKey"];
  820. string appSecret = _configuration["DingDingAuth:appSecret"];
  821. //string divide = _configuration["CustomParam:SiteScope"];
  822. string divide = _option.Location;
  823. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  824. //HttpClient httpClient = _http.CreateClient();
  825. //string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  826. //获取access_token
  827. IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  828. OapiGettokenRequest tokenRequest = new() { Appkey = appKey, Appsecret = appSecret };
  829. tokenRequest.SetHttpMethod("Get");
  830. OapiGettokenResponse tokenRespone = tokenClient.Execute(tokenRequest);
  831. if (tokenRespone.IsError)
  832. {
  833. return BadRequest();
  834. }
  835. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  836. string access_token = tokenRespone.AccessToken;
  837. //获取部门接口
  838. IDingTalkClient deptListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
  839. //一级部门
  840. OapiV2DepartmentListsubRequest reqDeptList1 = new() { DeptId = 1L, Language = "zh_CN" };
  841. OapiV2DepartmentListsubResponse rspDeptList1 = deptListClient.Execute(reqDeptList1, access_token);
  842. List<DingDingUserInfo> ddUserInfos = new();
  843. if (rspDeptList1.Result != null)
  844. {
  845. foreach (var tempDept1 in rspDeptList1.Result)
  846. {
  847. //获取一级部门用户信息
  848. List<DingDingUserInfo> dingDingUserInfos1 = await GetDingDingUserInfo(divide, tempDept1.DeptId, tempDept1.ParentId, tempDept1.Name, access_token);
  849. //if (dingDingUserInfos1.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos1.ToList()));
  850. if (dingDingUserInfos1.Count > 0) ddUserInfos.AddRange(dingDingUserInfos1);
  851. //获取二级部门
  852. OapiV2DepartmentListsubRequest reqDeptList2 = new() { DeptId = tempDept1.DeptId, Language = "zh_CN" };
  853. OapiV2DepartmentListsubResponse rspDeptList2 = deptListClient.Execute(reqDeptList2, access_token);
  854. if (rspDeptList2.Result != null)
  855. {
  856. foreach (var tempDept2 in rspDeptList2.Result)
  857. {
  858. //获取二级部门用户信息
  859. List<DingDingUserInfo> dingDingUserInfos2 = await GetDingDingUserInfo(divide, tempDept2.DeptId, tempDept2.ParentId, tempDept2.Name, access_token);
  860. //if (dingDingUserInfos2.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos2.ToList()));
  861. if (dingDingUserInfos2.Count > 0) ddUserInfos.AddRange(dingDingUserInfos2);
  862. //获取三级部门
  863. OapiV2DepartmentListsubRequest reqDeptList3 = new() { DeptId = tempDept2.DeptId, Language = "zh_CN" };
  864. OapiV2DepartmentListsubResponse rspDeptList3 = deptListClient.Execute(reqDeptList3, access_token);
  865. if (rspDeptList3.Result != null)
  866. {
  867. foreach (var tempDept3 in rspDeptList3.Result)
  868. {
  869. //获取三级部门用户信息
  870. List<DingDingUserInfo> dingDingUserInfos3 = await GetDingDingUserInfo(divide, tempDept3.DeptId, tempDept3.ParentId, tempDept3.Name, access_token);
  871. //if (dingDingUserInfos3.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos3.ToList()));
  872. if (dingDingUserInfos3.Count > 0) ddUserInfos.AddRange(dingDingUserInfos3);
  873. //获取四级部门
  874. OapiV2DepartmentListsubRequest reqDeptList4 = new() { DeptId = tempDept3.DeptId, Language = "zh_CN" };
  875. OapiV2DepartmentListsubResponse rspDeptList4 = deptListClient.Execute(reqDeptList4, access_token);
  876. if (rspDeptList4.Result != null)
  877. {
  878. foreach (var tempDept4 in rspDeptList4.Result)
  879. {
  880. //获取四级部门用户信息
  881. List<DingDingUserInfo> dingDingUserInfos4 = await GetDingDingUserInfo(divide, tempDept4.DeptId, tempDept4.ParentId, tempDept4.Name, access_token);
  882. //if (dingDingUserInfos4.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos4.ToList()));
  883. if (dingDingUserInfos4.Count > 0) ddUserInfos.AddRange(dingDingUserInfos4);
  884. //获取五级部门
  885. OapiV2DepartmentListsubRequest reqDeptList5 = new() { DeptId = tempDept4.DeptId, Language = "zh_CN" };
  886. OapiV2DepartmentListsubResponse rspDeptList5 = deptListClient.Execute(reqDeptList5, access_token);
  887. if (rspDeptList5.Result != null)
  888. {
  889. foreach (var tempDept5 in rspDeptList5.Result)
  890. {
  891. //获取五级部门用户信息
  892. List<DingDingUserInfo> dingDingUserInfos5 = await GetDingDingUserInfo(divide, tempDept5.DeptId, tempDept5.ParentId, tempDept5.Name, access_token);
  893. //if (dingDingUserInfos5.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos5).ToList());
  894. if (dingDingUserInfos5.Count > 0) ddUserInfos.AddRange(dingDingUserInfos5);
  895. }
  896. }
  897. }
  898. }
  899. }
  900. }
  901. }
  902. }
  903. }
  904. }
  905. //保存操作记录
  906. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{_tmdName}【{_tmdId}】从钉钉组织结构初始化至Azure Table表【DDUserInfo】中。", _dingDing, httpContext: HttpContext);
  907. var tempddUserInfos = ddUserInfos.GroupBy(c => c.userId).Select(c => c.First()).ToList();//去重
  908. //List<DingDingUserInfo> TempdingDingUserInfos = await _azureStorage.SaveOrUpdateAll(dingDingUserInfos); //只是保存至Table
  909. //查询数据的数据 并和钉钉查询的数据对比,找出不同的数据,并删除 待后期测试
  910. var users = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{divide}" } });
  911. List<DingDingUserInfo> noExisits = new();
  912. if (users.Count > 0)
  913. {
  914. //var temps = users.Union(tempddUserInfos).Except(users.Intersect(tempddUserInfos));
  915. List<DingDingUserInfo> existsUserInfo = users.Where(u => !tempddUserInfos.Exists(e => u.userId.Equals(e.userId) && u.PartitionKey.Equals(e.PartitionKey))).ToList();
  916. if (users.Count >= tempddUserInfos.Count)
  917. {
  918. existsUserInfo.AddRange(tempddUserInfos.Where(e => !users.Exists(u => e.userId.Equals(u.userId) && e.PartitionKey.Equals(u.PartitionKey))).ToList());
  919. }
  920. ////List<DingDingUserInfo> existsUserInfo = users.Where((x, i) => users.FindIndex(z => z.userId.Equals(x.userId) && x.PartitionKey.Equals(divide)) == i).Select(x => x).ToList();
  921. if (existsUserInfo.Count > 0)
  922. {
  923. noExisits = await table.DeleteAll(existsUserInfo);
  924. }
  925. }
  926. List<DingDingUserInfo> UserInfo = await table.SaveOrUpdateAll(tempddUserInfos); //保存和修改至Table
  927. return Ok(new { state = 200, UserInfo, noExisits });
  928. }
  929. catch (Exception ex)
  930. {
  931. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/get-dingdingusers \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  932. return BadRequest();
  933. }
  934. }
  935. /// <summary>
  936. /// 后端钉钉账户和醍摩豆账户进行绑定
  937. /// </summary>
  938. /// <param name="jsonElement"></param>
  939. /// <returns></returns>
  940. [ProducesDefaultResponseType]
  941. [AuthToken(Roles = "admin,rdc")]
  942. [HttpPost("set-backenbind")]
  943. public async Task<IActionResult> SetBackenBind(JsonElement jsonElement)
  944. {
  945. try
  946. {
  947. if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
  948. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  949. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  950. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  951. var tableClient = _azureStorage.GetCloudTableClient();
  952. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  953. ////分开部署,就不需要,一站多用时,取消注释
  954. //if ($"{site}".Equals(BIConst.Global))
  955. //{
  956. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  957. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  958. //}
  959. var table = tableClient.GetTableReference("BIDDUserInfo");
  960. List<DingDingUserInfo> tempddUsers = null;
  961. List<DingDingUserInfo> ddUsers = new();
  962. StringBuilder tableSql = new();
  963. if (!string.IsNullOrEmpty($"{rowKey}"))
  964. tableSql.Append($"RowKey {QueryComparisons.Equal} '{rowKey}'");
  965. string tmdId = null;
  966. string tmdName = null;
  967. string tmdMobile = null;
  968. string mail = null;
  969. string picture = null;
  970. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{mobile}" } }, _option.Location, _configuration);
  971. if (coreUser != null && coreUser.id != null)
  972. {
  973. tmdId = coreUser.id;
  974. tmdName = coreUser.name;
  975. tmdMobile = coreUser.mobile;
  976. mail = coreUser.mail;
  977. picture = coreUser.picture;
  978. }else return Ok(new { state = 1, message = "该手机号未找到醍摩豆账户" });
  979. tempddUsers = await table.QueryWhereString<DingDingUserInfo>(tableSql.ToString());
  980. if (tempddUsers.Count > 0)
  981. {
  982. foreach (var item in tempddUsers)
  983. {
  984. if (item.RowKey.Equals($"{rowKey}"))
  985. {
  986. item.tmdId = tmdId;
  987. item.tmdName = tmdName;
  988. item.tmdMobile = tmdMobile;
  989. item.mail = mail;
  990. item.picture = picture;
  991. ddUsers.Add(item);
  992. }
  993. }
  994. }
  995. else return Ok(new { state = 2, message = "钉钉ID错误请检查钉钉ID" });
  996. if (ddUsers.Count > 0) ddUsers = await table.SaveOrUpdateAll(ddUsers);
  997. //保存操作记录
  998. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{_tmdName}【{_tmdId}】操作:绑定钉钉账户[{rowKey}]和醍摩豆账户[{tmdId}]", _dingDing, httpContext: HttpContext);
  999. return Ok(new { state = 200, ddUsers });
  1000. }
  1001. catch (Exception ex)
  1002. {
  1003. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backenbind \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1004. return BadRequest();
  1005. }
  1006. }
  1007. /// <summary>
  1008. /// 后端初始化管理员
  1009. /// </summary>
  1010. /// <param name="jsonElement"></param>
  1011. /// <returns></returns>
  1012. [ProducesDefaultResponseType]
  1013. [HttpPost("set-apiphoneadmin")]
  1014. public async Task<IActionResult> SetPhoneAdmin(JsonElement jsonElement)
  1015. {
  1016. jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey);
  1017. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  1018. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  1019. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  1020. var partKey = _option.Location;
  1021. if (string.IsNullOrEmpty($"{partitionKey}"))
  1022. {
  1023. partKey = $"{partitionKey}";
  1024. };
  1025. var tableClient = _azureStorage.GetCloudTableClient();
  1026. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  1027. ////分开部署,就不需要,一站多用时,取消注释
  1028. //if ($"{site}".Equals(BIConst.Global))
  1029. //{
  1030. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  1031. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  1032. //}
  1033. var table = tableClient.GetTableReference("BIDDUserInfo");
  1034. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partKey}" }, { "mobile", $"{mobile}" } });
  1035. List<string> roles = new();//角色列表
  1036. List<string> permissions = new();//权限列表
  1037. StringBuilder msg = new();
  1038. foreach (var user in tempUser)
  1039. {
  1040. if (string.IsNullOrEmpty(user.roles))
  1041. {
  1042. user.roles = "admin,assist";
  1043. }
  1044. List<string> tempRoles = new(user.roles.Split(","));
  1045. if (!tempRoles.Contains("admin"))
  1046. {
  1047. tempRoles.Add("admin");
  1048. }
  1049. user.roles = string.Join(",", tempRoles);
  1050. user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1051. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  1052. if (respUser != null)
  1053. {
  1054. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  1055. }
  1056. msg.Append($"初始将{respUser.name}【{respUser.RowKey}】账号的BI管理员");
  1057. }
  1058. //保存操作记录
  1059. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
  1060. return Ok(new { state = 200, roles });
  1061. }
  1062. /// <summary>
  1063. /// 解除钉钉和醍摩豆的绑定
  1064. /// </summary>
  1065. /// <param name="jsonElement"></param>
  1066. /// <returns></returns>
  1067. [ProducesDefaultResponseType]
  1068. [HttpPost("set-unbind")]
  1069. public async Task<IActionResult> SetUnbind(JsonElement jsonElement)
  1070. {
  1071. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  1072. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1073. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  1074. ////分开部署,就不需要,一站多用时,取消注释
  1075. //if ($"{site}".Equals(BIConst.Global))
  1076. // table = _azureStorage.GetCloudTableClient(BIConst.Global).GetTableReference("BIDDUserInfo");
  1077. //string divide = _configuration["CustomParam:SiteScope"];
  1078. string divide = _option.Location;
  1079. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
  1080. if (!string.IsNullOrEmpty($"{mobile}"))
  1081. dic.Add("tmdMobile", $"{mobile}");
  1082. else
  1083. dic.Add("tmdMobile", "18281911681");
  1084. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  1085. List<DingDingUserInfo> tempDDUI = new();
  1086. if (ddUserInfoList.Count > 0)
  1087. {
  1088. foreach (var item in ddUserInfoList)
  1089. {
  1090. item.tmdId = null;
  1091. item.tmdName = null;
  1092. item.tmdMobile = null;
  1093. item.picture = null;
  1094. tempDDUI.Add(item);
  1095. }
  1096. }
  1097. else return Ok(new { state = 404, msg = "未找到手机号匹配的绑定号码!,请检查手机号" });
  1098. var userInfos = await table.SaveOrUpdateAll(tempDDUI); //保存和修改至Table
  1099. return Ok(new { state = 200, userInfos });
  1100. }
  1101. /// <summary>
  1102. /// 查询钉钉待入职人员的ID添加至Table数据表中
  1103. /// </summary>
  1104. /// <returns></returns>
  1105. [ProducesDefaultResponseType]
  1106. [AuthToken(Roles = "admin,rdc")]
  1107. [HttpPost("set-ddinductionuser")]
  1108. public async Task<IActionResult> SetDingDingInductionUser(JsonElement jsonElement)
  1109. {
  1110. try
  1111. {
  1112. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1113. var tableClient = _azureStorage.GetCloudTableClient();
  1114. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  1115. ////分开部署,就不需要,一站多用时,取消注释
  1116. //if ($"{site}".Equals(BIConst.Global))
  1117. //{
  1118. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  1119. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  1120. //}
  1121. var table = tableClient.GetTableReference("BIDDUserInfo");
  1122. string appKey = _configuration["DingDingAuth:appKey"];
  1123. string appSecret = _configuration["DingDingAuth:appSecret"];
  1124. //string divide = _configuration["CustomParam:SiteScope"];
  1125. string divide = _option.Location;
  1126. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  1127. //获取access_token
  1128. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  1129. OapiGettokenRequest request = new() { Appkey = appKey, Appsecret = appSecret };
  1130. request.SetHttpMethod("Get");
  1131. OapiGettokenResponse response = client.Execute(request);
  1132. if (response.IsError)
  1133. {
  1134. return BadRequest();
  1135. }
  1136. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  1137. string access_token = response.AccessToken;
  1138. IDingTalkClient InductionClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querypreentry");
  1139. OapiSmartworkHrmEmployeeQuerypreentryRequest reqInduction = new() { Offset = 0L, Size = 50 };
  1140. reqInduction.SetHttpMethod("GET");
  1141. OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
  1142. if (rspInduction.Result.DataList != null)
  1143. {
  1144. List<DingDingUserInfo> ddUserInfos = new();
  1145. foreach (var itemId in rspInduction.Result.DataList)
  1146. {
  1147. DingDingUserInfo ddUserInfo = new();
  1148. ddUserInfo.PartitionKey = divide;
  1149. ddUserInfo.RowKey = itemId;
  1150. ddUserInfos.Add(ddUserInfo);
  1151. }
  1152. List<DingDingUserInfo> tempddUserInfos = await table.SaveAll(ddUserInfos);
  1153. //保存操作记录
  1154. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-add", $"{_tmdName}【{_tmdId}】添加待入职员工至table数据表中", _dingDing, httpContext: HttpContext);
  1155. if (ddUserInfos.Count == tempddUserInfos.Count)
  1156. return Ok(new { state = 200, UserInfo = tempddUserInfos });
  1157. else
  1158. {
  1159. var diffArr = tempddUserInfos.Where(c => !ddUserInfos.Contains(c)).ToList();
  1160. return Ok(new { state = 201, notUserInfo = diffArr });
  1161. }
  1162. }
  1163. else
  1164. return Ok(new { state = 400, rspInduction.SubErrCode, rspInduction.SubErrMsg });
  1165. }
  1166. catch (Exception ex)
  1167. {
  1168. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-ddinductionuser \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1169. return BadRequest();
  1170. }
  1171. }
  1172. /// <summary>
  1173. /// 获取钉钉离职人员ID并删除Table表中的数据
  1174. /// </summary>
  1175. /// <returns></returns>
  1176. [ProducesDefaultResponseType]
  1177. [AuthToken(Roles = "admin,rdc")]
  1178. [HttpPost("del-ddquituser")]
  1179. public async Task<IActionResult> DeleteDDQuitUser(JsonElement jsonElement)
  1180. {
  1181. try
  1182. {
  1183. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1184. var tableClient = _azureStorage.GetCloudTableClient();
  1185. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  1186. ////分开部署,就不需要,一站多用时,取消注释
  1187. //if ($"{site}".Equals(BIConst.Global))
  1188. //{
  1189. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  1190. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  1191. //}
  1192. var table = tableClient.GetTableReference("BIDDUserInfo");
  1193. string appKey = _configuration["DingDingAuth:appKey"];
  1194. string appSecret = _configuration["DingDingAuth:appSecret"];
  1195. //string divide = _configuration["CustomParam:SiteScope"];
  1196. string divide = _option.Location;
  1197. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  1198. //获取access_token
  1199. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  1200. OapiGettokenRequest request = new() { Appkey = appKey, Appsecret = appSecret };
  1201. request.SetHttpMethod("Get");
  1202. OapiGettokenResponse response = client.Execute(request);
  1203. if (response.IsError)
  1204. {
  1205. return BadRequest();
  1206. }
  1207. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  1208. string access_token = response.AccessToken;
  1209. IDingTalkClient quitStaffClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
  1210. OapiSmartworkHrmEmployeeQuerydimissionRequest reqDimission = new() { Offset = 0L, Size = 50L };
  1211. OapiSmartworkHrmEmployeeQuerydimissionResponse rspDimission = quitStaffClient.Execute(reqDimission, access_token);
  1212. if (rspDimission.Result != null)
  1213. {
  1214. List<DingDingUserInfo> ddUserInfos = new();
  1215. foreach (var itemId in rspDimission.Result.DataList)
  1216. {
  1217. await table.DeleteSingle<DingDingUserInfo>(divide, $"{itemId}");
  1218. }
  1219. //保存操作记录
  1220. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-del", $"{_tmdName}【{_tmdId}】从table数据表中删除离职员工", _dingDing, httpContext: HttpContext);
  1221. return Ok(new { state = 200 });
  1222. }
  1223. else
  1224. {
  1225. return Ok(new { state = rspDimission.SubErrCode });
  1226. }
  1227. }
  1228. catch (Exception ex)
  1229. {
  1230. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/del-ddquituser \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1231. return BadRequest();
  1232. }
  1233. }
  1234. /// <summary>
  1235. /// 获取钉钉用户信息
  1236. /// 并查询本地Table数据表中是否存在
  1237. /// </summary>
  1238. /// <param name="deptId"></param>
  1239. /// <param name="parentId"></param>
  1240. /// <param name="name"></param>
  1241. /// <param name="access_token"></param>
  1242. /// <returns></returns>
  1243. public async Task<List<DingDingUserInfo>> GetDingDingUserInfo(string partitionKey, long deptId, long parentId, string name, string access_token)
  1244. {
  1245. List<DingDingUserInfo> ddUserInfos = new();
  1246. //获取部门人员信息
  1247. IDingTalkClient userListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
  1248. //long joinDate = DateTimeOffset.UtcNow.AddDays(-91).ToUnixTimeMilliseconds();
  1249. //获取部门用户
  1250. OapiV2UserListRequest reqUserList = new()
  1251. {
  1252. DeptId = deptId,
  1253. Cursor = 0L,
  1254. Size = 50L,
  1255. OrderField = "custom",
  1256. Language = "zh_CN"
  1257. };
  1258. reqUserList.SetHttpMethod("GET");
  1259. OapiV2UserListResponse rspV2UserList = userListClient.Execute(reqUserList, access_token);
  1260. if (rspV2UserList.Result.List != null)
  1261. {
  1262. foreach (var itemUser in rspV2UserList.Result.List)
  1263. {
  1264. //long isDisble = 0;
  1265. //if (!string.IsNullOrEmpty($"{itemUser.HiredDate}"))
  1266. //{
  1267. // if (itemUser.HiredDate < joinDate)
  1268. // isDisble = 1;
  1269. // else
  1270. // isDisble = 0;
  1271. //}
  1272. var tempInfo = ddUserInfos.Find(x => x.RowKey.Equals(itemUser.Unionid));
  1273. if (string.IsNullOrEmpty($"{tempInfo}"))
  1274. {
  1275. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  1276. var users = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "userId", $"{itemUser.Userid}" }, { "unionId", $"{itemUser.Unionid}" } });
  1277. if (users.Count > 0)
  1278. {
  1279. foreach (var user in users)
  1280. {
  1281. DingDingUserInfo ddUserInfo = new()
  1282. {
  1283. PartitionKey = user.PartitionKey,
  1284. RowKey = user.RowKey,
  1285. userId = itemUser.Userid,
  1286. unionId = itemUser.Unionid,
  1287. name = itemUser.Name,
  1288. email = itemUser.Email,
  1289. title = itemUser.Title,
  1290. stateCode = itemUser.StateCode,
  1291. mobile = itemUser.Mobile,
  1292. jobNumber = itemUser.JobNumber,
  1293. pid = parentId,
  1294. deptId = deptId,
  1295. deptName = name,
  1296. depts = string.Join(",", itemUser.DeptIdList.ToArray()),
  1297. avatar = itemUser.Avatar,
  1298. isAdmin = itemUser.Admin,
  1299. tmdId = user.tmdId,
  1300. tmdName = user.tmdName,
  1301. tmdMobile = user.tmdMobile,
  1302. mail = user.mail,
  1303. picture = user.picture,
  1304. roles = user.roles,
  1305. joinTime = user.joinTime,
  1306. permissions = user.permissions,
  1307. schoolIds = user.schoolIds,
  1308. isDisable = 1,
  1309. };
  1310. ddUserInfos.Add(ddUserInfo);
  1311. }
  1312. }
  1313. else
  1314. {
  1315. DingDingUserInfo ddUserInfo = new()
  1316. {
  1317. RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
  1318. userId = itemUser.Userid,
  1319. unionId = itemUser.Unionid,
  1320. name = itemUser.Name,
  1321. email = itemUser.Email,
  1322. title = itemUser.Title,
  1323. stateCode = itemUser.StateCode,
  1324. mobile = itemUser.Mobile,
  1325. jobNumber = itemUser.JobNumber,
  1326. pid = parentId,
  1327. deptId = deptId,
  1328. deptName = name,
  1329. depts = string.Join(",", itemUser.DeptIdList.ToArray()),
  1330. avatar = itemUser.Avatar,
  1331. isAdmin = itemUser.Admin,
  1332. PartitionKey = partitionKey,
  1333. tmdId = "",
  1334. tmdName = "",
  1335. tmdMobile = "",
  1336. mail = "",
  1337. picture = "",
  1338. roles = "",
  1339. joinTime = 0,
  1340. permissions = "areadata-read,areadata-upd,schooldata-read,schooldata-upd",
  1341. schoolIds = "",
  1342. isDisable = 0,
  1343. };
  1344. ddUserInfos.Add(ddUserInfo);
  1345. }
  1346. }
  1347. }
  1348. }
  1349. return ddUserInfos;
  1350. }
  1351. public record DDUserInfo
  1352. {
  1353. public string partitionKey { get; set; }
  1354. public string rowKey { get; set; }
  1355. public string userId { get; set; }
  1356. public string unionId { get; set; }
  1357. public string name { get; set; }
  1358. public string title { get; set; }
  1359. public string stateCode { get; set; }
  1360. public string mobile { get; set; }
  1361. public string jobNumber { get; set; }
  1362. public long pid { get; set; }
  1363. public long deptId { get; set; }
  1364. public string deptName { get; set; }
  1365. public string depts { get; set; }
  1366. public string avatar { get; set; }
  1367. public bool isAdmin { get; set; }
  1368. public string tmdId { get; set; }
  1369. public string tmdName { get; set; }
  1370. public string tmdMobile { get; set; }
  1371. public string mail { get; set; }
  1372. public string picture { get; set; }
  1373. public string roles { get; set; }
  1374. public long joinTime { get; set; }
  1375. public long isDisable { get; set; }
  1376. public string permissions { get; set; }
  1377. public List<string> handleRoles { get; set; }
  1378. public List<string> handlePermissions { get; set; }
  1379. public List<BaseInfo> handleSchools { get; set; } = new List<BaseInfo>();
  1380. }
  1381. }
  1382. }