TableDingDingInfoController.cs 46 KB

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