123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139 |
- using Microsoft.Azure.Cosmos;
- 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;
- using Pipelines.Sockets.Unofficial.Arenas;
- using Microsoft.Identity.Client;
- using TEAMModelOS.SDK.Models.Dtos;
- using TEAMModelOS.SDK.Models.Service.BI;
- using TEAMModelOS.SDK.Models.Cosmos.BI.BISchool;
- using System.Net.Http.Headers;
- using System.Text.Encodings.Web;
- using System.ComponentModel.DataAnnotations;
- 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;
- private readonly HttpTrigger _httpTrigger;
- public BatchSchoolController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IWebHostEnvironment hostingEnvironment, IConfiguration configuration, IHttpClientFactory http, CoreAPIHttpService coreAPIHttpService, HttpTrigger httpTrigger)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _azureStorage = azureStorage;
- _option = option?.Value;
- _environment = hostingEnvironment;
- _configuration = configuration;
- _http = http;
- _coreAPIHttpService = coreAPIHttpService;
- _httpTrigger = httpTrigger;
- }
- /// <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() { { "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>
- /// 生成学校Code信息
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("get-schoolcode")]
- public async Task<IActionResult> GetSchoolCode(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("schools", out JsonElement schools)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<CreateSchoolInfo> cSchools = schools.ToObject<List<CreateSchoolInfo>>();
- List<CreateSchoolInfo> createScInfo = new(); //生成好的学校Codd信息
- foreach (var item in cSchools)
- {
- CreateSchoolInfo createSchoolInfo = item;
- //生成学校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.StatusCode != HttpStatusCode.OK) tempStaus = false;
- else createSchoolInfo.createCount = createSchoolInfo.createCount >= 3 ? createSchoolInfo.createCount = 3 : createSchoolInfo.createCount += 1;
- } while (tempStaus);
- createScInfo.Add(createSchoolInfo);
- }
- return Ok(new { state = RespondCode.Ok, createScInfo });
- }
- /// <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();
- List<CreateSchoolInfo> scInfos = new();
- List<string> upSc = new();
- StringBuilder stringBuilder = new($"{_tmdName}【{_tmdId}】使用批量创校功能:");
- StringBuilder vsSql = new();
- StringBuilder noticeDD = new(); //创校信息通知
- 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)
- {
- #region 新版直接创建
- foreach (BISchool bischool in foundSchools.biSchools)
- {
- Area area = null;
- //查询区是否存在
- var respAreaId = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{bischool.areaId}", new PartitionKey("Base-Area"));
- if (respAreaId.StatusCode == HttpStatusCode.OK)
- {
- using var areaBase = await JsonDocument.ParseAsync(respAreaId.Content);
- area = areaBase.ToObject<Area>();
- }
- CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo()
- {
- province = bischool.province,
- id = bischool.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.StatusCode != HttpStatusCode.OK) 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();
- TEAMModelOS.SDK.Models.Edition edition = new();
- edition.scaleVersion = bischool.scaleVersion;
- 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,
- isinit = true,
- //modules=bischool?.modules,
- openLessonRecord = (_option.Location.Contains("Global")) ? false : true,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- edition = edition
- };
- scInfos.Add(createSchoolInfo);
- vsSql.Append($"{upSchool.name}【{upSchool.id}】,");
- stringBuilder.Append($"创建学校:{upSchool.name}【{upSchool.id}】");
- noticeDD.Append($"{upSchool.name}【{upSchool.id}】 \r 学校管理员信息:");
- upSc.Add(upSchool.id);
- //创建学校
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<School>(upSchool, new PartitionKey(upSchool.code));
- //创建学校信息中间件
- //_ = _httpTrigger.RequestHttpTrigger(new { school = $"{upSchool}" }, _option.Location, "set-sc-birelation");
- await BIStats.SetSchoolBIRelation(cosmosClient, blobClient, tableClient, _dingDing, upSchool);
- //创建BI和统计信息
- await BIStats.SetScStatsInfo(cosmosClient, _dingDing,upSchool);
- var content = new StringContent(bischool.admin.ToArray().ToJsonString(), Encoding.UTF8, "application/json");
- string json = await _coreAPIHttpService.GetUserInfos(content);
- List<TmdUserinfo> tmdInfos = json.ToObject<List<TmdUserinfo>>();
- foreach (var tmdIndo in tmdInfos)
- {
- Teacher teacher = new();
- var resTeache = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync($"{tmdIndo.id}", new PartitionKey("Base"));
- if (resTeache.StatusCode == HttpStatusCode.OK)
- {
- using var tchJson = await JsonDocument.ParseAsync(resTeache.Content);
- teacher = tchJson.ToObject<Teacher>();
- Teacher.TeacherSchool tchSc = null;
- //var tempTch = teacher.schools.Select(x => x.schoolId.Equals(upSchool.id)).ToString();
- tchSc = teacher.schools.Find(x => x.schoolId.Equals(upSchool.id));
- if (tchSc == null)
- {
- //教师存在,在该教师信息中添加要管理的学校信息
- 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 = tmdIndo.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)}】");
- noticeDD.Append($"{schoolTeacher.name}【{schoolTeacher.id}】");
- 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 = tmdIndo.id,
- pk = "Base",
- code = "Base",
- name = $"{tmdIndo.name}",
- picture = $"{tmdIndo.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 = tmdIndo.id,
- code = $"Teacher-{createSchoolInfo.id}",
- roles = new List<string> { "admin", "teacher" },
- job = "管理员",
- name = $"{tmdIndo.name}",
- picture = "",
- status = "join",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- pk = "Teacher",
- ttl = -1
- };
- stringBuilder.Append($"权限:{string.Join(",", schoolTeacher.roles)}】");
- noticeDD.Append($"{schoolTeacher.name}【{schoolTeacher.id}】");
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey(schoolTeacher.code));
- }
- }
- }
- }
- #endregion
- #region 旧版先检测 在创建
- //foreach (BISchool bischool in foundSchools.biSchools)
- //{
- // List<string> scName = new();
- // //查询学校名称是否全字段匹配
- // await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<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.Content);
- // 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.Content);
- // 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}】");
- // noticeDD.Append($"【ID:{upSchool.id}|名称:{upSchool.name}】 ");
- // upSc.Add(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.Content);
- // 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);
- //}
- #endregion
- }
- else return Ok(new { state = 1, message = "创校信息为空" });
- if (upSc.Count > 1)
- await _dingDing.SendBotMsg($"BI,{_option.Location} \n 批量建校信息:{noticeDD}", GroupNames.成都开发測試群組);
- else if (upSc.Count == 1)
- await _dingDing.SendBotMsg($"BI,{_option.Location} \n 单个建校信息:{noticeDD}", GroupNames.成都开发測試群組);
- ////v2通知
- //Teacher targetTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{_tmdId}", new PartitionKey($"Base"));
- //_coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "create-school", Constant.NotifyType_IES5_Management, new Dictionary<string, object> { { "tmdname", $"{_tmdName}" }, { "schooName", $"{vsSql}" } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- //保存操作记录
- 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 = "批量创校已全部完成", scInfos });
- }
- }
- 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("role", out JsonElement role);
- jsonElement.TryGetProperty("scId", out JsonElement scId);
- jsonElement.TryGetProperty("name", out JsonElement name);
- jsonElement.TryGetProperty("order", out JsonElement order);
- jsonElement.TryGetProperty("province", out JsonElement province);
- jsonElement.TryGetProperty("city", out JsonElement city);
- jsonElement.TryGetProperty("dist", out JsonElement dist);
- //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
- var cosmosClient = _azureCosmos.GetCosmosClient();
- ////分开部署,就不需要,一站多用时,取消注释
- //if ($"{site}".Equals(BIConst.Global))
- // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- int scCnt = 0;
- int? pageSize = 100; //默认不指定返回大小
- 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 ");
- StringBuilder scCntSql = new($"select value(count(c.id)) 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($"{scId}") && string.IsNullOrEmpty($"{name}"))
- {
- stringBuilder.Append($" where c.id='{scId}'");
- scCntSql.Append($" where c.id='{scId}'");
- }
- if (string.IsNullOrEmpty($"{scId}") && !string.IsNullOrEmpty($"{name}"))
- {
- stringBuilder.Append($" where Contains(c.name,'{name}')");
- scCntSql.Append($" where Contains(c.name,'{name}')");
- }
- if (!string.IsNullOrEmpty($"{province}") && string.IsNullOrEmpty($"{city}") && string.IsNullOrEmpty($"{dist}"))
- {
- stringBuilder.Append($" where Contains(c.province,'{province}')");
- scCntSql.Append($" where Contains(c.province,'{province}')");
- }
- if (!string.IsNullOrEmpty($"{city}") && !string.IsNullOrEmpty($"{city}") && string.IsNullOrEmpty($"{dist}"))
- {
- stringBuilder.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}')");
- scCntSql.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}')");
- }
- if (!string.IsNullOrEmpty($"{dist}") && !string.IsNullOrEmpty($"{city}") && !string.IsNullOrEmpty($"{dist}"))
- {
- stringBuilder.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}') and Contains(c.dist,'{dist}')");
- scCntSql.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}') and Contains(c.dist,'{dist}')");
- }
- if ($"{order}".Equals("desc"))
- stringBuilder.Append(" order by c.createTime desc");
- if (!string.IsNullOrEmpty($"{tmdId}"))
- {
- schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", roles: !string.IsNullOrEmpty($"{role}") ? $"{role}" : "assist", isMany: true);
- string scsSql = BICommonWay.ManyScSql("c.id", schoolIds);
- scCntSql.Append($" where {scsSql}");
- scCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", scCntSql.ToString(), "Base");
- foreach (var id in schoolIds)
- {
- StringBuilder sqlTxt = 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 where c.id='{id}'");
- if ($"{order}".Equals("desc"))
- sqlTxt.Append(" order by c.createTime desc");
- else
- sqlTxt.Append(" order by c.createTime asc");
- await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<AssistSchool>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- schoolAssists.Add(itemSchool);
- }
- }
- }
- else
- {
- scCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", scCntSql.ToString(), "Base");
- await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), continuationToken: pageToken, requestOptions: new QueryRequestOptions() { MaxItemCount = pageSize, PartitionKey = new PartitionKey("Base") }))
- {
- using var json = await JsonDocument.ParseAsync(itemSchool.Content);
- 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.ContinuationToken;
- break;
- }
- }
- }
- }
- //if (schoolIds.Count > 0)
- //{
- // scCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", scCntSql.ToString(), "Base");
- // foreach (var id in schoolIds)
- // {
- // StringBuilder sqlTxt = 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 where c.id='{id}'");
- // if ($"{order}".Equals("desc"))
- // sqlTxt.Append(" order by c.createTime desc");
- // await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<AssistSchool>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- // {
- // schoolAssists.Add(itemSchool);
- // }
- // }
- //}
- //else
- //{
- // if (!string.IsNullOrEmpty($"{scId}") && string.IsNullOrEmpty($"{name}"))
- // {
- // stringBuilder.Append($" where c.id='{scId}'");
- // scCntSql.Append($" where c.id='{scId}'");
- // }
- // if (string.IsNullOrEmpty($"{scId}") && !string.IsNullOrEmpty($"{name}"))
- // {
- // stringBuilder.Append($" where Contains(c.name,'{name}')");
- // scCntSql.Append($" where Contains(c.name,'{name}')");
- // }
- // if (!string.IsNullOrEmpty($"{province}") && string.IsNullOrEmpty($"{city}") && string.IsNullOrEmpty($"{dist}"))
- // {
- // stringBuilder.Append($" where Contains(c.province,'{province}')");
- // scCntSql.Append($" where Contains(c.province,'{province}')");
- // }
- // if (!string.IsNullOrEmpty($"{city}") && !string.IsNullOrEmpty($"{city}") && string.IsNullOrEmpty($"{dist}"))
- // {
- // stringBuilder.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}')");
- // scCntSql.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}')");
- // }
- // if (!string.IsNullOrEmpty($"{dist}") && !string.IsNullOrEmpty($"{city}") && !string.IsNullOrEmpty($"{dist}"))
- // {
- // stringBuilder.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}') and Contains(c.dist,'{dist}')");
- // scCntSql.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}') and Contains(c.dist,'{dist}')");
- // }
- // if ($"{order}".Equals("desc"))
- // stringBuilder.Append(" order by c.createTime desc");
- // scCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", scCntSql.ToString(), "Base");
- // await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), continuationToken: pageToken, requestOptions: new QueryRequestOptions() { MaxItemCount = pageSize, PartitionKey = new PartitionKey("Base") }))
- // {
- // using var json = await JsonDocument.ParseAsync(itemSchool.Content);
- // 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.ContinuationToken;
- // break;
- // }
- // }
- // }
- //}
- foreach (var item in schoolAssists)
- {
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(item.id, new PartitionKey("ProductSum"));
- if (response.StatusCode == HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
- item.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
- item.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
- item.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
- }
- item.assists = await CommonFind.FindSchoolRoles(cosmosClient, item.id, "assist");
- item.scAdmin = await CommonFind.FindSchoolRoles(cosmosClient, item.id, "admin");
- item.lessonCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c ", $"LessonRecord-{item.id}");
- }
- //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.Content);
- // 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, scCnt, continuationToken, schoolAssists });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/get-schoolsinfo \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 所有信息
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-allscinfo")]
- public async Task<IActionResult> GetAllScsInfo(JsonElement jsonElement)
- {
- try
- {
- jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
- jsonElement.TryGetProperty("role", out JsonElement role);
- jsonElement.TryGetProperty("scId", out JsonElement scId);
- jsonElement.TryGetProperty("name", out JsonElement name);
- jsonElement.TryGetProperty("order", out JsonElement order);
- jsonElement.TryGetProperty("province", out JsonElement province);
- jsonElement.TryGetProperty("city", out JsonElement city);
- jsonElement.TryGetProperty("dist", out JsonElement dist);
- //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
- var cosmosClient = _azureCosmos.GetCosmosClient();
- ////分开部署,就不需要,一站多用时,取消注释
- //if ($"{site}".Equals(BIConst.Global))
- // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- int scCnt = 0;
- 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 ");
- StringBuilder scCntSql = new($"select value(count(c.id)) from c");
- if (!string.IsNullOrEmpty($"{scId}") && string.IsNullOrEmpty($"{name}"))
- {
- stringBuilder.Append($" where c.id='{scId}'");
- scCntSql.Append($" where c.id='{scId}'");
- }
- if (string.IsNullOrEmpty($"{scId}") && !string.IsNullOrEmpty($"{name}"))
- {
- stringBuilder.Append($" where Contains(c.name,'{name}')");
- scCntSql.Append($" where Contains(c.name,'{name}')");
- }
- if (!string.IsNullOrEmpty($"{province}") && string.IsNullOrEmpty($"{city}") && string.IsNullOrEmpty($"{dist}"))
- {
- stringBuilder.Append($" where Contains(c.province,'{province}')");
- scCntSql.Append($" where Contains(c.province,'{province}')");
- }
- if (!string.IsNullOrEmpty($"{city}") && !string.IsNullOrEmpty($"{city}") && string.IsNullOrEmpty($"{dist}"))
- {
- stringBuilder.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}')");
- scCntSql.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}')");
- }
- if (!string.IsNullOrEmpty($"{dist}") && !string.IsNullOrEmpty($"{city}") && !string.IsNullOrEmpty($"{dist}"))
- {
- stringBuilder.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}') and Contains(c.dist,'{dist}')");
- scCntSql.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}') and Contains(c.dist,'{dist}')");
- }
- if (!string.IsNullOrEmpty($"{tmdId}"))
- {
- schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", roles: !string.IsNullOrEmpty($"{role}") ? $"{role}" : "assist", isMany: true);
- string scsSql = BICommonWay.ManyScSql("c.id", schoolIds);
- scCntSql.Append($" where {scsSql}");
- scCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", scCntSql.ToString(), "Base");
- foreach (var id in schoolIds)
- {
- StringBuilder sqlTxt = 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 where c.id='{id}'");
- if ($"{order}".Equals("desc"))
- sqlTxt.Append(" order by c.createTime desc");
- await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<AssistSchool>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- schoolAssists.Add(itemSchool);
- }
- }
- }
- else
- {
- if ($"{order}".Equals("desc"))
- stringBuilder.Append(" order by c.createTime desc");
- scCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", scCntSql.ToString(), "Base");
- await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- using var json = await JsonDocument.ParseAsync(itemSchool.Content);
- 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>());
- }
- }
- }
- }
- foreach (var item in schoolAssists)
- {
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(item.id, new PartitionKey("ProductSum"));
- if (response.StatusCode == HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
- item.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
- item.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
- item.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
- }
- item.assists = await CommonFind.FindSchoolRoles(cosmosClient, item.id, "assist");
- item.scAdmin = await CommonFind.FindSchoolRoles(cosmosClient, item.id, "admin");
- item.lessonCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c ", $"LessonRecord-{item.id}");
- }
- return Ok(new { state = 200, scCnt, schoolAssists });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/get-allscinfo() \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.StatusCode == HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- 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();
- 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").GetItemQueryStreamIteratorSql(queryText: managerSql, requestOptions: new QueryRequestOptions() { }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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();
- 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").GetItemQueryStreamIteratorSql(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.Content);
- 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").GetItemQueryStreamIteratorSql(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.Content);
- 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("type", out JsonElement _type)) return BadRequest();
- jsonElement.TryGetProperty("province", out JsonElement province);
- jsonElement.TryGetProperty("city", out JsonElement city);
- jsonElement.TryGetProperty("dist", out JsonElement dist);
- jsonElement.TryGetProperty("address", out JsonElement address);
- string code = (jsonElement.TryGetProperty("code", out JsonElement _code))? _code.GetString() : string.Empty;
- jsonElement.TryGetProperty("assist", out JsonElement assist);
- jsonElement.TryGetProperty("scaleVersion", out JsonElement scaleVersion);
- //手動追加商業模組的部分先封印,商業模組需要經過訂單系統下單控管。
- //List<string> modules = null ;
- //if (!jsonElement.TryGetProperty("modules ", out JsonElement _modules))
- //{
- // return BadRequest();
- //}
- //else {
- // modules= _modules.ToObject<List<string>>();
- //}
- List<IdInfo> idInfos = assist.ToObject<List<IdInfo>>();
- //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- 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);
- //}
- //IES5 實體學校變更
- if (!code.Equals("VirtualBase"))
- {
- School tempShool = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{_schoolId}", new PartitionKey("Base"));
- if (tempShool != null)
- {
- List<Period> periods = new();
- string campusId = Guid.NewGuid().ToString();
- //periodS.ForEach(x =>
- //{
- // periods.Add(new Period { id = Guid.NewGuid().ToString(), name = x.ToString(), campusId = campusId });
- //});
- //tempShool.period = periods;
- //if (modules!=null) {
- // tempShool.modules=modules;
- //}
- 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}";
- tempShool.province = string.IsNullOrEmpty($"{province}") ? tempShool.province : $"{province}";
- tempShool.city = string.IsNullOrEmpty($"{city}") ? tempShool.city : $"{city}";
- tempShool.dist = string.IsNullOrEmpty($"{dist}") ? tempShool.dist : $"{dist}";
- tempShool.address = string.IsNullOrEmpty($"{address}") ? tempShool.address : $"{address}";
-
- //計算學校版本
- List<SchoolProductSumData> services = new List<SchoolProductSumData>();
- ResponseMessage productSumResponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{_schoolId}", new PartitionKey("ProductSum"));
- if (productSumResponse.StatusCode == HttpStatusCode.OK)
- {
- var doc = JsonDocument.Parse(productSumResponse.Content);
- if (doc.RootElement.TryGetProperty("service", out JsonElement service))
- {
- services.AddRange(service.ToObject<List<SchoolProductSumData>>());
- }
- }
- tempShool.edition = BISchoolService.calSchoolEdition(tempShool, services.Select(s => s.prodCode).ToList());
- //tempShool.edition.scaleVersion = string.IsNullOrEmpty($"{scaleVersion}") ? tempShool.edition.scaleVersion : $"{scaleVersion}";
- tempShool.edition.scaleVersion = ($"{scaleVersion}" == null) ? tempShool.edition.scaleVersion : $"{scaleVersion}";
- //修改学校
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(tempShool, tempShool.id, new PartitionKey("Base"));
- //创建学校信息中间件
- await BIStats.SetSchoolBIRelation(cosmosClient, blobClient, tableClient, _dingDing, tempShool);
- //修改学校教师关联的信息
- string sql = $"SELECT distinct value(c) FROM c join A1 in c.schools where A1.schoolId='{tempShool.id}'";
- List<Teacher> teachers = new();
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<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"));
- }
- //学校信息中间件更新
- BIRelation biRel = new();
- var respRel = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(tempShool.id, new PartitionKey("BIRel"));
- if (respRel.StatusCode == HttpStatusCode.OK)
- {
- using var fileJson = await JsonDocument.ParseAsync(respRel.Content);
- biRel = fileJson.ToObject<BIRelation>();
- }
- else
- {
- biRel.id = tempShool.id;
- }
- string aName = null;
- if (!string.IsNullOrEmpty($"{tempShool.areaId}"))
- {
- aName = await CosmosQueryHelper.GetStr(cosmosClient, "Normal", $"select value(c.name) from c where c.id='{tempShool.areaId}'", "Base-Area");
- }
- biRel.name = tempShool.name;
- biRel.picture = tempShool.picture;
- biRel.region = tempShool.region;
- biRel.province = tempShool.province;
- biRel.city = tempShool.city;
- biRel.dist = tempShool.dist;
- biRel.address = tempShool.address;
- biRel.areaId = tempShool.areaId;
- biRel.size = tempShool.size;
- biRel.scale = tempShool.scale;
- biRel.upDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- biRel.areaName = aName;
- biRel.edition = tempShool.edition;
- if (idInfos.Count > 0)
- {
- foreach (var item in idInfos)
- {
- var tempAss = biRel.assists.Find(f => f.id.Equals(item.id));
- if (tempAss == null)
- biRel.assists.Add(item);
- }
- }
- else
- {
- biRel.assists = idInfos;
- }
- if (respRel.StatusCode == HttpStatusCode.OK)
- {
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<BIRelation>(biRel, biRel.id, new PartitionKey("BIRel"));
- }
- else
- {
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<BIRelation>(biRel, new PartitionKey("BIRel"));
- }
- }
-
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", $"{_tmdName}【{_tmdId}】修改学校功能,修改的学校:{_schoolId},{_type},{picture},{size},{idInfos.ToArray()}", _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200 });
- }
- //IES5 虛擬學校變更
- else
- {
- VirtualBase tempVirtual = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<VirtualBase>($"{_schoolId}", new PartitionKey("VirtualBase"));
- if (tempVirtual != null)
- {
- tempVirtual.picture = $"{picture}";
- tempVirtual.type = int.Parse($"{_type}");
- tempVirtual.name = $"{schoolName}";
- tempVirtual.areaId = $"{areaId}";
- tempVirtual.standard = $"{standard}";
- tempVirtual.province = string.IsNullOrEmpty($"{province}") ? tempVirtual.province : $"{province}";
- tempVirtual.city = string.IsNullOrEmpty($"{city}") ? tempVirtual.city : $"{city}";
- tempVirtual.dist = string.IsNullOrEmpty($"{dist}") ? tempVirtual.dist : $"{dist}";
- tempVirtual.address = string.IsNullOrEmpty($"{address}") ? tempVirtual.address : $"{address}";
- string aName = null;
- if (!string.IsNullOrEmpty($"{tempVirtual.areaId}"))
- {
- aName = await CosmosQueryHelper.GetStr(cosmosClient, "Normal", $"select value(c.name) from c where c.id='{tempVirtual.areaId}'", "Base-Area");
- }
- tempVirtual.areaName = aName;
- //修改学校
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<VirtualBase>(tempVirtual, tempVirtual.id, new PartitionKey("VirtualBase"));
- }
- // 保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", $"{_tmdName}【{_tmdId}】修改学校功能,修改的学校:{_schoolId},{_type},{picture},{size},{idInfos.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").GetItemQueryIteratorSql<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>
- [ProducesDefaultResponseType]
- [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").GetItemQueryIteratorSql<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 });
- }
- /// <summary>
- /// 创校前检查数据
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-checlkexist")]
- public async Task<IActionResult> GetCheckExist(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("scNames", out JsonElement _scNames)) return BadRequest();
- if (!jsonElement.TryGetProperty("accounts", out JsonElement _accounts)) return BadRequest();
- if (!jsonElement.TryGetProperty("areaIds", out JsonElement _areaIds)) return BadRequest();
- jsonElement.TryGetProperty("schools", out JsonElement schools);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<CreateSchoolInfo> cSchools = new();
- if (!string.IsNullOrEmpty($"{schools}"))
- cSchools = schools.ToObject<List<CreateSchoolInfo>>();
- List<string> scNames = _scNames.ToObject<List<string>>();
- List<string> accounts = _accounts.ToObject<List<string>>();
- List<string> areaIds = _areaIds.ToObject<List<string>>();
- List<string> existScNames = new(); //存在的学校
- List<string> noAccounts = new(); // 不存在的账户
- List<string> noAreaIds = new(); //不存在的学区
- List<string> synPro = new(); //已同步省平台
- List<CreateSchoolInfo> createScInfo = new(); //学校简码信息
- if (scNames.Count > 0)
- {
- foreach (var item in scNames)
- {
- //查询学校名称是否全字段匹配
- await foreach (var sc in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<string>(queryText: $"select value(c.name) from c where c.name='{item}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- existScNames.Add(item);
- }
- }
- }
- if (accounts.Count > 0)
- {
- var content = new StringContent(_accounts.ToString(), Encoding.UTF8, "application/json");
- string json = await _coreAPIHttpService.GetUserInfos(content);
- List<TmdUserinfo> tmdInfos = json.ToObject<List<TmdUserinfo>>();
- accounts.ForEach(ac =>
- {
- TmdUserinfo noTmdInfo = null;
- tmdInfos.ForEach(tmd =>
- {
- if (!string.IsNullOrEmpty(tmd.id))
- if (tmd.id.Equals($"{ac}"))
- noTmdInfo = tmd;
- if (!string.IsNullOrEmpty(tmd.mobile))
- if (tmd.mobile.Equals($"{ac}"))
- noTmdInfo = tmd;
- if (!string.IsNullOrEmpty(tmd.mail))
- if (tmd.mail.Equals($"{ac}"))
- noTmdInfo = tmd;
- });
- //noTmdInfo = tmdInfos.Find(f => f.id.Equals($"{ac}") || f.mail.Equals($"{ac}") || f.mobile.Equals($"{ac}"));
- if (noTmdInfo == null)
- noAccounts.Add(ac);
- });
- }
- if (areaIds.Count > 0)
- {
- foreach (var item in areaIds)
- {
- //查询区是否存在
- var respAreaId = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{item}", new PartitionKey("Base-Area"));
- if (respAreaId.StatusCode != HttpStatusCode.OK)
- {
- noAreaIds.Add(item);
- }
- //查询去是否同步省平台
- var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{item}", new PartitionKey("AreaSetting"));
- if (responseSet.StatusCode == HttpStatusCode.OK)
- {
- using var fileJson = await JsonDocument.ParseAsync(responseSet.Content);
- AreaSetting delSet = fileJson.ToObject<AreaSetting>();
- if (!string.IsNullOrEmpty(delSet.accessConfig))
- synPro.Add(item);
- }
- }
- }
- foreach (var item in cSchools)
- {
- CreateSchoolInfo createSchoolInfo = item;
- //生成学校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.StatusCode != HttpStatusCode.OK) tempStaus = false;
- else createSchoolInfo.createCount = createSchoolInfo.createCount >= 3 ? createSchoolInfo.createCount = 3 : createSchoolInfo.createCount += 1;
- } while (tempStaus);
- createScInfo.Add(createSchoolInfo);
- }
- if (existScNames.Count > 0 || noAccounts.Count > 0 || noAreaIds.Count > 0 || synPro.Count > 0)
- return Ok(new { state = RespondCode.Created, existScNames, noAccounts, noAreaIds, synPro, createScInfo });
- else
- return Ok(new { state = RespondCode.Ok, createScInfo });
- }
- /// <summary>
- /// 批量创校前检查数据
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-checkexists")]
- public async Task<IActionResult> GetCheckExists(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("checkScs", out JsonElement checkScs)) return BadRequest();
- List<BISchool> bISchools = checkScs.ToObject<List<BISchool>>();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<BISchool> existScNames = new(); //存在的学校
- List<BISchool> noAccounts = new(); // 不存在的账户
- List<BISchool> noAreaIds = new(); //不存在的学区
- List<BISchool> synPro = new(); //已同步省平台
- List<BISchool> createScInfo = new(); //学校简码信息
- foreach (BISchool bISchool in bISchools)
- {
- //查询学校名称是否全字段匹配
- await foreach (var sc in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<string>(queryText: $"select value(c.name) from c where c.name='{bISchool.name}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- existScNames.Add(bISchool);
- }
- var content = new StringContent(bISchool.admin.ToJsonString(), Encoding.UTF8, "application/json");
- string json = await _coreAPIHttpService.GetUserInfos(content);
- List<TmdUserinfo> tmdInfos = json.ToObject<List<TmdUserinfo>>();
- bISchool.admin.ForEach(ac =>
- {
- TmdUserinfo noTmdInfo = null;
- tmdInfos.ForEach(tmd =>
- {
- if (!string.IsNullOrEmpty(tmd.id))
- if (tmd.id.Equals($"{ac}"))
- noTmdInfo = tmd;
- if (!string.IsNullOrEmpty(tmd.mobile))
- if (tmd.mobile.Equals($"{ac}"))
- noTmdInfo = tmd;
- if (!string.IsNullOrEmpty(tmd.mail))
- if (tmd.mail.Equals($"{ac}"))
- noTmdInfo = tmd;
- });
- //noTmdInfo = tmdInfos.Find(f => f.id.Equals($"{ac}") || f.mail.Equals($"{ac}") || f.mobile.Equals($"{ac}"));
- if (noTmdInfo == null)
- noAccounts.Add(bISchool);
- });
- if (!string.IsNullOrEmpty(bISchool.areaId))
- {
- //查询区是否存在
- var respAreaId = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{bISchool.areaId}", new PartitionKey("Base-Area"));
- if (respAreaId.StatusCode != HttpStatusCode.OK)
- {
- noAreaIds.Add(bISchool);
- }
- //查询去是否同步省平台
- var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{bISchool.areaId}", new PartitionKey("AreaSetting"));
- if (responseSet.StatusCode == HttpStatusCode.OK)
- {
- using var fileJson = await JsonDocument.ParseAsync(responseSet.Content);
- AreaSetting delSet = fileJson.ToObject<AreaSetting>();
- if (!string.IsNullOrEmpty(delSet.accessConfig))
- synPro.Add(bISchool);
- }
- }
- 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.StatusCode != HttpStatusCode.OK) tempStaus = false;
- else createSchoolInfo.createCount = createSchoolInfo.createCount >= 3 ? createSchoolInfo.createCount = 3 : createSchoolInfo.createCount += 1;
- } while (tempStaus);
- bISchool.id = createSchoolInfo.id;
- createScInfo.Add(bISchool);
- }
- if (existScNames.Count > 0 || noAccounts.Count > 0 || noAreaIds.Count > 0 || synPro.Count > 0)
- return Ok(new { state = RespondCode.Created, existScNames, noAccounts, noAreaIds, synPro, createScInfo });
- else
- return Ok(new { state = RespondCode.Ok, createScInfo });
- }
- /// <summary>
- /// 添加多个学校添加多个管理员
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("set-batchmanage")]
- public async Task<IActionResult> SetBatchManage(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("scIds", out JsonElement _scIds)) return BadRequest();
- if (!jsonElement.TryGetProperty("manages", out JsonElement _manages)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<string> scIds = _scIds.ToObject<List<string>>();
- List<string> manages = _manages.ToObject<List<string>>();
- List<ExistScManage> existScManages = new();
- if (scIds.Count > 0 && manages.Count > 0)
- {
- foreach (var scId in scIds)
- {
- foreach (var msId in manages)
- {
- //不存在则在原来的基础上添加顾问角色
- Teacher tempTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>($"{msId}", new PartitionKey("Base"));
- if (tempTeacher != null)
- {
- var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{msId}", new PartitionKey($"Teacher-{scId}"));
- if (response.StatusCode == HttpStatusCode.OK)
- {
- using var tchJson = await JsonDocument.ParseAsync(response.Content);
- SchoolTeacher tchSc = tchJson.ToObject<SchoolTeacher>();
- if (tchSc.roles.Contains("admin"))
- {
- tchSc.roles.Add("admin");
- //添加顾问权限
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(tchSc, tchSc.id, new PartitionKey($"Teacher-{scId}"));
- }
- else
- existScManages.Add(new ExistScManage() { scId = scId, tmdId = msId });
- }
- else
- {
- SchoolTeacher addSchoolTeacher = new()
- {
- id = tempTeacher.id,
- code = $"Teacher-{scId}",
- pk = "Teacher",
- status = "join",
- roles = new List<string>() { "admin" },
- name = tempTeacher.name,
- job = $"管理员",
- size = 0,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- var haveTeacher = tempTeacher.schools.Find(x => x.schoolId.Equals($"{scId}"));
- if (haveTeacher == null)
- {
- School school = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<School>(scId, new PartitionKey("Base"));
- //教师存在,在该教师信息中添加要管理的学校信息
- tempTeacher.schools.Add(new Teacher.TeacherSchool { areaId = string.IsNullOrEmpty(school.areaId) ? "" : school.areaId, schoolId = school.id, name = school.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
- tempTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(tempTeacher, msId, new PartitionKey("Base"));
- }
- //添加学校学校管理员
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(addSchoolTeacher, new PartitionKey($"Teacher-{scId}"));
- }
- }
- else
- {
- CoreUser coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{msId}" } }, _option.Location, _configuration);
- Teacher teacher = new() { id = coreUser.id, name = coreUser.name, picture = coreUser.picture, pk = "Base", code = "Base", size = 1, createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() };
- var responseSc = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(scId, new PartitionKey("Base"));
- if (responseSc.StatusCode == HttpStatusCode.OK)
- {
- using var tchJson = await JsonDocument.ParseAsync(responseSc.Content);
- School scInfo = tchJson.ToObject<School>();
- teacher.schools.Add(new() { schoolId = scInfo.id, name = scInfo.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = scInfo.picture, areaId = scInfo.areaId });
- }
- teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
- SchoolTeacher addSchoolTeacher = new()
- {
- id = coreUser.id,
- code = $"Teacher-{scId}",
- pk = "Teacher",
- status = "join",
- roles = new List<string>() { "admin" },
- name = coreUser.name,
- job = $"管理员",
- size = 0,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- //添加学校学校管理员
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(addSchoolTeacher, new PartitionKey($"Teacher-{scId}"));
- }
- }
- }
- }
- if (existScManages.Count > 0)
- return Ok(new { state = RespondCode.Created, existScManages });
- else
- return Ok(new { state = RespondCode.Ok });
- }
- /// <summary>
- /// 批量设置学校集合中学校多个管理员
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin")]
- [HttpPost("batch-scmanage")]
- public async Task<IActionResult> BatchScManage(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("scManages", out JsonElement _scManages)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<ScManages> scManages = _scManages.ToObject<List<ScManages>>();
- List<ScManages> error = new(); //异常数据
- foreach (var item in scManages)
- {
- School school = new();
- var resSc = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{item.id}", new PartitionKey("Base"));
- if (resSc.StatusCode == HttpStatusCode.OK)
- {
- using var sJson = await JsonDocument.ParseAsync(resSc.Content);
- school = sJson.ToObject<School>();
- //CoreUser coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"19940828843" } }, _option.Location, _configuration);
- var content = new StringContent(item.mobiles.ToArray().ToJsonString(), Encoding.UTF8, "application/json");
- string json = await _coreAPIHttpService.GetUserInfos(content);
- List<TmdUserinfo> tmdInfos = json.ToObject<List<TmdUserinfo>>();
- Teacher teacher = new();
- foreach (var tmd in tmdInfos)
- {
- var respone = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync($"{tmd.id}", new PartitionKey("Base"));
- if (respone.StatusCode == HttpStatusCode.OK)
- {
- using var tchJson = await JsonDocument.ParseAsync(respone.Content);
- teacher = tchJson.ToObject<Teacher>();
- var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{tmd.id}", new PartitionKey($"Teacher-{item.id}"));
- if (response.StatusCode == HttpStatusCode.OK)
- {
- using var scTchJson = await JsonDocument.ParseAsync(response.Content);
- SchoolTeacher tchSc = scTchJson.ToObject<SchoolTeacher>();
- if (tchSc.roles.Contains("admin"))
- {
- tchSc.roles.Add("admin");
- //添加顾问权限
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(tchSc, tchSc.id, new PartitionKey($"Teacher-{item.id}"));
- }
- else
- {
- var exsitI = error.Find(f => f.id.Equals(item.id));
- if (exsitI != null)
- {
- var replacts = error.Where(w => w.id.Equals(item.id)).FirstOrDefault();
- replacts.mobiles.Add($"{item.id}");
- }
- else
- error.Add(new ScManages { id = item.id, name = item.name, mobiles = new List<string>() { $"{tmd.id}" } });
- }
- }
- else
- {
- SchoolTeacher addSchoolTeacher = new()
- {
- id = tmd.id,
- code = $"Teacher-{item.id}",
- pk = "Teacher",
- status = "join",
- roles = new List<string>() { "admin" },
- name = tmd.name,
- job = $"管理员",
- size = 0,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- var haveTeacher = teacher.schools.Find(x => x.schoolId.Equals($"{item.id}"));
- if (haveTeacher == null)
- {
- //教师存在,在该教师信息中添加要管理的学校信息
- teacher.schools.Add(new Teacher.TeacherSchool { areaId = string.IsNullOrEmpty(school.areaId) ? "" : school.areaId, schoolId = school.id, name = school.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
- teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
- }
- //添加学校学校顾问
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(addSchoolTeacher, new PartitionKey($"Teacher-{item.id}"));
- }
- }
- else
- {
- teacher = new()
- {
- id = $"{tmd.id}",
- name = $"{tmd.name}",
- picture = $"{tmd.picture}",
- pk = "Base",
- code = "Base",
- size = 1,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- schools = new List<Teacher.TeacherSchool>() { new Teacher.TeacherSchool { schoolId = $"{school.id}", name = $"{school.name}", status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = school.province, areaId = school.areaId } }
- };
- teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
- SchoolTeacher addSchoolTeacher = new()
- {
- id = tmd.id,
- code = $"Teacher-{item.id}",
- pk = "Teacher",
- status = "join",
- roles = new List<string>() { "admin" },
- name = tmd.name,
- job = $"管理员",
- size = 0,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- //添加学校学校管理员
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(addSchoolTeacher, new PartitionKey($"Teacher-{item.id}"));
- }
- }
- }
- else
- error.Add(new ScManages { id = item.id, name = item.name, mobiles = new List<string>() });
- }
- return Ok(new { state = RespondCode.Ok, error });
- }
- /// <summary>
- /// 根據地理位置搜尋學校基本訊息
- /// </summary>
- /// <param name="GenerateCouponRequest"></param>
- /// <returns></returns>
- //[AuthToken(Roles = "admin,rdc,assist,sales")]
- [HttpPost("get-school-basic-info")]
- public async Task<IActionResult> GetSchoolBasicInfo(SchoolDataRequest request)
- {
- try
- {
- string url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
- string AccessToken = await getCoreAccessToken();
- var client = _http.CreateClient();
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
- HttpResponseMessage response = await client.PostAsJsonAsync($"{url}/Service/SchoolData", request);
- if (response.StatusCode == HttpStatusCode.OK)
- {
- string jsonStr = await response.Content.ReadAsStringAsync();
- var options1 = new JsonSerializerOptions
- {
- Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
- };
-
- return Ok(jsonStr.ToObject<JsonElement>());
- }
- else
- {
- return BadRequest();
- }
- }
- catch (Exception ex)
- {
- return BadRequest();
- }
- }
- /// <summary>
- /// 弱歸戶
- /// </summary>
- /// <param name="GenerateCouponRequest"></param>
- /// <returns></returns>
- //[AuthToken(Roles = "admin,rdc,assist,sales")]
- [HttpPost("upd-user-schoolw")]
- public async Task<IActionResult> UpdUserSchoolW(UpdateUserSchoolCodeWRequest request)
- {
- try
- {
- string url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
- string AccessToken = await getCoreAccessToken();
- var client = _http.CreateClient();
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
- HttpResponseMessage response = await client.PostAsJsonAsync($"{url}/Service/UpdateUserSchoolCodeW", request);
- if (response.StatusCode == HttpStatusCode.OK)
- {
- string jsonStr = await response.Content.ReadAsStringAsync();
- var options1 = new JsonSerializerOptions
- {
- Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
- };
- return Ok(jsonStr.ToObject<JsonElement>());
- }
- else
- {
- return BadRequest();
- }
- }
- catch (Exception ex)
- {
- return BadRequest();
- }
- }
- private async Task<string> getCoreAccessToken()
- {
- string AccessToken = "";
- try
- {
- string Url = _configuration.GetValue<string>("HaBookAuth:CoreAPI") + "/oauth2/token";
- string GrantType = "device";
- string ClientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- string Secret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var content = new { grant_type = GrantType, client_id = ClientID, client_secret = Secret };
- var response = await _http.CreateClient().PostAsJsonAsync($"{Url}", content);
- if (response.IsSuccessStatusCode)
- {
- string responseBody = response.Content.ReadAsStringAsync().Result;
- using (JsonDocument document = JsonDocument.Parse(responseBody.ToString()))
- {
- if (document.RootElement.TryGetProperty("access_token", out JsonElement AccessTokenObj))
- {
- AccessToken = AccessTokenObj.ToString();
- }
- }
- }
- return AccessToken;
- }
- catch (Exception ex)
- {
- return AccessToken;
- }
- }
- #region 预设学校基础信息 多语言
- /// <summary>
- /// 预设学校基础信息 多语言
- /// </summary>
- /// <param name="period"></param>
- /// <param name="Language"></param>
- /// <param name="campusId"></param>
- /// <returns></returns>
- public List<Period> PresetSchoolPeriod(List<PeriodType> 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();
- if (period.Count > 0)
- {
- period.ForEach(x =>
- {
- periods.Add(new Period
- {
- id = Guid.NewGuid().ToString(),
- name = x.name,
- 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
- },
- periodType = x.value
- });
- });
- }
- else
- {
- periods.Add(new Period
- {
- id = Guid.NewGuid().ToString(),
- name = "默认学段",
- 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;
- }
- #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()
- {
- public string id { get; set; }
- /// <summary>
- /// 学校名称
- /// </summary>
- public string name { get; set; }
- /// <summary>
- /// 学校管理员
- /// </summary>
- public List<string> admin { get; set; }
- /// <summary>
- /// 学校的学段
- /// </summary>
- public List<PeriodType> 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; }
- /// <summary>
- /// 規模版本
- /// </summary>
- public string scaleVersion { get; set; }
- /// <summary>
- /// 手动增加的模块 ["art"]
- /// </summary>
- //public List<string> modules { get; set; } = new List<string>();
- }
-
- /// <summary>
- /// 学段类型和学段名称
- /// </summary>
- public record PeriodType
- {
- public string name { get; set; }
- public string value { get; set; }
- }
- /// <summary>
- /// 存在的学校
- /// </summary>
- public record ExistScManage
- {
- public string scId { get; set; }
- public string tmdId { get; set; }
- }
- /// <summary>
- /// 管理员
- /// </summary>
- public record ScManages
- {
- public string id { get; set; }
- public string name { get; set; }
- public List<string> mobiles { get; set; }
- }
- public record SchoolDataRequest
- (
- string countryId,
- string provinceId,
- string cityId,
- string shortCode,
- bool fullData = false
- );
- public record UpdateUserSchoolCodeWRequest
- (
- [Required] List<string> ids,
- [Required] string schoolDocId
- );
- }
- }
|