TableDingDingInfoController.cs 66 KB

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