TableDingDingInfoController.cs 58 KB

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