TableDingDingInfoController.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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. joinTime = item.joinTime,
  227. permissions = item.permissions,
  228. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  229. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  230. };
  231. if (!string.IsNullOrEmpty(item.schoolIds))
  232. {
  233. List<string> tempSchoolIds = new(item.schoolIds.Split("|"));
  234. ddUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  235. }
  236. ddUserInfos.Add(ddUserInfo);
  237. }
  238. }
  239. break;
  240. default:
  241. foreach (var item in ddUserInfoList)
  242. {
  243. DDUserInfo ddUserInfo = new()
  244. {
  245. partitionKey = item.PartitionKey,
  246. rowKey = item.RowKey,
  247. userId = item.userId,
  248. unionId = item.unionId,
  249. name = item.name,
  250. title = item.title,
  251. stateCode = item.stateCode,
  252. mobile = item.mobile,
  253. jobNumber = item.jobNumber,
  254. pid = item.pid,
  255. deptId = item.deptId,
  256. deptName = item.deptName,
  257. depts = item.depts,
  258. avatar = item.avatar,
  259. isAdmin = item.isAdmin,
  260. tmdId = item.tmdId,
  261. tmdName = item.tmdName,
  262. tmdMobile = item.tmdMobile,
  263. mail = item.mail,
  264. picture = item.picture,
  265. roles = item.roles,
  266. joinTime = item.joinTime,
  267. permissions = item.permissions,
  268. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  269. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  270. };
  271. if (!string.IsNullOrEmpty(item.schoolIds))
  272. {
  273. List<string> tempSchoolIds = new(item.schoolIds.Split("|"));
  274. ddUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  275. }
  276. ddUserInfos.Add(ddUserInfo);
  277. }
  278. break;
  279. }
  280. return Ok(new { state = 200, ddUserInfos = ddUserInfos });
  281. }
  282. catch (Exception ex)
  283. {
  284. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/get-ddusers \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  285. return BadRequest();
  286. }
  287. }
  288. /// <summary>
  289. /// 查询钉钉待入职人员的ID添加至Table数据表中
  290. /// </summary>
  291. /// <returns></returns>
  292. [ProducesDefaultResponseType]
  293. [AuthToken(Roles = "assist")]
  294. [HttpPost("set-ddinductionuser")]
  295. public async Task<IActionResult> SetDingDingInductionUser(JsonElement jsonElement)
  296. {
  297. try
  298. {
  299. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  300. string appKey = _configuration["DingDingAuth:appKey"];
  301. string appSecret = _configuration["DingDingAuth:appSecret"];
  302. //string divide = _configuration["CustomParam:SiteScope"];
  303. string divide = _option.Location;
  304. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  305. //获取access_token
  306. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  307. OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  308. request.SetHttpMethod("Get");
  309. OapiGettokenResponse response = client.Execute(request);
  310. if (response.IsError)
  311. {
  312. return BadRequest();
  313. }
  314. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  315. string access_token = response.AccessToken;
  316. IDingTalkClient InductionClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querypreentry");
  317. OapiSmartworkHrmEmployeeQuerypreentryRequest reqInduction = new OapiSmartworkHrmEmployeeQuerypreentryRequest() { Offset = 0L, Size = 50 };
  318. reqInduction.SetHttpMethod("GET");
  319. OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
  320. if (rspInduction.Result.DataList != null)
  321. {
  322. List<DingDingUserInfo> ddUserInfos = new List<DingDingUserInfo>();
  323. foreach (var itemId in rspInduction.Result.DataList)
  324. {
  325. DingDingUserInfo ddUserInfo = new DingDingUserInfo();
  326. ddUserInfo.PartitionKey = divide;
  327. ddUserInfo.RowKey = itemId;
  328. ddUserInfos.Add(ddUserInfo);
  329. }
  330. List<DingDingUserInfo> tempddUserInfos = await table.SaveAll(ddUserInfos);
  331. //保存操作记录
  332. await _azureStorage.SaveBILog("tabledd-add", $"{_tmdName}【{_tmdId}】添加待入职员工至table数据表中", _dingDing, httpContext: HttpContext);
  333. if (ddUserInfos.Count == tempddUserInfos.Count)
  334. {
  335. return Ok(new { state = 200, UserInfo = tempddUserInfos });
  336. }
  337. else
  338. {
  339. var diffArr = tempddUserInfos.Where(c => !ddUserInfos.Contains(c)).ToList();
  340. return Ok(new { state = 201, notUserInfo = diffArr });
  341. }
  342. }
  343. else
  344. {
  345. return Ok(new { state = 400, rspInduction.SubErrCode, rspInduction.SubErrMsg });
  346. }
  347. }
  348. catch (Exception ex)
  349. {
  350. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-ddinductionuser \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  351. return BadRequest();
  352. }
  353. }
  354. /// <summary>
  355. /// 获取钉钉离职人员ID并删除Table表中的数据
  356. /// </summary>
  357. /// <returns></returns>
  358. [ProducesDefaultResponseType]
  359. [AuthToken(Roles = "assist")]
  360. [HttpPost("del-ddquituser")]
  361. public async Task<IActionResult> DeleteDDQuitUser(JsonElement jsonElement)
  362. {
  363. try
  364. {
  365. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  366. string appKey = _configuration["DingDingAuth:appKey"];
  367. string appSecret = _configuration["DingDingAuth:appSecret"];
  368. //string divide = _configuration["CustomParam:SiteScope"];
  369. string divide = _option.Location;
  370. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  371. //获取access_token
  372. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  373. OapiGettokenRequest request = new() { Appkey = appKey, Appsecret = appSecret };
  374. request.SetHttpMethod("Get");
  375. OapiGettokenResponse response = client.Execute(request);
  376. if (response.IsError)
  377. {
  378. return BadRequest();
  379. }
  380. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  381. string access_token = response.AccessToken;
  382. IDingTalkClient quitStaffClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
  383. OapiSmartworkHrmEmployeeQuerydimissionRequest reqDimission = new OapiSmartworkHrmEmployeeQuerydimissionRequest() { Offset = 0L, Size = 50L };
  384. OapiSmartworkHrmEmployeeQuerydimissionResponse rspDimission = quitStaffClient.Execute(reqDimission, access_token);
  385. if (rspDimission.Result != null)
  386. {
  387. List<DingDingUserInfo> ddUserInfos = new();
  388. foreach (var itemId in rspDimission.Result.DataList)
  389. {
  390. await table.DeleteSingle<DingDingUserInfo>(divide, $"{itemId}");
  391. }
  392. //保存操作记录
  393. await _azureStorage.SaveBILog("tabledd-del", $"{_tmdName}【{_tmdId}】从table数据表中删除离职员工", _dingDing, httpContext: HttpContext);
  394. return Ok(new { state = 200 });
  395. }
  396. else
  397. {
  398. return Ok(new { state = rspDimission.SubErrCode });
  399. }
  400. }
  401. catch (Exception ex)
  402. {
  403. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/del-ddquituser \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  404. return BadRequest();
  405. }
  406. }
  407. /// <summary>
  408. /// 更新钉钉和醍摩豆的BI权限
  409. /// </summary>
  410. /// <param name="jsonElement"></param>
  411. /// <returns></returns>
  412. [ProducesDefaultResponseType]
  413. [AuthToken(Roles = "admin")]
  414. [HttpPost("set-rolesper")]
  415. public async Task<IActionResult> SetPermissions(JsonElement jsonElement)
  416. {
  417. try
  418. {
  419. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  420. jsonElement.TryGetProperty("userId", out JsonElement userId);
  421. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  422. if (!jsonElement.TryGetProperty("permissions", out JsonElement _permissions)) return BadRequest();
  423. if (!jsonElement.TryGetProperty("roles", out JsonElement _roles)) return BadRequest();
  424. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  425. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  426. List<DingDingUserInfo> ddUserInfo = new();
  427. List<string> listper = _permissions.ToObject<List<string>>();
  428. List<string> listroles = _roles.ToObject<List<string>>();
  429. List<string> roles = new();//角色列表
  430. List<string> permissions = new();//权限列表
  431. StringBuilder stringBuilder = new($"{_tmdName}【{_tmdId}】醍摩豆账号");
  432. Dictionary<string, object> dic = new() { { "PartitionKey", $"{partitionKey}" } };
  433. if (!string.IsNullOrEmpty($"{userId}"))
  434. {
  435. dic.Add("userId", $"{userId}");
  436. }
  437. if (!string.IsNullOrEmpty($"{tmdId}"))
  438. {
  439. dic.Add("tmdId", $"{tmdId}");
  440. }
  441. if (string.IsNullOrEmpty($"{userId}") && string.IsNullOrEmpty($"{tmdId}"))
  442. {
  443. return BadRequest();
  444. }
  445. var tempUser = await table.FindListByDict<DingDingUserInfo>(dic);
  446. foreach (var item in tempUser)
  447. {
  448. stringBuilder.Append($"操作醍摩豆账户{item.tmdName}【{item.tmdId}】修改权限:{string.Join("|", listper.ToArray())}");
  449. item.roles = listroles.Count > 0 ? string.Join(",", listroles) : "assist";
  450. item.permissions = string.Join(",", listper);
  451. ddUserInfo.Add(item);
  452. roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  453. permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
  454. }
  455. ddUserInfo = await table.UpdateAll<DingDingUserInfo>(ddUserInfo);
  456. //保存操作记录
  457. await _azureStorage.SaveBILog("tabledd-update", stringBuilder?.ToString(), _dingDing, httpContext: HttpContext);
  458. return Ok(new { state = 200, ddUserInfo, roles, permissions });
  459. }
  460. catch (Exception ex)
  461. {
  462. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-permissions \n {ex.Message}{ex.StackTrace} ", GroupNames.成都开发測試群組);
  463. return BadRequest();
  464. }
  465. }
  466. /// <summary>
  467. /// 依据部门ID获取部门列表
  468. /// </summary>
  469. /// <param name="jsonElement"></param>
  470. /// <returns></returns>
  471. [ProducesDefaultResponseType]
  472. [HttpPost("get-dddeptiduser")]
  473. public async Task<IActionResult> GetDDDeptIdUser(JsonElement jsonElement)
  474. {
  475. try
  476. {
  477. var cosmosCliet = _azureCosmos.GetCosmosClient();
  478. if (!jsonElement.TryGetProperty("deptId", out JsonElement deptId)) return BadRequest();
  479. //string divide = _configuration["CustomParam:SiteScope"];
  480. string divide = _option.Location;
  481. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
  482. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  483. List<DingDingUserInfo> tempUserInfos = await table.FindListByDict<DingDingUserInfo>(dic);
  484. List<DingDingUserInfo> userInfo = new();
  485. tempUserInfos.ForEach(x => {
  486. if (x.depts.Contains($"{deptId}"))
  487. {
  488. userInfo.Add(x);
  489. }
  490. if (x.pid.Equals(long.Parse($"{deptId}")))
  491. {
  492. userInfo.Add(x);
  493. }
  494. });
  495. //userInfo.Distinct().ToList(); //Equals实现去重
  496. userInfo.Where((x, i) => userInfo.FindIndex(z => z.RowKey.Equals(x.RowKey)) == i);//Lambda表达式去重
  497. //userInfo.GroupBy(p => p).Select(p => p.Key).ToList();//去重复
  498. //List<DingDingUserInfo> ddUserInfo = new();
  499. //List<DingDingUserInfo> tempUser = new();
  500. //tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "deptId", $"{deptId}" } });
  501. //if (tempUser.Count == 0)
  502. //{
  503. // tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{deptId}" } });
  504. //}
  505. //foreach (var itemUser in tempUser)
  506. //{
  507. // var tempUser1 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{deptId}" } });
  508. // foreach (var itemUser1 in tempUser1)
  509. // {
  510. // if (!long.Parse($"{deptId}").Equals(itemUser1.pid))
  511. // {
  512. // var tempUser2 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{itemUser1.pid}" } });
  513. // foreach (var itemUser2 in tempUser2)
  514. // {
  515. // if (!itemUser1.pid.Equals(itemUser2.pid))
  516. // {
  517. // var tempUser3 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{itemUser2.pid}" } });
  518. // foreach (var itemUser3 in tempUser3)
  519. // {
  520. // if (!itemUser2.pid.Equals(itemUser3.pid))
  521. // {
  522. // var tempUser4 = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "pid", $"{itemUser3.pid}" } });
  523. // foreach (var itemUser4 in tempUser4)
  524. // {
  525. // if (!itemUser3.pid.Equals(itemUser4.pid)) { }
  526. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser4.RowKey)) == null)
  527. // {
  528. // ddUserInfo.Add(itemUser4);
  529. // }
  530. // }
  531. // }
  532. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser3.RowKey)) == null)
  533. // {
  534. // ddUserInfo.Add(itemUser3);
  535. // }
  536. // }
  537. // }
  538. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser2.RowKey)) == null)
  539. // {
  540. // ddUserInfo.Add(itemUser2);
  541. // }
  542. // }
  543. // }
  544. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser1.RowKey)) == null)
  545. // {
  546. // ddUserInfo.Add(itemUser1);
  547. // }
  548. // }
  549. // if (ddUserInfo.Find(x => x.RowKey.Equals(itemUser.RowKey)) == null)
  550. // {
  551. // ddUserInfo.Add(itemUser);
  552. // }
  553. //}
  554. List<DDUserInfo> ddUserInfos = new();
  555. foreach (var item in userInfo)
  556. {
  557. DDUserInfo tempUserInfo = new DDUserInfo()
  558. {
  559. partitionKey = item.PartitionKey,
  560. rowKey = item.RowKey,
  561. userId = item.userId,
  562. unionId = item.unionId,
  563. name = item.name,
  564. title = item.title,
  565. stateCode = item.stateCode,
  566. mobile = item.mobile,
  567. jobNumber = item.jobNumber,
  568. pid = item.pid,
  569. deptId = item.deptId,
  570. deptName = item.deptName,
  571. depts = item.depts,
  572. avatar = item.avatar,
  573. isAdmin = item.isAdmin,
  574. tmdId = item.tmdId,
  575. tmdName = item.tmdName,
  576. tmdMobile = item.tmdMobile,
  577. mail = item.mail,
  578. picture = item.picture,
  579. roles = item.roles,
  580. joinTime = item.joinTime,
  581. permissions = item.permissions,
  582. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  583. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  584. };
  585. if (!string.IsNullOrEmpty(item.schoolIds))
  586. {
  587. List<string> tempSchoolIds = new List<string>(item.schoolIds.Split("|"));
  588. tempUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  589. }
  590. ddUserInfos.Add(tempUserInfo);
  591. }
  592. return Ok(new { state = 200, ddUserInfos });
  593. }
  594. catch (Exception ex)
  595. {
  596. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/get-dddeptiduser \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  597. return BadRequest();
  598. }
  599. }
  600. /// <summary>
  601. /// 后端钉钉账户和醍摩豆账户进行绑定
  602. /// </summary>
  603. /// <param name="jsonElement"></param>
  604. /// <returns></returns>
  605. [ProducesDefaultResponseType]
  606. [AuthToken(Roles = "assist")]
  607. [HttpPost("set-backenbind")]
  608. public async Task<IActionResult> SetBackenBind(JsonElement jsonElement)
  609. {
  610. try
  611. {
  612. if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
  613. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  614. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  615. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  616. List<DingDingUserInfo> tempddUsers = null;
  617. List<DingDingUserInfo> ddUsers = new();
  618. StringBuilder tableSql = new();
  619. if (!string.IsNullOrEmpty($"{rowKey}"))
  620. tableSql.Append($"RowKey {QueryComparisons.Equal} '{rowKey}'");
  621. string tmdId = null;
  622. string tmdName = null;
  623. string tmdMobile = null;
  624. string mail = null;
  625. string picture = null;
  626. HttpClient httpClient = _http.CreateClient();
  627. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  628. List<string> mobiles = new List<string>() { $"{mobile}" };
  629. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
  630. if (responseMessage.StatusCode == HttpStatusCode.OK)
  631. {
  632. string temp = responseMessage.Content.ReadAsStringAsync().Result;
  633. List<JsonElement> json_id = temp.ToObject<List<JsonElement>>();
  634. if (json_id.Count > 0)
  635. {
  636. foreach (var item in json_id)
  637. {
  638. tmdId = item.GetProperty("id").ToString();
  639. tmdName = item.GetProperty("name").ToString();
  640. tmdMobile = item.GetProperty("mobile").ToString();
  641. mail = item.GetProperty("mail").ToString();
  642. picture = item.GetProperty("picture").ToString();
  643. }
  644. }
  645. else return Ok(new { state = 1, message = "该手机号未找到醍摩豆账户" });
  646. }
  647. tempddUsers = await table.QueryWhereString<DingDingUserInfo>(tableSql.ToString());
  648. if (tempddUsers.Count > 0)
  649. {
  650. foreach (var item in tempddUsers)
  651. {
  652. if (item.RowKey.Equals($"{rowKey}"))
  653. {
  654. item.tmdId = tmdId;
  655. item.tmdName = tmdName;
  656. item.tmdMobile = tmdMobile;
  657. item.mail = mail;
  658. item.picture = picture;
  659. ddUsers.Add(item);
  660. }
  661. }
  662. }
  663. else return Ok(new { state = 2, message = "钉钉ID错误请检查钉钉ID" });
  664. if (ddUsers.Count > 0) ddUsers = await table.SaveOrUpdateAll(ddUsers);
  665. //保存操作记录
  666. await _azureStorage.SaveBILog("tabledd-update", $"{_tmdName}【{_tmdId}】操作:绑定钉钉账户[{rowKey}]和醍摩豆账户[{tmdId}]", _dingDing, httpContext: HttpContext);
  667. return Ok(new { state = 200, ddUsers });
  668. }
  669. catch (Exception ex)
  670. {
  671. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backenbind \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  672. return BadRequest();
  673. }
  674. }
  675. /// <summary>
  676. /// 设置系统管理员
  677. /// </summary>
  678. /// <param name="jsonElement"></param>
  679. /// <returns></returns>
  680. [ProducesDefaultResponseType]
  681. [AuthToken(Roles = "admin")]
  682. [HttpPost("set-backend")]
  683. public async Task<IActionResult> SetBackendAdmin(JsonElement jsonElement)
  684. {
  685. try
  686. {
  687. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  688. if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
  689. if (!jsonElement.TryGetProperty("isAdmin", out JsonElement isAdmin)) return BadRequest();
  690. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  691. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  692. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{rowKey}" } });
  693. List<DDUserInfo> ddUserInfos = new();
  694. List<string> roles = new();//角色列表
  695. List<string> permissions = new();//权限列表
  696. StringBuilder msg = new($"{_tmdName}【{_tmdId}】");
  697. if (bool.Parse($"{isAdmin}") == true)
  698. {
  699. foreach (var user in tempUser)
  700. {
  701. if (string.IsNullOrEmpty(user.roles))
  702. {
  703. user.roles = "admin,assist";
  704. }
  705. List<string> tempRoles = new(user.roles.Split(","));
  706. if (!tempRoles.Contains("admin"))
  707. {
  708. tempRoles.Add("admin");
  709. }
  710. user.roles = string.Join(",", tempRoles);
  711. user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  712. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  713. if (respUser != null)
  714. {
  715. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  716. }
  717. msg.Append($"添加{respUser.name}【{respUser.RowKey}】账号的BI管理员");
  718. }
  719. }
  720. else
  721. {
  722. foreach (var user in tempUser)
  723. {
  724. List<string> tempRoles = new(user.roles.Split(","));
  725. if (tempRoles.Contains("admin"))
  726. {
  727. tempRoles.Remove("admin");
  728. }
  729. user.roles = string.Join(",", tempRoles);
  730. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  731. if (respUser != null)
  732. {
  733. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  734. msg.Append($"取消{respUser.name}【{respUser.RowKey}】账号的BI管理员");
  735. }
  736. }
  737. }
  738. //保存操作记录
  739. await _azureStorage.SaveBILog("tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
  740. return Ok(new { state = 200, roles });
  741. }
  742. catch (Exception ex)
  743. {
  744. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backend \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  745. return BadRequest();
  746. }
  747. }
  748. /// <summary>
  749. /// 通过醍摩豆账户信息 设置BI后台管理员
  750. /// </summary>
  751. /// <param name="jsonElement"></param>
  752. /// <returns></returns>
  753. [ProducesDefaultResponseType]
  754. [AuthToken(Roles = "admin")]
  755. [HttpPost("set-tmdadmin")]
  756. public async Task<IActionResult> SetTmdBackendAdmin(JsonElement jsonElement)
  757. {
  758. try
  759. {
  760. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  761. if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
  762. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  763. jsonElement.TryGetProperty("picture ", out JsonElement picture);
  764. jsonElement.TryGetProperty("mail ", out JsonElement mail);
  765. var cosmosCliet = _azureCosmos.GetCosmosClient();
  766. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  767. List<DDUserInfo> ddUserInfos = new();
  768. List<string> roles = new();//角色列表
  769. List<string> permissions = new();//权限列表
  770. StringBuilder msg = new($"{_tmdName}【{_tmdId}】");
  771. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  772. //string divide = _configuration["CustomParam:SiteScope"];
  773. string divide = _option.Location;
  774. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" }, { "mobile", $"{mobile}" } };
  775. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  776. if (ddUserInfoList.Count > 0)
  777. {
  778. foreach (var user in ddUserInfoList)
  779. {
  780. List<string> tempRoles = new(user.roles.Split(","));
  781. if (tempRoles.Count > 0)
  782. {
  783. if (!tempRoles.Contains("admin"))
  784. {
  785. tempRoles.Add("admin");
  786. }
  787. }
  788. else
  789. tempRoles.Add("admin");
  790. user.roles = string.Join(",", tempRoles);
  791. user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  792. user.tmdId = $"{tmdId}";
  793. user.tmdName = $"{tmdName}";
  794. user.tmdMobile = $"{mobile}";
  795. if (!string.IsNullOrEmpty($"{picture}"))
  796. {
  797. user.picture = $"{picture}";
  798. }
  799. if (!string.IsNullOrEmpty($"{mail}"))
  800. {
  801. user.mail = $"{mail}";
  802. }
  803. msg.Append($" 将:{tmdName}【{tmdId}】醍摩豆账号和({user.name}【{user.unionId}】) 钉钉账户绑定,并设置管理员");
  804. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  805. if (respUser != null)
  806. {
  807. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  808. }
  809. DDUserInfo dDUserInfo = new()
  810. {
  811. partitionKey = respUser.PartitionKey,
  812. rowKey = respUser.RowKey,
  813. userId = respUser.userId,
  814. unionId = respUser.unionId,
  815. name = respUser.name,
  816. title = respUser.title,
  817. stateCode = respUser.stateCode,
  818. mobile = respUser.mobile,
  819. jobNumber = respUser.jobNumber,
  820. pid = respUser.pid,
  821. deptId = respUser.deptId,
  822. deptName = respUser.deptName,
  823. depts = respUser.depts,
  824. avatar = respUser.avatar,
  825. isAdmin = respUser.isAdmin,
  826. tmdId = respUser.tmdId,
  827. tmdName = respUser.tmdName,
  828. tmdMobile = respUser.tmdMobile,
  829. mail = respUser.mail,
  830. picture = respUser.picture,
  831. roles = respUser.roles,
  832. joinTime = respUser.joinTime,
  833. permissions = respUser.permissions,
  834. handleRoles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>(),
  835. handlePermissions = !string.IsNullOrEmpty($"{respUser.permissions}") ? new List<string>(respUser.permissions.Split(",")) : new List<string>()
  836. };
  837. if (!string.IsNullOrEmpty(respUser.schoolIds))
  838. {
  839. List<string> tempSchoolIds = new List<string>(respUser.schoolIds.Split("|"));
  840. dDUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  841. }
  842. ddUserInfos.Add(dDUserInfo);
  843. }
  844. }
  845. else
  846. {
  847. DingDingUserInfo dingDingUserInfo = new()
  848. {
  849. PartitionKey = divide,
  850. RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
  851. roles = "admin",
  852. tmdId = $"{tmdId}",
  853. tmdName = $"{tmdName}",
  854. tmdMobile = $"{mobile}",
  855. };
  856. if (!string.IsNullOrEmpty($"{picture}"))
  857. {
  858. dingDingUserInfo.picture = $"{picture}";
  859. }
  860. if (!string.IsNullOrEmpty($"{mail}"))
  861. {
  862. dingDingUserInfo.mail = $"{mail}";
  863. }
  864. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(dingDingUserInfo);
  865. return Ok(new { state = 201, msg = "新生成的BIadmin", respUser });
  866. }
  867. //保存操作记录
  868. await _azureStorage.SaveBILog("tabledd-update",msg.ToString(), _dingDing, httpContext: HttpContext);
  869. return Ok(new { state = 200, ddUserInfos });
  870. }
  871. catch (Exception ex)
  872. {
  873. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-tmdadmin \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  874. return BadRequest();
  875. }
  876. }
  877. /// <summary>
  878. /// 解除钉钉和醍摩豆的绑定
  879. /// </summary>
  880. /// <param name="jsonElement"></param>
  881. /// <returns></returns>
  882. [ProducesDefaultResponseType]
  883. [HttpPost("set-unbind")]
  884. public async Task<IActionResult> SetUnbind(JsonElement jsonElement)
  885. {
  886. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  887. //string divide = _configuration["CustomParam:SiteScope"];
  888. string divide = _option.Location;
  889. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
  890. if (!string.IsNullOrEmpty($"{mobile}"))
  891. dic.Add("tmdMobile", $"{mobile}");
  892. else
  893. dic.Add("tmdMobile", "18281911681");
  894. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  895. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  896. List<DingDingUserInfo> tempDDUI = new();
  897. if (ddUserInfoList.Count > 0)
  898. {
  899. foreach (var item in ddUserInfoList)
  900. {
  901. item.tmdId = null;
  902. item.tmdName = null;
  903. item.tmdMobile = null;
  904. item.picture = null;
  905. tempDDUI.Add(item);
  906. }
  907. }
  908. else return Ok(new { state = 404, msg = "未找到手机号匹配的绑定号码!,请检查手机号" });
  909. var userInfos = await table.SaveOrUpdateAll(tempDDUI); //保存和修改至Table
  910. return Ok(new { state = 200, userInfos });
  911. }
  912. /// <summary>
  913. /// 获取钉钉用户信息
  914. /// 并查询本地Table数据表中是否存在
  915. /// </summary>
  916. /// <param name="deptId"></param>
  917. /// <param name="parentId"></param>
  918. /// <param name="name"></param>
  919. /// <param name="access_token"></param>
  920. /// <returns></returns>
  921. public async Task<List<DingDingUserInfo>> GetDingDingUserInfo(string partitionKey, long deptId, long parentId, string name, string access_token)
  922. {
  923. List<DingDingUserInfo> ddUserInfos = new();
  924. //获取部门人员信息
  925. IDingTalkClient userListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
  926. //获取部门用户
  927. OapiV2UserListRequest reqUserList = new()
  928. {
  929. DeptId = deptId,
  930. Cursor = 0L,
  931. Size = 50L,
  932. OrderField = "custom",
  933. Language = "zh_CN"
  934. };
  935. reqUserList.SetHttpMethod("GET");
  936. OapiV2UserListResponse rspV2UserList = userListClient.Execute(reqUserList, access_token);
  937. if (rspV2UserList.Result.List != null)
  938. {
  939. foreach (var itemUser in rspV2UserList.Result.List)
  940. {
  941. var tempInfo = ddUserInfos.Find(x => x.RowKey.Equals(itemUser.Unionid));
  942. if (string.IsNullOrEmpty($"{tempInfo}"))
  943. {
  944. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  945. var users = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "userId", $"{itemUser.Userid}" }, { "unionId", $"{itemUser.Unionid}" } });
  946. if (users.Count > 0)
  947. {
  948. foreach (var user in users)
  949. {
  950. DingDingUserInfo ddUserInfo = new()
  951. {
  952. PartitionKey = user.PartitionKey,
  953. RowKey = user.RowKey,
  954. userId = itemUser.Userid,
  955. unionId = itemUser.Unionid,
  956. name = itemUser.Name,
  957. email = itemUser.Email,
  958. title = itemUser.Title,
  959. stateCode = itemUser.StateCode,
  960. mobile = itemUser.Mobile,
  961. jobNumber = itemUser.JobNumber,
  962. pid = parentId,
  963. deptId = deptId,
  964. deptName = name,
  965. depts = string.Join(",", itemUser.DeptIdList.ToArray()),
  966. avatar = itemUser.Avatar,
  967. isAdmin = itemUser.Admin,
  968. tmdId = user.tmdId,
  969. tmdName = user.tmdName,
  970. tmdMobile = user.tmdMobile,
  971. mail = user.mail,
  972. picture = user.picture,
  973. roles = user.roles,
  974. joinTime = user.joinTime,
  975. permissions = user.permissions,
  976. schoolIds = user.schoolIds
  977. };
  978. ddUserInfos.Add(ddUserInfo);
  979. }
  980. }
  981. else
  982. {
  983. DingDingUserInfo ddUserInfo = new()
  984. {
  985. RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
  986. userId = itemUser.Userid,
  987. unionId = itemUser.Unionid,
  988. name = itemUser.Name,
  989. email = itemUser.Email,
  990. title = itemUser.Title,
  991. stateCode = itemUser.StateCode,
  992. mobile = itemUser.Mobile,
  993. jobNumber = itemUser.JobNumber,
  994. pid = parentId,
  995. deptId = deptId,
  996. deptName = name,
  997. depts = string.Join(",", itemUser.DeptIdList.ToArray()),
  998. avatar = itemUser.Avatar,
  999. isAdmin = itemUser.Admin,
  1000. PartitionKey = partitionKey,
  1001. tmdId = "",
  1002. tmdName = "",
  1003. tmdMobile = "",
  1004. mail = "",
  1005. picture = "",
  1006. roles = "assist",
  1007. joinTime = 0,
  1008. permissions = "areadata-read,areadata-upd,schooldata-read,schooldata-upd",
  1009. schoolIds = ""
  1010. };
  1011. ddUserInfos.Add(ddUserInfo);
  1012. }
  1013. }
  1014. }
  1015. }
  1016. return ddUserInfos;
  1017. }
  1018. public record DDUserInfo
  1019. {
  1020. public string partitionKey { get; set; }
  1021. public string rowKey { get; set; }
  1022. public string userId { get; set; }
  1023. public string unionId { get; set; }
  1024. public string name { get; set; }
  1025. public string title { get; set; }
  1026. public string stateCode { get; set; }
  1027. public string mobile { get; set; }
  1028. public string jobNumber { get; set; }
  1029. public long pid { get; set; }
  1030. public long deptId { get; set; }
  1031. public string deptName { get; set; }
  1032. public string depts { get; set; }
  1033. public string avatar { get; set; }
  1034. public bool isAdmin { get; set; }
  1035. public string tmdId { get; set; }
  1036. public string tmdName { get; set; }
  1037. public string tmdMobile { get; set; }
  1038. public string mail { get; set; }
  1039. public string picture { get; set; }
  1040. public string roles { get; set; }
  1041. public long joinTime { get; set; }
  1042. public string permissions { get; set; }
  1043. public List<string> handleRoles { get; set; }
  1044. public List<string> handlePermissions { get; set; }
  1045. public List<AdvSchool> handleSchools { get; set; } = new List<AdvSchool>();
  1046. }
  1047. }
  1048. }