TableDingDingInfoController.cs 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787
  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 System.Text;
  21. using Microsoft.Azure.Cosmos;
  22. using TEAMModelBI.Filter;
  23. using TEAMModelBI.Tool.Extension;
  24. using TEAMModelBI.Models;
  25. using TEAMModelBI.Tool.CosmosBank;
  26. using TEAMModelOS.SDK;
  27. using TEAMModelOS.SDK.Context.BI;
  28. using TEAMModelOS.SDK.Models;
  29. using TEAMModelOS.SDK.Context.Constant;
  30. using TEAMModelOS.SDK.Models.Dtos;
  31. using TEAMModelOS.SDK.Models.Cosmos.BI.BISchool;
  32. namespace TEAMModelBI.Controllers.BITable
  33. {
  34. [Route("tabledd")]
  35. [ApiController]
  36. public class TableDingDingInfoController : ControllerBase
  37. {
  38. //读取配置文件
  39. private readonly IConfiguration _configuration;
  40. //数据容器
  41. private readonly AzureCosmosFactory _azureCosmos;
  42. //blob和table容器
  43. private readonly AzureStorageFactory _azureStorage;
  44. //钉钉提示信息
  45. private readonly DingDing _dingDing;
  46. private readonly Option _option;
  47. private readonly IHttpClientFactory _http;
  48. private readonly CoreAPIHttpService _coreAPIHttpService;
  49. public TableDingDingInfoController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IConfiguration configuration, IHttpClientFactory http, CoreAPIHttpService coreAPIHttpService)
  50. {
  51. _azureCosmos = azureCosmos;
  52. _dingDing = dingDing;
  53. _azureStorage = azureStorage;
  54. _option = option?.Value;
  55. _http = http;
  56. _configuration = configuration;
  57. _coreAPIHttpService = coreAPIHttpService;
  58. }
  59. /// <summary>
  60. /// 从钉钉的组织架构中人员信息数据,并保存或者更新至Blob中 已对接
  61. /// </summary>
  62. /// <returns></returns>
  63. [ProducesDefaultResponseType]
  64. [AuthToken(Roles = "admin,rdc")]
  65. [HttpPost("get-dingdingusers")]
  66. public async Task<IActionResult> GetDingDingUser(JsonElement jsonElement)
  67. {
  68. try
  69. {
  70. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  71. var tableClient = _azureStorage.GetCloudTableClient();
  72. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  73. ////分开部署,就不需要,一站多用时,取消注释
  74. //if ($"{site}".Equals(BIConst.Global))
  75. //{
  76. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  77. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  78. //}
  79. var table = tableClient.GetTableReference("BIDDUserInfo");
  80. string appKey = _configuration["DingDingAuth:appKey"];
  81. string appSecret = _configuration["DingDingAuth:appSecret"];
  82. //string divide = _configuration["CustomParam:SiteScope"];
  83. string divide = _option.Location;
  84. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  85. //获取access_token
  86. IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  87. OapiGettokenRequest tokenRequest = new() { 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() { 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() { 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() { 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() { 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() { 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. var tempddUserInfos = ddUserInfos.GroupBy(c => c.userId).Select(c => c.First()).ToList();//去重
  165. //List<DingDingUserInfo> TempdingDingUserInfos = await _azureStorage.SaveOrUpdateAll(dingDingUserInfos); //只是保存至Table
  166. //查询数据的数据 并和钉钉查询的数据对比,找出不同的数据,并删除 待后期测试
  167. var users = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{divide}" } });
  168. List<DingDingUserInfo> noExisits = new();
  169. if (users.Count > 0)
  170. {
  171. //var temps = users.Union(tempddUserInfos).Except(users.Intersect(tempddUserInfos));
  172. List<DingDingUserInfo> existsUserInfo = users.Where(u => !tempddUserInfos.Exists(e => u.userId.Equals(e.userId) && u.PartitionKey.Equals(e.PartitionKey))).ToList();
  173. //if (users.Count > tempddUserInfos.Count)
  174. //{
  175. // existsUserInfo.AddRange(tempddUserInfos.Where(e => !users.Exists(u => e.userId.Equals(u.userId) && e.PartitionKey.Equals(u.PartitionKey))).ToList());
  176. //}
  177. ////List<DingDingUserInfo> existsUserInfo = users.Where((x, i) => users.FindIndex(z => z.userId.Equals(x.userId) && x.PartitionKey.Equals(divide)) == i).Select(x => x).ToList();
  178. if (existsUserInfo.Count > 0)
  179. {
  180. noExisits = await table.DeleteAll(existsUserInfo);
  181. }
  182. }
  183. //保存和修改至Table
  184. List<DingDingUserInfo> UserInfo = await table.SaveOrUpdateAll(tempddUserInfos);
  185. //保存操作记录
  186. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{_tmdName}【{_tmdId}】从钉钉组织结构更新至Azure Table表【DDUserInfo】中。", _dingDing, httpContext: HttpContext);
  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. ////分开部署,就不需要,一站多用时,取消注释
  210. //if ($"{site}".Equals(BIConst.Global))
  211. // table = _azureStorage.GetCloudTableClient(BIConst.Global).GetTableReference("BIDDUserInfo");
  212. //string divide = _configuration["CustomParam:SiteScope"];
  213. string divide = _option.Location;
  214. List<DDUserInfo> ddUserInfos = new();
  215. Dictionary<string, object> dic = new() { { "PartitionKey", $"{divide}" } };
  216. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  217. switch ($"{busy}")
  218. {
  219. case "admin":
  220. foreach (var item in ddUserInfoList)
  221. {
  222. if (item.roles.Contains("admin"))
  223. {
  224. DDUserInfo ddUserInfo = new()
  225. {
  226. partitionKey = item.PartitionKey,
  227. rowKey = item.RowKey,
  228. userId = item.userId,
  229. unionId = item.unionId,
  230. name = item.name,
  231. title = item.title,
  232. stateCode = item.stateCode,
  233. mobile = item.mobile,
  234. jobNumber = item.jobNumber,
  235. pid = item.pid,
  236. deptId = item.deptId,
  237. deptName = item.deptName,
  238. depts = item.depts,
  239. avatar = item.avatar,
  240. isAdmin = item.isAdmin,
  241. tmdId = item.tmdId,
  242. tmdName = item.tmdName,
  243. tmdMobile = item.tmdMobile,
  244. mail = item.mail,
  245. picture = item.picture,
  246. roles = item.roles,
  247. joinTime = item.joinTime,
  248. isDisable = item.isDisable,
  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. isDisable = item.isDisable,
  290. permissions = item.permissions,
  291. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  292. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  293. };
  294. if (!string.IsNullOrEmpty(item.schoolIds))
  295. {
  296. List<string> tempSchoolIds = new(item.schoolIds.Split("|"));
  297. ddUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  298. }
  299. ddUserInfos.Add(ddUserInfo);
  300. }
  301. break;
  302. }
  303. return Ok(new { state = 200, ddUserInfos = ddUserInfos });
  304. }
  305. catch (Exception ex)
  306. {
  307. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/get-ddusers \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  308. return BadRequest();
  309. }
  310. }
  311. /// <summary>
  312. /// 更新钉钉和醍摩豆的BI权限 //已对接
  313. /// </summary>
  314. /// <param name="jsonElement"></param>
  315. /// <returns></returns>
  316. [ProducesDefaultResponseType]
  317. [AuthToken(Roles = "admin,rdc")]
  318. [HttpPost("set-rolesper")]
  319. public async Task<IActionResult> SetPermissions(JsonElement jsonElement)
  320. {
  321. try
  322. {
  323. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  324. jsonElement.TryGetProperty("userId", out JsonElement userId);
  325. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  326. if (!jsonElement.TryGetProperty("permissions", out JsonElement _permissions)) return BadRequest();
  327. if (!jsonElement.TryGetProperty("roles", out JsonElement _roles)) return BadRequest();
  328. if (!jsonElement.TryGetProperty("isDisable", out JsonElement _isDisable)) return BadRequest();
  329. var cosmosCliet = _azureCosmos.GetCosmosClient();
  330. var tableClient = _azureStorage.GetCloudTableClient();
  331. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  332. long isDisable = 0;
  333. try
  334. {
  335. isDisable = long.Parse($"{_isDisable}");
  336. if (isDisable != 1 && isDisable != 0)
  337. return Ok(new { state = RespondCode.ParamsError, msg = "账户禁用参数错误!" });
  338. }
  339. catch
  340. {
  341. return Ok(new { state = RespondCode.ParamsError, msg = "账户禁用参数错误!" });
  342. }
  343. var table = tableClient.GetTableReference("BIDDUserInfo");
  344. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  345. List<DingDingUserInfo> ddUserInfos = new();
  346. List<string> listper = _permissions.ToObject<List<string>>();
  347. List<string> listroles = _roles.ToObject<List<string>>();
  348. List<string> roles = new();//角色列表
  349. List<string> permissions = new();//权限列表
  350. StringBuilder stringBuilder = new($"{_tmdName}【{_tmdId}】醍摩豆账号");
  351. Dictionary<string, object> dic = new() { { "PartitionKey", $"{partitionKey}" } };
  352. if (!string.IsNullOrEmpty($"{userId}"))
  353. dic.Add("userId", $"{userId}");
  354. if (!string.IsNullOrEmpty($"{tmdId}"))
  355. dic.Add("tmdId", $"{tmdId}");
  356. if (string.IsNullOrEmpty($"{userId}") && string.IsNullOrEmpty($"{tmdId}"))
  357. {
  358. return BadRequest();
  359. }
  360. var tempUser = await table.FindListByDict<DingDingUserInfo>(dic);
  361. List<string> oldRoles = new();
  362. List<Task<ItemResponse<BIRelation>>> upBIRel = new();
  363. //List<Task<ItemResponse<SchoolTeacher>>> upScTch = new();
  364. foreach (var item in tempUser)
  365. {
  366. oldRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  367. stringBuilder.Append($"操作醍摩豆账户{item.tmdName}【{item.tmdId}】修改权限:{string.Join("|", listper.ToArray())}");
  368. item.roles = listroles.Count > 0 ? string.Join(",", listroles) : "assist";
  369. item.permissions = string.Join(",", listper);
  370. item.isDisable = isDisable;
  371. ddUserInfos.Add(item);
  372. roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  373. permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
  374. foreach (var itemR in listroles)
  375. {
  376. if(itemR.Equals("assist"))
  377. {
  378. string tempSql = $"select value(c) from c join a in c.sales where a.id='{itemR}'";
  379. await foreach (var itemRel in cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<BIRelation>(queryText: tempSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
  380. {
  381. var tempRel = itemRel.sales.Find(f => f.id.Equals(itemR));
  382. itemRel.sales.Remove(tempRel);
  383. itemRel.assists.Add(tempRel);
  384. itemRel.upDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  385. upBIRel.Add(cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<BIRelation>(itemRel, itemRel.id, new PartitionKey("BIRel")));
  386. }
  387. //string sql = $"select value(c) from c where c.pk='Teacher' and c.id='{item.tmdId}'";
  388. //await foreach (var scTch in cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<SchoolTeacher>(queryText: sql, requestOptions: new QueryRequestOptions() { }))
  389. //{
  390. // if (scTch.roles.Contains("sales"))
  391. // {
  392. // //int index = scTch.roles.FindIndex(fi => fi.Equals("sales"));
  393. // //scTch.roles[index]= "assist";
  394. // //scTch.job = "顾问";
  395. // //upScTch.Add(cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(scTch, scTch.id, new PartitionKey($"{scTch.code}")));
  396. // int index = scTch.roles.FindIndex(fi => fi.Equals("sales"));
  397. // if (index >= 0)
  398. // {
  399. // scTch.roles[index] = "assist";
  400. // scTch.job = "顾问";
  401. // upScTch.Add(cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(scTch, scTch.id, new PartitionKey($"{scTch.code}")));
  402. // }
  403. // }
  404. //}
  405. }
  406. if (itemR.Equals("sales"))
  407. {
  408. string tempSql = $"select value(c) from c join a in c.assists where a.id='{itemR}'";
  409. await foreach (var itemRel in cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<BIRelation>(queryText: tempSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
  410. {
  411. var tempRel = itemRel.sales.Find(f => f.id.Equals(itemR));
  412. itemRel.assists.Remove(tempRel);
  413. itemRel.sales.Add(tempRel);
  414. itemRel.upDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  415. upBIRel.Add(cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<BIRelation>(itemRel, itemRel.id, new PartitionKey("BIRel")));
  416. }
  417. //string sql = $"select value(c) from c where c.pk='Teacher' and c.id='{item.tmdId}'";
  418. //await foreach (var scTch in cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<SchoolTeacher>(queryText: sql, requestOptions: new QueryRequestOptions() { }))
  419. //{
  420. // if (scTch.roles.Contains("assist"))
  421. // {
  422. // int index = scTch.roles.FindIndex(fi => fi.Equals("assist"));
  423. // if (index >= 0)
  424. // {
  425. // scTch.roles[index] = "sales";
  426. // scTch.job = "销售";
  427. // upScTch.Add(cosmosCliet.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(scTch, scTch.id, new PartitionKey($"{scTch.code}")));
  428. // }
  429. // }
  430. //}
  431. }
  432. }
  433. }
  434. if (upBIRel.Count < 256)
  435. {
  436. await Task.WhenAll(upBIRel);
  437. }
  438. else
  439. {
  440. int pages = (upBIRel.Count + 255) / 256;
  441. for (int i = 0; i < pages; i++)
  442. {
  443. List<Task<ItemResponse<BIRelation>>> tempRel = upBIRel.Skip((i) * 256).Take(256).ToList();
  444. await Task.WhenAll(tempRel);
  445. }
  446. }
  447. ddUserInfos = await table.UpdateAll<DingDingUserInfo>(ddUserInfos);
  448. List<DDUserInfo> ddUserInfo = new();
  449. foreach (var item in ddUserInfos)
  450. {
  451. DDUserInfo tempInfo = new()
  452. {
  453. partitionKey = item.PartitionKey,
  454. rowKey = item.RowKey,
  455. userId = item.userId,
  456. unionId = item.unionId,
  457. name = item.name,
  458. title = item.title,
  459. stateCode = item.stateCode,
  460. mobile = item.mobile,
  461. jobNumber = item.jobNumber,
  462. pid = item.pid,
  463. deptId = item.deptId,
  464. deptName = item.deptName,
  465. depts = item.depts,
  466. avatar = item.avatar,
  467. isAdmin = item.isAdmin,
  468. tmdId = item.tmdId,
  469. tmdName = item.tmdName,
  470. tmdMobile = item.tmdMobile,
  471. mail = item.mail,
  472. picture = item.picture,
  473. roles = item.roles,
  474. joinTime = item.joinTime,
  475. isDisable = item.isDisable,
  476. permissions = item.permissions,
  477. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  478. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  479. };
  480. if (!string.IsNullOrEmpty(item.schoolIds))
  481. {
  482. List<string> tempSchoolIds = new(item.schoolIds.Split("|"));
  483. tempInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  484. }
  485. ddUserInfo.Add(tempInfo);
  486. }
  487. //保存操作记录
  488. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", stringBuilder?.ToString(), _dingDing, httpContext: HttpContext);
  489. return Ok(new { state = 200, ddUserInfo, roles, permissions });
  490. }
  491. catch (Exception ex)
  492. {
  493. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/tabledd-update \n {ex.Message}\n{ex.StackTrace} ", GroupNames.成都开发測試群組);
  494. return BadRequest();
  495. }
  496. }
  497. /// <summary>
  498. /// 依据部门ID获取部门列表 //已对接
  499. /// </summary>
  500. /// <param name="jsonElement"></param>
  501. /// <returns></returns>
  502. [ProducesDefaultResponseType]
  503. [HttpPost("get-dddeptiduser")]
  504. public async Task<IActionResult> GetDDDeptIdUser(JsonElement jsonElement)
  505. {
  506. try
  507. {
  508. if (!jsonElement.TryGetProperty("deptId", out JsonElement deptId)) return BadRequest();
  509. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  510. var cosmosCliet = _azureCosmos.GetCosmosClient();
  511. var tableClient = _azureStorage.GetCloudTableClient();
  512. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  513. ////分开部署,就不需要,一站多用时,取消注释
  514. //if ($"{site}".Equals(BIConst.Global))
  515. //{
  516. // cosmosCliet = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  517. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  518. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  519. //};
  520. var table = tableClient.GetTableReference("BIDDUserInfo");
  521. //string divide = _configuration["CustomParam:SiteScope"];
  522. string divide = _option.Location;
  523. Dictionary<string, object> dic = new() { { "PartitionKey", $"{divide}" } };
  524. List<DingDingUserInfo> tempUserInfos = await table.FindListByDict<DingDingUserInfo>(dic);
  525. List<DingDingUserInfo> userInfo = new();
  526. tempUserInfos.ForEach(x => {
  527. if (x.depts.Contains($"{deptId}"))
  528. {
  529. userInfo.Add(x);
  530. }
  531. if (x.pid.Equals(long.Parse($"{deptId}")))
  532. {
  533. userInfo.Add(x);
  534. }
  535. });
  536. //userInfo.Distinct().ToList(); //Equals实现去重
  537. userInfo.Where((x, i) => userInfo.FindIndex(z => z.RowKey.Equals(x.RowKey)) == i);//Lambda表达式去重
  538. //userInfo.GroupBy(p => p).Select(p => p.Key).ToList();//去重复
  539. List<DDUserInfo> ddUserInfos = new();
  540. foreach (var item in userInfo)
  541. {
  542. DDUserInfo tempUserInfo = new DDUserInfo()
  543. {
  544. partitionKey = item.PartitionKey,
  545. rowKey = item.RowKey,
  546. userId = item.userId,
  547. unionId = item.unionId,
  548. name = item.name,
  549. title = item.title,
  550. stateCode = item.stateCode,
  551. mobile = item.mobile,
  552. jobNumber = item.jobNumber,
  553. pid = item.pid,
  554. deptId = item.deptId,
  555. deptName = item.deptName,
  556. depts = item.depts,
  557. avatar = item.avatar,
  558. isAdmin = item.isAdmin,
  559. tmdId = item.tmdId,
  560. tmdName = item.tmdName,
  561. tmdMobile = item.tmdMobile,
  562. mail = item.mail,
  563. picture = item.picture,
  564. roles = item.roles,
  565. joinTime = item.joinTime,
  566. isDisable = item.isDisable,
  567. permissions = item.permissions,
  568. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  569. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  570. };
  571. if (!string.IsNullOrEmpty(item.schoolIds))
  572. {
  573. List<string> tempSchoolIds = new(item.schoolIds.Split("|"));
  574. tempUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  575. }
  576. ddUserInfos.Add(tempUserInfo);
  577. }
  578. return Ok(new { state = 200, ddUserInfos });
  579. }
  580. catch (Exception ex)
  581. {
  582. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/get-dddeptiduser \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  583. return BadRequest();
  584. }
  585. }
  586. /// <summary>
  587. /// 通过醍摩豆账户信息 设置BI后台管理员 //已对接
  588. /// </summary>
  589. /// <param name="jsonElement"></param>
  590. /// <returns></returns>
  591. [ProducesDefaultResponseType]
  592. [AuthToken(Roles = "admin,rdc")]
  593. [HttpPost("set-tmdadmin")]
  594. public async Task<IActionResult> SetTmdBackendAdmin(JsonElement jsonElement)
  595. {
  596. try
  597. {
  598. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  599. if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
  600. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  601. jsonElement.TryGetProperty("picture ", out JsonElement picture);
  602. jsonElement.TryGetProperty("mail ", out JsonElement mail);
  603. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  604. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  605. var cosmosCliet = _azureCosmos.GetCosmosClient();
  606. var tableClient = _azureStorage.GetCloudTableClient();
  607. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  608. ////分开部署,就不需要,一站多用时,取消注释
  609. //if ($"{site}".Equals(BIConst.Global))
  610. //{
  611. // cosmosCliet = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  612. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  613. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  614. //}
  615. var table = tableClient.GetTableReference("BIDDUserInfo");
  616. List<DDUserInfo> ddUserInfos = new();
  617. List<string> roles = new();//角色列表
  618. List<string> permissions = new();//权限列表
  619. StringBuilder msg = new($"{_tmdName}【{_tmdId}】");
  620. //string divide = _configuration["CustomParam:SiteScope"];
  621. string divide = _option.Location;
  622. Dictionary<string, object> dic = new() { { "PartitionKey", $"{divide}" }, { "mobile", $"{mobile}" } };
  623. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  624. if (ddUserInfoList.Count > 0)
  625. {
  626. foreach (var user in ddUserInfoList)
  627. {
  628. List<string> tempRoles = new(user.roles.Split(","));
  629. if (tempRoles.Count > 0)
  630. {
  631. if (!tempRoles.Contains("admin"))
  632. {
  633. tempRoles.Add("admin");
  634. }
  635. }
  636. else
  637. tempRoles.Add("admin");
  638. user.roles = string.Join(",", tempRoles);
  639. user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  640. user.tmdId = $"{tmdId}";
  641. user.tmdName = $"{tmdName}";
  642. user.tmdMobile = $"{mobile}";
  643. if (!string.IsNullOrEmpty($"{picture}"))
  644. {
  645. user.picture = $"{picture}";
  646. }
  647. if (!string.IsNullOrEmpty($"{mail}"))
  648. {
  649. user.mail = $"{mail}";
  650. }
  651. msg.Append($" 将:{tmdName}【{tmdId}】醍摩豆账号和({user.name}【{user.unionId}】) 钉钉账户绑定,并设置管理员");
  652. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  653. if (respUser != null)
  654. {
  655. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  656. }
  657. DDUserInfo dDUserInfo = new()
  658. {
  659. partitionKey = respUser.PartitionKey,
  660. rowKey = respUser.RowKey,
  661. userId = respUser.userId,
  662. unionId = respUser.unionId,
  663. name = respUser.name,
  664. title = respUser.title,
  665. stateCode = respUser.stateCode,
  666. mobile = respUser.mobile,
  667. jobNumber = respUser.jobNumber,
  668. pid = respUser.pid,
  669. deptId = respUser.deptId,
  670. deptName = respUser.deptName,
  671. depts = respUser.depts,
  672. avatar = respUser.avatar,
  673. isAdmin = respUser.isAdmin,
  674. tmdId = respUser.tmdId,
  675. tmdName = respUser.tmdName,
  676. tmdMobile = respUser.tmdMobile,
  677. mail = respUser.mail,
  678. picture = respUser.picture,
  679. roles = respUser.roles,
  680. joinTime = respUser.joinTime,
  681. isDisable = respUser.isDisable,
  682. permissions = respUser.permissions,
  683. handleRoles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>(),
  684. handlePermissions = !string.IsNullOrEmpty($"{respUser.permissions}") ? new List<string>(respUser.permissions.Split(",")) : new List<string>()
  685. };
  686. if (!string.IsNullOrEmpty(respUser.schoolIds))
  687. {
  688. List<string> tempSchoolIds = new(respUser.schoolIds.Split("|"));
  689. dDUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosCliet, tempSchoolIds);
  690. }
  691. ddUserInfos.Add(dDUserInfo);
  692. }
  693. }
  694. else
  695. {
  696. DingDingUserInfo dingDingUserInfo = new()
  697. {
  698. PartitionKey = divide,
  699. RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
  700. roles = "admin",
  701. tmdId = $"{tmdId}",
  702. tmdName = $"{tmdName}",
  703. tmdMobile = $"{mobile}",
  704. };
  705. if (!string.IsNullOrEmpty($"{picture}"))
  706. {
  707. dingDingUserInfo.picture = $"{picture}";
  708. }
  709. if (!string.IsNullOrEmpty($"{mail}"))
  710. {
  711. dingDingUserInfo.mail = $"{mail}";
  712. }
  713. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(dingDingUserInfo);
  714. return Ok(new { state = 201, msg = "新生成的BIadmin", respUser });
  715. }
  716. //保存操作记录
  717. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
  718. return Ok(new { state = 200, ddUserInfos });
  719. }
  720. catch (Exception ex)
  721. {
  722. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-tmdadmin \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  723. return BadRequest();
  724. }
  725. }
  726. /// <summary>
  727. /// 设置系统管理员 //已对接
  728. /// </summary>
  729. /// <param name="jsonElement"></param>
  730. /// <returns></returns>
  731. [ProducesDefaultResponseType]
  732. [AuthToken(Roles = "admin,rdc")]
  733. [HttpPost("set-backend")]
  734. public async Task<IActionResult> SetBackendAdmin(JsonElement jsonElement)
  735. {
  736. try
  737. {
  738. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  739. if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
  740. if (!jsonElement.TryGetProperty("isAdmin", out JsonElement isAdmin)) return BadRequest();
  741. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  742. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  743. var tableClient = _azureStorage.GetCloudTableClient();
  744. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  745. ////分开部署,就不需要,一站多用时,取消注释
  746. //if ($"{site}".Equals(BIConst.Global))
  747. //{
  748. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  749. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  750. //}
  751. var table = tableClient.GetTableReference("BIDDUserInfo");
  752. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{rowKey}" } });
  753. List<DDUserInfo> ddUserInfos = new();
  754. List<string> roles = new();//角色列表
  755. List<string> permissions = new();//权限列表
  756. StringBuilder msg = new($"{_tmdName}【{_tmdId}】");
  757. if (bool.Parse($"{isAdmin}") == true)
  758. {
  759. foreach (var user in tempUser)
  760. {
  761. if (string.IsNullOrEmpty(user.roles))
  762. {
  763. user.roles = "admin";
  764. }
  765. List<string> tempRoles = new(user.roles.Split(","));
  766. if (!tempRoles.Contains("admin"))
  767. {
  768. tempRoles.Add("admin");
  769. }
  770. user.roles = string.Join(",", tempRoles);
  771. user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  772. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  773. if (respUser != null)
  774. {
  775. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  776. }
  777. msg.Append($"添加{respUser.name}【{respUser.RowKey}】账号的BI管理员");
  778. }
  779. }
  780. else
  781. {
  782. var userInfos = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" } });
  783. var adminInfos = userInfos.FindAll(x => x.roles.Contains("admin"));
  784. if (adminInfos.Count == 1)
  785. {
  786. return Ok(new { state = 403, msg = "已经是最后一个管理员了" });
  787. }
  788. else
  789. {
  790. foreach (var user in tempUser)
  791. {
  792. if (!user.userId.Equals($"{did}"))
  793. {
  794. List<string> tempRoles = new(user.roles.Split(","));
  795. if (tempRoles.Contains("admin"))
  796. {
  797. tempRoles.Remove("admin");
  798. }
  799. user.roles = string.Join(",", tempRoles);
  800. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  801. if (respUser != null)
  802. {
  803. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  804. msg.Append($"取消{respUser.name}【{respUser.RowKey}】账号的BI管理员");
  805. }
  806. }
  807. else return Ok(new { state = 1, msg = "不能删除自己" });
  808. }
  809. }
  810. }
  811. //保存操作记录
  812. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
  813. return Ok(new { state = 200, roles });
  814. }
  815. catch (Exception ex)
  816. {
  817. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backend \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  818. return BadRequest();
  819. }
  820. }
  821. /// <summary>
  822. /// 从钉钉的组织架构中人员信息数据,并保存或者更新至Blob中 初始化使用该接口
  823. /// </summary>
  824. /// <returns></returns>
  825. [ProducesDefaultResponseType]
  826. [HttpPost("get-dduserinitial")]
  827. public async Task<IActionResult> GetddUserInitial(JsonElement jsonElement)
  828. {
  829. try
  830. {
  831. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  832. var tableClient = _azureStorage.GetCloudTableClient();
  833. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  834. ////分开部署,就不需要,一站多用时,取消注释
  835. //if ($"{site}".Equals(BIConst.Global))
  836. //{
  837. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  838. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  839. //}
  840. var table = tableClient.GetTableReference("BIDDUserInfo");
  841. string appKey = _configuration["DingDingAuth:appKey"];
  842. string appSecret = _configuration["DingDingAuth:appSecret"];
  843. //string divide = _configuration["CustomParam:SiteScope"];
  844. string divide = _option.Location;
  845. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  846. //获取access_token
  847. IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  848. OapiGettokenRequest tokenRequest = new() { Appkey = appKey, Appsecret = appSecret };
  849. tokenRequest.SetHttpMethod("Get");
  850. OapiGettokenResponse tokenRespone = tokenClient.Execute(tokenRequest);
  851. if (tokenRespone.IsError)
  852. {
  853. return BadRequest();
  854. }
  855. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  856. string access_token = tokenRespone.AccessToken;
  857. //获取部门接口
  858. IDingTalkClient deptListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
  859. //一级部门
  860. OapiV2DepartmentListsubRequest reqDeptList1 = new() { DeptId = 1L, Language = "zh_CN" };
  861. OapiV2DepartmentListsubResponse rspDeptList1 = deptListClient.Execute(reqDeptList1, access_token);
  862. List<DingDingUserInfo> ddUserInfos = new();
  863. if (rspDeptList1.Result != null)
  864. {
  865. foreach (var tempDept1 in rspDeptList1.Result)
  866. {
  867. //获取一级部门用户信息
  868. List<DingDingUserInfo> dingDingUserInfos1 = await GetDingDingUserInfo(divide, tempDept1.DeptId, tempDept1.ParentId, tempDept1.Name, access_token);
  869. //if (dingDingUserInfos1.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos1.ToList()));
  870. if (dingDingUserInfos1.Count > 0) ddUserInfos.AddRange(dingDingUserInfos1);
  871. //获取二级部门
  872. OapiV2DepartmentListsubRequest reqDeptList2 = new() { DeptId = tempDept1.DeptId, Language = "zh_CN" };
  873. OapiV2DepartmentListsubResponse rspDeptList2 = deptListClient.Execute(reqDeptList2, access_token);
  874. if (rspDeptList2.Result != null)
  875. {
  876. foreach (var tempDept2 in rspDeptList2.Result)
  877. {
  878. //获取二级部门用户信息
  879. List<DingDingUserInfo> dingDingUserInfos2 = await GetDingDingUserInfo(divide, tempDept2.DeptId, tempDept2.ParentId, tempDept2.Name, access_token);
  880. //if (dingDingUserInfos2.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos2.ToList()));
  881. if (dingDingUserInfos2.Count > 0) ddUserInfos.AddRange(dingDingUserInfos2);
  882. //获取三级部门
  883. OapiV2DepartmentListsubRequest reqDeptList3 = new() { DeptId = tempDept2.DeptId, Language = "zh_CN" };
  884. OapiV2DepartmentListsubResponse rspDeptList3 = deptListClient.Execute(reqDeptList3, access_token);
  885. if (rspDeptList3.Result != null)
  886. {
  887. foreach (var tempDept3 in rspDeptList3.Result)
  888. {
  889. //获取三级部门用户信息
  890. List<DingDingUserInfo> dingDingUserInfos3 = await GetDingDingUserInfo(divide, tempDept3.DeptId, tempDept3.ParentId, tempDept3.Name, access_token);
  891. //if (dingDingUserInfos3.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos3.ToList()));
  892. if (dingDingUserInfos3.Count > 0) ddUserInfos.AddRange(dingDingUserInfos3);
  893. //获取四级部门
  894. OapiV2DepartmentListsubRequest reqDeptList4 = new() { DeptId = tempDept3.DeptId, Language = "zh_CN" };
  895. OapiV2DepartmentListsubResponse rspDeptList4 = deptListClient.Execute(reqDeptList4, access_token);
  896. if (rspDeptList4.Result != null)
  897. {
  898. foreach (var tempDept4 in rspDeptList4.Result)
  899. {
  900. //获取四级部门用户信息
  901. List<DingDingUserInfo> dingDingUserInfos4 = await GetDingDingUserInfo(divide, tempDept4.DeptId, tempDept4.ParentId, tempDept4.Name, access_token);
  902. //if (dingDingUserInfos4.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos4.ToList()));
  903. if (dingDingUserInfos4.Count > 0) ddUserInfos.AddRange(dingDingUserInfos4);
  904. //获取五级部门
  905. OapiV2DepartmentListsubRequest reqDeptList5 = new() { DeptId = tempDept4.DeptId, Language = "zh_CN" };
  906. OapiV2DepartmentListsubResponse rspDeptList5 = deptListClient.Execute(reqDeptList5, access_token);
  907. if (rspDeptList5.Result != null)
  908. {
  909. foreach (var tempDept5 in rspDeptList5.Result)
  910. {
  911. //获取五级部门用户信息
  912. List<DingDingUserInfo> dingDingUserInfos5 = await GetDingDingUserInfo(divide, tempDept5.DeptId, tempDept5.ParentId, tempDept5.Name, access_token);
  913. //if (dingDingUserInfos5.Count > 0) ddUserInfos.AddRange(ddUserInfos.Union(dingDingUserInfos5).ToList());
  914. if (dingDingUserInfos5.Count > 0) ddUserInfos.AddRange(dingDingUserInfos5);
  915. }
  916. }
  917. }
  918. }
  919. }
  920. }
  921. }
  922. }
  923. }
  924. }
  925. //保存操作记录
  926. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{_tmdName}【{_tmdId}】从钉钉组织结构初始化至Azure Table表【DDUserInfo】中。", _dingDing, httpContext: HttpContext);
  927. var tempddUserInfos = ddUserInfos.GroupBy(c => c.userId).Select(c => c.First()).ToList();//去重
  928. //List<DingDingUserInfo> TempdingDingUserInfos = await _azureStorage.SaveOrUpdateAll(dingDingUserInfos); //只是保存至Table
  929. //查询数据的数据 并和钉钉查询的数据对比,找出不同的数据,并删除 待后期测试
  930. var users = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{divide}" } });
  931. List<DingDingUserInfo> noExisits = new();
  932. if (users.Count > 0)
  933. {
  934. //var temps = users.Union(tempddUserInfos).Except(users.Intersect(tempddUserInfos));
  935. List<DingDingUserInfo> existsUserInfo = users.Where(u => !tempddUserInfos.Exists(e => u.userId.Equals(e.userId) && u.PartitionKey.Equals(e.PartitionKey))).ToList();
  936. if (users.Count >= tempddUserInfos.Count)
  937. {
  938. existsUserInfo.AddRange(tempddUserInfos.Where(e => !users.Exists(u => e.userId.Equals(u.userId) && e.PartitionKey.Equals(u.PartitionKey))).ToList());
  939. }
  940. ////List<DingDingUserInfo> existsUserInfo = users.Where((x, i) => users.FindIndex(z => z.userId.Equals(x.userId) && x.PartitionKey.Equals(divide)) == i).Select(x => x).ToList();
  941. if (existsUserInfo.Count > 0)
  942. {
  943. noExisits = await table.DeleteAll(existsUserInfo);
  944. }
  945. }
  946. List<DingDingUserInfo> UserInfo = await table.SaveOrUpdateAll(tempddUserInfos); //保存和修改至Table
  947. return Ok(new { state = 200, UserInfo, noExisits });
  948. }
  949. catch (Exception ex)
  950. {
  951. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/get-dingdingusers \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  952. return BadRequest();
  953. }
  954. }
  955. /// <summary>
  956. /// 后端钉钉账户和醍摩豆账户进行绑定
  957. /// </summary>
  958. /// <param name="jsonElement"></param>
  959. /// <returns></returns>
  960. [ProducesDefaultResponseType]
  961. [AuthToken(Roles = "admin,rdc")]
  962. [HttpPost("set-backenbind")]
  963. public async Task<IActionResult> SetBackenBind(JsonElement jsonElement)
  964. {
  965. try
  966. {
  967. if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
  968. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  969. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  970. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  971. var tableClient = _azureStorage.GetCloudTableClient();
  972. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  973. ////分开部署,就不需要,一站多用时,取消注释
  974. //if ($"{site}".Equals(BIConst.Global))
  975. //{
  976. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  977. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  978. //}
  979. var table = tableClient.GetTableReference("BIDDUserInfo");
  980. List<DingDingUserInfo> tempddUsers = null;
  981. List<DingDingUserInfo> ddUsers = new();
  982. StringBuilder tableSql = new();
  983. if (!string.IsNullOrEmpty($"{rowKey}"))
  984. tableSql.Append($"RowKey {QueryComparisons.Equal} '{rowKey}'");
  985. string tmdId = null;
  986. string tmdName = null;
  987. string tmdMobile = null;
  988. string mail = null;
  989. string picture = null;
  990. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{mobile}" } }, _option.Location, _configuration);
  991. if (coreUser != null && coreUser.id != null)
  992. {
  993. tmdId = coreUser.id;
  994. tmdName = coreUser.name;
  995. tmdMobile = coreUser.mobile;
  996. mail = coreUser.mail;
  997. picture = coreUser.picture;
  998. }else return Ok(new { state = 1, message = "该手机号未找到醍摩豆账户" });
  999. tempddUsers = await table.QueryWhereString<DingDingUserInfo>(tableSql.ToString());
  1000. if (tempddUsers.Count > 0)
  1001. {
  1002. foreach (var item in tempddUsers)
  1003. {
  1004. if (item.RowKey.Equals($"{rowKey}"))
  1005. {
  1006. item.tmdId = tmdId;
  1007. item.tmdName = tmdName;
  1008. item.tmdMobile = tmdMobile;
  1009. item.mail = mail;
  1010. item.picture = picture;
  1011. ddUsers.Add(item);
  1012. }
  1013. }
  1014. }
  1015. else return Ok(new { state = 2, message = "钉钉ID错误请检查钉钉ID" });
  1016. if (ddUsers.Count > 0) ddUsers = await table.SaveOrUpdateAll(ddUsers);
  1017. //保存操作记录
  1018. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{_tmdName}【{_tmdId}】操作:绑定钉钉账户[{rowKey}]和醍摩豆账户[{tmdId}]", _dingDing, httpContext: HttpContext);
  1019. return Ok(new { state = 200, ddUsers });
  1020. }
  1021. catch (Exception ex)
  1022. {
  1023. await _dingDing.SendBotMsg($"BI, {_option.Location} /tabledd/set-backenbind \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1024. return BadRequest();
  1025. }
  1026. }
  1027. /// <summary>
  1028. /// 后端初始化管理员
  1029. /// </summary>
  1030. /// <param name="jsonElement"></param>
  1031. /// <returns></returns>
  1032. [ProducesDefaultResponseType]
  1033. [HttpPost("set-apiphoneadmin")]
  1034. public async Task<IActionResult> SetPhoneAdmin(JsonElement jsonElement)
  1035. {
  1036. jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey);
  1037. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  1038. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  1039. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  1040. var partKey = _option.Location;
  1041. if (string.IsNullOrEmpty($"{partitionKey}"))
  1042. {
  1043. partKey = $"{partitionKey}";
  1044. };
  1045. var tableClient = _azureStorage.GetCloudTableClient();
  1046. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  1047. ////分开部署,就不需要,一站多用时,取消注释
  1048. //if ($"{site}".Equals(BIConst.Global))
  1049. //{
  1050. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  1051. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  1052. //}
  1053. var table = tableClient.GetTableReference("BIDDUserInfo");
  1054. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partKey}" }, { "mobile", $"{mobile}" } });
  1055. List<string> roles = new();//角色列表
  1056. List<string> permissions = new();//权限列表
  1057. StringBuilder msg = new();
  1058. foreach (var user in tempUser)
  1059. {
  1060. if (string.IsNullOrEmpty(user.roles))
  1061. {
  1062. user.roles = "admin";
  1063. }
  1064. List<string> tempRoles = new(user.roles.Split(","));
  1065. if (!tempRoles.Contains("admin"))
  1066. {
  1067. tempRoles.Add("admin");
  1068. }
  1069. user.roles = string.Join(",", tempRoles);
  1070. user.joinTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1071. DingDingUserInfo respUser = await table.SaveOrUpdate<DingDingUserInfo>(user);
  1072. if (respUser != null)
  1073. {
  1074. roles = !string.IsNullOrEmpty($"{respUser.roles}") ? new List<string>(respUser.roles.Split(",")) : new List<string>();
  1075. }
  1076. msg.Append($"初始将{respUser.name}【{respUser.RowKey}】账号的BI管理员");
  1077. }
  1078. //保存操作记录
  1079. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", msg.ToString(), _dingDing, httpContext: HttpContext);
  1080. return Ok(new { state = 200, roles });
  1081. }
  1082. /// <summary>
  1083. /// 解除钉钉和醍摩豆的绑定
  1084. /// </summary>
  1085. /// <param name="jsonElement"></param>
  1086. /// <returns></returns>
  1087. [ProducesDefaultResponseType]
  1088. [HttpPost("set-unbind")]
  1089. public async Task<IActionResult> SetUnbind(JsonElement jsonElement)
  1090. {
  1091. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  1092. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1093. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  1094. ////分开部署,就不需要,一站多用时,取消注释
  1095. //if ($"{site}".Equals(BIConst.Global))
  1096. // table = _azureStorage.GetCloudTableClient(BIConst.Global).GetTableReference("BIDDUserInfo");
  1097. //string divide = _configuration["CustomParam:SiteScope"];
  1098. string divide = _option.Location;
  1099. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
  1100. if (!string.IsNullOrEmpty($"{mobile}"))
  1101. dic.Add("tmdMobile", $"{mobile}");
  1102. else
  1103. dic.Add("tmdMobile", "18281911681");
  1104. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  1105. List<DingDingUserInfo> tempDDUI = new();
  1106. if (ddUserInfoList.Count > 0)
  1107. {
  1108. foreach (var item in ddUserInfoList)
  1109. {
  1110. item.tmdId = null;
  1111. item.tmdName = null;
  1112. item.tmdMobile = null;
  1113. item.picture = null;
  1114. tempDDUI.Add(item);
  1115. }
  1116. }
  1117. else return Ok(new { state = 404, msg = "未找到手机号匹配的绑定号码!,请检查手机号" });
  1118. var userInfos = await table.SaveOrUpdateAll(tempDDUI); //保存和修改至Table
  1119. return Ok(new { state = 200, userInfos });
  1120. }
  1121. /// <summary>
  1122. /// 查询钉钉待入职人员的ID添加至Table数据表中
  1123. /// </summary>
  1124. /// <returns></returns>
  1125. [ProducesDefaultResponseType]
  1126. [AuthToken(Roles = "admin,rdc")]
  1127. [HttpPost("set-ddinductionuser")]
  1128. public async Task<IActionResult> SetDingDingInductionUser(JsonElement jsonElement)
  1129. {
  1130. try
  1131. {
  1132. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1133. var tableClient = _azureStorage.GetCloudTableClient();
  1134. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  1135. ////分开部署,就不需要,一站多用时,取消注释
  1136. //if ($"{site}".Equals(BIConst.Global))
  1137. //{
  1138. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  1139. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  1140. //}
  1141. var table = tableClient.GetTableReference("BIDDUserInfo");
  1142. string appKey = _configuration["DingDingAuth:appKey"];
  1143. string appSecret = _configuration["DingDingAuth:appSecret"];
  1144. //string divide = _configuration["CustomParam:SiteScope"];
  1145. string divide = _option.Location;
  1146. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  1147. //获取access_token
  1148. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  1149. OapiGettokenRequest request = new() { Appkey = appKey, Appsecret = appSecret };
  1150. request.SetHttpMethod("Get");
  1151. OapiGettokenResponse response = client.Execute(request);
  1152. if (response.IsError)
  1153. {
  1154. return BadRequest();
  1155. }
  1156. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  1157. string access_token = response.AccessToken;
  1158. IDingTalkClient InductionClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querypreentry");
  1159. OapiSmartworkHrmEmployeeQuerypreentryRequest reqInduction = new() { Offset = 0L, Size = 50 };
  1160. reqInduction.SetHttpMethod("GET");
  1161. OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
  1162. if (rspInduction.Result.DataList != null)
  1163. {
  1164. List<DingDingUserInfo> ddUserInfos = new();
  1165. foreach (var itemId in rspInduction.Result.DataList)
  1166. {
  1167. DingDingUserInfo ddUserInfo = new();
  1168. ddUserInfo.PartitionKey = divide;
  1169. ddUserInfo.RowKey = itemId;
  1170. ddUserInfos.Add(ddUserInfo);
  1171. }
  1172. List<DingDingUserInfo> tempddUserInfos = await table.SaveAll(ddUserInfos);
  1173. //保存操作记录
  1174. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-add", $"{_tmdName}【{_tmdId}】添加待入职员工至table数据表中", _dingDing, httpContext: HttpContext);
  1175. if (ddUserInfos.Count == tempddUserInfos.Count)
  1176. return Ok(new { state = 200, UserInfo = tempddUserInfos });
  1177. else
  1178. {
  1179. var diffArr = tempddUserInfos.Where(c => !ddUserInfos.Contains(c)).ToList();
  1180. return Ok(new { state = 201, notUserInfo = diffArr });
  1181. }
  1182. }
  1183. else
  1184. return Ok(new { state = 400, rspInduction.SubErrCode, rspInduction.SubErrMsg });
  1185. }
  1186. catch (Exception ex)
  1187. {
  1188. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-ddinductionuser \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1189. return BadRequest();
  1190. }
  1191. }
  1192. /// <summary>
  1193. /// 获取钉钉离职人员ID并删除Table表中的数据
  1194. /// </summary>
  1195. /// <returns></returns>
  1196. [ProducesDefaultResponseType]
  1197. [AuthToken(Roles = "admin,rdc")]
  1198. [HttpPost("del-ddquituser")]
  1199. public async Task<IActionResult> DeleteDDQuitUser(JsonElement jsonElement)
  1200. {
  1201. try
  1202. {
  1203. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1204. var tableClient = _azureStorage.GetCloudTableClient();
  1205. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  1206. ////分开部署,就不需要,一站多用时,取消注释
  1207. //if ($"{site}".Equals(BIConst.Global))
  1208. //{
  1209. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  1210. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  1211. //}
  1212. var table = tableClient.GetTableReference("BIDDUserInfo");
  1213. string appKey = _configuration["DingDingAuth:appKey"];
  1214. string appSecret = _configuration["DingDingAuth:appSecret"];
  1215. //string divide = _configuration["CustomParam:SiteScope"];
  1216. string divide = _option.Location;
  1217. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  1218. //获取access_token
  1219. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  1220. OapiGettokenRequest request = new() { Appkey = appKey, Appsecret = appSecret };
  1221. request.SetHttpMethod("Get");
  1222. OapiGettokenResponse response = client.Execute(request);
  1223. if (response.IsError)
  1224. {
  1225. return BadRequest();
  1226. }
  1227. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  1228. string access_token = response.AccessToken;
  1229. IDingTalkClient quitStaffClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
  1230. OapiSmartworkHrmEmployeeQuerydimissionRequest reqDimission = new() { Offset = 0L, Size = 50L };
  1231. OapiSmartworkHrmEmployeeQuerydimissionResponse rspDimission = quitStaffClient.Execute(reqDimission, access_token);
  1232. if (rspDimission.Result != null)
  1233. {
  1234. List<DingDingUserInfo> ddUserInfos = new();
  1235. foreach (var itemId in rspDimission.Result.DataList)
  1236. {
  1237. await table.DeleteSingle<DingDingUserInfo>(divide, $"{itemId}");
  1238. }
  1239. //保存操作记录
  1240. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-del", $"{_tmdName}【{_tmdId}】从table数据表中删除离职员工", _dingDing, httpContext: HttpContext);
  1241. return Ok(new { state = 200 });
  1242. }
  1243. else
  1244. {
  1245. return Ok(new { state = rspDimission.SubErrCode });
  1246. }
  1247. }
  1248. catch (Exception ex)
  1249. {
  1250. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/del-ddquituser \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1251. return BadRequest();
  1252. }
  1253. }
  1254. /// <summary>
  1255. /// 依据人员信息唯一编码修改人员信息表中的醍摩豆id信息相关的事情。
  1256. /// </summary>
  1257. /// <param name="jsonElement"></param>
  1258. /// <returns></returns>
  1259. [ProducesDefaultResponseType]
  1260. [AuthToken(Roles = "admin")]
  1261. [HttpPost("set-usettmdinfo")]
  1262. public async Task<IActionResult> UpUserTmdInfo(JsonElement jsonElement)
  1263. {
  1264. try
  1265. {
  1266. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  1267. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partKey)) return BadRequest();
  1268. if (!jsonElement.TryGetProperty("rowKey", out JsonElement rowKey)) return BadRequest();
  1269. if (!jsonElement.TryGetProperty("role", out JsonElement role)) return BadRequest();
  1270. var cosmosClient = _azureCosmos.GetCosmosClient();
  1271. var tableClient = _azureStorage.GetCloudTableClient();
  1272. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  1273. var table = tableClient.GetTableReference("BIDDUserInfo");
  1274. StringBuilder msg = new($"{_tmdName}[{_tmdId}]将");
  1275. List<DingDingUserInfo> upUserInfos = new();
  1276. List<DDUserInfo> upUserInfo = new();
  1277. CoreUser coreUser = new();
  1278. string oldTmdId = null;
  1279. string reole = null;
  1280. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partKey}" }, { "RowKey", $"{rowKey}" } });
  1281. if (tempUser.Count > 0)
  1282. {
  1283. foreach (var item in tempUser)
  1284. {
  1285. oldTmdId = item.tmdId;
  1286. reole = item.roles;
  1287. coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{item.mobile}" } }, _option.Location, _configuration);
  1288. if (!string.IsNullOrEmpty(coreUser.id))
  1289. {
  1290. item.tmdId = coreUser.id;
  1291. item.tmdName = coreUser.name;
  1292. item.tmdMobile = coreUser.mobile;
  1293. item.picture = coreUser.picture;
  1294. item.mail = coreUser.mail;
  1295. msg.Append($"{item.name}的{item.tmdId}账号改为新的{coreUser.id}账号;");
  1296. upUserInfos.Add(item);
  1297. }
  1298. else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  1299. }
  1300. }
  1301. if (!string.IsNullOrEmpty(coreUser.id))
  1302. {
  1303. msg.Append("并将学校就的学校信息移植到新的账号,移植的学校:");
  1304. Teacher teacher = new();
  1305. var respone = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(coreUser.id, new PartitionKey("Base"));
  1306. if (respone.StatusCode == HttpStatusCode.OK)
  1307. {
  1308. using var json = await JsonDocument.ParseAsync(respone.Content);
  1309. teacher = json.ToObject<Teacher>();
  1310. }
  1311. else
  1312. {
  1313. teacher = new Teacher()
  1314. {
  1315. id = coreUser.id,
  1316. code = "Base",
  1317. name = coreUser.name,
  1318. picture = coreUser.picture,
  1319. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1320. };
  1321. }
  1322. List<Task<ItemResponse<BIRelation>>> scRole = new();
  1323. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<BIRelation>(queryText: $"select value(c) from c join a in c.assists join s in c.sales where c.code='BIRel' and s.id='{oldTmdId}' or a.id='{oldTmdId}'", requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
  1324. {
  1325. var tempAss = item.assists.Find(f => f.id.Equals($"{oldTmdId}"));
  1326. if (tempAss != null)
  1327. item.assists.Remove(tempAss);
  1328. var tempSa = item.sales.Find(f => f.id.Equals($"{oldTmdId}"));
  1329. if (tempSa != null)
  1330. item.sales.Remove(tempAss);
  1331. switch ($"{role}")
  1332. {
  1333. case "assist":
  1334. item.assists.Add(new IdInfo() { id = coreUser.id, name = coreUser.name, picture = coreUser.picture });
  1335. break;
  1336. case "sales":
  1337. item.sales.Add(new IdInfo() { id = coreUser.id, name = coreUser.name, picture = coreUser.picture });
  1338. break;
  1339. }
  1340. item.upDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1341. scRole.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<BIRelation>(item, item.id, new PartitionKey("BIRel")));
  1342. }
  1343. if (scRole.Count < 256)
  1344. await Task.WhenAll(scRole);
  1345. else
  1346. {
  1347. int pages = (scRole.Count + 255) / 256;
  1348. for (int i = 0; i < pages; i++)
  1349. {
  1350. List<Task<ItemResponse<BIRelation>>> tempScRole = scRole.Skip((i) * 256).Take(256).ToList();
  1351. await Task.WhenAll(tempScRole);
  1352. }
  1353. }
  1354. //List<Task<ItemResponse<SchoolTeacher>>> schoolTeachers = new();
  1355. //await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<SchoolTeacher>($"select value(c) from c where c.pk='Teacher' and c.id='{oldTmdId}'"))
  1356. //{
  1357. // item.id = coreUser.id;
  1358. // var resp = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{coreUser.id}", new PartitionKey($"{item.code}"));
  1359. // if (resp.Status == 200)
  1360. // {
  1361. // using var json = await JsonDocument.ParseAsync(resp.Content);
  1362. // SchoolTeacher scTeacher = json.ToObject<SchoolTeacher>();
  1363. // if (scTeacher.roles.Contains("sales"))
  1364. // scTeacher.roles.Remove("sales");
  1365. // if (scTeacher.roles.Contains("assist"))
  1366. // scTeacher.roles.Remove("assist");
  1367. // string scId = scTeacher.code.Substring(scTeacher.code.IndexOf("-") + 1);
  1368. // Teacher.TeacherSchool isExitId = null;
  1369. // isExitId = teacher.schools.Find(s => s.schoolId.Equals(scId));
  1370. // if (isExitId == null)
  1371. // {
  1372. // ScEasyInfo school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<ScEasyInfo>(scId, new PartitionKey("Base"));
  1373. // msg.Append($"{school.name}[{school.id}],");
  1374. // teacher.schools.Add(new Teacher.TeacherSchool() { schoolId = school.id, name = school.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = school.picture, areaId = school.areaId });
  1375. // }
  1376. // scTeacher.roles.Add(reole);
  1377. // schoolTeachers.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(scTeacher, scTeacher.id, new PartitionKey($"{scTeacher.code}")));
  1378. // }
  1379. // else
  1380. // {
  1381. // item.name = coreUser.name;
  1382. // string scId = item.code.Substring(item.code.IndexOf("-") + 1);
  1383. // Teacher.TeacherSchool isExitId = null;
  1384. // isExitId = teacher.schools.Find(s => s.schoolId.Equals(scId));
  1385. // if (isExitId == null)
  1386. // {
  1387. // ScEasyInfo school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<ScEasyInfo>(scId, new PartitionKey("Base"));
  1388. // msg.Append($"{school.name}[{school.id}],");
  1389. // teacher.schools.Add(new Teacher.TeacherSchool() { schoolId = school.id, name = school.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = school.picture, areaId = school.areaId });
  1390. // }
  1391. // schoolTeachers.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(item, new PartitionKey($"{item.code}")));
  1392. // }
  1393. //}
  1394. //if (schoolTeachers.Count < 256)
  1395. // await Task.WhenAll(schoolTeachers);
  1396. //else
  1397. //{
  1398. // int pages = (schoolTeachers.Count + 255) / 256;
  1399. // for (int i = 0; i < pages; i++)
  1400. // {
  1401. // List<Task<ItemResponse<SchoolTeacher>>> tempScTeachers = schoolTeachers.Skip((i) * 256).Take(256).ToList();
  1402. // await Task.WhenAll(tempScTeachers);
  1403. // }
  1404. //}
  1405. if (respone.StatusCode == HttpStatusCode.OK)
  1406. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  1407. else
  1408. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  1409. upUserInfos = await table.SaveOrUpdateAll<DingDingUserInfo>(upUserInfos);
  1410. }
  1411. //保存操作记录
  1412. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update-tmdinfo", msg.ToString(), _dingDing, httpContext: HttpContext);
  1413. foreach (var item in upUserInfos)
  1414. {
  1415. DDUserInfo tempUserInfo = new()
  1416. {
  1417. partitionKey = item.PartitionKey,
  1418. rowKey = item.RowKey,
  1419. userId = item.userId,
  1420. unionId = item.unionId,
  1421. name = item.name,
  1422. title = item.title,
  1423. stateCode = item.stateCode,
  1424. mobile = item.mobile,
  1425. jobNumber = item.jobNumber,
  1426. pid = item.pid,
  1427. deptId = item.deptId,
  1428. deptName = item.deptName,
  1429. depts = item.depts,
  1430. avatar = item.avatar,
  1431. isAdmin = item.isAdmin,
  1432. tmdId = item.tmdId,
  1433. tmdName = item.tmdName,
  1434. tmdMobile = item.tmdMobile,
  1435. mail = item.mail,
  1436. picture = item.picture,
  1437. roles = item.roles,
  1438. joinTime = item.joinTime,
  1439. isDisable = item.isDisable,
  1440. permissions = item.permissions,
  1441. handleRoles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>(),
  1442. handlePermissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>(),
  1443. };
  1444. if (!string.IsNullOrEmpty(item.schoolIds))
  1445. {
  1446. List<string> tempSchoolIds = new(item.schoolIds.Split("|"));
  1447. tempUserInfo.handleSchools = await SchoolWay.GetSchoolInfos(cosmosClient, tempSchoolIds);
  1448. }
  1449. upUserInfo.Add(tempUserInfo);
  1450. }
  1451. return Ok(new { state = RespondCode.Ok, upUserInfo });
  1452. }
  1453. catch (Exception ex)
  1454. {
  1455. await _dingDing.SendBotMsg($"BI,{_option.Location} /tabledd/set-usettmdinfo \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1456. return BadRequest();
  1457. }
  1458. }
  1459. /// <summary>
  1460. /// 获取钉钉用户信息
  1461. /// 并查询本地Table数据表中是否存在
  1462. /// </summary>
  1463. /// <param name="deptId"></param>
  1464. /// <param name="parentId"></param>
  1465. /// <param name="name"></param>
  1466. /// <param name="access_token"></param>
  1467. /// <returns></returns>
  1468. public async Task<List<DingDingUserInfo>> GetDingDingUserInfo(string partitionKey, long deptId, long parentId, string name, string access_token)
  1469. {
  1470. List<DingDingUserInfo> ddUserInfos = new();
  1471. //获取部门人员信息
  1472. IDingTalkClient userListClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
  1473. //long joinDate = DateTimeOffset.UtcNow.AddDays(-91).ToUnixTimeMilliseconds();
  1474. //获取部门用户
  1475. OapiV2UserListRequest reqUserList = new()
  1476. {
  1477. DeptId = deptId,
  1478. Cursor = 0L,
  1479. Size = 50L,
  1480. OrderField = "custom",
  1481. Language = "zh_CN"
  1482. };
  1483. reqUserList.SetHttpMethod("GET");
  1484. OapiV2UserListResponse rspV2UserList = userListClient.Execute(reqUserList, access_token);
  1485. if (rspV2UserList.Result.List != null)
  1486. {
  1487. foreach (var itemUser in rspV2UserList.Result.List)
  1488. {
  1489. //long isDisble = 0;
  1490. //if (!string.IsNullOrEmpty($"{itemUser.HiredDate}"))
  1491. //{
  1492. // if (itemUser.HiredDate < joinDate)
  1493. // isDisble = 1;
  1494. // else
  1495. // isDisble = 0;
  1496. //}
  1497. var tempInfo = ddUserInfos.Find(x => x.RowKey.Equals(itemUser.Unionid));
  1498. if (string.IsNullOrEmpty($"{tempInfo}"))
  1499. {
  1500. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  1501. var users = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "userId", $"{itemUser.Userid}" }, { "unionId", $"{itemUser.Unionid}" } });
  1502. if (users.Count > 0)
  1503. {
  1504. foreach (var user in users)
  1505. {
  1506. DingDingUserInfo ddUserInfo = new()
  1507. {
  1508. PartitionKey = user.PartitionKey,
  1509. RowKey = user.RowKey,
  1510. userId = itemUser.Userid,
  1511. unionId = itemUser.Unionid,
  1512. name = itemUser.Name,
  1513. email = itemUser.Email,
  1514. title = itemUser.Title,
  1515. stateCode = itemUser.StateCode,
  1516. mobile = itemUser.Mobile,
  1517. jobNumber = itemUser.JobNumber,
  1518. pid = parentId,
  1519. deptId = deptId,
  1520. deptName = name,
  1521. depts = string.Join(",", itemUser.DeptIdList.ToArray()),
  1522. avatar = itemUser.Avatar,
  1523. isAdmin = itemUser.Admin,
  1524. tmdId = user.tmdId,
  1525. tmdName = user.tmdName,
  1526. tmdMobile = user.tmdMobile,
  1527. mail = user.mail,
  1528. picture = user.picture,
  1529. roles = user.roles,
  1530. joinTime = user.joinTime,
  1531. permissions = user.permissions,
  1532. schoolIds = user.schoolIds,
  1533. isDisable = 1,
  1534. };
  1535. ddUserInfos.Add(ddUserInfo);
  1536. }
  1537. }
  1538. else
  1539. {
  1540. DingDingUserInfo ddUserInfo = new()
  1541. {
  1542. RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
  1543. userId = itemUser.Userid,
  1544. unionId = itemUser.Unionid,
  1545. name = itemUser.Name,
  1546. email = itemUser.Email,
  1547. title = itemUser.Title,
  1548. stateCode = itemUser.StateCode,
  1549. mobile = itemUser.Mobile,
  1550. jobNumber = itemUser.JobNumber,
  1551. pid = parentId,
  1552. deptId = deptId,
  1553. deptName = name,
  1554. depts = string.Join(",", itemUser.DeptIdList.ToArray()),
  1555. avatar = itemUser.Avatar,
  1556. isAdmin = itemUser.Admin,
  1557. PartitionKey = partitionKey,
  1558. tmdId = "",
  1559. tmdName = "",
  1560. tmdMobile = "",
  1561. mail = "",
  1562. picture = "",
  1563. roles = "",
  1564. joinTime = 0,
  1565. permissions = "areadata-read,areadata-upd,schooldata-read,schooldata-upd",
  1566. schoolIds = "",
  1567. isDisable = 0,
  1568. };
  1569. ddUserInfos.Add(ddUserInfo);
  1570. }
  1571. }
  1572. }
  1573. }
  1574. return ddUserInfos;
  1575. }
  1576. public record DDUserInfo
  1577. {
  1578. public string partitionKey { get; set; }
  1579. public string rowKey { get; set; }
  1580. public string userId { get; set; }
  1581. public string unionId { get; set; }
  1582. public string name { get; set; }
  1583. public string title { get; set; }
  1584. public string stateCode { get; set; }
  1585. public string mobile { get; set; }
  1586. public string jobNumber { get; set; }
  1587. public long pid { get; set; }
  1588. public long deptId { get; set; }
  1589. public string deptName { get; set; }
  1590. public string depts { get; set; }
  1591. public string avatar { get; set; }
  1592. public bool isAdmin { get; set; }
  1593. public string tmdId { get; set; }
  1594. public string tmdName { get; set; }
  1595. public string tmdMobile { get; set; }
  1596. public string mail { get; set; }
  1597. public string picture { get; set; }
  1598. public string roles { get; set; }
  1599. public long joinTime { get; set; }
  1600. public long isDisable { get; set; }
  1601. public string permissions { get; set; }
  1602. public List<string> handleRoles { get; set; }
  1603. public List<string> handlePermissions { get; set; }
  1604. public List<BaseInfo> handleSchools { get; set; } = new List<BaseInfo>();
  1605. }
  1606. }
  1607. }