TableDingDingInfoController.cs 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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. namespace TEAMModelBI.Controllers.DingDingStruc
  27. {
  28. [Route("tabledd")]
  29. [ApiController]
  30. public class TableDingDingInfoController : ControllerBase
  31. {
  32. //读取配置文件
  33. private readonly IConfiguration _configuration;
  34. //数据容器
  35. private readonly AzureCosmosFactory _azureCosmos;
  36. //blob和table容器
  37. private readonly AzureStorageFactory _azureStorage;
  38. //钉钉提示信息
  39. private readonly DingDing _dingDing;
  40. private readonly Option _option;
  41. private readonly IHttpClientFactory _http;
  42. public TableDingDingInfoController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IConfiguration configuration, IHttpClientFactory http)
  43. {
  44. _azureCosmos = azureCosmos;
  45. _dingDing = dingDing;
  46. _azureStorage = azureStorage;
  47. _option = option?.Value;
  48. _http = http;
  49. _configuration = configuration;
  50. }
  51. /// <summary>
  52. /// 从钉钉的组织架构中人员信息数据,并保存或者更新至Blob中
  53. /// </summary>
  54. /// <returns></returns>
  55. [ProducesDefaultResponseType]
  56. [AuthToken(Roles = "admin")]
  57. [HttpPost("get-dingdingusers")]
  58. public async Task<IActionResult> GetDingDingUser(JsonElement jsonElement)
  59. {
  60. try
  61. {
  62. string appKey = _configuration["DingDingAuth:appKey"];
  63. string appSecret = _configuration["DingDingAuth:appSecret"];
  64. //string divide = _configuration["CustomParam:SiteScope"];
  65. string divide = _option.Location;
  66. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  67. HttpClient httpClient = _http.CreateClient();
  68. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  69. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  70. //获取access_token
  71. IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  72. OapiGettokenRequest tokenRequest = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  73. tokenRequest.SetHttpMethod("Get");
  74. OapiGettokenResponse tokenRespone = tokenClient.Execute(tokenRequest);
  75. if (tokenRespone.IsError)
  76. {
  77. return BadRequest();
  78. }
  79. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  80. string access_token = tokenRespone.AccessToken;
  81. //获取部门接口
  82. IDingTalkClient deptListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
  83. //一级部门
  84. OapiV2DepartmentListsubRequest reqDeptList1 = new OapiV2DepartmentListsubRequest() { DeptId = 1L, Language = "zh_CN" };
  85. OapiV2DepartmentListsubResponse rspDeptList1 = deptListClient.Execute(reqDeptList1, access_token);
  86. List<DingDingUserInfo> ddUserInfos = new();
  87. if (rspDeptList1.Result != null)
  88. {
  89. foreach (var tempDept1 in rspDeptList1.Result)
  90. {
  91. //获取一级部门用户信息
  92. List<DingDingUserInfo> dingDingUserInfos1 = await GetDingDingUserInfo(divide, tempDept1.DeptId, tempDept1.ParentId, tempDept1.Name, access_token);
  93. //if (dingDingUserInfos1.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos1.ToList()));
  94. if (dingDingUserInfos1.Count > 0) ddUserInfos.AddRange(dingDingUserInfos1);
  95. //获取二级部门
  96. OapiV2DepartmentListsubRequest reqDeptList2 = new OapiV2DepartmentListsubRequest() { DeptId = tempDept1.DeptId, Language = "zh_CN" };
  97. OapiV2DepartmentListsubResponse rspDeptList2 = deptListClient.Execute(reqDeptList2, access_token);
  98. if (rspDeptList2.Result != null)
  99. {
  100. foreach (var tempDept2 in rspDeptList2.Result)
  101. {
  102. //获取二级部门用户信息
  103. List<DingDingUserInfo> dingDingUserInfos2 = await GetDingDingUserInfo(divide, tempDept2.DeptId, tempDept2.ParentId, tempDept2.Name, access_token);
  104. //if (dingDingUserInfos2.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos2.ToList()));
  105. if (dingDingUserInfos2.Count > 0) ddUserInfos.AddRange(dingDingUserInfos2);
  106. //获取三级部门
  107. OapiV2DepartmentListsubRequest reqDeptList3 = new OapiV2DepartmentListsubRequest() { DeptId = tempDept2.DeptId, Language = "zh_CN" };
  108. OapiV2DepartmentListsubResponse rspDeptList3 = deptListClient.Execute(reqDeptList3, access_token);
  109. if (rspDeptList3.Result != null)
  110. {
  111. foreach (var tempDept3 in rspDeptList3.Result)
  112. {
  113. //获取三级部门用户信息
  114. List<DingDingUserInfo> dingDingUserInfos3 = await GetDingDingUserInfo(divide, tempDept3.DeptId, tempDept3.ParentId, tempDept3.Name, access_token);
  115. //if (dingDingUserInfos3.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos3.ToList()));
  116. if (dingDingUserInfos3.Count > 0) ddUserInfos.AddRange(dingDingUserInfos3);
  117. //获取四级部门
  118. OapiV2DepartmentListsubRequest reqDeptList4 = new OapiV2DepartmentListsubRequest() { DeptId = tempDept3.DeptId, Language = "zh_CN" };
  119. OapiV2DepartmentListsubResponse rspDeptList4 = deptListClient.Execute(reqDeptList4, access_token);
  120. if (rspDeptList4.Result != null)
  121. {
  122. foreach (var tempDept4 in rspDeptList4.Result)
  123. {
  124. //获取四级部门用户信息
  125. List<DingDingUserInfo> dingDingUserInfos4 = await GetDingDingUserInfo(divide, tempDept4.DeptId, tempDept4.ParentId, tempDept4.Name, access_token);
  126. //if (dingDingUserInfos4.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos4.ToList()));
  127. if (dingDingUserInfos4.Count > 0) ddUserInfos.AddRange(dingDingUserInfos4);
  128. //获取五级部门
  129. OapiV2DepartmentListsubRequest reqDeptList5 = new OapiV2DepartmentListsubRequest() { DeptId = tempDept4.DeptId, Language = "zh_CN" };
  130. OapiV2DepartmentListsubResponse rspDeptList5 = deptListClient.Execute(reqDeptList5, access_token);
  131. if (rspDeptList5.Result != null)
  132. {
  133. foreach (var tempDept5 in rspDeptList5.Result)
  134. {
  135. //获取五级部门用户信息
  136. List<DingDingUserInfo> dingDingUserInfos5 = await GetDingDingUserInfo(divide, tempDept5.DeptId, tempDept5.ParentId, tempDept5.Name, access_token);
  137. //if (dingDingUserInfos5.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos5).ToList());
  138. if (dingDingUserInfos5.Count > 0) ddUserInfos.AddRange(dingDingUserInfos5);
  139. }
  140. }
  141. }
  142. }
  143. }
  144. }
  145. }
  146. }
  147. }
  148. }
  149. //保存操作记录
  150. await _azureStorage.SaveBILog("tabledd-update", $"{_tmdName}【{_tmdId}】从钉钉组织结构更新至Azure Table表【DDUserInfo】中。", _dingDing, httpContext: HttpContext);
  151. var tempddUserInfos = ddUserInfos.GroupBy(c => c.userId).Select(c => c.First()).ToList();//去重
  152. //List<DingDingUserInfo> TempdingDingUserInfos = await _azureStorage.SaveOrUpdateAll(dingDingUserInfos); //只是保存至Table
  153. //查询数据的数据 并和钉钉查询的数据对比,找出不同的数据,并删除 待后期测试
  154. var users = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{divide}" } });
  155. List<DingDingUserInfo> noExisits = new();
  156. if (users.Count > 0)
  157. {
  158. List<DingDingUserInfo> existsUserInfo = users.Where(u => !tempddUserInfos.Exists(e => u.userId.Equals(e.userId) && u.PartitionKey.Equals(e.PartitionKey))).ToList();
  159. existsUserInfo.AddRange(tempddUserInfos.Where(e => !users.Exists(u => e.userId.Equals(u.userId) && e.PartitionKey.Equals(u.PartitionKey))).ToList());
  160. noExisits = await table.DeleteAll(existsUserInfo);
  161. }
  162. List<DingDingUserInfo> UserInfo = await table.SaveOrUpdateAll(tempddUserInfos); //保存和修改至Table
  163. return Ok(new { state = 200, UserInfo, noExisits });
  164. }
  165. catch (Exception ex)
  166. {
  167. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/get-dingdingusers \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  168. return BadRequest();
  169. }
  170. }
  171. /// <summary>
  172. /// 查询钉钉信息和醍摩豆信息
  173. /// </summary>
  174. /// <returns></returns>
  175. [ProducesDefaultResponseType]
  176. [HttpPost("get-ddusers")]
  177. public async Task<IActionResult> GetDingDingUsers(JsonElement jsonElement)
  178. {
  179. try
  180. {
  181. jsonElement.TryGetProperty("busy", out JsonElement busy);
  182. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  183. //string divide = _configuration["CustomParam:SiteScope"];
  184. string divide = _option.Location;
  185. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
  186. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  187. List<DDUserInfo> ddUserInfos = new();
  188. switch ($"{busy}")
  189. {
  190. case "admin":
  191. foreach (var item in ddUserInfoList)
  192. {
  193. if (item.roles.Contains("admin"))
  194. {
  195. DDUserInfo ddUserInfo = new()
  196. {
  197. partitionKey = item.PartitionKey,
  198. rowKey = item.RowKey,
  199. userId = item.userId,
  200. unionId = item.unionId,
  201. name = item.name,
  202. title = item.title,
  203. stateCode = item.stateCode,
  204. mobile = item.mobile,
  205. jobNumber = item.jobNumber,
  206. pid = item.pid,
  207. deptId = item.deptId,
  208. deptName = item.deptName,
  209. depts = item.depts,
  210. avatar = item.avatar,
  211. isAdmin = item.isAdmin,
  212. tmdId = item.tmdId,
  213. tmdName = item.tmdName,
  214. tmdMobile = item.tmdMobile,
  215. mail = item.mail,
  216. picture = item.picture,
  217. roles = item.roles,
  218. permissions = item.permissions,
  219. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  220. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  221. };
  222. ddUserInfos.Add(ddUserInfo);
  223. }
  224. }
  225. break;
  226. default:
  227. foreach (var item in ddUserInfoList)
  228. {
  229. DDUserInfo ddUserInfo = new()
  230. {
  231. partitionKey = item.PartitionKey,
  232. rowKey = item.RowKey,
  233. userId = item.userId,
  234. unionId = item.unionId,
  235. name = item.name,
  236. title = item.title,
  237. stateCode = item.stateCode,
  238. mobile = item.mobile,
  239. jobNumber = item.jobNumber,
  240. pid = item.pid,
  241. deptId = item.deptId,
  242. deptName = item.deptName,
  243. depts = item.depts,
  244. avatar = item.avatar,
  245. isAdmin = item.isAdmin,
  246. tmdId = item.tmdId,
  247. tmdName = item.tmdName,
  248. tmdMobile = item.tmdMobile,
  249. mail = item.mail,
  250. picture = item.picture,
  251. roles = item.roles,
  252. permissions = item.permissions,
  253. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  254. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  255. };
  256. ddUserInfos.Add(ddUserInfo);
  257. }
  258. break;
  259. }
  260. return Ok(new { state = 200, ddUserInfos = ddUserInfos });
  261. }
  262. catch (Exception ex)
  263. {
  264. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/get-ddusers \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  265. return BadRequest();
  266. }
  267. }
  268. /// <summary>
  269. /// 查询钉钉待入职人员的ID添加至Table数据表中
  270. /// </summary>
  271. /// <returns></returns>
  272. [ProducesDefaultResponseType]
  273. [AuthToken(Roles = "assist")]
  274. [HttpPost("set-ddinductionuser")]
  275. public async Task<IActionResult> SetDingDingInductionUser(JsonElement jsonElement)
  276. {
  277. try
  278. {
  279. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  280. string appKey = _configuration["DingDingAuth:appKey"];
  281. string appSecret = _configuration["DingDingAuth:appSecret"];
  282. //string divide = _configuration["CustomParam:SiteScope"];
  283. string divide = _option.Location;
  284. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  285. //获取access_token
  286. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  287. OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  288. request.SetHttpMethod("Get");
  289. OapiGettokenResponse response = client.Execute(request);
  290. if (response.IsError)
  291. {
  292. return BadRequest();
  293. }
  294. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  295. string access_token = response.AccessToken;
  296. IDingTalkClient InductionClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querypreentry");
  297. OapiSmartworkHrmEmployeeQuerypreentryRequest reqInduction = new OapiSmartworkHrmEmployeeQuerypreentryRequest() { Offset = 0L, Size = 50 };
  298. reqInduction.SetHttpMethod("GET");
  299. OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
  300. if (rspInduction.Result.DataList != null)
  301. {
  302. List<DingDingUserInfo> ddUserInfos = new List<DingDingUserInfo>();
  303. foreach (var itemId in rspInduction.Result.DataList)
  304. {
  305. DingDingUserInfo ddUserInfo = new DingDingUserInfo();
  306. ddUserInfo.PartitionKey = divide;
  307. ddUserInfo.RowKey = itemId;
  308. ddUserInfos.Add(ddUserInfo);
  309. }
  310. List<DingDingUserInfo> tempddUserInfos = await table.SaveAll(ddUserInfos);
  311. //保存操作记录
  312. await _azureStorage.SaveBILog("tabledd-add", $"{_tmdName}【{_tmdId}】添加待入职员工至table数据表中", _dingDing, httpContext: HttpContext);
  313. if (ddUserInfos.Count == tempddUserInfos.Count)
  314. {
  315. return Ok(new { state = 200, UserInfo = tempddUserInfos });
  316. }
  317. else
  318. {
  319. var diffArr = tempddUserInfos.Where(c => !ddUserInfos.Contains(c)).ToList();
  320. return Ok(new { state = 201, notUserInfo = diffArr });
  321. }
  322. }
  323. else
  324. {
  325. return Ok(new { state = 400, rspInduction.SubErrCode, rspInduction.SubErrMsg });
  326. }
  327. }
  328. catch (Exception ex)
  329. {
  330. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-ddinductionuser \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  331. return BadRequest();
  332. }
  333. }
  334. /// <summary>
  335. /// 获取钉钉离职人员ID并删除Table表中的数据
  336. /// </summary>
  337. /// <returns></returns>
  338. [ProducesDefaultResponseType]
  339. [AuthToken(Roles = "assist")]
  340. [HttpPost("del-ddquituser")]
  341. public async Task<IActionResult> DeleteDDQuitUser(JsonElement jsonElement)
  342. {
  343. try
  344. {
  345. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  346. string appKey = _configuration["DingDingAuth:appKey"];
  347. string appSecret = _configuration["DingDingAuth:appSecret"];
  348. //string divide = _configuration["CustomParam:SiteScope"];
  349. string divide = _option.Location;
  350. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  351. //获取access_token
  352. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  353. OapiGettokenRequest request = new() { Appkey = appKey, Appsecret = appSecret };
  354. request.SetHttpMethod("Get");
  355. OapiGettokenResponse response = client.Execute(request);
  356. if (response.IsError)
  357. {
  358. return BadRequest();
  359. }
  360. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  361. string access_token = response.AccessToken;
  362. IDingTalkClient quitStaffClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
  363. OapiSmartworkHrmEmployeeQuerydimissionRequest reqDimission = new OapiSmartworkHrmEmployeeQuerydimissionRequest() { Offset = 0L, Size = 50L };
  364. OapiSmartworkHrmEmployeeQuerydimissionResponse rspDimission = quitStaffClient.Execute(reqDimission, access_token);
  365. if (rspDimission.Result != null)
  366. {
  367. List<DingDingUserInfo> ddUserInfos = new();
  368. foreach (var itemId in rspDimission.Result.DataList)
  369. {
  370. await table.DeleteSingle<DingDingUserInfo>(divide, $"{itemId}");
  371. }
  372. //保存操作记录
  373. await _azureStorage.SaveBILog("tabledd-del", $"{_tmdName}【{_tmdId}】从table数据表中删除离职员工", _dingDing, httpContext: HttpContext);
  374. return Ok(new { state = 200 });
  375. }
  376. else
  377. {
  378. return Ok(new { state = rspDimission.SubErrCode });
  379. }
  380. }
  381. catch (Exception ex)
  382. {
  383. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/del-ddquituser \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  384. return BadRequest();
  385. }
  386. }
  387. /// <summary>
  388. /// 更新钉钉和醍摩豆的BI权限
  389. /// </summary>
  390. /// <param name="jsonElement"></param>
  391. /// <returns></returns>
  392. [ProducesDefaultResponseType]
  393. [AuthToken(Roles = "admin")]
  394. [HttpPost("set-permissions")]
  395. public async Task<IActionResult> SetPermissions(JsonElement jsonElement)
  396. {
  397. try
  398. {
  399. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  400. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  401. if (!jsonElement.TryGetProperty("permissions", out JsonElement _permissions)) return BadRequest();
  402. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  403. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  404. StringBuilder stringBuilder = new($"{_tmdName}【{_tmdId}】醍摩豆账号");
  405. List<DingDingUserInfo> ddUserInfo = new();
  406. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
  407. List<string> listper = _permissions.ToObject<List<string>>();
  408. List<string> roles = new();//角色列表
  409. List<string> permissions = new ();//权限列表
  410. foreach (var item in tempUser)
  411. {
  412. stringBuilder.Append($"操作醍摩豆账户{item.tmdName}【{item.tmdId}】修改权限:{string.Join("|", listper.ToArray())}");
  413. if (string.IsNullOrEmpty($"{item.roles}"))
  414. {
  415. item.roles = "assist";
  416. }
  417. string tempPermissions = "";
  418. foreach (var itemPer in listper)
  419. {
  420. tempPermissions += !string.IsNullOrEmpty($"{tempPermissions}") ? $",{itemPer}" : $"{itemPer}";
  421. }
  422. item.permissions = tempPermissions;
  423. ddUserInfo.Add(item);
  424. roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  425. permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
  426. }
  427. ddUserInfo = await table.UpdateAll<DingDingUserInfo>(ddUserInfo);
  428. //保存操作记录
  429. await _azureStorage.SaveBILog("tabledd-update", stringBuilder?.ToString(), _dingDing, httpContext: HttpContext);
  430. return Ok(new { state = 200, ddUserInfo, roles, permissions });
  431. }
  432. catch (Exception ex)
  433. {
  434. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-permissions \n {ex.Message}{ex.StackTrace} ", GroupNames.成都开发測試群組);
  435. return BadRequest();
  436. }
  437. }
  438. /// <summary>
  439. /// 依据部门ID获取部门列表
  440. /// </summary>
  441. /// <param name="jsonElement"></param>
  442. /// <returns></returns>
  443. [ProducesDefaultResponseType]
  444. [HttpPost("get-dddeptiduser")]
  445. public async Task<IActionResult> GetDDDeptIdUser(JsonElement jsonElement)
  446. {
  447. try
  448. {
  449. if (!jsonElement.TryGetProperty("deptId", out JsonElement deptId)) return BadRequest();
  450. //string divide = _configuration["CustomParam:SiteScope"];
  451. string divide = _option.Location;
  452. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
  453. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  454. List<DingDingUserInfo> tempUserInfos = await table.FindListByDict<DingDingUserInfo>(dic);
  455. List<DingDingUserInfo> userInfo = new();
  456. tempUserInfos.ForEach(x => {
  457. if (x.depts.Contains($"{deptId}"))
  458. {
  459. userInfo.Add(x);
  460. }
  461. if (x.pid.Equals(long.Parse($"{deptId}")))
  462. {
  463. userInfo.Add(x);
  464. }
  465. });
  466. //userInfo.Distinct().ToList(); //Equals实现去重
  467. userInfo.Where((x, i) => userInfo.FindIndex(z => z.RowKey.Equals(x.RowKey)) == i);//Lambda表达式去重
  468. //userInfo.GroupBy(p => p).Select(p => p.Key).ToList();//去重复
  469. //List<DingDingUserInfo> ddUserInfo = new();
  470. //List<DingDingUserInfo> tempUser = new();
  471. //tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "deptId", $"{deptId}" } });
  472. //if (tempUser.Count == 0)
  473. //{
  474. // tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{deptId}" } });
  475. //}
  476. //foreach (var itemUser in tempUser)
  477. //{
  478. // var tempUser1 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{deptId}" } });
  479. // foreach (var itemUser1 in tempUser1)
  480. // {
  481. // if (!long.Parse($"{deptId}").Equals(itemUser1.pid))
  482. // {
  483. // var tempUser2 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{itemUser1.pid}" } });
  484. // foreach (var itemUser2 in tempUser2)
  485. // {
  486. // if (!itemUser1.pid.Equals(itemUser2.pid))
  487. // {
  488. // var tempUser3 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{itemUser2.pid}" } });
  489. // foreach (var itemUser3 in tempUser3)
  490. // {
  491. // if (!itemUser2.pid.Equals(itemUser3.pid))
  492. // {
  493. // var tempUser4 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{itemUser3.pid}" } });
  494. // foreach (var itemUser4 in tempUser4)
  495. // {
  496. // if (!itemUser3.pid.Equals(itemUser4.pid)) { }
  497. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser4.RowKey)) == null)
  498. // {
  499. // ddUserInfo.Add(itemUser4);
  500. // }
  501. // }
  502. // }
  503. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser3.RowKey)) == null)
  504. // {
  505. // ddUserInfo.Add(itemUser3);
  506. // }
  507. // }
  508. // }
  509. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser2.RowKey)) == null)
  510. // {
  511. // ddUserInfo.Add(itemUser2);
  512. // }
  513. // }
  514. // }
  515. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser1.RowKey)) == null)
  516. // {
  517. // ddUserInfo.Add(itemUser1);
  518. // }
  519. // }
  520. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser.RowKey)) == null)
  521. // {
  522. // ddUserInfo.Add(itemUser);
  523. // }
  524. //}
  525. List<DDUserInfo> ddUserInfos = new();
  526. foreach (var item in userInfo)
  527. {
  528. DDUserInfo tempUserInfo = new DDUserInfo()
  529. {
  530. partitionKey = item.PartitionKey,
  531. rowKey = item.RowKey,
  532. userId = item.userId,
  533. unionId = item.unionId,
  534. name = item.name,
  535. title = item.title,
  536. stateCode = item.stateCode,
  537. mobile = item.mobile,
  538. jobNumber = item.jobNumber,
  539. pid = item.pid,
  540. deptId = item.deptId,
  541. deptName = item.deptName,
  542. depts = item.depts,
  543. avatar = item.avatar,
  544. isAdmin = item.isAdmin,
  545. tmdId = item.tmdId,
  546. tmdName = item.tmdName,
  547. tmdMobile = item.tmdMobile,
  548. mail = item.mail,
  549. picture = item.picture,
  550. roles = item.roles,
  551. permissions = item.permissions,
  552. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  553. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  554. };
  555. ddUserInfos.Add(tempUserInfo);
  556. }
  557. return Ok(new { state = 200, ddUserInfos });
  558. }
  559. catch (Exception ex)
  560. {
  561. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/get-dddeptiduser \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  562. return BadRequest();
  563. }
  564. }
  565. /// <summary>
  566. /// 后端钉钉账户和醍摩豆账户进行绑定
  567. /// </summary>
  568. /// <param name="jsonElement"></param>
  569. /// <returns></returns>
  570. [ProducesDefaultResponseType]
  571. [AuthToken(Roles = "assist")]
  572. [HttpPost("set-backenbind")]
  573. public async Task<IActionResult> SetBackenBind(JsonElement jsonElement)
  574. {
  575. try
  576. {
  577. if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
  578. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  579. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  580. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  581. List<DingDingUserInfo> tempddUsers = null;
  582. List<DingDingUserInfo> ddUsers = new();
  583. StringBuilder tableSql = new();
  584. if (!string.IsNullOrEmpty($"{rowKey}"))
  585. tableSql.Append($"RowKey {QueryComparisons.Equal} '{rowKey}'");
  586. string tmdId = null;
  587. string tmdName = null;
  588. string tmdMobile = null;
  589. string mail = null;
  590. string picture = null;
  591. HttpClient httpClient = _http.CreateClient();
  592. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  593. List<string> mobiles = new List<string>() { $"{mobile}" };
  594. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
  595. if (responseMessage.StatusCode == HttpStatusCode.OK)
  596. {
  597. string temp = responseMessage.Content.ReadAsStringAsync().Result;
  598. List<JsonElement> json_id = temp.ToObject<List<JsonElement>>();
  599. if (json_id.Count > 0)
  600. {
  601. foreach (var item in json_id)
  602. {
  603. tmdId = item.GetProperty("id").ToString();
  604. tmdName = item.GetProperty("name").ToString();
  605. tmdMobile = item.GetProperty("mobile").ToString();
  606. mail = item.GetProperty("mail").ToString();
  607. picture = item.GetProperty("picture").ToString();
  608. }
  609. }
  610. else return Ok(new { state = 1, message = "该手机号未找到醍摩豆账户" });
  611. }
  612. tempddUsers = await table.QueryWhereString<DingDingUserInfo>(tableSql.ToString());
  613. if (tempddUsers.Count > 0)
  614. {
  615. foreach (var item in tempddUsers)
  616. {
  617. if (item.RowKey.Equals($"{rowKey}"))
  618. {
  619. item.tmdId = tmdId;
  620. item.tmdName = tmdName;
  621. item.tmdMobile = tmdMobile;
  622. item.mail = mail;
  623. item.picture = picture;
  624. ddUsers.Add(item);
  625. }
  626. }
  627. }
  628. else return Ok(new { state = 2, message = "钉钉ID错误请检查钉钉ID" });
  629. if (ddUsers.Count > 0) ddUsers = await table.SaveOrUpdateAll(ddUsers);
  630. //保存操作记录
  631. await _azureStorage.SaveBILog("tabledd-update", $"{_tmdName}【{_tmdId}】操作:绑定钉钉账户[{rowKey}]和醍摩豆账户[{tmdId}]", _dingDing, httpContext: HttpContext);
  632. return Ok(new { state = 200, ddUsers });
  633. }
  634. catch (Exception ex)
  635. {
  636. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backenbind \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  637. return BadRequest();
  638. }
  639. }
  640. /// <summary>
  641. /// 设置系统管理员
  642. /// </summary>
  643. /// <param name="jsonElement"></param>
  644. /// <returns></returns>
  645. [ProducesDefaultResponseType]
  646. [AuthToken(Roles = "admin")]
  647. [HttpPost("set-backend")]
  648. public async Task<IActionResult> SetBackendAdmin(JsonElement jsonElement)
  649. {
  650. try
  651. {
  652. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  653. if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
  654. if (!jsonElement.TryGetProperty("isAdmin", out JsonElement isAdmin)) return BadRequest();
  655. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  656. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  657. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{rowKey}" } });
  658. List<DDUserInfo> ddUserInfos = new();
  659. List<string> roles = new();//角色列表
  660. List<string> permissions = new();//权限列表
  661. StringBuilder msg = new($"{_tmdName}【{_tmdId}】");
  662. if (bool.Parse($"{isAdmin}") == true)
  663. {
  664. foreach (var user in tempUser)
  665. {
  666. if (string.IsNullOrEmpty(user.roles))
  667. {
  668. user.roles = "admin,assist";
  669. }
  670. List<string> tempRoles = new(user.roles.Split(","));
  671. if (!tempRoles.Contains("admin"))
  672. {
  673. tempRoles.Add("admin");
  674. }
  675. user.roles = string.Join(",", tempRoles);
  676. user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  677. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  678. if (respUser != null)
  679. {
  680. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  681. }
  682. msg.Append($"添加{respUser.name}【{respUser.RowKey}】账号的BI管理员");
  683. }
  684. }
  685. else
  686. {
  687. foreach (var user in tempUser)
  688. {
  689. List<string> tempRoles = new(user.roles.Split(","));
  690. if (tempRoles.Contains("admin"))
  691. {
  692. tempRoles.Remove("admin");
  693. }
  694. user.roles = string.Join(",", tempRoles);
  695. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  696. if (respUser != null)
  697. {
  698. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  699. msg.Append($"取消{respUser.name}【{respUser.RowKey}】账号的BI管理员");
  700. }
  701. }
  702. }
  703. //保存操作记录
  704. await _azureStorage.SaveBILog("tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
  705. return Ok(new { state = 200, roles });
  706. }
  707. catch (Exception ex)
  708. {
  709. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backend \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  710. return BadRequest();
  711. }
  712. }
  713. /// <summary>
  714. /// 通过醍摩豆账户信息 设置BI后台管理员
  715. /// </summary>
  716. /// <param name="jsonElement"></param>
  717. /// <returns></returns>
  718. [ProducesDefaultResponseType]
  719. [AuthToken(Roles = "admin")]
  720. [HttpPost("set-tmdadmin")]
  721. public async Task<IActionResult> SetTmdBackendAdmin(JsonElement jsonElement)
  722. {
  723. try
  724. {
  725. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  726. if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
  727. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  728. jsonElement.TryGetProperty("picture ", out JsonElement picture);
  729. jsonElement.TryGetProperty("mail ", out JsonElement mail);
  730. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  731. List<DDUserInfo> ddUserInfos = new();
  732. List<string> roles = new();//角色列表
  733. List<string> permissions = new();//权限列表
  734. StringBuilder msg = new($"{_tmdName}【{_tmdId}】");
  735. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  736. //string divide = _configuration["CustomParam:SiteScope"];
  737. string divide = _option.Location;
  738. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" }, { "mobile", $"{mobile}" } };
  739. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  740. if (ddUserInfoList.Count > 0)
  741. {
  742. foreach (var user in ddUserInfoList)
  743. {
  744. List<string> tempRoles = new(user.roles.Split(","));
  745. if (tempRoles.Count > 0)
  746. {
  747. if (!tempRoles.Contains("admin"))
  748. {
  749. tempRoles.Add("admin");
  750. }
  751. }
  752. else
  753. tempRoles.Add("admin");
  754. user.roles = string.Join(",", tempRoles);
  755. user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  756. user.tmdId = $"{tmdId}";
  757. user.tmdName = $"{tmdName}";
  758. user.tmdMobile = $"{mobile}";
  759. if (!string.IsNullOrEmpty($"{picture}"))
  760. {
  761. user.picture = $"{picture}";
  762. }
  763. if (!string.IsNullOrEmpty($"{mail}"))
  764. {
  765. user.mail = $"{mail}";
  766. }
  767. msg.Append($" 将:{tmdName}【{tmdId}】醍摩豆账号和({user.name}【{user.unionId}】) 钉钉账户绑定,并设置管理员");
  768. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  769. if (respUser != null)
  770. {
  771. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  772. }
  773. DDUserInfo dDUserInfo = new()
  774. {
  775. partitionKey = respUser.PartitionKey,
  776. rowKey = respUser.RowKey,
  777. userId = respUser.userId,
  778. unionId = respUser.unionId,
  779. name = respUser.name,
  780. title = respUser.title,
  781. stateCode = respUser.stateCode,
  782. mobile = respUser.mobile,
  783. jobNumber = respUser.jobNumber,
  784. pid = respUser.pid,
  785. deptId = respUser.deptId,
  786. deptName = respUser.deptName,
  787. depts = respUser.depts,
  788. avatar = respUser.avatar,
  789. isAdmin = respUser.isAdmin,
  790. tmdId = respUser.tmdId,
  791. tmdName = respUser.tmdName,
  792. tmdMobile = respUser.tmdMobile,
  793. mail = respUser.mail,
  794. picture = respUser.picture,
  795. roles = respUser.roles,
  796. permissions = respUser.permissions,
  797. handleRoles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>(),
  798. handlePermissions = !string.IsNullOrEmpty($"{respUser.permissions}") ? new List<string>(respUser.permissions.Split(",")) : new List<string>()
  799. };
  800. ddUserInfos.Add(dDUserInfo);
  801. }
  802. }
  803. else
  804. {
  805. DingDingUserInfo dingDingUserInfo = new()
  806. {
  807. PartitionKey = divide,
  808. RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
  809. roles = "admin",
  810. tmdId = $"{tmdId}",
  811. tmdName = $"{tmdName}",
  812. tmdMobile = $"{mobile}",
  813. };
  814. if (!string.IsNullOrEmpty($"{picture}"))
  815. {
  816. dingDingUserInfo.picture = $"{picture}";
  817. }
  818. if (!string.IsNullOrEmpty($"{mail}"))
  819. {
  820. dingDingUserInfo.mail = $"{mail}";
  821. }
  822. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(dingDingUserInfo);
  823. return Ok(new { state = 201, msg = "新生成的BIadmin", respUser });
  824. }
  825. //保存操作记录
  826. await _azureStorage.SaveBILog("tabledd-update",msg.ToString(), _dingDing, httpContext: HttpContext);
  827. return Ok(new { state = 200, ddUserInfos });
  828. }
  829. catch (Exception ex)
  830. {
  831. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-tmdadmin \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  832. return BadRequest();
  833. }
  834. }
  835. /// <summary>
  836. /// 解除钉钉和醍摩豆的绑定
  837. /// </summary>
  838. /// <param name="jsonElement"></param>
  839. /// <returns></returns>
  840. [ProducesDefaultResponseType]
  841. [HttpPost("set-unbind")]
  842. public async Task<IActionResult> SetUnbind(JsonElement jsonElement)
  843. {
  844. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  845. //string divide = _configuration["CustomParam:SiteScope"];
  846. string divide = _option.Location;
  847. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
  848. if (!string.IsNullOrEmpty($"{mobile}"))
  849. dic.Add("tmdMobile", $"{mobile}");
  850. else
  851. dic.Add("tmdMobile", "18281911681");
  852. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  853. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  854. List<DingDingUserInfo> tempDDUI = new();
  855. if (ddUserInfoList.Count > 0)
  856. {
  857. foreach (var item in ddUserInfoList)
  858. {
  859. item.tmdId = null;
  860. item.tmdName = null;
  861. item.tmdMobile = null;
  862. item.picture = null;
  863. tempDDUI.Add(item);
  864. }
  865. }
  866. else return Ok(new { state = 404, msg = "未找到手机号匹配的绑定号码!,请检查手机号" });
  867. var userInfos = await table.SaveOrUpdateAll(tempDDUI); //保存和修改至Table
  868. return Ok(new { state = 200, userInfos });
  869. }
  870. /// <summary>
  871. /// 获取钉钉用户信息
  872. /// 并查询本地Table数据表中是否存在
  873. /// </summary>
  874. /// <param name="deptId"></param>
  875. /// <param name="parentId"></param>
  876. /// <param name="name"></param>
  877. /// <param name="access_token"></param>
  878. /// <returns></returns>
  879. public async Task<List<DingDingUserInfo>> GetDingDingUserInfo(string partitionKey, long deptId, long parentId, string name, string access_token)
  880. {
  881. List<DingDingUserInfo> ddUserInfos = new();
  882. //获取部门人员信息
  883. IDingTalkClient userListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
  884. //获取部门用户
  885. OapiV2UserListRequest reqUserList = new()
  886. {
  887. DeptId = deptId,
  888. Cursor = 0L,
  889. Size = 50L,
  890. OrderField = "custom",
  891. Language = "zh_CN"
  892. };
  893. reqUserList.SetHttpMethod("GET");
  894. OapiV2UserListResponse rspV2UserList = userListClient.Execute(reqUserList, access_token);
  895. if (rspV2UserList.Result.List != null)
  896. {
  897. foreach (var itemUser in rspV2UserList.Result.List)
  898. {
  899. var tempInfo = ddUserInfos.Find(x => x.RowKey.Equals(itemUser.Unionid));
  900. if (string.IsNullOrEmpty($"{tempInfo}"))
  901. {
  902. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  903. var users = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "userId", $"{itemUser.Userid}" }, { "unionId", $"{itemUser.Unionid}" } });
  904. if (users.Count > 0)
  905. {
  906. foreach (var user in users)
  907. {
  908. DingDingUserInfo ddUserInfo = new();
  909. ddUserInfo.PartitionKey = user.PartitionKey;
  910. ddUserInfo.RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
  911. ddUserInfo.userId = itemUser.Userid;
  912. ddUserInfo.unionId = itemUser.Unionid;
  913. ddUserInfo.name = itemUser.Name;
  914. ddUserInfo.email = itemUser.Email;
  915. ddUserInfo.title = itemUser.Title;
  916. ddUserInfo.stateCode = itemUser.StateCode;
  917. ddUserInfo.mobile = itemUser.Mobile;
  918. ddUserInfo.jobNumber = itemUser.JobNumber;
  919. ddUserInfo.pid = parentId;
  920. ddUserInfo.deptId = deptId;
  921. ddUserInfo.deptName = name;
  922. ddUserInfo.depts = string.Join(",", itemUser.DeptIdList.ToArray());
  923. ddUserInfo.avatar = itemUser.Avatar;
  924. ddUserInfo.isAdmin = itemUser.Admin;
  925. ddUserInfo.tmdId = user.tmdId;
  926. ddUserInfo.tmdName = user.tmdName;
  927. ddUserInfo.tmdMobile = user.tmdMobile;
  928. ddUserInfo.mail = user.mail;
  929. ddUserInfo.picture = user.picture;
  930. ddUserInfo.roles = user.roles;
  931. ddUserInfo.permissions = user.permissions;
  932. ddUserInfos.Add(ddUserInfo);
  933. }
  934. }
  935. else
  936. {
  937. DingDingUserInfo ddUserInfo = new()
  938. {
  939. RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
  940. userId = itemUser.Userid,
  941. unionId = itemUser.Unionid,
  942. name = itemUser.Name,
  943. email = itemUser.Email,
  944. title = itemUser.Title,
  945. mobile = itemUser.Mobile,
  946. jobNumber = itemUser.JobNumber,
  947. pid = parentId,
  948. deptId = deptId,
  949. deptName = name,
  950. depts = string.Join(",", itemUser.DeptIdList.ToArray()),
  951. avatar = itemUser.Avatar,
  952. isAdmin = itemUser.Admin,
  953. PartitionKey = partitionKey,
  954. tmdId = "",
  955. tmdName = "",
  956. tmdMobile = "",
  957. mail = "",
  958. picture = "",
  959. roles = "assist",
  960. permissions = "abilitystandard-read,batcharea-read,batchschool-read,orgusers-read"
  961. };
  962. ddUserInfos.Add(ddUserInfo);
  963. }
  964. }
  965. }
  966. }
  967. return ddUserInfos;
  968. }
  969. public record DDUserInfo
  970. {
  971. public string partitionKey { get; set; }
  972. public string rowKey { get; set; }
  973. public string userId { get; set; }
  974. public string unionId { get; set; }
  975. public string name { get; set; }
  976. public string title { get; set; }
  977. public string stateCode { get; set; }
  978. public string mobile { get; set; }
  979. public string jobNumber { get; set; }
  980. public long pid { get; set; }
  981. public long deptId { get; set; }
  982. public string deptName { get; set; }
  983. public string depts { get; set; }
  984. public string avatar { get; set; }
  985. public bool isAdmin { get; set; }
  986. public string tmdId { get; set; }
  987. public string tmdName { get; set; }
  988. public string tmdMobile { get; set; }
  989. public string mail { get; set; }
  990. public string picture { get; set; }
  991. public string roles { get; set; }
  992. public string permissions { get; set; }
  993. public List<string> handleRoles { get; set; }
  994. public List<string> handlePermissions { get; set; }
  995. }
  996. }
  997. }