TableDingDingInfoController.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  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 = "assist")]
  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. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  66. HttpClient httpClient = _http.CreateClient();
  67. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  68. //获取access_token
  69. IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  70. OapiGettokenRequest tokenRequest = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  71. tokenRequest.SetHttpMethod("Get");
  72. OapiGettokenResponse tokenRespone = tokenClient.Execute(tokenRequest);
  73. if (tokenRespone.IsError)
  74. {
  75. return BadRequest();
  76. }
  77. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  78. string access_token = tokenRespone.AccessToken;
  79. //获取部门接口
  80. IDingTalkClient deptListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
  81. //一级部门
  82. OapiV2DepartmentListsubRequest reqDeptList1 = new OapiV2DepartmentListsubRequest() { DeptId = 1L, Language = "zh_CN" };
  83. OapiV2DepartmentListsubResponse rspDeptList1 = deptListClient.Execute(reqDeptList1, access_token);
  84. List<DingDingUserInfo> ddUserInfos = new List<DingDingUserInfo>();
  85. if (rspDeptList1.Result != null)
  86. {
  87. foreach (var tempDept1 in rspDeptList1.Result)
  88. {
  89. //获取一级部门用户信息
  90. List<DingDingUserInfo> dingDingUserInfos1 = await GetDingDingUserInfo(divide, tempDept1.DeptId, tempDept1.ParentId, tempDept1.Name, access_token);
  91. //if (dingDingUserInfos1.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos1.ToList()));
  92. if (dingDingUserInfos1.Count > 0) ddUserInfos.AddRange(dingDingUserInfos1);
  93. //获取二级部门
  94. OapiV2DepartmentListsubRequest reqDeptList2 = new OapiV2DepartmentListsubRequest() { DeptId = tempDept1.DeptId, Language = "zh_CN" };
  95. OapiV2DepartmentListsubResponse rspDeptList2 = deptListClient.Execute(reqDeptList2, access_token);
  96. if (rspDeptList2.Result != null)
  97. {
  98. foreach (var tempDept2 in rspDeptList2.Result)
  99. {
  100. //获取二级部门用户信息
  101. List<DingDingUserInfo> dingDingUserInfos2 = await GetDingDingUserInfo(divide, tempDept2.DeptId, tempDept2.ParentId, tempDept2.Name, access_token);
  102. //if (dingDingUserInfos2.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos2.ToList()));
  103. if (dingDingUserInfos2.Count > 0) ddUserInfos.AddRange(dingDingUserInfos2);
  104. //获取三级部门
  105. OapiV2DepartmentListsubRequest reqDeptList3 = new OapiV2DepartmentListsubRequest() { DeptId = tempDept2.DeptId, Language = "zh_CN" };
  106. OapiV2DepartmentListsubResponse rspDeptList3 = deptListClient.Execute(reqDeptList3, access_token);
  107. if (rspDeptList3.Result != null)
  108. {
  109. foreach (var tempDept3 in rspDeptList3.Result)
  110. {
  111. //获取三级部门用户信息
  112. List<DingDingUserInfo> dingDingUserInfos3 = await GetDingDingUserInfo(divide, tempDept3.DeptId, tempDept3.ParentId, tempDept3.Name, access_token);
  113. //if (dingDingUserInfos3.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos3.ToList()));
  114. if (dingDingUserInfos3.Count > 0) ddUserInfos.AddRange(dingDingUserInfos3);
  115. //获取四级部门
  116. OapiV2DepartmentListsubRequest reqDeptList4 = new OapiV2DepartmentListsubRequest() { DeptId = tempDept3.DeptId, Language = "zh_CN" };
  117. OapiV2DepartmentListsubResponse rspDeptList4 = deptListClient.Execute(reqDeptList4, access_token);
  118. if (rspDeptList4.Result != null)
  119. {
  120. foreach (var tempDept4 in rspDeptList4.Result)
  121. {
  122. //获取四级部门用户信息
  123. List<DingDingUserInfo> dingDingUserInfos4 = await GetDingDingUserInfo(divide, tempDept4.DeptId, tempDept4.ParentId, tempDept4.Name, access_token);
  124. //if (dingDingUserInfos4.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos4.ToList()));
  125. if (dingDingUserInfos4.Count > 0) ddUserInfos.AddRange(dingDingUserInfos4);
  126. //获取五级部门
  127. OapiV2DepartmentListsubRequest reqDeptList5 = new OapiV2DepartmentListsubRequest() { DeptId = tempDept4.DeptId, Language = "zh_CN" };
  128. OapiV2DepartmentListsubResponse rspDeptList5 = deptListClient.Execute(reqDeptList5, access_token);
  129. if (rspDeptList5.Result != null)
  130. {
  131. foreach (var tempDept5 in rspDeptList5.Result)
  132. {
  133. //获取五级部门用户信息
  134. List<DingDingUserInfo> dingDingUserInfos5 = await GetDingDingUserInfo(divide, tempDept5.DeptId, tempDept5.ParentId, tempDept5.Name, access_token);
  135. //if (dingDingUserInfos5.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos5).ToList());
  136. if (dingDingUserInfos5.Count > 0) ddUserInfos.AddRange(dingDingUserInfos5);
  137. }
  138. }
  139. }
  140. }
  141. }
  142. }
  143. }
  144. }
  145. }
  146. }
  147. //保存操作记录
  148. await _azureStorage.SaveLog("tabledd-update", $"{_tmdName}【{_tmdId}】从钉钉组织结构更新至Azure Table表【DDUserInfo】中。", _dingDing, httpContext: HttpContext);
  149. var tempddUserInfos = ddUserInfos.GroupBy(c => c.RowKey).Select(c => c.First()).ToList();//去重
  150. //List<DingDingUserInfo> TempdingDingUserInfos = await _azureStorage.SaveOrUpdateAll(dingDingUserInfos); //只是保存至Table
  151. List<DingDingUserInfo> TempdingDingUserInfos = await _azureStorage.SaveOrUpdateAll(tempddUserInfos); //保存和修改至Table
  152. return Ok(new { state = 200, UserInfo = TempdingDingUserInfos });
  153. }
  154. catch (Exception ex)
  155. {
  156. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/get-dingdingusers \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  157. return BadRequest();
  158. }
  159. }
  160. /// <summary>
  161. /// 查询钉钉信息和醍摩豆信息
  162. /// </summary>
  163. /// <returns></returns>
  164. [ProducesDefaultResponseType]
  165. [HttpPost("get-ddusers")]
  166. public async Task<IActionResult> GetDingDingUsers()
  167. {
  168. try
  169. {
  170. string divide = _configuration["CustomParam:SiteScope"];
  171. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
  172. List<DingDingUserInfo> ddUserInfoList = await _azureStorage.FindListByDict<DingDingUserInfo>(dic);
  173. List<ddUserInfo> ddUserInfos = new();
  174. foreach (var item in ddUserInfoList)
  175. {
  176. ddUserInfo ddUserInfo = new ddUserInfo()
  177. {
  178. partitionKey = item.PartitionKey,
  179. rowKey = item.RowKey,
  180. unionId = item.unionId,
  181. name = item.name,
  182. title = item.title,
  183. mobile = item.mobile,
  184. jobNumber = item.jobNumber,
  185. pid = item.pid,
  186. deptId = item.deptId,
  187. deptName = item.deptName,
  188. depts = item.depts,
  189. avatar = item.avatar,
  190. isAdmin = item.isAdmin,
  191. tmdId = item.tmdId,
  192. tmdName = item.tmdName,
  193. tmdMobile = item.tmdMobile,
  194. mail = item.mail,
  195. picture = item.picture,
  196. roles = item.roles,
  197. permissions = item.permissions,
  198. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  199. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  200. };
  201. ddUserInfos.Add(ddUserInfo);
  202. }
  203. return Ok(new { state = 200, ddUserInfos = ddUserInfos });
  204. }
  205. catch (Exception ex)
  206. {
  207. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/get-ddusers \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  208. return BadRequest();
  209. }
  210. }
  211. /// <summary>
  212. /// 查询钉钉待入职人员的ID添加至Table数据表中
  213. /// </summary>
  214. /// <returns></returns>
  215. [ProducesDefaultResponseType]
  216. [AuthToken(Roles = "assist")]
  217. [HttpPost("set-ddinductionuser")]
  218. public async Task<IActionResult> SetDingDingInductionUser(JsonElement jsonElement)
  219. {
  220. try
  221. {
  222. string appKey = _configuration["DingDingAuth:appKey"];
  223. string appSecret = _configuration["DingDingAuth:appSecret"];
  224. string divide = _configuration["CustomParam:SiteScope"];
  225. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  226. //获取access_token
  227. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  228. OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  229. request.SetHttpMethod("Get");
  230. OapiGettokenResponse response = client.Execute(request);
  231. if (response.IsError)
  232. {
  233. return BadRequest();
  234. }
  235. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  236. string access_token = response.AccessToken;
  237. IDingTalkClient InductionClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querypreentry");
  238. OapiSmartworkHrmEmployeeQuerypreentryRequest reqInduction = new OapiSmartworkHrmEmployeeQuerypreentryRequest() { Offset = 0L, Size = 50 };
  239. reqInduction.SetHttpMethod("GET");
  240. OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
  241. if (rspInduction.Result.DataList != null)
  242. {
  243. List<DingDingUserInfo> ddUserInfos = new List<DingDingUserInfo>();
  244. foreach (var itemId in rspInduction.Result.DataList)
  245. {
  246. DingDingUserInfo ddUserInfo = new DingDingUserInfo();
  247. ddUserInfo.PartitionKey = divide;
  248. ddUserInfo.RowKey = itemId;
  249. ddUserInfos.Add(ddUserInfo);
  250. }
  251. List<DingDingUserInfo> tempddUserInfos = await _azureStorage.SaveAll(ddUserInfos);
  252. //保存操作记录
  253. await _azureStorage.SaveLog("tabledd-add", $"{_tmdName}【{_tmdId}】添加待入职员工至table数据表中", _dingDing, httpContext: HttpContext);
  254. if (ddUserInfos.Count == tempddUserInfos.Count)
  255. {
  256. return Ok(new { state = 200, UserInfo = tempddUserInfos });
  257. }
  258. else
  259. {
  260. var diffArr = tempddUserInfos.Where(c => !ddUserInfos.Contains(c)).ToList();
  261. return Ok(new { state = 201, notUserInfo = diffArr });
  262. }
  263. }
  264. else
  265. {
  266. return Ok(new { state = 400, rspInduction.SubErrCode, rspInduction.SubErrMsg });
  267. }
  268. }
  269. catch (Exception ex)
  270. {
  271. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-ddinductionuser \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  272. return BadRequest();
  273. }
  274. }
  275. /// <summary>
  276. /// 获取钉钉离职人员ID并删除Table表中的数据
  277. /// </summary>
  278. /// <returns></returns>
  279. [ProducesDefaultResponseType]
  280. [AuthToken(Roles = "assist")]
  281. [HttpPost("del-ddquituser")]
  282. public async Task<IActionResult> DeleteDDQuitUser(JsonElement jsonElement)
  283. {
  284. try
  285. {
  286. string appKey = _configuration["DingDingAuth:appKey"];
  287. string appSecret = _configuration["DingDingAuth:appSecret"];
  288. string divide = _configuration["CustomParam:SiteScope"];
  289. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  290. //获取access_token
  291. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  292. OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  293. request.SetHttpMethod("Get");
  294. OapiGettokenResponse response = client.Execute(request);
  295. if (response.IsError)
  296. {
  297. return BadRequest();
  298. }
  299. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  300. string access_token = response.AccessToken;
  301. IDingTalkClient quitStaffClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
  302. OapiSmartworkHrmEmployeeQuerydimissionRequest reqDimission = new OapiSmartworkHrmEmployeeQuerydimissionRequest() { Offset = 0L, Size = 50L };
  303. OapiSmartworkHrmEmployeeQuerydimissionResponse rspDimission = quitStaffClient.Execute(reqDimission, access_token);
  304. if (rspDimission.Result != null)
  305. {
  306. List<DingDingUserInfo> ddUserInfos = new List<DingDingUserInfo>();
  307. foreach (var itemId in rspDimission.Result.DataList)
  308. {
  309. await _azureStorage.DeleteSingle<DingDingUserInfo>(divide, $"{itemId}");
  310. }
  311. //保存操作记录
  312. await _azureStorage.SaveLog("tabledd-del", $"{_tmdName}【{_tmdId}】从table数据表中删除离职员工", _dingDing, httpContext: HttpContext);
  313. return Ok(new { state = 200 });
  314. }
  315. else
  316. {
  317. return Ok(new { state = rspDimission.SubErrCode });
  318. }
  319. }
  320. catch (Exception ex)
  321. {
  322. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/del-ddquituser \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  323. return BadRequest();
  324. }
  325. }
  326. /// <summary>
  327. /// 更新钉钉和醍摩豆的BI权限
  328. /// </summary>
  329. /// <param name="jsonElement"></param>
  330. /// <returns></returns>
  331. [ProducesDefaultResponseType]
  332. [AuthToken(Roles = "assist")]
  333. [HttpPost("set-permissions")]
  334. public async Task<IActionResult> SetPermissions(JsonElement jsonElement)
  335. {
  336. try
  337. {
  338. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  339. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  340. if (!jsonElement.TryGetProperty("permissions", out JsonElement _permissions)) return BadRequest();
  341. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  342. StringBuilder stringBuilder = new StringBuilder($"{_tmdName}【{_tmdId}】醍摩豆账号");
  343. List<DingDingUserInfo> ddUserInfo = new List<DingDingUserInfo>();
  344. var tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
  345. List<string> listper = _permissions.ToObject<List<string>>();
  346. List<string> roles = new();//角色列表
  347. List<string> permissions = new List<string>();//权限列表
  348. foreach (var item in tempUser)
  349. {
  350. stringBuilder.Append($"操作醍摩豆账户{item.tmdName}【{item.tmdId}】修改权限:{string.Join("|", listper.ToArray())}");
  351. if (string.IsNullOrEmpty($"{item.roles}"))
  352. {
  353. item.roles = "assist";
  354. }
  355. string tempPermissions = "";
  356. foreach (var itemPer in listper)
  357. {
  358. tempPermissions += !string.IsNullOrEmpty($"{tempPermissions}") ? $",{itemPer}" : $"{itemPer}";
  359. }
  360. item.permissions = tempPermissions;
  361. ddUserInfo.Add(item);
  362. roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  363. permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
  364. }
  365. ddUserInfo = await _azureStorage.UpdateAll<DingDingUserInfo>(ddUserInfo);
  366. //保存操作记录
  367. await _azureStorage.SaveLog("tabledd-update", stringBuilder?.ToString(), _dingDing, httpContext: HttpContext);
  368. return Ok(new { state = 200, ddUserInfo, roles, permissions });
  369. }
  370. catch (Exception ex)
  371. {
  372. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-permissions \n {ex.Message}{ex.StackTrace} ", GroupNames.成都开发測試群組);
  373. return BadRequest();
  374. }
  375. }
  376. /// <summary>
  377. /// 依据部门ID获取部门列表
  378. /// </summary>
  379. /// <param name="jsonElement"></param>
  380. /// <returns></returns>
  381. [ProducesDefaultResponseType]
  382. [HttpPost("get-dddeptiduser")]
  383. public async Task<IActionResult> GetDDDeptIdUser(JsonElement jsonElement)
  384. {
  385. try
  386. {
  387. if (!jsonElement.TryGetProperty("deptId", out JsonElement deptId)) return BadRequest();
  388. string divide = _configuration["CustomParam:SiteScope"];
  389. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
  390. List<DingDingUserInfo> tempUserInfos = await _azureStorage.FindListByDict<DingDingUserInfo>(dic);
  391. List<DingDingUserInfo> userInfo = new();
  392. tempUserInfos.ForEach(x => {
  393. if (x.depts.Contains($"{deptId}"))
  394. {
  395. userInfo.Add(x);
  396. }
  397. if (x.pid.Equals(long.Parse($"{deptId}")))
  398. {
  399. userInfo.Add(x);
  400. }
  401. });
  402. //userInfo.Distinct().ToList(); //Equals实现去重
  403. userInfo.Where((x, i) => userInfo.FindIndex(z => z.RowKey.Equals(x.RowKey)) == i);//Lambda表达式去重
  404. //userInfo.GroupBy(p => p).Select(p => p.Key).ToList();//去重复
  405. //List<DingDingUserInfo> ddUserInfo = new();
  406. //List<DingDingUserInfo> tempUser = new();
  407. //tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "deptId", $"{deptId}" } });
  408. //if (tempUser.Count == 0)
  409. //{
  410. // tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{deptId}" } });
  411. //}
  412. //foreach (var itemUser in tempUser)
  413. //{
  414. // var tempUser1 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{deptId}" } });
  415. // foreach (var itemUser1 in tempUser1)
  416. // {
  417. // if (!long.Parse($"{deptId}").Equals(itemUser1.pid))
  418. // {
  419. // var tempUser2 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{itemUser1.pid}" } });
  420. // foreach (var itemUser2 in tempUser2)
  421. // {
  422. // if (!itemUser1.pid.Equals(itemUser2.pid))
  423. // {
  424. // var tempUser3 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{itemUser2.pid}" } });
  425. // foreach (var itemUser3 in tempUser3)
  426. // {
  427. // if (!itemUser2.pid.Equals(itemUser3.pid))
  428. // {
  429. // var tempUser4 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{itemUser3.pid}" } });
  430. // foreach (var itemUser4 in tempUser4)
  431. // {
  432. // if (!itemUser3.pid.Equals(itemUser4.pid)) { }
  433. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser4.RowKey)) == null)
  434. // {
  435. // ddUserInfo.Add(itemUser4);
  436. // }
  437. // }
  438. // }
  439. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser3.RowKey)) == null)
  440. // {
  441. // ddUserInfo.Add(itemUser3);
  442. // }
  443. // }
  444. // }
  445. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser2.RowKey)) == null)
  446. // {
  447. // ddUserInfo.Add(itemUser2);
  448. // }
  449. // }
  450. // }
  451. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser1.RowKey)) == null)
  452. // {
  453. // ddUserInfo.Add(itemUser1);
  454. // }
  455. // }
  456. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser.RowKey)) == null)
  457. // {
  458. // ddUserInfo.Add(itemUser);
  459. // }
  460. //}
  461. List<ddUserInfo> ddUserInfos = new();
  462. foreach (var item in userInfo)
  463. {
  464. ddUserInfo tempUserInfo = new ddUserInfo()
  465. {
  466. partitionKey = item.PartitionKey,
  467. rowKey = item.RowKey,
  468. unionId = item.unionId,
  469. name = item.name,
  470. title = item.title,
  471. mobile = item.mobile,
  472. jobNumber = item.jobNumber,
  473. pid = item.pid,
  474. deptId = item.deptId,
  475. deptName = item.deptName,
  476. depts = item.depts,
  477. avatar = item.avatar,
  478. isAdmin = item.isAdmin,
  479. tmdId = item.tmdId,
  480. tmdName = item.tmdName,
  481. tmdMobile = item.tmdMobile,
  482. mail = item.mail,
  483. picture = item.picture,
  484. roles = item.roles,
  485. permissions = item.permissions,
  486. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  487. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  488. };
  489. ddUserInfos.Add(tempUserInfo);
  490. }
  491. return Ok(new { state = 200, ddUserInfos });
  492. }
  493. catch (Exception ex)
  494. {
  495. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/get-dddeptiduser \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  496. return BadRequest();
  497. }
  498. }
  499. /// <summary>
  500. /// 后端钉钉账户和醍摩豆账户进行绑定
  501. /// </summary>
  502. /// <param name="jsonElement"></param>
  503. /// <returns></returns>
  504. [ProducesDefaultResponseType]
  505. [AuthToken(Roles = "assist")]
  506. [HttpPost("set-backenbind")]
  507. public async Task<IActionResult> SetBackenBind(JsonElement jsonElement)
  508. {
  509. try
  510. {
  511. if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
  512. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  513. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  514. List<DingDingUserInfo> tempddUsers = null;
  515. List<DingDingUserInfo> ddUsers = new List<DingDingUserInfo>();
  516. StringBuilder tableSql = new StringBuilder();
  517. if (!string.IsNullOrEmpty($"{rowKey}"))
  518. tableSql.Append($"RowKey {QueryComparisons.Equal} '{rowKey}'");
  519. string tmdId = null;
  520. string tmdName = null;
  521. string tmdMobile = null;
  522. string mail = null;
  523. string picture = null;
  524. HttpClient httpClient = _http.CreateClient();
  525. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  526. List<string> mobiles = new List<string>() { $"{mobile}" };
  527. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
  528. if (responseMessage.StatusCode == HttpStatusCode.OK)
  529. {
  530. string temp = responseMessage.Content.ReadAsStringAsync().Result;
  531. List<JsonElement> json_id = temp.ToObject<List<JsonElement>>();
  532. if (json_id.Count > 0)
  533. {
  534. foreach (var item in json_id)
  535. {
  536. tmdId = item.GetProperty("id").ToString();
  537. tmdName = item.GetProperty("name").ToString();
  538. tmdMobile = item.GetProperty("mobile").ToString();
  539. mail = item.GetProperty("mail").ToString();
  540. picture = item.GetProperty("picture").ToString();
  541. }
  542. }
  543. else return Ok(new { state = 1, message = "该手机号未找到醍摩豆账户" });
  544. }
  545. tempddUsers = await _azureStorage.QueryWhereString<DingDingUserInfo>(tableSql.ToString());
  546. if (tempddUsers.Count > 0)
  547. {
  548. foreach (var item in tempddUsers)
  549. {
  550. if (item.RowKey.Equals($"{rowKey}"))
  551. {
  552. item.tmdId = tmdId;
  553. item.tmdName = tmdName;
  554. item.tmdMobile = tmdMobile;
  555. item.mail = mail;
  556. item.picture = picture;
  557. ddUsers.Add(item);
  558. }
  559. }
  560. }
  561. else return Ok(new { state = 2, message = "钉钉ID错误请检查钉钉ID" });
  562. if (ddUsers.Count > 0) ddUsers = await _azureStorage.SaveOrUpdateAll(ddUsers);
  563. //保存操作记录
  564. await _azureStorage.SaveLog("tabledd-update", $"{_tmdName}【{_tmdId}】操作:绑定钉钉账户[{rowKey}]和醍摩豆账户[{tmdId}]", _dingDing, httpContext: HttpContext);
  565. return Ok(new { state = 200, ddUsers });
  566. }
  567. catch (Exception ex)
  568. {
  569. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backenbind \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  570. return BadRequest();
  571. }
  572. }
  573. /// <summary>
  574. /// 设置系统管理员
  575. /// </summary>
  576. /// <param name="jsonElement"></param>
  577. /// <returns></returns>
  578. [ProducesDefaultResponseType]
  579. [AuthToken(Roles = "admin")]
  580. [HttpPost("set-backend")]
  581. public async Task<IActionResult> SetBackendAdmin(JsonElement jsonElement)
  582. {
  583. try
  584. {
  585. if (!jsonElement.TryGetProperty("columnKey", out JsonElement partitionKey)) return BadRequest();
  586. if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
  587. if (!jsonElement.TryGetProperty("isAdmin", out JsonElement isAdmin)) return BadRequest();
  588. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  589. var tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{rowKey}" } });
  590. List<ddUserInfo> ddUserInfos = new();
  591. List<string> roles = new();//角色列表
  592. List<string> permissions = new List<string>();//权限列表
  593. StringBuilder msg = new StringBuilder($"{_tmdName}【{_tmdId}】");
  594. if (bool.Parse($"{isAdmin}") == true)
  595. {
  596. foreach (var user in tempUser)
  597. {
  598. if (string.IsNullOrEmpty(user.roles))
  599. {
  600. user.roles = "admin,assist";
  601. }
  602. List<string> tempRoles = new List<string>(user.roles.Split(","));
  603. if (!tempRoles.Contains("admin"))
  604. {
  605. tempRoles.Add("admin");
  606. }
  607. user.roles = string.Join(",", tempRoles);
  608. DingDingUserInfo respUser = await _azureStorage.SaveOrUpdate<DingDingUserInfo>(user);
  609. if (respUser != null)
  610. {
  611. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  612. }
  613. }
  614. }
  615. else
  616. {
  617. foreach (var user in tempUser)
  618. {
  619. List<string> tempRoles = new List<string>(user.roles.Split(","));
  620. if (tempRoles.Contains("admin"))
  621. {
  622. tempRoles.Remove("admin");
  623. }
  624. user.roles = string.Join(",", tempRoles);
  625. DingDingUserInfo respUser = await _azureStorage.SaveOrUpdate<DingDingUserInfo>(user);
  626. if (respUser != null)
  627. {
  628. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  629. msg.Append($"取消{respUser.name}【{respUser.RowKey}】账号的BI管理员");
  630. }
  631. }
  632. }
  633. //保存操作记录
  634. await _azureStorage.SaveLog("tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
  635. return Ok(new { state = 200, roles });
  636. }
  637. catch (Exception ex)
  638. {
  639. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backend \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  640. return BadRequest();
  641. }
  642. }
  643. /// <summary>
  644. /// 获取钉钉用户信息
  645. /// 并查询本地Table数据表中是否存在
  646. /// </summary>
  647. /// <param name="deptId"></param>
  648. /// <param name="parentId"></param>
  649. /// <param name="name"></param>
  650. /// <param name="access_token"></param>
  651. /// <returns></returns>
  652. public async Task<List<DingDingUserInfo>> GetDingDingUserInfo(string partitionKey, long deptId, long parentId, string name, string access_token)
  653. {
  654. List<DingDingUserInfo> ddUserInfos = new List<DingDingUserInfo>();
  655. //获取部门人员信息
  656. IDingTalkClient userListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
  657. //获取部门用户
  658. OapiV2UserListRequest reqUserList = new OapiV2UserListRequest()
  659. {
  660. DeptId = deptId,
  661. Cursor = 0L,
  662. Size = 50L,
  663. OrderField = "custom",
  664. Language = "zh_CN"
  665. };
  666. reqUserList.SetHttpMethod("GET");
  667. OapiV2UserListResponse rspV2UserList = userListClient.Execute(reqUserList, access_token);
  668. if (rspV2UserList.Result.List != null)
  669. {
  670. foreach (var itemUser in rspV2UserList.Result.List)
  671. {
  672. var tempInfo = ddUserInfos.Find(x => x.RowKey.Equals(itemUser.Unionid));
  673. if (string.IsNullOrEmpty($"{tempInfo}"))
  674. {
  675. var tableUsers = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "RowKey", $"{itemUser.Userid}" }, { "unionId", $"{itemUser.Unionid}" } });
  676. if (tableUsers.Count > 0)
  677. {
  678. foreach (var tableUser in tableUsers)
  679. {
  680. DingDingUserInfo ddUserInfo = new DingDingUserInfo();
  681. ddUserInfo.PartitionKey = tableUser.PartitionKey;
  682. ddUserInfo.RowKey = itemUser.Userid;
  683. ddUserInfo.unionId = itemUser.Unionid;
  684. ddUserInfo.name = itemUser.Name;
  685. ddUserInfo.title = itemUser.Title;
  686. ddUserInfo.mobile = itemUser.Mobile;
  687. ddUserInfo.jobNumber = itemUser.JobNumber;
  688. ddUserInfo.pid = parentId;
  689. ddUserInfo.deptId = deptId;
  690. ddUserInfo.deptName = name;
  691. ddUserInfo.depts = string.Join(",", itemUser.DeptIdList.ToArray());
  692. ddUserInfo.avatar = itemUser.Avatar;
  693. ddUserInfo.isAdmin = itemUser.Admin;
  694. ddUserInfo.PartitionKey = partitionKey;
  695. ddUserInfo.tmdId = tableUser.tmdId;
  696. ddUserInfo.tmdName = tableUser.tmdName;
  697. ddUserInfo.tmdMobile = tableUser.tmdMobile;
  698. ddUserInfo.mail = tableUser.mail;
  699. ddUserInfo.picture = tableUser.picture;
  700. ddUserInfo.roles = tableUser.roles;
  701. ddUserInfo.permissions = tableUser.permissions;
  702. ddUserInfos.Add(ddUserInfo);
  703. }
  704. }
  705. else
  706. {
  707. DingDingUserInfo ddUserInfo = new DingDingUserInfo();
  708. ddUserInfo.RowKey = itemUser.Userid;
  709. ddUserInfo.unionId = itemUser.Unionid;
  710. ddUserInfo.name = itemUser.Name;
  711. ddUserInfo.title = itemUser.Title;
  712. ddUserInfo.mobile = itemUser.Mobile;
  713. ddUserInfo.jobNumber = itemUser.JobNumber;
  714. ddUserInfo.pid = parentId;
  715. ddUserInfo.deptId = deptId;
  716. ddUserInfo.deptName = name;
  717. ddUserInfo.depts = string.Join(",", itemUser.DeptIdList.ToArray());
  718. ddUserInfo.avatar = itemUser.Avatar;
  719. ddUserInfo.isAdmin = itemUser.Admin;
  720. ddUserInfo.PartitionKey = partitionKey;
  721. ddUserInfo.tmdId = "";
  722. ddUserInfo.tmdName = "";
  723. ddUserInfo.tmdMobile = "";
  724. ddUserInfo.mail = "";
  725. ddUserInfo.picture = "";
  726. ddUserInfo.roles = "assist";
  727. ddUserInfo.permissions = "abilitystandard-read,batcharea-read,batchschool-read,orgusers-read";
  728. ddUserInfos.Add(ddUserInfo);
  729. }
  730. }
  731. }
  732. }
  733. return ddUserInfos;
  734. }
  735. public record ddUserInfo
  736. {
  737. public string partitionKey { get; set; }
  738. public string rowKey { get; set; }
  739. public string unionId { get; set; }
  740. public string name { get; set; }
  741. public string title { get; set; }
  742. public string mobile { get; set; }
  743. public string jobNumber { get; set; }
  744. public long pid { get; set; }
  745. public long deptId { get; set; }
  746. public string deptName { get; set; }
  747. public string depts { get; set; }
  748. public string avatar { get; set; }
  749. public bool isAdmin { get; set; }
  750. public string tmdId { get; set; }
  751. public string tmdName { get; set; }
  752. public string tmdMobile { get; set; }
  753. public string mail { get; set; }
  754. public string picture { get; set; }
  755. public string roles { get; set; }
  756. public string permissions { get; set; }
  757. public List<string> handleRoles { get; set; }
  758. public List<string> handlePermissions { get; set; }
  759. }
  760. }
  761. }