TableDingDingInfoController.cs 69 KB

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