TestController.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  1. using Azure.Cosmos;
  2. using DingTalk.Api;
  3. using DingTalk.Api.Request;
  4. using DingTalk.Api.Response;
  5. using HTEXLib.COMM.Helpers;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.AspNetCore.Http;
  8. using Microsoft.AspNetCore.Mvc;
  9. using Microsoft.Azure.Cosmos.Table;
  10. using Microsoft.Extensions.Configuration;
  11. using Microsoft.Extensions.Options;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.ComponentModel.DataAnnotations;
  15. using System.Linq;
  16. using System.Text;
  17. using System.Text.Json;
  18. using System.Threading.Tasks;
  19. using TEAMModeBI.Filter;
  20. using TEAMModelOS.Models;
  21. using TEAMModelOS.SDK;//引用创建学校Code
  22. using TEAMModelOS.SDK.Context.Attributes.Azure;
  23. using TEAMModelOS.SDK.DI;
  24. using TEAMModelOS.SDK.Helper.Common.DateTimeHelper;
  25. using TEAMModelOS.SDK.Models;
  26. using TEAMModelOS.SDK.Models.Cosmos.BI;
  27. using TEAMModelOS.SDK.Models.Cosmos.Common;
  28. using TEAMModelOS.SDK.Models.Service;
  29. using TEAMModelOS.SDK.Models.Table;
  30. namespace TEAMModeBI.Controllers.BITest
  31. {
  32. [Route("apitest")]
  33. [ApiController]
  34. public class TestController : ControllerBase
  35. {
  36. private readonly AzureCosmosFactory _azureCosmos;
  37. private readonly DingDing _dingDing;
  38. private readonly Option _option;
  39. private readonly AzureStorageFactory _azureStorage;
  40. private readonly IWebHostEnvironment _environment; //读取文件
  41. //读取配置文件
  42. private readonly IConfiguration _configuration;
  43. public readonly string mobel = "测试接口";
  44. public TestController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IWebHostEnvironment hostingEnvironment, IConfiguration configuration)
  45. {
  46. _azureCosmos = azureCosmos;
  47. _dingDing = dingDing;
  48. _azureStorage = azureStorage;
  49. _option = option?.Value;
  50. _environment = hostingEnvironment;
  51. _configuration = configuration;
  52. }
  53. /// <summary>
  54. /// 查询学校
  55. /// </summary>
  56. /// <returns></returns>
  57. [ProducesDefaultResponseType]
  58. [HttpPost("get-school")]
  59. public async Task<IActionResult> GetSchools()
  60. {
  61. var cosmosClient = _azureCosmos.GetCosmosClient();
  62. List<School> schools = new List<School>();
  63. string sqltxt = $"select c.schoolCode,c.name,c.region,c.province,c.city,c.dist,c.areaId,c.standard,c.id from c ";
  64. await foreach (var itemSchool in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: sqltxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  65. {
  66. schools.Add(itemSchool);
  67. }
  68. return Ok(new { schools });
  69. }
  70. /// <summary>
  71. /// 测试接口
  72. /// </summary>
  73. /// <param name="foundSchools"></param>
  74. /// <returns></returns>
  75. [HttpPost("batch-createschoolcodetest")]
  76. public async Task<IActionResult> BatchCreateSchoolCodeTest(FoundSchools foundSchools)
  77. {
  78. try
  79. {
  80. List<BISchool> schools = new List<BISchool>();
  81. if (foundSchools.biSchools.Count > 0)
  82. {
  83. var cosmosClient = _azureCosmos.GetCosmosClient();
  84. foreach (BISchool bischool in foundSchools.biSchools)
  85. {
  86. var schoolStatus = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{bischool.id}", new PartitionKey($"Base"));
  87. if (schoolStatus.Status == 200)
  88. {
  89. schools.Add(bischool);
  90. }
  91. else
  92. {
  93. List<Period> periods = new List<Period>();
  94. string campusId = Guid.NewGuid().ToString();
  95. bischool.period.ForEach(x =>
  96. {
  97. periods.Add(new Period
  98. {
  99. id = Guid.NewGuid().ToString(),
  100. name = x,
  101. campusId = campusId,
  102. semesters = new List<Semester>() {
  103. new Semester { name = "上学期", start = 0, month = 3, day = 1, id = Guid.NewGuid().ToString() },
  104. new Semester { name = "下学期", start = 1, month = 8, day = 1, id = Guid.NewGuid().ToString() }
  105. }
  106. });
  107. });
  108. CreateSchoolCode createSchool = new CreateSchoolCode
  109. {
  110. province = bischool.province,
  111. id = bischool.id,
  112. name = bischool.name,
  113. city = bischool.city,
  114. aname = bischool.name
  115. };
  116. //JsonElement jsonElement = createSchool;
  117. //dynamic data = await SchoolService.GenerateSchoolCode(jsonElement, _dingDing, _environment);
  118. School upSchool = new School
  119. {
  120. id = bischool.id,
  121. name = bischool.name,
  122. size = bischool.size,
  123. code = "Base",
  124. campuses = new List<Campus> { new Campus { name = bischool.name, id = campusId } },
  125. region = bischool.region,
  126. province = bischool.province,
  127. city = bischool.city,
  128. dist = bischool.dist,
  129. address = bischool.address,
  130. picture = "https://teammodelstorage.blob.core.chinacloudapi.cn/0-public/school/bbf54fb3-3fc8-43ae-a358-107281c174cc.png",
  131. timeZone = new TEAMModelOS.SDK.Models.TimeZone { label = "(UTC+08:00) 北京,重庆,香港特别行政区,乌鲁木齐", value = "+08:00" },
  132. type = 2,
  133. pk = "School",
  134. ttl = -1,
  135. schoolCode = bischool.id,
  136. period = periods
  137. };
  138. }
  139. }
  140. }
  141. if (schools.Count > 0)
  142. return Ok(new { state = 201, message = "已有部分学校批量创建成功;学校编号已经重复!请检查学校编号!", schools = schools });
  143. else
  144. return Ok(new { state = 200, message = "批量创校已全部完成" });
  145. }
  146. catch (Exception ex)
  147. {
  148. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/batch-school \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  149. return BadRequest();
  150. }
  151. }
  152. /// <summary>
  153. /// 测试接口
  154. /// </summary>
  155. /// <param name="jsonElement"></param>
  156. /// <returns></returns>
  157. [ProducesDefaultResponseType]
  158. [HttpPost("get-schoolcode")]
  159. public async Task<IActionResult> GetTest(JsonElement jsonElement)
  160. {
  161. //string data = await SchoolCode.GenerateSchoolCode(jsonElement, _dingDing, _environment).ToString();
  162. CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo();
  163. createSchoolInfo.province = "四川省";
  164. createSchoolInfo.id = "tmdplc";
  165. createSchoolInfo.name = "醍摩豆批量创校学校";
  166. createSchoolInfo.city = "成都市";
  167. createSchoolInfo.aname = "";
  168. createSchoolInfo.createCount = 0;
  169. //Random random = new Random();
  170. ////随机小写字母
  171. //int a = random.Next(0, 26);
  172. //char ch = (char)('a' + a);
  173. //string Number = GenerateRandom.Number(1);
  174. //string Number1 = GenerateRandom.Number(1, true);
  175. //string Str = GenerateRandom.Str(1);
  176. //string Str1 = GenerateRandom.Str(1, true);
  177. //string Str_char = GenerateRandom.Str_char(1);
  178. //string Str_char1 = GenerateRandom.Str_char(1, true);
  179. CreateSchoolInfo data = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  180. string temp = null;
  181. return Ok(new { state = 200, data, data.id });
  182. }
  183. /// <summary>
  184. /// 批量创校
  185. /// </summary>
  186. /// <param name="school"></param>
  187. /// <returns></returns>
  188. [ProducesDefaultResponseType]
  189. [HttpPost("batch-school")]
  190. public async Task<IActionResult> BatchCreateSchool(FoundSchools foundSchools)
  191. {
  192. try
  193. {
  194. List<BISchool> schools = new List<BISchool>();
  195. StringBuilder stringBuilder = new StringBuilder($"{foundSchools.tmdName}【{foundSchools.tmdId}】操作了批量创校功能;");
  196. List<School> tempSchools = new List<School>();
  197. if (foundSchools.biSchools.Count > 0)
  198. {
  199. var cosmosClient = _azureCosmos.GetCosmosClient();
  200. foreach (BISchool bischool in foundSchools.biSchools)
  201. {
  202. CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo()
  203. {
  204. province = bischool.province,
  205. id = "",
  206. name = bischool.name,
  207. city = bischool.city,
  208. aname = "",
  209. createCount = 0,
  210. };
  211. createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  212. var schoolStatus = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
  213. bool isExist = false;
  214. if (schoolStatus.Status == 200)
  215. {
  216. createSchoolInfo.createCount = 1;
  217. createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  218. var schoolStatu1 = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
  219. if (schoolStatu1.Status == 200)
  220. {
  221. createSchoolInfo.createCount = 2;
  222. createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  223. var schoolStatu2 = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
  224. if (schoolStatu2.Status == 200)
  225. {
  226. createSchoolInfo.createCount = 3;
  227. createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  228. isExist = true;
  229. }
  230. while (isExist)
  231. {
  232. createSchoolInfo.createCount = 3;
  233. createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  234. var schoolStatu3 = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
  235. if (schoolStatu3.Status == 200)
  236. isExist = true;
  237. else isExist = false;
  238. }
  239. }
  240. }
  241. if (createSchoolInfo.id != null)
  242. {
  243. List<Period> periods = new List<Period>();
  244. string campusId = Guid.NewGuid().ToString();
  245. bischool.period.ForEach(x =>
  246. {
  247. periods.Add(new Period
  248. {
  249. id = Guid.NewGuid().ToString(),
  250. name = x,
  251. campusId = campusId,
  252. semesters = new List<Semester>() {
  253. new Semester { name = "上学期", start = 0, month = 3, day = 1, id = Guid.NewGuid().ToString() },
  254. new Semester { name = "下学期", start = 1, month = 8, day = 1, id = Guid.NewGuid().ToString() }
  255. }
  256. });
  257. });
  258. School upSchool = new School
  259. {
  260. id = createSchoolInfo.id,
  261. name = bischool.name,
  262. size = bischool.size,
  263. code = "Base",
  264. campuses = new List<Campus> { new Campus { name = bischool.name, id = campusId } },
  265. region = bischool.region,
  266. province = bischool.province,
  267. city = bischool.city,
  268. dist = bischool.dist,
  269. address = bischool.address,
  270. picture = "https://teammodelstorage.blob.core.chinacloudapi.cn/0-public/school/bbf54fb3-3fc8-43ae-a358-107281c174cc.png",
  271. timeZone = new TEAMModelOS.SDK.Models.TimeZone { label = "(UTC+08:00) 北京,重庆,香港特别行政区,乌鲁木齐", value = "+08:00" },
  272. type = 2,
  273. pk = "School",
  274. ttl = -1,
  275. schoolCode = createSchoolInfo.id,
  276. period = periods
  277. };
  278. stringBuilder.Append($"创建学校:{upSchool.name}【{upSchool.id}】");
  279. tempSchools.Add(upSchool);
  280. //创建学校
  281. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<School>(upSchool, new PartitionKey(upSchool.code));
  282. Teacher teacher = null;
  283. try
  284. {
  285. //查询该教师是否存在
  286. teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>($"{bischool.admin}", new PartitionKey("Base"));
  287. }
  288. catch
  289. {
  290. }
  291. if (teacher != null)
  292. {
  293. //教师存在,在该教师信息中添加要管理的学校信息
  294. teacher.schools.Add(new Teacher.TeacherSchool { schoolId = createSchoolInfo.id, name = bischool.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
  295. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, bischool.admin, new PartitionKey("Base"));
  296. SchoolTeacher schoolTeacher = new SchoolTeacher
  297. {
  298. id = bischool.admin,
  299. code = $"Teacher-{createSchoolInfo.id}",
  300. roles = new List<string> { "admin", "teacher" },
  301. job = "管理员",
  302. name = teacher.name,
  303. picture = teacher.picture,
  304. status = "join",
  305. createTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
  306. pk = "Teacher",
  307. ttl = -1
  308. };
  309. stringBuilder.Append($"教师信息:{schoolTeacher.name}【{schoolTeacher.id}】,教师权限:{schoolTeacher.roles.ToString()}");
  310. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey(schoolTeacher.code));
  311. }
  312. else
  313. {
  314. //不存在 新建教师和新建要管理的学校信息
  315. Teacher addteacher = new Teacher
  316. {
  317. id = bischool.admin,
  318. pk = "Base",
  319. code = "Base",
  320. name = $"{bischool.name}-管理员"?.ToString(),
  321. picture = "",
  322. //创建账号并第一次登录IES5则默认赠送1G
  323. size = 1,
  324. defaultSchool = createSchoolInfo.id,
  325. schools = new List<Teacher.TeacherSchool>() { new Teacher.TeacherSchool { schoolId = createSchoolInfo.id, name = bischool.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() } }
  326. };
  327. stringBuilder.Append($"没有该教师信息创建的教师信息:{addteacher.name}【{addteacher.id}】");
  328. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(addteacher, new PartitionKey("Base"));
  329. SchoolTeacher schoolTeacher = new SchoolTeacher
  330. {
  331. id = bischool.admin,
  332. code = $"Teacher-{bischool.id}",
  333. roles = new List<string> { "admin", "teacher" },
  334. job = "管理员",
  335. name = bischool.admin,
  336. picture = "",
  337. status = "join",
  338. createTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
  339. pk = "Teacher",
  340. ttl = -1
  341. };
  342. stringBuilder.Append($"教师权限:{schoolTeacher.roles}");
  343. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey(schoolTeacher.code));
  344. }
  345. }
  346. }
  347. }
  348. else return Ok(new { state = 1, message = "创校信息为空" });
  349. //保存操作记录
  350. await _azureStorage.SaveLog("operatelog-del", stringBuilder?.ToString(), _dingDing, httpContext: HttpContext);
  351. if (schools.Count > 0)
  352. return Ok(new { state = 201, message = "已有部分学校批量创建成功;学校编号已经重复!请检查学校编号!", schools = schools });
  353. else
  354. return Ok(new { state = 200, message = "批量创校已全部完成", tempSchools });
  355. }
  356. catch (Exception ex)
  357. {
  358. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/batch-school \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  359. return BadRequest();
  360. }
  361. }
  362. [HttpPost("file-table")]
  363. public async Task<IActionResult> SaveTable(JsonElement jsonElement)
  364. {
  365. jsonElement.TryGetProperty("single", out JsonElement single);
  366. jsonElement.TryGetProperty("startDate", out JsonElement startDate);
  367. jsonElement.TryGetProperty("endDate", out JsonElement endDate);
  368. jsonElement.TryGetProperty("platform", out JsonElement platform);
  369. List<string> strlist = new List<string>();
  370. if (!string.IsNullOrEmpty($"{single}"))
  371. strlist.Add($"RowKey {QueryComparisons.Equal} {single}");
  372. if (!string.IsNullOrEmpty($"{startDate}"))
  373. strlist.Add($"RowKey {QueryComparisons.GreaterThanOrEqual} {startDate}");
  374. if (!string.IsNullOrEmpty($"{endDate}"))
  375. strlist.Add($"RowKey {QueryComparisons.LessThanOrEqual} {endDate}");
  376. if (!string.IsNullOrEmpty($"{platform}"))
  377. strlist.Add($"platform {QueryComparisons.Equal} {platform}");
  378. string sql = string.Join(" and ", strlist);
  379. var temp = _azureStorage.QueryWhereString<OptLog>(sql);
  380. return Ok(new { state = 200, temp });
  381. }
  382. /// <summary>
  383. /// 查询BI操作记录
  384. /// </summary>
  385. /// <param name="jsonElement"></param>
  386. /// <returns></returns>
  387. [HttpPost("get-operatelogbydate")]
  388. public async Task<IActionResult> GetOperateLogByDate(JsonElement jsonElement)
  389. {
  390. try
  391. {
  392. jsonElement.TryGetProperty("single", out JsonElement single);
  393. jsonElement.TryGetProperty("startDate", out JsonElement startDate);
  394. jsonElement.TryGetProperty("endDate", out JsonElement endDate);
  395. jsonElement.TryGetProperty("platform", out JsonElement platform);
  396. List<OptLog> operateLogs = null;
  397. StringBuilder tableSql = new StringBuilder();
  398. if (!string.IsNullOrEmpty($"{single}"))
  399. tableSql.Append($"RowKey {QueryComparisons.Equal} '{single}' ");
  400. if (!string.IsNullOrEmpty($"{startDate}"))
  401. tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} RowKey {QueryComparisons.GreaterThanOrEqual} '{startDate}' " : $"RowKey {QueryComparisons.GreaterThanOrEqual} '{startDate}' ");
  402. if (!string.IsNullOrEmpty($"{endDate}"))
  403. tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} RowKey {QueryComparisons.LessThanOrEqual} '{endDate}' " : $" RowKey { QueryComparisons.LessThanOrEqual} '{endDate}' ");
  404. if (!string.IsNullOrEmpty($"{platform}"))
  405. tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} platform {QueryComparisons.Equal} '{platform}' " : $" platform {QueryComparisons.Equal} '{platform}' ");
  406. operateLogs = await _azureStorage.QueryWhereString<OptLog>(tableSql.ToString());
  407. return Ok(new { state = 200, operateLogs });
  408. }
  409. catch (Exception ex)
  410. {
  411. await _dingDing.SendBotMsg($"BI,{_option.Location} /operatelog/get-operatelogbydate {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  412. return BadRequest();
  413. }
  414. }
  415. /// <summary>
  416. /// 查询离职信息
  417. /// </summary>
  418. /// <returns></returns>
  419. [ProducesDefaultResponseType]
  420. [HttpPost("quitstaff")]
  421. public async Task<IActionResult> QuitStaff()
  422. {
  423. try
  424. {
  425. string appKey = _configuration["DingDingAuth:appKey"];
  426. string appSecret = _configuration["DingDingAuth:appSecret"];
  427. string agentld = _configuration["DingDingAuth:Agentld"];
  428. //获取access_token
  429. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  430. OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  431. request.SetHttpMethod("Get");
  432. OapiGettokenResponse response = client.Execute(request);
  433. if (response.IsError)
  434. {
  435. return BadRequest();
  436. }
  437. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  438. string access_token = response.AccessToken;
  439. List<string> datalist = new List<string>();
  440. IDingTalkClient quitStaffClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
  441. OapiSmartworkHrmEmployeeQuerydimissionRequest reqDimission = new OapiSmartworkHrmEmployeeQuerydimissionRequest() { Offset = 0L, Size = 50L };
  442. OapiSmartworkHrmEmployeeQuerydimissionResponse rspDimission = quitStaffClient.Execute(reqDimission, access_token);
  443. if (rspDimission.SubErrCode == "60011")
  444. {
  445. return Ok(new { state = 60011, message = "没有调用该接口的权限!" });
  446. }
  447. else if (rspDimission.Result != null)
  448. {
  449. datalist = rspDimission.Result.DataList;
  450. return Ok(new { state = 200, datalist = datalist });
  451. }
  452. else
  453. {
  454. return Ok(new { state = rspDimission.SubErrCode, message = rspDimission.Errmsg });
  455. }
  456. }
  457. catch (Exception ex)
  458. {
  459. return BadRequest();
  460. }
  461. }
  462. /// <summary>
  463. /// 测试获取待入职人员的userId接口
  464. /// </summary>
  465. /// <returns></returns>
  466. [ProducesDefaultResponseType]
  467. [HttpPost("Induction")]
  468. public async Task<IActionResult> Induction()
  469. {
  470. try
  471. {
  472. string appKey = _configuration["DingDingAuth:appKey"];
  473. string appSecret = _configuration["DingDingAuth:appSecret"];
  474. string agentld = _configuration["DingDingAuth:Agentld"];
  475. //获取access_token
  476. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  477. OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  478. request.SetHttpMethod("Get");
  479. OapiGettokenResponse response = client.Execute(request);
  480. if (response.IsError)
  481. {
  482. return BadRequest();
  483. }
  484. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  485. string access_token = response.AccessToken;
  486. IDingTalkClient InductionClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querypreentry");
  487. OapiSmartworkHrmEmployeeQuerypreentryRequest reqInduction = new OapiSmartworkHrmEmployeeQuerypreentryRequest() { Offset = 0L, Size = 50 };
  488. reqInduction.SetHttpMethod("GET");
  489. OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
  490. if (rspInduction.Result.DataList != null)
  491. {
  492. foreach (var itemId in rspInduction.Result.DataList)
  493. {
  494. IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  495. OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
  496. {
  497. Userid = itemId,
  498. Language = "zh_CN"
  499. };
  500. OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
  501. }
  502. return Ok(new { state = 200, rspInduction.Result.DataList });
  503. }
  504. else
  505. {
  506. return Ok(new { state = 400, rspInduction.SubErrCode, rspInduction.SubErrMsg });
  507. }
  508. }
  509. catch (Exception ex)
  510. {
  511. return BadRequest();
  512. }
  513. }
  514. /// <summary>
  515. /// 分页
  516. /// </summary>
  517. /// <returns></returns>
  518. [HttpPost("get-testpage")]
  519. public async Task<IActionResult> GetTestPage()
  520. {
  521. List<string> st = new List<string> { { "1-23" }, { "2-022" }, { "3-ijjis" }, { "4-ssss" }, { "5-02rrr2" }, { "6-00srr22" }, { "7-002sr2" }, { "8-00s2srg2" }, { "9-0022ssgf" }, { "10-0ssa022" }, { "11-002saf2" }, { "12-0022" } };
  522. List<pageTest> pageTests = new List<pageTest>();
  523. List<pageTest1> pageTests1 = new List<pageTest1>();
  524. foreach (var item in st)
  525. {
  526. int i = 0;
  527. pageTest pageTest = new pageTest();
  528. pageTest.keyt = $"分页{i}";
  529. pageTest.listv = item;
  530. pageTests.Add(pageTest);
  531. i += 1;
  532. }
  533. for (int i = 0; i < st.Count; i++)
  534. {
  535. pageTest1 pageTest = new pageTest1();
  536. pageTest.keyt = $"分页{i}";
  537. pageTest.listv = st.Skip(i).Take(1).ToList();
  538. pageTests1.Add(pageTest);
  539. }
  540. return Ok(new { pageTests1 });
  541. }
  542. /// <summary>
  543. /// 删除册别,删除章节
  544. /// </summary>
  545. /// <param name="jsonElement"></param>
  546. /// <returns></returns>
  547. [HttpPost("del-standard")]
  548. public async Task<IActionResult> DelStandard(JsonElement jsonElement)
  549. {
  550. if (!jsonElement.TryGetProperty("oldStandard", out JsonElement _oldStandard)) return BadRequest();
  551. var cosmosClient = _azureCosmos.GetCosmosClient();
  552. List<string> abilityIds = new List<string>(); //册别的ID集合
  553. //查询册别信息
  554. await foreach (var tempAbility in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Ability>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Ability-{_oldStandard}") }))
  555. {
  556. abilityIds.Add(tempAbility.id); //查询出来册别ID添加册别ID集合
  557. }
  558. //删除册别
  559. if (abilityIds.IsNotEmpty())
  560. {
  561. //var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityIds, $"Ability-{_oldStandard}");
  562. }
  563. List<string> abilityTaskIds = new List<string>(); //章节ID集合
  564. foreach (var abilityId in abilityIds)
  565. {
  566. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AbilityTask>(queryText: $"select value(c) from c where c.abilityId='{abilityId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilityTask-{_oldStandard}") }))
  567. {
  568. abilityTaskIds.Add(item.id); //查询出来的章节信息ID添加到战绩集合
  569. }
  570. }
  571. //删除章节
  572. if (abilityTaskIds.IsNotEmpty())
  573. {
  574. //var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityTaskIds, $"AbilityTask-{_oldStandard}");
  575. }
  576. return Ok(new { state = 200 });
  577. }
  578. /// <summary>
  579. /// 保存日志文件
  580. /// </summary>
  581. /// <returns></returns>
  582. [AuthToken(Roles = "assist")]
  583. [HttpPost("save-tablelog")]
  584. public async Task<IActionResult> SaveTableLogTest()
  585. {
  586. //await OperateLogHelper.SaveTableLog(_azureStorage, "BI", "1636016499", "彭礼", "测试保存方法", "table-save", "save-tablelog");
  587. await _azureStorage.SaveLog(type:"table-save", msg:"测试保存方法01",dingDing: _dingDing,httpContext:HttpContext);
  588. return Ok(123);
  589. }
  590. [HttpPost("get-test")]
  591. public async Task<IActionResult> test(JsonElement jsonElement)
  592. {
  593. var cosmosClient = _azureCosmos.GetCosmosClient();
  594. List<LessonCount> scount = new List<LessonCount>();
  595. List<lessons> lessonCounts = new List<lessons>();
  596. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS,"School").GetItemQueryIterator<LessonCount>(queryText:$"select value(c) from c where c.pk='LessonCount'",requestOptions:new QueryRequestOptions() { }))
  597. {
  598. lessons le = new lessons() {
  599. countB =item.beginCount.Count,
  600. countP = item.pCount.Count,
  601. countT = item.tCount.Count,
  602. countPT = item.ptCount.Count,
  603. lesson = item
  604. };
  605. lessonCounts.Add(le);
  606. }
  607. return Ok(new { state = 200 , lessonCounts });
  608. }
  609. public record lessons
  610. {
  611. public long countB { get; set; }
  612. public long countP { get; set; }
  613. public long countT { get; set; }
  614. public long countPT { get; set; }
  615. public LessonCount lesson { get; set; }
  616. }
  617. public record pageTest
  618. {
  619. public string keyt { get; set; }
  620. public string listv { get; set; }
  621. }
  622. public record pageTest1
  623. {
  624. public string keyt { get; set; }
  625. public List<string> listv { get; set; }
  626. }
  627. [HttpPost("tablesavetestlist")]
  628. public async Task<IActionResult> cares()
  629. {
  630. List<string> temp = new List<string>() { { "123456" }, { "123456" } };
  631. StringBuilder stringBuilder = new StringBuilder();
  632. temp.ForEach(p => { stringBuilder.Append(p).Append(","); });
  633. List<SaveTestList> saveTestLists = new List<SaveTestList>();
  634. SaveTestList saveTestList = new SaveTestList();
  635. saveTestList.PartitionKey = "TestJose";
  636. saveTestList.RowKey = "1640762925550";
  637. saveTestList.name = "前台";
  638. saveTestList.sex = "男";
  639. saveTestList.dept = "行政部";
  640. saveTestList.describe = "你好我是行政部的前台的1640762925550";
  641. saveTestLists.Add(saveTestList);
  642. var temp1 = await _azureStorage.SaveOrUpdateAll<SaveTestList>(saveTestLists);
  643. return Ok(new { state = 200, temp1 });
  644. }
  645. [TableName(Name = ("BITestTable"))]
  646. public class SaveTestList : TableEntity
  647. {
  648. public string name { get; set; }
  649. public string sex { get; set; }
  650. public string dept { get; set; }
  651. public string describe { get; set; }
  652. [Range(-100,+200)]
  653. public double min { get; set; }
  654. }
  655. public class GenerateRandom
  656. {
  657. /// <summary>
  658. /// 生成随机数字
  659. /// </summary>
  660. /// <param name="length">生成长度</param>
  661. /// <returns></returns>
  662. public static string Number(int Length)
  663. {
  664. return Number(Length, false);
  665. }
  666. /// <summary>
  667. /// 生成随机数字
  668. /// </summary>
  669. /// <param name="Length">生成长度</param>
  670. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  671. /// <returns></returns>
  672. public static string Number(int Length, bool Sleep)
  673. {
  674. if (Sleep)
  675. System.Threading.Thread.Sleep(3);
  676. string result = "";
  677. System.Random random = new Random();
  678. for (int i = 0; i < Length; i++)
  679. {
  680. result += random.Next(10).ToString();
  681. }
  682. return result;
  683. }
  684. /// <summary>
  685. /// 生成随机字母与数字
  686. /// </summary>
  687. /// <param name="IntStr">生成长度</param>
  688. /// <returns></returns>
  689. public static string Str(int Length)
  690. {
  691. return Str(Length, false);
  692. }
  693. /// <summary>
  694. /// 生成随机字母与数字
  695. /// </summary>
  696. /// <param name="Length">生成长度</param>
  697. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  698. /// <returns></returns>
  699. public static string Str(int Length, bool Sleep)
  700. {
  701. if (Sleep)
  702. System.Threading.Thread.Sleep(3);
  703. char[] Pattern = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
  704. string result = "";
  705. int n = Pattern.Length;
  706. System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
  707. for (int i = 0; i < Length; i++)
  708. {
  709. int rnd = random.Next(0, n);
  710. result += Pattern[rnd];
  711. }
  712. return result;
  713. }
  714. /// <summary>
  715. /// 生成随机纯字母随机数
  716. /// </summary>
  717. /// <param name="IntStr">生成长度</param>
  718. /// <returns></returns>
  719. public static string Str_char(int Length)
  720. {
  721. return Str_char(Length, false);
  722. }
  723. /// <summary>
  724. /// 生成随机纯字母随机数
  725. /// </summary>
  726. /// <param name="Length">生成长度</param>
  727. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  728. /// <returns></returns>
  729. public static string Str_char(int Length, bool Sleep)
  730. {
  731. if (Sleep) System.Threading.Thread.Sleep(3);
  732. //char[] Pattern = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
  733. char[] Pattern = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
  734. string result = "";
  735. int n = Pattern.Length;
  736. System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
  737. for (int i = 0; i < Length; i++)
  738. {
  739. int rnd = random.Next(0, n);
  740. result += Pattern[rnd];
  741. }
  742. return result;
  743. }
  744. }
  745. public class TableBatchHelper<T> where T : ITableEntity
  746. {
  747. const int batchMaxSize = 100;
  748. public static IEnumerable<TableBatchOperation> GetBatchesForDelete(IEnumerable<T> items)
  749. {
  750. var list = new List<TableBatchOperation>();
  751. var partitionGroups = items.GroupBy(arg => arg.PartitionKey).ToArray();
  752. foreach (var group in partitionGroups)
  753. {
  754. T[] groupList = group.ToArray();
  755. int offSet = batchMaxSize;
  756. T[] entities = groupList.Take(offSet).ToArray();
  757. while (entities.Any())
  758. {
  759. var tableBatchOperation = new TableBatchOperation();
  760. foreach (var entity in entities)
  761. {
  762. tableBatchOperation.Add(TableOperation.Delete(entity));
  763. }
  764. list.Add(tableBatchOperation);
  765. entities = groupList.Skip(offSet).Take(batchMaxSize).ToArray();
  766. offSet += batchMaxSize;
  767. }
  768. }
  769. return list;
  770. }
  771. public static async Task BatchDeleteAsync(CloudTable table, IEnumerable<T> items)
  772. {
  773. var batches = GetBatchesForDelete(items);
  774. await Task.WhenAll(batches.Select(table.ExecuteBatchAsync));
  775. }
  776. private async Task DeleteAllRows<T>(string table, CloudTableClient client) where T : ITableEntity, new()
  777. {
  778. // query all rows
  779. CloudTable tableref = client.GetTableReference(table);
  780. var query = new TableQuery<T>();
  781. TableContinuationToken token = null;
  782. var result = await tableref.ExecuteQuerySegmentedAsync(query, token);
  783. do
  784. {
  785. foreach (var row in result)
  786. {
  787. TableOperation.Delete(row);
  788. }
  789. } while (token != null);
  790. }
  791. }
  792. public record CreateSchoolCode
  793. {
  794. public string province { get; set; }
  795. public string id { get; set; }
  796. public string name { get; set; }
  797. public string city { get; set; }
  798. public string aname { get; set; }
  799. }
  800. /// <summary>
  801. /// 创建多个学校实体
  802. /// </summary>
  803. public record FoundSchools()
  804. {
  805. /// <summary>
  806. ///醍摩豆账户ID
  807. /// </summary>
  808. public string tmdId { get; set; }
  809. /// <summary>
  810. /// 醍摩豆账户名称
  811. /// </summary>
  812. public string tmdName { get; set; }
  813. /// <summary>
  814. /// 批量创校的数据结构
  815. /// </summary>
  816. public List<BISchool> biSchools { get; set; } = new List<BISchool>();
  817. }
  818. /// <summary>
  819. /// 批量创校的数据结构
  820. /// </summary>
  821. public record BISchool()
  822. {
  823. /// <summary>
  824. /// 学校ID
  825. /// </summary>
  826. public string id { get; set; }
  827. /// <summary>
  828. /// 学校名称
  829. /// </summary>
  830. public string name { get; set; }
  831. /// <summary>
  832. /// 学校管理员
  833. /// </summary>
  834. public string admin { get; set; }
  835. /// <summary>
  836. /// 学校的学段
  837. /// </summary>
  838. public List<string> period { get; set; }
  839. /// <summary>
  840. /// 学校空间大小
  841. /// </summary>
  842. public int size { get; set; }
  843. /// <summary>
  844. /// 地区
  845. /// </summary>
  846. public string region { get; set; }
  847. /// <summary>
  848. /// 省份
  849. /// </summary>
  850. public string province { get; set; }
  851. /// <summary>
  852. /// 城市
  853. /// </summary>
  854. public string city { get; set; }
  855. /// <summary>
  856. /// 县,区,郡
  857. /// </summary>
  858. public string dist { get; set; }
  859. /// <summary>
  860. /// 学校详细地址
  861. /// </summary>
  862. public string address { get; set; }
  863. }
  864. }
  865. }