TableDingDingInfoController.cs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  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}\n{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}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  285. return BadRequest();
  286. }
  287. }
  288. /// <summary>
  289. /// 查询钉钉待入职人员的ID添加至Table数据表中
  290. /// </summary>
  291. /// <returns></returns>
  292. [ProducesDefaultResponseType]
  293. [AuthToken(Roles = "admin,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}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  351. return BadRequest();
  352. }
  353. }
  354. /// <summary>
  355. /// 获取钉钉离职人员ID并删除Table表中的数据
  356. /// </summary>
  357. /// <returns></returns>
  358. [ProducesDefaultResponseType]
  359. [AuthToken(Roles = "admin,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}\n{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}\n{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}\n{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 = "admin,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}\n{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. var userInfos = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" } });
  723. var adminInfos = userInfos.FindAll(x => x.roles.Contains("admin"));
  724. if (adminInfos.Count == 1)
  725. {
  726. return Ok(new { state = 403, msg = "已经是最后一个管理员了" });
  727. }
  728. else
  729. {
  730. foreach (var user in tempUser)
  731. {
  732. if (!user.userId.Equals($"{did}"))
  733. {
  734. List<string> tempRoles = new(user.roles.Split(","));
  735. if (tempRoles.Contains("admin"))
  736. {
  737. tempRoles.Remove("admin");
  738. }
  739. user.roles = string.Join(",", tempRoles);
  740. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  741. if (respUser != null)
  742. {
  743. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  744. msg.Append($"取消{respUser.name}【{respUser.RowKey}】账号的BI管理员");
  745. }
  746. }
  747. else return Ok(new { state = 1, msg = "不能删除自己" });
  748. }
  749. }
  750. }
  751. //保存操作记录
  752. await _azureStorage.SaveBILog("tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
  753. return Ok(new { state = 200, roles });
  754. }
  755. catch (Exception ex)
  756. {
  757. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backend \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  758. return BadRequest();
  759. }
  760. }
  761. /// <summary>
  762. /// 通过醍摩豆账户信息 设置BI后台管理员
  763. /// </summary>
  764. /// <param name="jsonElement"></param>
  765. /// <returns></returns>
  766. [ProducesDefaultResponseType]
  767. [AuthToken(Roles = "admin")]
  768. [HttpPost("set-tmdadmin")]
  769. public async Task<IActionResult> SetTmdBackendAdmin(JsonElement jsonElement)
  770. {
  771. try
  772. {
  773. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  774. if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
  775. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  776. jsonElement.TryGetProperty("picture ", out JsonElement picture);
  777. jsonElement.TryGetProperty("mail ", out JsonElement mail);
  778. var cosmosCliet = _azureCosmos.GetCosmosClient();
  779. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  780. List<DDUserInfo> ddUserInfos = new();
  781. List<string> roles = new();//角色列表
  782. List<string> permissions = new();//权限列表
  783. StringBuilder msg = new($"{_tmdName}【{_tmdId}】");
  784. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  785. //string divide = _configuration["CustomParam:SiteScope"];
  786. string divide = _option.Location;
  787. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" }, { "mobile", $"{mobile}" } };
  788. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  789. if (ddUserInfoList.Count > 0)
  790. {
  791. foreach (var user in ddUserInfoList)
  792. {
  793. List<string> tempRoles = new(user.roles.Split(","));
  794. if (tempRoles.Count > 0)
  795. {
  796. if (!tempRoles.Contains("admin"))
  797. {
  798. tempRoles.Add("admin");
  799. }
  800. }
  801. else
  802. tempRoles.Add("admin");
  803. user.roles = string.Join(",", tempRoles);
  804. user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  805. user.tmdId = $"{tmdId}";
  806. user.tmdName = $"{tmdName}";
  807. user.tmdMobile = $"{mobile}";
  808. if (!string.IsNullOrEmpty($"{picture}"))
  809. {
  810. user.picture = $"{picture}";
  811. }
  812. if (!string.IsNullOrEmpty($"{mail}"))
  813. {
  814. user.mail = $"{mail}";
  815. }
  816. msg.Append($" 将:{tmdName}【{tmdId}】醍摩豆账号和({user.name}【{user.unionId}】) 钉钉账户绑定,并设置管理员");
  817. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  818. if (respUser != null)
  819. {
  820. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  821. }
  822. DDUserInfo dDUserInfo = new()
  823. {
  824. partitionKey = respUser.PartitionKey,
  825. rowKey = respUser.RowKey,
  826. userId = respUser.userId,
  827. unionId = respUser.unionId,
  828. name = respUser.name,
  829. title = respUser.title,
  830. stateCode = respUser.stateCode,
  831. mobile = respUser.mobile,
  832. jobNumber = respUser.jobNumber,
  833. pid = respUser.pid,
  834. deptId = respUser.deptId,
  835. deptName = respUser.deptName,
  836. depts = respUser.depts,
  837. avatar = respUser.avatar,
  838. isAdmin = respUser.isAdmin,
  839. tmdId = respUser.tmdId,
  840. tmdName = respUser.tmdName,
  841. tmdMobile = respUser.tmdMobile,
  842. mail = respUser.mail,
  843. picture = respUser.picture,
  844. roles = respUser.roles,
  845. joinTime = respUser.joinTime,
  846. permissions = respUser.permissions,
  847. handleRoles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>(),
  848. handlePermissions = !string.IsNullOrEmpty($"{respUser.permissions}") ? new List<string>(respUser.permissions.Split(",")) : new List<string>()
  849. };
  850. if (!string.IsNullOrEmpty(respUser.schoolIds))
  851. {
  852. List<string> tempSchoolIds = new List<string>(respUser.schoolIds.Split("|"));
  853. dDUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  854. }
  855. ddUserInfos.Add(dDUserInfo);
  856. }
  857. }
  858. else
  859. {
  860. DingDingUserInfo dingDingUserInfo = new()
  861. {
  862. PartitionKey = divide,
  863. RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
  864. roles = "admin",
  865. tmdId = $"{tmdId}",
  866. tmdName = $"{tmdName}",
  867. tmdMobile = $"{mobile}",
  868. };
  869. if (!string.IsNullOrEmpty($"{picture}"))
  870. {
  871. dingDingUserInfo.picture = $"{picture}";
  872. }
  873. if (!string.IsNullOrEmpty($"{mail}"))
  874. {
  875. dingDingUserInfo.mail = $"{mail}";
  876. }
  877. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(dingDingUserInfo);
  878. return Ok(new { state = 201, msg = "新生成的BIadmin", respUser });
  879. }
  880. //保存操作记录
  881. await _azureStorage.SaveBILog("tabledd-update",msg.ToString(), _dingDing, httpContext: HttpContext);
  882. return Ok(new { state = 200, ddUserInfos });
  883. }
  884. catch (Exception ex)
  885. {
  886. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-tmdadmin \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  887. return BadRequest();
  888. }
  889. }
  890. /// <summary>
  891. /// 解除钉钉和醍摩豆的绑定
  892. /// </summary>
  893. /// <param name="jsonElement"></param>
  894. /// <returns></returns>
  895. [ProducesDefaultResponseType]
  896. [HttpPost("set-unbind")]
  897. public async Task<IActionResult> SetUnbind(JsonElement jsonElement)
  898. {
  899. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  900. //string divide = _configuration["CustomParam:SiteScope"];
  901. string divide = _option.Location;
  902. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
  903. if (!string.IsNullOrEmpty($"{mobile}"))
  904. dic.Add("tmdMobile", $"{mobile}");
  905. else
  906. dic.Add("tmdMobile", "18281911681");
  907. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  908. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  909. List<DingDingUserInfo> tempDDUI = new();
  910. if (ddUserInfoList.Count > 0)
  911. {
  912. foreach (var item in ddUserInfoList)
  913. {
  914. item.tmdId = null;
  915. item.tmdName = null;
  916. item.tmdMobile = null;
  917. item.picture = null;
  918. tempDDUI.Add(item);
  919. }
  920. }
  921. else return Ok(new { state = 404, msg = "未找到手机号匹配的绑定号码!,请检查手机号" });
  922. var userInfos = await table.SaveOrUpdateAll(tempDDUI); //保存和修改至Table
  923. return Ok(new { state = 200, userInfos });
  924. }
  925. /// <summary>
  926. /// 获取钉钉用户信息
  927. /// 并查询本地Table数据表中是否存在
  928. /// </summary>
  929. /// <param name="deptId"></param>
  930. /// <param name="parentId"></param>
  931. /// <param name="name"></param>
  932. /// <param name="access_token"></param>
  933. /// <returns></returns>
  934. public async Task<List<DingDingUserInfo>> GetDingDingUserInfo(string partitionKey, long deptId, long parentId, string name, string access_token)
  935. {
  936. List<DingDingUserInfo> ddUserInfos = new();
  937. //获取部门人员信息
  938. IDingTalkClient userListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
  939. //获取部门用户
  940. OapiV2UserListRequest reqUserList = new()
  941. {
  942. DeptId = deptId,
  943. Cursor = 0L,
  944. Size = 50L,
  945. OrderField = "custom",
  946. Language = "zh_CN"
  947. };
  948. reqUserList.SetHttpMethod("GET");
  949. OapiV2UserListResponse rspV2UserList = userListClient.Execute(reqUserList, access_token);
  950. if (rspV2UserList.Result.List != null)
  951. {
  952. foreach (var itemUser in rspV2UserList.Result.List)
  953. {
  954. var tempInfo = ddUserInfos.Find(x => x.RowKey.Equals(itemUser.Unionid));
  955. if (string.IsNullOrEmpty($"{tempInfo}"))
  956. {
  957. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  958. var users = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "userId", $"{itemUser.Userid}" }, { "unionId", $"{itemUser.Unionid}" } });
  959. if (users.Count > 0)
  960. {
  961. foreach (var user in users)
  962. {
  963. DingDingUserInfo ddUserInfo = new()
  964. {
  965. PartitionKey = user.PartitionKey,
  966. RowKey = user.RowKey,
  967. userId = itemUser.Userid,
  968. unionId = itemUser.Unionid,
  969. name = itemUser.Name,
  970. email = itemUser.Email,
  971. title = itemUser.Title,
  972. stateCode = itemUser.StateCode,
  973. mobile = itemUser.Mobile,
  974. jobNumber = itemUser.JobNumber,
  975. pid = parentId,
  976. deptId = deptId,
  977. deptName = name,
  978. depts = string.Join(",", itemUser.DeptIdList.ToArray()),
  979. avatar = itemUser.Avatar,
  980. isAdmin = itemUser.Admin,
  981. tmdId = user.tmdId,
  982. tmdName = user.tmdName,
  983. tmdMobile = user.tmdMobile,
  984. mail = user.mail,
  985. picture = user.picture,
  986. roles = user.roles,
  987. joinTime = user.joinTime,
  988. permissions = user.permissions,
  989. schoolIds = user.schoolIds
  990. };
  991. ddUserInfos.Add(ddUserInfo);
  992. }
  993. }
  994. else
  995. {
  996. DingDingUserInfo ddUserInfo = new()
  997. {
  998. RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
  999. userId = itemUser.Userid,
  1000. unionId = itemUser.Unionid,
  1001. name = itemUser.Name,
  1002. email = itemUser.Email,
  1003. title = itemUser.Title,
  1004. stateCode = itemUser.StateCode,
  1005. mobile = itemUser.Mobile,
  1006. jobNumber = itemUser.JobNumber,
  1007. pid = parentId,
  1008. deptId = deptId,
  1009. deptName = name,
  1010. depts = string.Join(",", itemUser.DeptIdList.ToArray()),
  1011. avatar = itemUser.Avatar,
  1012. isAdmin = itemUser.Admin,
  1013. PartitionKey = partitionKey,
  1014. tmdId = "",
  1015. tmdName = "",
  1016. tmdMobile = "",
  1017. mail = "",
  1018. picture = "",
  1019. roles = "",
  1020. joinTime = 0,
  1021. permissions = "areadata-read,areadata-upd,schooldata-read,schooldata-upd",
  1022. schoolIds = ""
  1023. };
  1024. ddUserInfos.Add(ddUserInfo);
  1025. }
  1026. }
  1027. }
  1028. }
  1029. return ddUserInfos;
  1030. }
  1031. public record DDUserInfo
  1032. {
  1033. public string partitionKey { get; set; }
  1034. public string rowKey { get; set; }
  1035. public string userId { get; set; }
  1036. public string unionId { get; set; }
  1037. public string name { get; set; }
  1038. public string title { get; set; }
  1039. public string stateCode { get; set; }
  1040. public string mobile { get; set; }
  1041. public string jobNumber { get; set; }
  1042. public long pid { get; set; }
  1043. public long deptId { get; set; }
  1044. public string deptName { get; set; }
  1045. public string depts { get; set; }
  1046. public string avatar { get; set; }
  1047. public bool isAdmin { get; set; }
  1048. public string tmdId { get; set; }
  1049. public string tmdName { get; set; }
  1050. public string tmdMobile { get; set; }
  1051. public string mail { get; set; }
  1052. public string picture { get; set; }
  1053. public string roles { get; set; }
  1054. public long joinTime { get; set; }
  1055. public string permissions { get; set; }
  1056. public List<string> handleRoles { get; set; }
  1057. public List<string> handlePermissions { get; set; }
  1058. public List<AdvSchool> handleSchools { get; set; } = new List<AdvSchool>();
  1059. }
  1060. }
  1061. }