TableDingDingInfoController.cs 92 KB

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