1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042 |
- using Azure.Cosmos;
- using HTEXLib.COMM.Helpers;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.Dynamic;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos.BI;
- using Microsoft.AspNetCore.Hosting; //引用读取文件
- using TEAMModelOS.SDK.Models.Service;
- using System.IO;
- using System.Net.Http;
- using Microsoft.Extensions.Configuration;
- using System.Net.Http.Json;
- using System.Net;
- using TEAMModelBI.Filter;
- using TEAMModelBI.Tool.Extension;
- using TEAMModelBI.Tool;
- using TEAMModelBI.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.Context.BI;
- using TEAMModelOS.SDK.Context.Constant;
- namespace TEAMModelBI.Controllers.BISchool
- {
- [Route("batchschool")]
- [ApiController]
- public class BatchSchoolController : ControllerBase
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureStorageFactory _azureStorage;
- private readonly IWebHostEnvironment _environment; //读取文件
- private readonly IHttpClientFactory _http;
- //读取配置信息
- private readonly IConfiguration _configuration;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- public BatchSchoolController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IWebHostEnvironment hostingEnvironment, IConfiguration configuration, IHttpClientFactory http, CoreAPIHttpService coreAPIHttpService)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _azureStorage = azureStorage;
- _option = option?.Value;
- _environment = hostingEnvironment;
- _configuration = configuration;
- _http = http;
- _coreAPIHttpService = coreAPIHttpService;
- }
- /// <summary>
- /// 获取BI权限列表 //已对接
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-teacher-authoritybilist")]
- public async Task<IActionResult> GetAuthorityBIList(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("site", out JsonElement site);
- Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", "authority-bi" } };
- var table = _azureStorage.GetCloudTableClient().GetTableReference("SchoolSetting");
- if ($"{site}".Equals(BIConst.Global))
- table = _azureStorage.GetCloudTableClient(BIConst.Global).GetTableReference("SchoolSetting");
- List<Authority> authorityBIList = await table.FindListByDict<Authority>(dic);
- return Ok(new { authorityBIList });
- }
- /// <summary>
- /// 批量创校 //已对接
- /// </summary>
- /// <param name="school"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("batch-school")]
- public async Task<IActionResult> BatchCreateSchool(FoundSchools foundSchools)
- {
- try
- {
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- List<BISchool> schools = new();
- List<BISchool> userScs = new();
- List<BISchool> cutArea = new();
- StringBuilder stringBuilder = new($"{_tmdName}【{_tmdId}】使用批量创校功能:");
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if (BIConst.Global.Equals($"{foundSchools.site}"))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- if (foundSchools.biSchools.Count > 0)
- {
- foreach (BISchool bischool in foundSchools.biSchools)
- {
- List<string> scName = new();
- //查询学校名称是否全字段匹配
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: $"select value(c.name) from c where c.name='{bischool.name}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- scName.Add(item);
- }
- Area area = null;
- //查询区是否存在
- var respAreaId = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{bischool.areaId}", new PartitionKey("Base-Area"));
- if (respAreaId.Status == 200)
- {
- using var areaBase = await JsonDocument.ParseAsync(respAreaId.ContentStream);
- area = areaBase.ToObject<Area>();
- }
- bool isSYNCArea = false;
- //查询去是否同步省平台
- var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{bischool.areaId}", new PartitionKey("AreaSetting"));
- if (responseSet.Status == 200)
- {
- using var fileJson = await JsonDocument.ParseAsync(responseSet.ContentStream);
- AreaSetting delSet = fileJson.ToObject<AreaSetting>();
- if (!string.IsNullOrEmpty(delSet.accessConfig))
- isSYNCArea = true;
- }
- if (scName.Count <= 0)
- {
- if (isSYNCArea == false)
- {
- var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{bischool.admin}" } }, _option.Location, _configuration);
- if (coreUser != null && coreUser.id != null)
- {
- CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo()
- {
- province = bischool.province,
- id = "",
- name = bischool.name,
- city = bischool.city,
- aname = "",
- createCount = 0,
- };
- //生成学校ID
- bool tempStaus = true;
- do
- {
- createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
- var schoolStatu = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
- if (schoolStatu.Status != 200) tempStaus = false;
- else createSchoolInfo.createCount = createSchoolInfo.createCount >= 3 ? createSchoolInfo.createCount = 3 : createSchoolInfo.createCount += 1;
- } while (tempStaus);
- if (createSchoolInfo.id != null)
- {
- string campusId = Guid.NewGuid().ToString();
- School upSchool = new()
- {
- id = createSchoolInfo.id,
- name = bischool.name,
- size = bischool.size == 0 ? 100 : 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 = string.IsNullOrEmpty(bischool.type.ToString()) ? 1 : bischool.type,
- pk = "School",
- ttl = -1,
- areaId = area == null ? "" : area.id,
- standard = area == null ? "" : area.standard,
- schoolCode = createSchoolInfo.id,
- period = PresetSchoolPeriod(bischool.period, foundSchools.lang, campusId),
- scale = bischool.size >= 300 ? 500 : 0,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- stringBuilder.Append($"创建学校:{upSchool.name}【{upSchool.id}】");
- //创建学校
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<School>(upSchool, new PartitionKey(upSchool.code));
- //创建学校管理员
- Teacher teacher = null;
- var resTeache = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync($"{coreUser.id}", new PartitionKey("Base"));
- if (resTeache.Status == 200)
- {
- using var tchJson = await JsonDocument.ParseAsync(resTeache.ContentStream);
- teacher = tchJson.ToObject<Teacher>();
- //教师存在,在该教师信息中添加要管理的学校信息
- teacher.schools.Add(new Teacher.TeacherSchool { areaId = string.IsNullOrEmpty(bischool.areaId) ? "" : bischool.areaId, schoolId = createSchoolInfo.id, name = bischool.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
- //await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, coreUser.id, new PartitionKey("Base"));
- SchoolTeacher schoolTeacher = new()
- {
- id = coreUser.id,
- code = $"Teacher-{createSchoolInfo.id}",
- roles = new List<string> { "admin", "teacher" },
- job = "管理员",
- name = teacher.name,
- picture = teacher.picture,
- status = "join",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- pk = "Teacher",
- ttl = -1
- };
- stringBuilder.Append($"教师信息:{schoolTeacher.name}【{schoolTeacher.id}】,教师权限:{string.Join(",", schoolTeacher.roles)}");
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey(schoolTeacher.code));
- }
- else
- {
- //不存在 新建教师和新建要管理的学校信息
- Teacher addteacher = new()
- {
- id = coreUser.id,
- pk = "Base",
- code = "Base",
- name = $"{coreUser.name}",
- picture = $"{coreUser.picture}",
- //创建账号并第一次登录IES5则默认赠送1G
- size = 1,
- defaultSchool = createSchoolInfo.id,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- 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()
- {
- id = coreUser.id,
- code = $"Teacher-{createSchoolInfo.id}",
- roles = new List<string> { "admin", "teacher" },
- job = "管理员",
- name = $"{coreUser.name}",
- picture = "",
- status = "join",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- pk = "Teacher",
- ttl = -1
- };
- stringBuilder.Append($"教师权限:{string.Join(",", schoolTeacher.roles)}");
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey(schoolTeacher.code));
- }
- }
- }
- else userScs.Add(bischool);
- }
- else cutArea.Add(bischool);
- }
- else schools.Add(bischool);
- }
- }
- else return Ok(new { state = 1, message = "创校信息为空" });
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-batchAdd", stringBuilder?.ToString(), _dingDing, httpContext: HttpContext);
- if (schools.Count == foundSchools.biSchools.Count || userScs.Count == foundSchools.biSchools.Count)
- return Ok(new { state = RespondCode.CreateFailed, message = "已有部分学校批量创建成功;学校已经重复/学校信息有误!请检查学校信息!", schools, userScs });
- else
- {
- if (schools.Count > 0 || userScs.Count > 0 || cutArea.Count > 0)
- return Ok(new { state = RespondCode.Created, message = "已有部分学校批量创建成功;学校已经重复/学校信息有误/区域已在研修不能加区!请检查学校信息!", schools, userScs, cutArea });
- else
- return Ok(new { state = RespondCode.Ok, message = "批量创校已全部完成" });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/batch-school \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 依据学校编号查询学校信息;若是没有传学校编号,则查询所有学校信息 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-schoolsinfo")]
- public async Task<IActionResult> GetSchoolsInfo(JsonElement jsonElement)
- {
- try
- {
- jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
- jsonElement.TryGetProperty("schoolCode", out JsonElement _schoolCode);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- int? pageSize = null; //默认不指定返回大小
- string continuationToken = string.Empty; //返给前端分页token
- string pageToken = default;//接受前端的分页Tolen
- bool iscontinuation = false;//是否需要进行分页查询,默认不分页
- List<AssistSchool> schoolAssists = new(); //返回学校列表集合
- List<string> schoolIds = new();
- StringBuilder stringBuilder = new("select c.id,c.code,c.schoolCode,c.name,c.region,c.province,c.city,c.dist,c.size,c.address,c.picture,c.type,c.scale,c.areaId,c.standard from c");
- if (jsonElement.TryGetProperty("pageSize", out JsonElement jsonPageSize))
- {
- if (!jsonPageSize.ValueKind.Equals(JsonValueKind.Undefined) && !jsonPageSize.ValueKind.Equals(JsonValueKind.Null) && jsonPageSize.TryGetInt32(out int tempPageSize))
- {
- pageSize = tempPageSize;
- }
- }
- if (pageSize != null && pageSize.Value > 0)
- {
- iscontinuation = true;
- }
- if (jsonElement.TryGetProperty("contToken", out JsonElement ContToken))
- {
- pageToken = ContToken.GetString();
- }
- if (!string.IsNullOrEmpty($"{tmdId}"))
- {
- schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
- }
- if (schoolIds.Count > 0)
- {
- foreach (var id in schoolIds)
- {
- string sqlTxt = $"select c.id,c.code,c.schoolCode,c.name,c.region,c.province,c.city,c.dist,c.size,c.address,c.picture,c.type,c.scale,c.areaId,c.standard from c where c.id='{id}'";
- await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<AssistSchool>(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- schoolAssists.Add(itemSchool);
- }
- }
- }
- else
- {
- if (!string.IsNullOrEmpty($"{_schoolCode}"))
- {
- stringBuilder.Append($" where c.id='{_schoolCode}'");
- }
- await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), continuationToken: pageToken, requestOptions: new QueryRequestOptions() { MaxItemCount = pageSize, PartitionKey = new PartitionKey("Base") }))
- {
- using var json = await JsonDocument.ParseAsync(itemSchool.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- schoolAssists.Add(obj.ToObject<AssistSchool>());
- }
- if (iscontinuation)
- {
- continuationToken = itemSchool.GetContinuationToken();
- break;
- }
- }
- }
- }
- schoolAssists.ForEach(async school =>
- {
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school.id, new PartitionKey("ProductSum"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
- {
- school.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
- {
- school.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
- {
- school.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
- }
- }
- school.assists = await CommonFind.FindSchoolRoles(cosmosClient, school.id, "assist");
- school.lessonCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c ", $"LessonRecord-{school.id}");
- });
- return Ok(new { state = 200, continuationToken, schoolAssists, });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/get-schoolsinfo \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 使用yieId 关键字 本地效率未测出
- /// </summary>
- /// <param name="cosmosClient"></param>
- /// <param name="schoolAssists"></param>
- /// <returns></returns>
- private async IAsyncEnumerable<List<AssistSchool>> GetSchools(CosmosClient cosmosClient, List<AssistSchool> schoolAssists)
- {
- List<AssistSchool> tempSchoolAssists = new();
- foreach (var temp in schoolAssists)
- {
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(temp.id, new PartitionKey("ProductSum"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
- {
- temp.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
- {
- temp.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
- {
- temp.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
- }
- }
- temp.assists = await CommonFind.FindSchoolRoles(cosmosClient, temp.id, "assist");
- tempSchoolAssists.Add(temp);
- }
- yield return tempSchoolAssists;
- }
- /// <summary>
- /// 取得学校所有顾问列表
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-schoolassist")]
- public async Task<IActionResult> GetSchoolAssist(JsonElement jsonElement)
- {
- try
- {
- jsonElement.TryGetProperty("site", out JsonElement site);
- string schoolId = (jsonElement.TryGetProperty("schoolId", out JsonElement _schoolId)) ? _schoolId.GetString() : string.Empty;
- Dictionary<string, List<Dictionary<string, string>>> haveSchoolManger = new Dictionary<string, List<Dictionary<string, string>>>();
- string managerWhereOption = (!string.IsNullOrWhiteSpace(schoolId)) ? $" AND c.code = 'Teacher-{schoolId}'" : string.Empty;
- //查询学校的顾问
- string managerSql = $"SELECT DISTINCT REPLACE(c.code, 'Teacher-', '') AS schoolId, c.id, c.name FROM c WHERE ARRAY_CONTAINS(c.roles, 'assist', true) AND c.pk = 'Teacher' AND c.status = 'join'{managerWhereOption}";
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: managerSql, requestOptions: new QueryRequestOptions() { }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- string id = obj.GetProperty("id").GetString(); //管理员ID
- string name = obj.GetProperty("name").GetString(); //管理员姓名
- string tempSchoolId = obj.GetProperty("schoolId").GetString(); //学校ID
- Dictionary<string, string> managerDic = new Dictionary<string, string>();
- managerDic.Add("id", id);
- managerDic.Add("name", name);
- if (haveSchoolManger.ContainsKey(tempSchoolId))
- {
- haveSchoolManger[tempSchoolId].Add(managerDic);
- }
- else
- {
- List<Dictionary<string, string>> managerList = new List<Dictionary<string, string>>();
- managerList.Add(managerDic);
- haveSchoolManger.Add(tempSchoolId, managerList);
- }
- }
- }
- //管理模组学校
- List<string> baseModuleSchoos = new List<string>();
- string baseWhereOption = (!string.IsNullOrEmpty(schoolId)) ? $" and c.id='{schoolId}'" : string.Empty;
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"select c.id from c join serviceProduct in c.service.product where serviceProduct.prodCode = 'IPDYZYLC' {baseWhereOption}", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Product") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- string tempSchoolId = obj.GetProperty("id").GetString(); //学校ID
- baseModuleSchoos.Add(tempSchoolId);
- }
- }
- //学校信息
- List<object> schools = new List<object>();
- string schoolWhereOption = (!string.IsNullOrEmpty(schoolId)) ? $" where c.id='{schoolId}'" : string.Empty;
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"select c.id,c.name,c.period,c.schoolCode,c.region,c.province,c.city,c.picture from c {schoolWhereOption}", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- dynamic schoolExpando = new ExpandoObject();
- schoolExpando.id = obj.GetProperty("id").GetString();
- schoolExpando.name = obj.GetProperty("name").GetString();
- //schoolExpando.period = obj.GetProperty("period");
- schoolExpando.schoolCode = obj.GetProperty("schoolCode").GetString();
- schoolExpando.region = obj.GetProperty("region").GetString();
- schoolExpando.province = obj.GetProperty("province").GetString();
- schoolExpando.city = obj.GetProperty("city").GetString();
- schoolExpando.picture = obj.GetProperty("picture").GetString();
- if (haveSchoolManger.ContainsKey(schoolExpando.id))
- {
- schoolExpando.hasMarger = true;
- schoolExpando.managers = haveSchoolManger[schoolExpando.id];
- }
- else
- {
- schoolExpando.hasMarger = false;
- schoolExpando.managers = new List<object>();
- }
- schoolExpando.hasBaseModule = (baseModuleSchoos.Contains(schoolExpando.id)) ? true : false;
- schools.Add(schoolExpando);
- }
- }
- return Ok(new { state = 200, schools });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/get-schools \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 修改学校信息和顾问信息 //已经对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("upd-schoolassist")]
- public async Task<IActionResult> UpdSchoolAssist(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("schoolId", out JsonElement _schoolId)) return BadRequest();
- if (!jsonElement.TryGetProperty("name", out JsonElement schoolName)) return BadRequest();
- if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
- if (!jsonElement.TryGetProperty("standard", out JsonElement standard)) return BadRequest();
- //if (!jsonElement.TryGetProperty("period", out JsonElement period)) return BadRequest();
- if (!jsonElement.TryGetProperty("picture", out JsonElement picture)) return BadRequest();
- if (!jsonElement.TryGetProperty("size", out JsonElement size)) return BadRequest();
- if (!jsonElement.TryGetProperty("scale", out JsonElement scale)) return BadRequest();
- if (!jsonElement.TryGetProperty("assistId", out JsonElement _assistId)) return BadRequest();
- if (!jsonElement.TryGetProperty("type", out JsonElement _type)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- List<string> assistId = _assistId.ToObject<List<string>>();
- //List<string> periodS = period.ToObject<List<string>>();
- Dictionary<string, List<Dictionary<string, string>>> haveSchoolManger = new Dictionary<string, List<Dictionary<string, string>>>();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- School tempShool = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{_schoolId}", new PartitionKey("Base"));
- if (tempShool != null)
- {
- List<Period> periods = new List<Period>();
- string campusId = Guid.NewGuid().ToString();
- //periodS.ForEach(x =>
- //{
- // periods.Add(new Period { id = Guid.NewGuid().ToString(), name = x.ToString(), campusId = campusId });
- //});
- //tempShool.period = periods;
- tempShool.size = !string.IsNullOrEmpty($"{size}") ? int.Parse($"{size}") : tempShool.size;
- tempShool.scale = !string.IsNullOrEmpty($"{scale}") ? int.Parse($"{scale}") : tempShool.scale;
- tempShool.picture = $"{picture}";
- tempShool.type = int.Parse($"{_type}");
- tempShool.name = $"{schoolName}";
- tempShool.areaId = $"{areaId}";
- tempShool.standard = $"{standard}";
- //修改学校
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(tempShool, tempShool.id, new PartitionKey("Base"));
- //修改学校教师关联的信息
- string sql = $"SELECT distinct value(c) FROM c join A1 in c.schools where A1.schoolId='{tempShool.id}'";
- List<Teacher> teachers = new List<Teacher>();
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- teachers.Add(item);
- }
- foreach (var item in teachers)
- {
- Teacher.TeacherSchool teacherSchool = item.schools.Find(x => x.schoolId.Equals(tempShool.id));
- if (teacherSchool != null)
- {
- teacherSchool.name = tempShool.name;
- teacherSchool.picture = tempShool.picture;
- teacherSchool.areaId = tempShool.areaId;
- }
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey($"Base"));
- }
- if (assistId.Count > 0)
- {
- //修改学校顾问
- string sqlTxt = $"SELECT value(c) From c WHERE ARRAY_CONTAINS(c.roles,'assist',true)";
- List<SchoolTeacher> schoolTeachers = new List<SchoolTeacher>();
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<SchoolTeacher>(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{tempShool.id}") }))
- {
- if (!assistId.Contains(item.id))
- {
- if (item.roles.Contains("assist"))
- {
- item.roles.Remove("assist");
- if (item.roles.Count > 0)
- {
- await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(item, item.id, new PartitionKey(item.code));
- }
- else
- {
- await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemAsync<SchoolTeacher>(item.id, new PartitionKey(item.code));
- }
- }
- }
- }
- foreach (var itemTeacher in assistId)
- {
- Teacher tempTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>($"{itemTeacher}", new PartitionKey("Base"));
- if (tempTeacher != null)
- {
- var haveTeacher = tempTeacher.schools.Find(x => x.schoolId.Equals($"{_schoolId}"));
- if (haveTeacher != null)
- {
- //查询该教师是否存在该校
- SchoolTeacher schoolTeacher = null;
- try
- {
- schoolTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolTeacher>($"{itemTeacher}", new PartitionKey($"Teacher-{tempShool.id}"));
- }
- catch
- {
- }
- if (schoolTeacher != null)
- {
- if (!schoolTeacher.roles.Contains("assist"))
- {
- schoolTeacher.roles.Add("assist");
- //添加顾问权限
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, schoolTeacher.id, new PartitionKey($"Teacher-{tempShool.id}"));
- }
- }
- else
- {
- SchoolTeacher addSchoolTeacher = new SchoolTeacher
- {
- id = itemTeacher,
- code = $"Teacher-{tempShool.id}",
- pk = "Teacher",
- status = "join",
- roles = new List<string>() { "assist" },
- name = tempTeacher.name,
- job = $"{tempShool.name}-顾问",
- size = 0,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- //添加学校顾问
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(addSchoolTeacher, new PartitionKey($"Teacher-{tempShool.id}"));
- }
- }
- else
- {
- Teacher.TeacherSchool teacherSchool = new Teacher.TeacherSchool
- {
- schoolId = tempShool.id,
- name = tempShool.name,
- status = "join",
- time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- picture = tempShool.picture,
- areaId = tempShool.areaId
- };
- tempTeacher.schools.Add(teacherSchool);
- //给醍摩豆顾问添加学校
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(tempTeacher, tempTeacher.id, new PartitionKey($"Base"));
- //不存在则在原来的基础上添加顾问角色
- SchoolTeacher addSchoolTeacher = new SchoolTeacher
- {
- id = itemTeacher,
- code = $"Teacher-{tempShool.id}",
- pk = "Teacher",
- status = "join",
- roles = new List<string>() { "assist" },
- name = tempTeacher.name,
- job = $"{tempShool.name}-顾问",
- size = 0,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- //添加学校学校顾问
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(addSchoolTeacher, new PartitionKey($"Teacher-{tempShool.id}"));
- }
- }
- }
- }
- }
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", $"{_tmdName}【{_tmdId}】修改学校功能,修改的学校:{_schoolId},{_type},{picture},{size},{string.Join("|", assistId.ToArray())}", _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI, {_option.Location} /batchschool/upd-schoolassist \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 查询区域的学校
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-schooldist")]
- public async Task<IActionResult> GetSchoolDist(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("dist", out JsonElement _dist)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- string sqltxt = $"SELECT * FROM c where c.dist='{_dist}'";
- List<School> schools = new List<School>();
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: sqltxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- schools.Add(item);
- }
- return Ok(new { state = 200, schools });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/get-schooldist \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 分页学校和顾问信息
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-schools")]
- public async Task<IActionResult> GetSchools(JsonElement jsonElement)
- {
- //List<School> schools = new List<School>();
- List<AssistSchool> schoolAssists = new List<AssistSchool>();
- if (!jsonElement.TryGetProperty("endPosition", out JsonElement endPosition)) return BadRequest();
- if (!jsonElement.TryGetProperty("pageSize", out JsonElement pageSize)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- string sqltxt = $"SELECT * FROM c order by c.id offset {endPosition} limit {pageSize}";
- await foreach (var itemSchool in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: sqltxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- AssistSchool schoolAssist = new()
- {
- id = itemSchool.id,
- code = itemSchool.code,
- schoolCode = itemSchool.schoolCode,
- name = itemSchool.name,
- region = itemSchool.region,
- province = itemSchool.province,
- city = itemSchool.city,
- dist = itemSchool.dist,
- size = itemSchool.size,
- address = itemSchool.address,
- picture = itemSchool.picture,
- type = itemSchool.type,
- scale = itemSchool.scale,
- areaId = itemSchool.areaId,
- standard = itemSchool.standard
- };
- schoolAssist.assists = await CommonFind.FindSchoolRoles(cosmosClient, itemSchool.id, "assist");
- schoolAssists.Add(schoolAssist);
- }
- return Ok(new { state = 200, schoolAssists });
- }
- #region 预设学校基础信息 多语言
- /// <summary>
- /// 预设学校基础信息 多语言
- /// </summary>
- /// <param name="period"></param>
- /// <param name="Language"></param>
- /// <param name="campusId"></param>
- /// <returns></returns>
- public List<Period> PresetSchoolPeriod(List<string> period, string Language, string campusId)
- {
- var builder = $"{_environment.ContentRootPath}/JsonFile/Preset/LangSchoolConfig.json";
- StreamReader streamReader = new(new FileStream(builder, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8);
- StringBuilder stringBuilder = new();
- string text;
- while ((text = streamReader.ReadLine()) != null)
- {
- stringBuilder.Append(text.ToString());
- }
- streamReader.Close();
- string input = stringBuilder.ToString();
- List<SchoolConfig> schoolConfigs = input.ToObject<List<SchoolConfig>>();
- SchoolConfig schoolConfig = schoolConfigs.Find(x => x.Lang.Contains($"{Language}"));
- if (schoolConfig == null)
- {
- if (Language.Contains("en"))
- schoolConfig = schoolConfigs.Find(x => x.Lang.Contains("en-US"));
- else
- schoolConfig = schoolConfigs.Find(x => x.Lang.Contains("zh-CN"));
- }
- List<Period> periods = new();
- period.ForEach(x =>
- {
- periods.Add(new Period
- {
- id = Guid.NewGuid().ToString(),
- name = x,
- campusId = campusId,
- semesters = new List<Semester>() { new Semester { name = schoolConfig.semester[0].term, start = schoolConfig.semester[0].start, month = schoolConfig.semester[0].month, day = schoolConfig.semester[0].day, id = Guid.NewGuid().ToString() },
- new Semester { name = schoolConfig.semester[1].term, start = schoolConfig.semester[1].start, month = schoolConfig.semester[1].month, day = schoolConfig.semester[1].day, id = Guid.NewGuid().ToString() } },
- subjects = new List<Subject>() {
- new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[0].name,type=schoolConfig.PresetSubject[0].type },
- new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[1].name,type=schoolConfig.PresetSubject[1].type },
- new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[2].name,type=schoolConfig.PresetSubject[2].type }
- },
- grades = schoolConfig.grades,
- analysis = new Analysis()
- {
- type = new List<ExamSimple>() { new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[0].name },
- new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[1].name },
- new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[2].name },
- new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[3].name } },
- income = schoolConfig.PresetExam[0].income,
- eugenics = schoolConfig.PresetExam[0].eugenics,
- touch = schoolConfig.PresetExam[0].touch
- }
- });
- });
- return periods;
- }
- public record SchoolConfig
- {
- public string Lang { get; set; }
- public List<semester> semester { get; set; }
- public List<string> grades { get; set; }
- public List<PresetSubject> PresetSubject { get; set; }
- public List<PresetExam> PresetExam { get; set; }
- }
- public record semester
- {
- public string id { get; set; } = Guid.NewGuid().ToString();
- public string term { get; set; }
- public int start { get; set; }
- public int month { get; set; }
- public int day { get; set; }
- }
- public record PresetSubject
- {
- public string id { get; set; } = Guid.NewGuid().ToString();
- public string name { get; set; }
- public int type { get; set; }
- }
- public record PresetExam
- {
- public List<StudyType> type { get; set; }
- public int income { get; set; }
- public int eugenics { get; set; }
- public int touch { get; set; }
- }
- public record StudyType
- {
- public string id { get; set; } = Guid.NewGuid().ToString();
- public string name { get; set; }
- }
- #endregion
- //public class SchoolAssist
- //{
- // public string id { get; set; }
- // public string code { get; set; }
- // public string schoolCode { get; set; }
- // public string name { get; set; }
- // public string region { get; set; }
- // public string province { get; set; }
- // public string city { get; set; }
- // public string dist { get; set; }
- // public int size { get; set; }
- // public string address { get; set; }
- // public string picture { get; set; }
- // public int type { get; set; }
- // public int scale { get; set; }
- // public string standard { get; set; }
- // public string areaId { get; set; }
- // public List<SchoolTeacherRoles> assists { get; set; }
- // public int serial { get; set; } //软体
- // public int service { get; set; } //服务
- // public int hard { get; set; } //硬体
- // //public List<SchoolProductSumData> serial { get; set; } //软体
- // //public List<SchoolProductSumData> service { get; set; } //服务
- // //public List<SchoolProductSumDataHard> hard { get; set; } //硬体
- //}
- /// <summary>
- /// 创建多个学校实体
- /// </summary>
- public record FoundSchools()
- {
- /// <summary>
- /// 语系
- /// </summary>
- public string lang { get; set; }
- /// <summary>
- /// 站点
- /// </summary>
- public string site { get; set; }
- /// <summary>
- /// 批量创校的数据结构
- /// </summary>
- public List<BISchool> biSchools { get; set; } = new List<BISchool>();
- }
- /// <summary>
- /// 批量创校的数据结构
- /// </summary>
- public record BISchool()
- {
- /// <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; }
- /// <summary>
- /// 学校类型
- /// </summary>
- public int type { get; set; }
- /// <summary>
- /// 区域ID
- /// </summary>
- public string areaId { get; set; }
- /// <summary>
- /// 区域标准
- /// </summary>
- public string standard { get; set; }
- }
- public record Exist()
- {
- public string ID { get; set; }
- public string name { get; set; }
- }
- }
- }
|