TestController.cs 45 KB

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