TableDingDingInfoController.cs 97 KB

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