TableDingDingInfoController.cs 59 KB

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