TableDingDingInfoController.cs 70 KB

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