1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018 |
- using Azure.Cosmos;
- using DingTalk.Api;
- using DingTalk.Api.Request;
- using DingTalk.Api.Response;
- using HTEXLib.COMM.Helpers;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Azure.Cosmos.Table;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelBI.Filter;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK;//引用创建学校Code
- using TEAMModelOS.SDK.Context.Attributes.Azure;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Helper.Common.DateTimeHelper;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos.BI;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Models.Table;
- namespace TEAMModelBI.Controllers.BITest
- {
- [Route("apitest")]
- [ApiController]
- public class TestController : ControllerBase
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureStorageFactory _azureStorage;
- private readonly IWebHostEnvironment _environment; //读取文件
- //读取配置文件
- private readonly IConfiguration _configuration;
- public readonly string mobel = "测试接口";
- public TestController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IWebHostEnvironment hostingEnvironment, IConfiguration configuration)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _azureStorage = azureStorage;
- _option = option?.Value;
- _environment = hostingEnvironment;
- _configuration = configuration;
- }
- /// <summary>
- /// 删除册别,删除章节 创区
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("del-standard")]
- public async Task<IActionResult> DelStandard(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("oldStandard", out JsonElement _oldStandard)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<string> abilityIds = new List<string>(); //册别的ID集合
- //查询册别信息
- 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}") }))
- {
- abilityIds.Add(tempAbility.id); //查询出来册别ID添加册别ID集合
- }
- //删除册别
- if (abilityIds.IsNotEmpty())
- {
- var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityIds, $"Ability-{_oldStandard}");
- }
- List<string> abilityTaskIds = new List<string>(); //章节ID集合
- 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}") }))
- {
- abilityTaskIds.Add(item.id); //查询出来的章节信息ID添加到战绩集合
- }
- //删除章节
- if (abilityTaskIds.IsNotEmpty())
- {
- var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityTaskIds, $"AbilityTask-{_oldStandard}");
- }
- return Ok(new { state = 200 });
- }
- [HttpPost("get-query")]
- public async Task<IActionResult> QueryTest(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("oldId", out JsonElement oldId)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- StandardFile tempFile = new();
- try
- {
- //tempFile = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<StandardFile>($"{oldId}", new PartitionKey("StandardFile"));
- 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") }))
- {
- tempFile = item;
- }
- }
- catch(Exception ex)
- {
- }
- return Ok(new { state = 200, tempFile });
- }
- public async Task<IActionResult> DelSchool(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
- List<string> ids = schoolId.ToObject<List<string>>();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- string sql = $"select value(v) from c";
- return Ok(new { state = 200 });
- }
- /// <summary>
- /// 查询学校
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-school")]
- public async Task<IActionResult> GetSchools()
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<School> schools = new List<School>();
- string sqltxt = $"select c.schoolCode,c.name,c.region,c.province,c.city,c.dist,c.areaId,c.standard,c.id from c ";
- await foreach (var itemSchool in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: sqltxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- schools.Add(itemSchool);
- }
- return Ok(new { schools });
- }
- /// <summary>
- /// 测试接口
- /// </summary>
- /// <param name="foundSchools"></param>
- /// <returns></returns>
- [HttpPost("batch-createschoolcodetest")]
- public async Task<IActionResult> BatchCreateSchoolCodeTest(FoundSchools foundSchools)
- {
- try
- {
- List<BISchool> schools = new List<BISchool>();
- if (foundSchools.biSchools.Count > 0)
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- foreach (BISchool bischool in foundSchools.biSchools)
- {
- var schoolStatus = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{bischool.id}", new PartitionKey($"Base"));
- if (schoolStatus.Status == 200)
- {
- schools.Add(bischool);
- }
- else
- {
- List<Period> periods = new List<Period>();
- string campusId = Guid.NewGuid().ToString();
- bischool.period.ForEach(x =>
- {
- periods.Add(new Period
- {
- id = Guid.NewGuid().ToString(),
- name = x,
- campusId = campusId,
- semesters = new List<Semester>() {
- new Semester { name = "上学期", start = 0, month = 3, day = 1, id = Guid.NewGuid().ToString() },
- new Semester { name = "下学期", start = 1, month = 8, day = 1, id = Guid.NewGuid().ToString() }
- }
- });
- });
- CreateSchoolCode createSchool = new CreateSchoolCode
- {
- province = bischool.province,
- id = bischool.id,
- name = bischool.name,
- city = bischool.city,
- aname = bischool.name
- };
- //JsonElement jsonElement = createSchool;
- //dynamic data = await SchoolService.GenerateSchoolCode(jsonElement, _dingDing, _environment);
- School upSchool = new School
- {
- id = bischool.id,
- name = bischool.name,
- size = bischool.size,
- code = "Base",
- campuses = new List<Campus> { new Campus { name = bischool.name, id = campusId } },
- region = bischool.region,
- province = bischool.province,
- city = bischool.city,
- dist = bischool.dist,
- address = bischool.address,
- picture = "https://teammodelstorage.blob.core.chinacloudapi.cn/0-public/school/bbf54fb3-3fc8-43ae-a358-107281c174cc.png",
- timeZone = new TEAMModelOS.SDK.Models.TimeZone { label = "(UTC+08:00) 北京,重庆,香港特别行政区,乌鲁木齐", value = "+08:00" },
- type = 2,
- pk = "School",
- ttl = -1,
- schoolCode = bischool.id,
- period = periods
- };
- }
- }
- }
- if (schools.Count > 0)
- return Ok(new { state = 201, message = "已有部分学校批量创建成功;学校编号已经重复!请检查学校编号!", schools = schools });
- else
- return Ok(new { state = 200, message = "批量创校已全部完成" });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/batch-school \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 测试接口
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-schoolcode")]
- public async Task<IActionResult> GetTest(JsonElement jsonElement)
- {
- //string data = await SchoolCode.GenerateSchoolCode(jsonElement, _dingDing, _environment).ToString();
- CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo();
- createSchoolInfo.province = "四川省";
- createSchoolInfo.id = "tmdplc";
- createSchoolInfo.name = "醍摩豆批量创校学校";
- createSchoolInfo.city = "成都市";
- createSchoolInfo.aname = "";
- createSchoolInfo.createCount = 0;
- //Random random = new Random();
- ////随机小写字母
- //int a = random.Next(0, 26);
- //char ch = (char)('a' + a);
- //string Number = GenerateRandom.Number(1);
- //string Number1 = GenerateRandom.Number(1, true);
- //string Str = GenerateRandom.Str(1);
- //string Str1 = GenerateRandom.Str(1, true);
- //string Str_char = GenerateRandom.Str_char(1);
- //string Str_char1 = GenerateRandom.Str_char(1, true);
- CreateSchoolInfo data = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
- return Ok(new { state = 200, data, data.id });
- }
- /// <summary>
- /// 批量创校
- /// </summary>
- /// <param name="school"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("batch-school")]
- public async Task<IActionResult> BatchCreateSchool(FoundSchools foundSchools)
- {
- try
- {
- List<BISchool> schools = new List<BISchool>();
- StringBuilder stringBuilder = new StringBuilder($"{foundSchools.tmdName}【{foundSchools.tmdId}】操作了批量创校功能;");
- List<School> tempSchools = new List<School>();
- if (foundSchools.biSchools.Count > 0)
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- foreach (BISchool bischool in foundSchools.biSchools)
- {
- CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo()
- {
- province = bischool.province,
- id = "",
- name = bischool.name,
- city = bischool.city,
- aname = "",
- createCount = 0,
- };
- createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
- var schoolStatus = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
- bool isExist = false;
- if (schoolStatus.Status == 200)
- {
- createSchoolInfo.createCount = 1;
- createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
- var schoolStatu1 = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
- if (schoolStatu1.Status == 200)
- {
- createSchoolInfo.createCount = 2;
- createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
- var schoolStatu2 = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
- if (schoolStatu2.Status == 200)
- {
- createSchoolInfo.createCount = 3;
- createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
- isExist = true;
- }
- while (isExist)
- {
- createSchoolInfo.createCount = 3;
- createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
- var schoolStatu3 = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
- if (schoolStatu3.Status == 200)
- isExist = true;
- else isExist = false;
- }
- }
- }
- if (createSchoolInfo.id != null)
- {
- List<Period> periods = new List<Period>();
- string campusId = Guid.NewGuid().ToString();
- bischool.period.ForEach(x =>
- {
- periods.Add(new Period
- {
- id = Guid.NewGuid().ToString(),
- name = x,
- campusId = campusId,
- semesters = new List<Semester>() {
- new Semester { name = "上学期", start = 0, month = 3, day = 1, id = Guid.NewGuid().ToString() },
- new Semester { name = "下学期", start = 1, month = 8, day = 1, id = Guid.NewGuid().ToString() }
- }
- });
- });
- School upSchool = new School
- {
- id = createSchoolInfo.id,
- name = bischool.name,
- size = bischool.size,
- code = "Base",
- campuses = new List<Campus> { new Campus { name = bischool.name, id = campusId } },
- region = bischool.region,
- province = bischool.province,
- city = bischool.city,
- dist = bischool.dist,
- address = bischool.address,
- picture = "https://teammodelstorage.blob.core.chinacloudapi.cn/0-public/school/bbf54fb3-3fc8-43ae-a358-107281c174cc.png",
- timeZone = new TEAMModelOS.SDK.Models.TimeZone { label = "(UTC+08:00) 北京,重庆,香港特别行政区,乌鲁木齐", value = "+08:00" },
- type = 2,
- pk = "School",
- ttl = -1,
- schoolCode = createSchoolInfo.id,
- period = periods
- };
- stringBuilder.Append($"创建学校:{upSchool.name}【{upSchool.id}】");
- tempSchools.Add(upSchool);
- //创建学校
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<School>(upSchool, new PartitionKey(upSchool.code));
- Teacher teacher = null;
- try
- {
- //查询该教师是否存在
- teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>($"{bischool.admin}", new PartitionKey("Base"));
- }
- catch
- {
- }
- if (teacher != null)
- {
- //教师存在,在该教师信息中添加要管理的学校信息
- teacher.schools.Add(new Teacher.TeacherSchool { schoolId = createSchoolInfo.id, name = bischool.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, bischool.admin, new PartitionKey("Base"));
- SchoolTeacher schoolTeacher = new SchoolTeacher
- {
- id = bischool.admin,
- code = $"Teacher-{createSchoolInfo.id}",
- roles = new List<string> { "admin", "teacher" },
- job = "管理员",
- name = teacher.name,
- picture = teacher.picture,
- status = "join",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
- pk = "Teacher",
- ttl = -1
- };
- stringBuilder.Append($"教师信息:{schoolTeacher.name}【{schoolTeacher.id}】,教师权限:{schoolTeacher.roles.ToString()}");
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey(schoolTeacher.code));
- }
- else
- {
- //不存在 新建教师和新建要管理的学校信息
- Teacher addteacher = new Teacher
- {
- id = bischool.admin,
- pk = "Base",
- code = "Base",
- name = $"{bischool.name}-管理员"?.ToString(),
- picture = "",
- //创建账号并第一次登录IES5则默认赠送1G
- size = 1,
- defaultSchool = createSchoolInfo.id,
- schools = new List<Teacher.TeacherSchool>() { new Teacher.TeacherSchool { schoolId = createSchoolInfo.id, name = bischool.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() } }
- };
- stringBuilder.Append($"没有该教师信息创建的教师信息:{addteacher.name}【{addteacher.id}】");
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(addteacher, new PartitionKey("Base"));
- SchoolTeacher schoolTeacher = new SchoolTeacher
- {
- id = bischool.admin,
- code = $"Teacher-{bischool.id}",
- roles = new List<string> { "admin", "teacher" },
- job = "管理员",
- name = bischool.admin,
- picture = "",
- status = "join",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
- pk = "Teacher",
- ttl = -1
- };
- stringBuilder.Append($"教师权限:{schoolTeacher.roles}");
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey(schoolTeacher.code));
- }
- }
- }
- }
- else return Ok(new { state = 1, message = "创校信息为空" });
- //保存操作记录
- await _azureStorage.SaveLog("operatelog-del", stringBuilder?.ToString(), _dingDing, httpContext: HttpContext);
- if (schools.Count > 0)
- return Ok(new { state = 201, message = "已有部分学校批量创建成功;学校编号已经重复!请检查学校编号!", schools = schools });
- else
- return Ok(new { state = 200, message = "批量创校已全部完成", tempSchools });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/batch-school \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- [HttpPost("file-table")]
- public async Task<IActionResult> SaveTable(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("single", out JsonElement single);
- jsonElement.TryGetProperty("startDate", out JsonElement startDate);
- jsonElement.TryGetProperty("endDate", out JsonElement endDate);
- jsonElement.TryGetProperty("platform", out JsonElement platform);
- List<string> strlist = new List<string>();
- if (!string.IsNullOrEmpty($"{single}"))
- strlist.Add($"RowKey {QueryComparisons.Equal} {single}");
- if (!string.IsNullOrEmpty($"{startDate}"))
- strlist.Add($"RowKey {QueryComparisons.GreaterThanOrEqual} {startDate}");
- if (!string.IsNullOrEmpty($"{endDate}"))
- strlist.Add($"RowKey {QueryComparisons.LessThanOrEqual} {endDate}");
- if (!string.IsNullOrEmpty($"{platform}"))
- strlist.Add($"platform {QueryComparisons.Equal} {platform}");
- string sql = string.Join(" and ", strlist);
- var temp = _azureStorage.QueryWhereString<OptLog>(sql);
- return Ok(new { state = 200, temp });
- }
- /// <summary>
- /// 查询BI操作记录
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-operatelogbydate")]
- public async Task<IActionResult> GetOperateLogByDate(JsonElement jsonElement)
- {
- try
- {
- jsonElement.TryGetProperty("single", out JsonElement single);
- jsonElement.TryGetProperty("startDate", out JsonElement startDate);
- jsonElement.TryGetProperty("endDate", out JsonElement endDate);
- jsonElement.TryGetProperty("platform", out JsonElement platform);
- List<OptLog> operateLogs = null;
- StringBuilder tableSql = new StringBuilder();
- if (!string.IsNullOrEmpty($"{single}"))
- tableSql.Append($"RowKey {QueryComparisons.Equal} '{single}' ");
- if (!string.IsNullOrEmpty($"{startDate}"))
- tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} RowKey {QueryComparisons.GreaterThanOrEqual} '{startDate}' " : $"RowKey {QueryComparisons.GreaterThanOrEqual} '{startDate}' ");
- if (!string.IsNullOrEmpty($"{endDate}"))
- tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} RowKey {QueryComparisons.LessThanOrEqual} '{endDate}' " : $" RowKey { QueryComparisons.LessThanOrEqual} '{endDate}' ");
- if (!string.IsNullOrEmpty($"{platform}"))
- tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} platform {QueryComparisons.Equal} '{platform}' " : $" platform {QueryComparisons.Equal} '{platform}' ");
- operateLogs = await _azureStorage.QueryWhereString<OptLog>(tableSql.ToString());
- return Ok(new { state = 200, operateLogs });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /operatelog/get-operatelogbydate {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 查询离职信息
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("quitstaff")]
- public async Task<IActionResult> QuitStaff()
- {
- try
- {
- string appKey = _configuration["DingDingAuth:appKey"];
- string appSecret = _configuration["DingDingAuth:appSecret"];
- string agentld = _configuration["DingDingAuth:Agentld"];
- //获取access_token
- IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
- request.SetHttpMethod("Get");
- OapiGettokenResponse response = client.Execute(request);
- if (response.IsError)
- {
- return BadRequest();
- }
- //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
- string access_token = response.AccessToken;
- List<string> datalist = new List<string>();
- IDingTalkClient quitStaffClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
- OapiSmartworkHrmEmployeeQuerydimissionRequest reqDimission = new OapiSmartworkHrmEmployeeQuerydimissionRequest() { Offset = 0L, Size = 50L };
- OapiSmartworkHrmEmployeeQuerydimissionResponse rspDimission = quitStaffClient.Execute(reqDimission, access_token);
- if (rspDimission.SubErrCode == "60011")
- {
- return Ok(new { state = 60011, message = "没有调用该接口的权限!" });
- }
- else if (rspDimission.Result != null)
- {
- datalist = rspDimission.Result.DataList;
- return Ok(new { state = 200, datalist = datalist });
- }
- else
- {
- return Ok(new { state = rspDimission.SubErrCode, message = rspDimission.Errmsg });
- }
- }
- catch (Exception ex)
- {
- return BadRequest();
- }
- }
- /// <summary>
- /// 测试获取待入职人员的userId接口
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("Induction")]
- public async Task<IActionResult> Induction()
- {
- try
- {
- string appKey = _configuration["DingDingAuth:appKey"];
- string appSecret = _configuration["DingDingAuth:appSecret"];
- string agentld = _configuration["DingDingAuth:Agentld"];
- //获取access_token
- IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
- request.SetHttpMethod("Get");
- OapiGettokenResponse response = client.Execute(request);
- if (response.IsError)
- {
- return BadRequest();
- }
- //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
- string access_token = response.AccessToken;
- IDingTalkClient InductionClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querypreentry");
- OapiSmartworkHrmEmployeeQuerypreentryRequest reqInduction = new OapiSmartworkHrmEmployeeQuerypreentryRequest() { Offset = 0L, Size = 50 };
- reqInduction.SetHttpMethod("GET");
- OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
- if (rspInduction.Result.DataList != null)
- {
- foreach (var itemId in rspInduction.Result.DataList)
- {
- IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
- OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
- {
- Userid = itemId,
- Language = "zh_CN"
- };
- OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
- }
- return Ok(new { state = 200, rspInduction.Result.DataList });
- }
- else
- {
- return Ok(new { state = 400, rspInduction.SubErrCode, rspInduction.SubErrMsg });
- }
- }
- catch (Exception ex)
- {
- return BadRequest();
- }
- }
- /// <summary>
- /// 分页
- /// </summary>
- /// <returns></returns>
- [HttpPost("get-testpage")]
- public async Task<IActionResult> GetTestPage()
- {
- 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" } };
- List<pageTest> pageTests = new List<pageTest>();
- List<pageTest1> pageTests1 = new List<pageTest1>();
- foreach (var item in st)
- {
- int i = 0;
- pageTest pageTest = new pageTest();
- pageTest.keyt = $"分页{i}";
- pageTest.listv = item;
- pageTests.Add(pageTest);
- i += 1;
- }
- for (int i = 0; i < st.Count; i++)
- {
- pageTest1 pageTest = new pageTest1();
- pageTest.keyt = $"分页{i}";
- pageTest.listv = st.Skip(i).Take(1).ToList();
- pageTests1.Add(pageTest);
- }
- return Ok(new { pageTests1 });
- }
-
- /// <summary>
- /// 保存日志文件
- /// </summary>
- /// <returns></returns>
- [AuthToken(Roles = "assist")]
- [HttpPost("save-tablelog")]
- public async Task<IActionResult> SaveTableLogTest()
- {
- //await OperateLogHelper.SaveTableLog(_azureStorage, "BI", "1636016499", "彭礼", "测试保存方法", "table-save", "save-tablelog");
- await _azureStorage.SaveLog(type:"table-save", msg:"测试保存方法01",dingDing: _dingDing,httpContext:HttpContext);
- return Ok(123);
- }
- [HttpPost("get-test")]
- public async Task<IActionResult> test(JsonElement jsonElement)
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<LessonCount> scount = new List<LessonCount>();
- List<lessons> lessonCounts = new List<lessons>();
- 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() { }))
- {
- lessons le = new lessons() {
- countB =item.beginCount.Count,
- countP = item.pCount.Count,
- countT = item.tCount.Count,
- countPT = item.ptCount.Count,
- lesson = item
- };
- lessonCounts.Add(le);
- }
- return Ok(new { state = 200 , lessonCounts });
- }
- public record lessons
- {
- public long countB { get; set; }
- public long countP { get; set; }
- public long countT { get; set; }
- public long countPT { get; set; }
- public LessonCount lesson { get; set; }
- }
- public record pageTest
- {
- public string keyt { get; set; }
- public string listv { get; set; }
- }
- public record pageTest1
- {
- public string keyt { get; set; }
- public List<string> listv { get; set; }
- }
- [HttpPost("tablesavetestlist")]
- public async Task<IActionResult> cares()
- {
- List<string> temp = new List<string>() { { "123456" }, { "123456" } };
- StringBuilder stringBuilder = new StringBuilder();
- temp.ForEach(p => { stringBuilder.Append(p).Append(","); });
- List<SaveTestList> saveTestLists = new List<SaveTestList>();
- SaveTestList saveTestList = new SaveTestList();
- saveTestList.PartitionKey = "TestJose";
- saveTestList.RowKey = "1640762925550";
- saveTestList.name = "前台";
- saveTestList.sex = "男";
- saveTestList.dept = "行政部";
- saveTestList.describe = "你好我是行政部的前台的1640762925550";
- saveTestLists.Add(saveTestList);
- var temp1 = await _azureStorage.SaveOrUpdateAll<SaveTestList>(saveTestLists);
- return Ok(new { state = 200, temp1 });
- }
- [TableName(Name = ("BITestTable"))]
- public class SaveTestList : TableEntity
- {
- public string name { get; set; }
- public string sex { get; set; }
- public string dept { get; set; }
- public string describe { get; set; }
- [Range(-100,+200)]
- public double min { get; set; }
- }
- public class GenerateRandom
- {
- /// <summary>
- /// 生成随机数字
- /// </summary>
- /// <param name="length">生成长度</param>
- /// <returns></returns>
- public static string Number(int Length)
- {
- return Number(Length, false);
- }
- /// <summary>
- /// 生成随机数字
- /// </summary>
- /// <param name="Length">生成长度</param>
- /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
- /// <returns></returns>
- public static string Number(int Length, bool Sleep)
- {
- if (Sleep)
- System.Threading.Thread.Sleep(3);
- string result = "";
- System.Random random = new Random();
- for (int i = 0; i < Length; i++)
- {
- result += random.Next(10).ToString();
- }
- return result;
- }
- /// <summary>
- /// 生成随机字母与数字
- /// </summary>
- /// <param name="IntStr">生成长度</param>
- /// <returns></returns>
- public static string Str(int Length)
- {
- return Str(Length, false);
- }
- /// <summary>
- /// 生成随机字母与数字
- /// </summary>
- /// <param name="Length">生成长度</param>
- /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
- /// <returns></returns>
- public static string Str(int Length, bool Sleep)
- {
- if (Sleep)
- System.Threading.Thread.Sleep(3);
- 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' };
- string result = "";
- int n = Pattern.Length;
- System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
- for (int i = 0; i < Length; i++)
- {
- int rnd = random.Next(0, n);
- result += Pattern[rnd];
- }
- return result;
- }
- /// <summary>
- /// 生成随机纯字母随机数
- /// </summary>
- /// <param name="IntStr">生成长度</param>
- /// <returns></returns>
- public static string Str_char(int Length)
- {
- return Str_char(Length, false);
- }
- /// <summary>
- /// 生成随机纯字母随机数
- /// </summary>
- /// <param name="Length">生成长度</param>
- /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
- /// <returns></returns>
- public static string Str_char(int Length, bool Sleep)
- {
- if (Sleep) System.Threading.Thread.Sleep(3);
- //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' };
- 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' };
- string result = "";
- int n = Pattern.Length;
- System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
- for (int i = 0; i < Length; i++)
- {
- int rnd = random.Next(0, n);
- result += Pattern[rnd];
- }
- return result;
- }
- }
- public class TableBatchHelper<T> where T : ITableEntity
- {
- const int batchMaxSize = 100;
- public static IEnumerable<TableBatchOperation> GetBatchesForDelete(IEnumerable<T> items)
- {
- var list = new List<TableBatchOperation>();
- var partitionGroups = items.GroupBy(arg => arg.PartitionKey).ToArray();
- foreach (var group in partitionGroups)
- {
- T[] groupList = group.ToArray();
- int offSet = batchMaxSize;
- T[] entities = groupList.Take(offSet).ToArray();
- while (entities.Any())
- {
- var tableBatchOperation = new TableBatchOperation();
- foreach (var entity in entities)
- {
- tableBatchOperation.Add(TableOperation.Delete(entity));
- }
- list.Add(tableBatchOperation);
- entities = groupList.Skip(offSet).Take(batchMaxSize).ToArray();
- offSet += batchMaxSize;
- }
- }
- return list;
- }
- public static async Task BatchDeleteAsync(CloudTable table, IEnumerable<T> items)
- {
- var batches = GetBatchesForDelete(items);
- await Task.WhenAll(batches.Select(table.ExecuteBatchAsync));
- }
- private async Task DeleteAllRows<T>(string table, CloudTableClient client) where T : ITableEntity, new()
- {
- // query all rows
- CloudTable tableref = client.GetTableReference(table);
- var query = new TableQuery<T>();
- TableContinuationToken token = null;
- var result = await tableref.ExecuteQuerySegmentedAsync(query, token);
- do
- {
- foreach (var row in result)
- {
- TableOperation.Delete(row);
- }
- } while (token != null);
- }
- }
- public record CreateSchoolCode
- {
- public string province { get; set; }
- public string id { get; set; }
- public string name { get; set; }
- public string city { get; set; }
- public string aname { get; set; }
- }
- /// <summary>
- /// 创建多个学校实体
- /// </summary>
- public record FoundSchools()
- {
- /// <summary>
- ///醍摩豆账户ID
- /// </summary>
- public string tmdId { get; set; }
- /// <summary>
- /// 醍摩豆账户名称
- /// </summary>
- public string tmdName { get; set; }
- /// <summary>
- /// 批量创校的数据结构
- /// </summary>
- public List<BISchool> biSchools { get; set; } = new List<BISchool>();
- }
- /// <summary>
- /// 批量创校的数据结构
- /// </summary>
- public record BISchool()
- {
- /// <summary>
- /// 学校ID
- /// </summary>
- public string id { get; set; }
- /// <summary>
- /// 学校名称
- /// </summary>
- public string name { get; set; }
- /// <summary>
- /// 学校管理员
- /// </summary>
- public string admin { get; set; }
- /// <summary>
- /// 学校的学段
- /// </summary>
- public List<string> period { get; set; }
- /// <summary>
- /// 学校空间大小
- /// </summary>
- public int size { get; set; }
- /// <summary>
- /// 地区
- /// </summary>
- public string region { get; set; }
- /// <summary>
- /// 省份
- /// </summary>
- public string province { get; set; }
- /// <summary>
- /// 城市
- /// </summary>
- public string city { get; set; }
- /// <summary>
- /// 县,区,郡
- /// </summary>
- public string dist { get; set; }
- /// <summary>
- /// 学校详细地址
- /// </summary>
- public string address { get; set; }
- }
- }
- }
|