BatchSchoolController.cs 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145
  1. using Azure.Cosmos;
  2. using HTEXLib.COMM.Helpers;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Extensions.Options;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Dynamic;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Text.Json;
  12. using System.Threading.Tasks;
  13. using TEAMModelOS.Models;
  14. using TEAMModelOS.SDK.DI;
  15. using TEAMModelOS.SDK.Extension;
  16. using TEAMModelOS.SDK.Models;
  17. using TEAMModelOS.SDK.Models.Cosmos.BI;
  18. using Microsoft.AspNetCore.Hosting; //引用读取文件
  19. using TEAMModelOS.SDK.Models.Service;
  20. using System.IO;
  21. using System.Net.Http;
  22. using Microsoft.Extensions.Configuration;
  23. using System.Net.Http.Json;
  24. using System.Net;
  25. using TEAMModelBI.Filter;
  26. using TEAMModelBI.Tool.Extension;
  27. using TEAMModelBI.Tool;
  28. using TEAMModelBI.Models;
  29. using TEAMModelOS.SDK;
  30. using TEAMModelOS.SDK.Context.BI;
  31. using TEAMModelOS.SDK.Context.Constant;
  32. using Pipelines.Sockets.Unofficial.Arenas;
  33. using Microsoft.Identity.Client;
  34. using TEAMModelOS.SDK.Models.Dtos;
  35. using DocumentFormat.OpenXml.Spreadsheet;
  36. using DocumentFormat.OpenXml.Wordprocessing;
  37. using DocumentFormat.OpenXml.Bibliography;
  38. using HTEXLib;
  39. using TEAMModelOS.SDK.Models.Service.BI;
  40. using TEAMModelOS.SDK.Models.Cosmos.BI.BISchool;
  41. using DocumentFormat.OpenXml.Vml.Office;
  42. using System.Net.Http.Headers;
  43. using System.Text.Encodings.Web;
  44. using System.ComponentModel.DataAnnotations;
  45. namespace TEAMModelBI.Controllers.BISchool
  46. {
  47. [Route("batchschool")]
  48. [ApiController]
  49. public class BatchSchoolController : ControllerBase
  50. {
  51. private readonly AzureCosmosFactory _azureCosmos;
  52. private readonly DingDing _dingDing;
  53. private readonly Option _option;
  54. private readonly AzureStorageFactory _azureStorage;
  55. private readonly IWebHostEnvironment _environment; //读取文件
  56. private readonly IHttpClientFactory _http;
  57. //读取配置信息
  58. private readonly IConfiguration _configuration;
  59. private readonly CoreAPIHttpService _coreAPIHttpService;
  60. private readonly HttpTrigger _httpTrigger;
  61. public BatchSchoolController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IWebHostEnvironment hostingEnvironment, IConfiguration configuration, IHttpClientFactory http, CoreAPIHttpService coreAPIHttpService, HttpTrigger httpTrigger)
  62. {
  63. _azureCosmos = azureCosmos;
  64. _dingDing = dingDing;
  65. _azureStorage = azureStorage;
  66. _option = option?.Value;
  67. _environment = hostingEnvironment;
  68. _configuration = configuration;
  69. _http = http;
  70. _coreAPIHttpService = coreAPIHttpService;
  71. _httpTrigger = httpTrigger;
  72. }
  73. /// <summary>
  74. /// 获取BI权限列表 //已对接
  75. /// </summary>
  76. /// <returns></returns>
  77. [ProducesDefaultResponseType]
  78. [HttpPost("get-teacher-authoritybilist")]
  79. public async Task<IActionResult> GetAuthorityBIList(JsonElement jsonElement)
  80. {
  81. //jsonElement.TryGetProperty("site", out JsonElement site);
  82. Dictionary<string, object> dic = new() { { "PartitionKey", "authority-bi" } };
  83. var table = _azureStorage.GetCloudTableClient().GetTableReference("SchoolSetting");
  84. ////分开部署,就不需要,一站多用时,取消注释
  85. //if ($"{site}".Equals(BIConst.Global))
  86. // table = _azureStorage.GetCloudTableClient(BIConst.Global).GetTableReference("SchoolSetting");
  87. List<Authority> authorityBIList = await table.FindListByDict<Authority>(dic);
  88. return Ok(new { authorityBIList });
  89. }
  90. /// <summary>
  91. /// 生成学校Code信息
  92. /// </summary>
  93. /// <param name="jsonElement"></param>
  94. /// <returns></returns>
  95. [ProducesDefaultResponseType]
  96. [AuthToken(Roles = "admin,rdc")]
  97. [HttpPost("get-schoolcode")]
  98. public async Task<IActionResult> GetSchoolCode(JsonElement jsonElement)
  99. {
  100. if (!jsonElement.TryGetProperty("schools", out JsonElement schools)) return BadRequest();
  101. var cosmosClient = _azureCosmos.GetCosmosClient();
  102. List<CreateSchoolInfo> cSchools = schools.ToObject<List<CreateSchoolInfo>>();
  103. List<CreateSchoolInfo> createScInfo = new(); //生成好的学校Codd信息
  104. foreach (var item in cSchools)
  105. {
  106. CreateSchoolInfo createSchoolInfo = item;
  107. //生成学校ID
  108. bool tempStaus = true;
  109. do
  110. {
  111. createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  112. var schoolStatu = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
  113. if (schoolStatu.Status != 200) tempStaus = false;
  114. else createSchoolInfo.createCount = createSchoolInfo.createCount >= 3 ? createSchoolInfo.createCount = 3 : createSchoolInfo.createCount += 1;
  115. } while (tempStaus);
  116. createScInfo.Add(createSchoolInfo);
  117. }
  118. return Ok(new { state = RespondCode.Ok, createScInfo });
  119. }
  120. /// <summary>
  121. /// 批量创校 //已对接
  122. /// </summary>
  123. /// <param name="school"></param>
  124. /// <returns></returns>
  125. [ProducesDefaultResponseType]
  126. [AuthToken(Roles = "admin,rdc")]
  127. [HttpPost("batch-school")]
  128. public async Task<IActionResult> BatchCreateSchool(FoundSchools foundSchools)
  129. {
  130. try
  131. {
  132. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  133. List<BISchool> schools = new();
  134. List<BISchool> userScs = new();
  135. List<BISchool> cutArea = new();
  136. List<CreateSchoolInfo> scInfos = new();
  137. List<string> upSc = new();
  138. StringBuilder stringBuilder = new($"{_tmdName}【{_tmdId}】使用批量创校功能:");
  139. StringBuilder vsSql = new();
  140. StringBuilder noticeDD = new(); //创校信息通知
  141. var cosmosClient = _azureCosmos.GetCosmosClient();
  142. var tableClient = _azureStorage.GetCloudTableClient();
  143. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  144. //if (BIConst.Global.Equals($"{foundSchools.site}"))
  145. //{
  146. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  147. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  148. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  149. //}
  150. if (foundSchools.biSchools.Count > 0)
  151. {
  152. #region 新版直接创建
  153. foreach (BISchool bischool in foundSchools.biSchools)
  154. {
  155. Area area = null;
  156. //查询区是否存在
  157. var respAreaId = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{bischool.areaId}", new PartitionKey("Base-Area"));
  158. if (respAreaId.Status == 200)
  159. {
  160. using var areaBase = await JsonDocument.ParseAsync(respAreaId.ContentStream);
  161. area = areaBase.ToObject<Area>();
  162. }
  163. CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo()
  164. {
  165. province = bischool.province,
  166. id = bischool.id,
  167. name = bischool.name,
  168. city = bischool.city,
  169. aname = "",
  170. createCount = 0,
  171. };
  172. //生成学校ID
  173. bool tempStaus = true;
  174. do
  175. {
  176. createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  177. var schoolStatu = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
  178. if (schoolStatu.Status != 200) tempStaus = false;
  179. else createSchoolInfo.createCount = createSchoolInfo.createCount >= 3 ? createSchoolInfo.createCount = 3 : createSchoolInfo.createCount += 1;
  180. } while (tempStaus);
  181. if (createSchoolInfo.id != null)
  182. {
  183. string campusId = Guid.NewGuid().ToString();
  184. TEAMModelOS.SDK.Models.Edition edition = new();
  185. edition.scaleVersion = bischool.scaleVersion;
  186. School upSchool = new()
  187. {
  188. id = createSchoolInfo.id,
  189. name = bischool.name,
  190. size = bischool.size == 0 ? 100 : bischool.size,
  191. code = "Base",
  192. campuses = new List<Campus> { new Campus { name = bischool.name, id = campusId } },
  193. region = bischool.region,
  194. province = bischool.province,
  195. city = bischool.city,
  196. dist = bischool.dist,
  197. address = bischool.address,
  198. picture = "https://teammodelstorage.blob.core.chinacloudapi.cn/0-public/school/bbf54fb3-3fc8-43ae-a358-107281c174cc.png",
  199. timeZone = new TEAMModelOS.SDK.Models.TimeZone { label = "(UTC+08:00) 北京,重庆,香港特别行政区,乌鲁木齐", value = "+08:00" },
  200. type = string.IsNullOrEmpty(bischool.type.ToString()) ? 1 : bischool.type,
  201. pk = "School",
  202. ttl = -1,
  203. areaId = area == null ? "" : area.id,
  204. standard = area == null ? "" : area.standard,
  205. schoolCode = createSchoolInfo.id,
  206. period = PresetSchoolPeriod(bischool.period, foundSchools.lang, campusId),
  207. scale = bischool.size >= 300 ? 500 : 0,
  208. isinit = true,
  209. //modules=bischool?.modules,
  210. openLessonRecord = (_option.Location.Contains("Global")) ? false : true,
  211. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  212. edition = edition
  213. };
  214. scInfos.Add(createSchoolInfo);
  215. vsSql.Append($"{upSchool.name}【{upSchool.id}】,");
  216. stringBuilder.Append($"创建学校:{upSchool.name}【{upSchool.id}】");
  217. noticeDD.Append($"{upSchool.name}【{upSchool.id}】 \r 学校管理员信息:");
  218. upSc.Add(upSchool.id);
  219. //创建学校
  220. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<School>(upSchool, new PartitionKey(upSchool.code));
  221. //创建学校信息中间件
  222. //_ = _httpTrigger.RequestHttpTrigger(new { school = $"{upSchool}" }, _option.Location, "set-sc-birelation");
  223. await BIStats.SetSchoolBIRelation(cosmosClient, blobClient, tableClient, _dingDing, upSchool);
  224. //创建BI和统计信息
  225. await BIStats.SetScStatsInfo(cosmosClient, _dingDing,upSchool);
  226. var content = new StringContent(bischool.admin.ToArray().ToJsonString(), Encoding.UTF8, "application/json");
  227. string json = await _coreAPIHttpService.GetUserInfos(content);
  228. List<TmdUserinfo> tmdInfos = json.ToObject<List<TmdUserinfo>>();
  229. foreach (var tmdIndo in tmdInfos)
  230. {
  231. Teacher teacher = new();
  232. var resTeache = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync($"{tmdIndo.id}", new PartitionKey("Base"));
  233. if (resTeache.Status == 200)
  234. {
  235. using var tchJson = await JsonDocument.ParseAsync(resTeache.ContentStream);
  236. teacher = tchJson.ToObject<Teacher>();
  237. Teacher.TeacherSchool tchSc = null;
  238. //var tempTch = teacher.schools.Select(x => x.schoolId.Equals(upSchool.id)).ToString();
  239. tchSc = teacher.schools.Find(x => x.schoolId.Equals(upSchool.id));
  240. if (tchSc == null)
  241. {
  242. //教师存在,在该教师信息中添加要管理的学校信息
  243. 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() });
  244. }
  245. //await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, coreUser.id, new PartitionKey("Base"));
  246. SchoolTeacher schoolTeacher = new()
  247. {
  248. id = tmdIndo.id,
  249. code = $"Teacher-{createSchoolInfo.id}",
  250. roles = new List<string> { "admin", "teacher" },
  251. job = "管理员",
  252. name = teacher.name,
  253. picture = teacher.picture,
  254. status = "join",
  255. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  256. pk = "Teacher",
  257. ttl = -1
  258. };
  259. stringBuilder.Append($"【基础:{schoolTeacher.name}【{schoolTeacher.id}】,权限:{string.Join(",", schoolTeacher.roles)}】");
  260. noticeDD.Append($"{schoolTeacher.name}【{schoolTeacher.id}】");
  261. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
  262. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey(schoolTeacher.code));
  263. }
  264. else
  265. {
  266. //不存在 新建教师和新建要管理的学校信息
  267. Teacher addteacher = new()
  268. {
  269. id = tmdIndo.id,
  270. pk = "Base",
  271. code = "Base",
  272. name = $"{tmdIndo.name}",
  273. picture = $"{tmdIndo.picture}",
  274. //创建账号并第一次登录IES5则默认赠送1G
  275. size = 1,
  276. defaultSchool = createSchoolInfo.id,
  277. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  278. schools = new List<Teacher.TeacherSchool>() { new Teacher.TeacherSchool { schoolId = createSchoolInfo.id, name = bischool.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() } }
  279. };
  280. stringBuilder.Append($"【没有该教师基础信息,创建的教师基本信息:{addteacher.name}【{addteacher.id}】");
  281. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(addteacher, new PartitionKey("Base"));
  282. SchoolTeacher schoolTeacher = new()
  283. {
  284. id = tmdIndo.id,
  285. code = $"Teacher-{createSchoolInfo.id}",
  286. roles = new List<string> { "admin", "teacher" },
  287. job = "管理员",
  288. name = $"{tmdIndo.name}",
  289. picture = "",
  290. status = "join",
  291. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  292. pk = "Teacher",
  293. ttl = -1
  294. };
  295. stringBuilder.Append($"权限:{string.Join(",", schoolTeacher.roles)}】");
  296. noticeDD.Append($"{schoolTeacher.name}【{schoolTeacher.id}】");
  297. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey(schoolTeacher.code));
  298. }
  299. }
  300. }
  301. }
  302. #endregion
  303. #region 旧版先检测 在创建
  304. //foreach (BISchool bischool in foundSchools.biSchools)
  305. //{
  306. // List<string> scName = new();
  307. // //查询学校名称是否全字段匹配
  308. // await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: $"select value(c.name) from c where c.name='{bischool.name}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  309. // {
  310. // scName.Add(item);
  311. // }
  312. // Area area = null;
  313. // //查询区是否存在
  314. // var respAreaId = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{bischool.areaId}", new PartitionKey("Base-Area"));
  315. // if (respAreaId.Status == 200)
  316. // {
  317. // using var areaBase = await JsonDocument.ParseAsync(respAreaId.ContentStream);
  318. // area = areaBase.ToObject<Area>();
  319. // }
  320. // bool isSYNCArea = false;
  321. // //查询去是否同步省平台
  322. // var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{bischool.areaId}", new PartitionKey("AreaSetting"));
  323. // if (responseSet.Status == 200)
  324. // {
  325. // using var fileJson = await JsonDocument.ParseAsync(responseSet.ContentStream);
  326. // AreaSetting delSet = fileJson.ToObject<AreaSetting>();
  327. // if (!string.IsNullOrEmpty(delSet.accessConfig))
  328. // isSYNCArea = true;
  329. // }
  330. // if (scName.Count <= 0)
  331. // {
  332. // if (isSYNCArea == false)
  333. // {
  334. // var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{bischool.admin}" } }, _option.Location, _configuration);
  335. // if (coreUser != null && coreUser.id != null)
  336. // {
  337. // CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo()
  338. // {
  339. // province = bischool.province,
  340. // id = "",
  341. // name = bischool.name,
  342. // city = bischool.city,
  343. // aname = "",
  344. // createCount = 0,
  345. // };
  346. // //生成学校ID
  347. // bool tempStaus = true;
  348. // do
  349. // {
  350. // createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  351. // var schoolStatu = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
  352. // if (schoolStatu.Status != 200) tempStaus = false;
  353. // else createSchoolInfo.createCount = createSchoolInfo.createCount >= 3 ? createSchoolInfo.createCount = 3 : createSchoolInfo.createCount += 1;
  354. // } while (tempStaus);
  355. // if (createSchoolInfo.id != null)
  356. // {
  357. // string campusId = Guid.NewGuid().ToString();
  358. // School upSchool = new()
  359. // {
  360. // id = createSchoolInfo.id,
  361. // name = bischool.name,
  362. // size = bischool.size == 0 ? 100 : bischool.size,
  363. // code = "Base",
  364. // campuses = new List<Campus> { new Campus { name = bischool.name, id = campusId } },
  365. // region = bischool.region,
  366. // province = bischool.province,
  367. // city = bischool.city,
  368. // dist = bischool.dist,
  369. // address = bischool.address,
  370. // picture = "https://teammodelstorage.blob.core.chinacloudapi.cn/0-public/school/bbf54fb3-3fc8-43ae-a358-107281c174cc.png",
  371. // timeZone = new TEAMModelOS.SDK.Models.TimeZone { label = "(UTC+08:00) 北京,重庆,香港特别行政区,乌鲁木齐", value = "+08:00" },
  372. // type = string.IsNullOrEmpty(bischool.type.ToString()) ? 1 : bischool.type,
  373. // pk = "School",
  374. // ttl = -1,
  375. // areaId = area == null ? "" : area.id,
  376. // standard = area == null ? "" : area.standard,
  377. // schoolCode = createSchoolInfo.id,
  378. // period = PresetSchoolPeriod(bischool.period, foundSchools.lang, campusId),
  379. // scale = bischool.size >= 300 ? 500 : 0,
  380. // createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  381. // };
  382. // stringBuilder.Append($"创建学校:{upSchool.name}【{upSchool.id}】");
  383. // noticeDD.Append($"【ID:{upSchool.id}|名称:{upSchool.name}】 ");
  384. // upSc.Add(upSchool.id);
  385. // //创建学校
  386. // await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<School>(upSchool, new PartitionKey(upSchool.code));
  387. // //创建学校管理员
  388. // Teacher teacher = null;
  389. // var resTeache = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync($"{coreUser.id}", new PartitionKey("Base"));
  390. // if (resTeache.Status == 200)
  391. // {
  392. // using var tchJson = await JsonDocument.ParseAsync(resTeache.ContentStream);
  393. // teacher = tchJson.ToObject<Teacher>();
  394. // //教师存在,在该教师信息中添加要管理的学校信息
  395. // 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() });
  396. // //await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, coreUser.id, new PartitionKey("Base"));
  397. // SchoolTeacher schoolTeacher = new()
  398. // {
  399. // id = coreUser.id,
  400. // code = $"Teacher-{createSchoolInfo.id}",
  401. // roles = new List<string> { "admin", "teacher" },
  402. // job = "管理员",
  403. // name = teacher.name,
  404. // picture = teacher.picture,
  405. // status = "join",
  406. // createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  407. // pk = "Teacher",
  408. // ttl = -1
  409. // };
  410. // stringBuilder.Append($"教师信息:{schoolTeacher.name}【{schoolTeacher.id}】,教师权限:{string.Join(",", schoolTeacher.roles)}");
  411. // await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
  412. // await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey(schoolTeacher.code));
  413. // }
  414. // else
  415. // {
  416. // //不存在 新建教师和新建要管理的学校信息
  417. // Teacher addteacher = new()
  418. // {
  419. // id = coreUser.id,
  420. // pk = "Base",
  421. // code = "Base",
  422. // name = $"{coreUser.name}",
  423. // picture = $"{coreUser.picture}",
  424. // //创建账号并第一次登录IES5则默认赠送1G
  425. // size = 1,
  426. // defaultSchool = createSchoolInfo.id,
  427. // createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  428. // schools = new List<Teacher.TeacherSchool>() { new Teacher.TeacherSchool { schoolId = createSchoolInfo.id, name = bischool.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() } }
  429. // };
  430. // stringBuilder.Append($"没有该教师信息创建的教师信息:{addteacher.name}【{addteacher.id}】");
  431. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(addteacher, new PartitionKey("Base"));
  432. // SchoolTeacher schoolTeacher = new()
  433. // {
  434. // id = coreUser.id,
  435. // code = $"Teacher-{createSchoolInfo.id}",
  436. // roles = new List<string> { "admin", "teacher" },
  437. // job = "管理员",
  438. // name = $"{coreUser.name}",
  439. // picture = "",
  440. // status = "join",
  441. // createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  442. // pk = "Teacher",
  443. // ttl = -1
  444. // };
  445. // stringBuilder.Append($"教师权限:{string.Join(",", schoolTeacher.roles)}");
  446. // await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey(schoolTeacher.code));
  447. // }
  448. // }
  449. // }
  450. // else userScs.Add(bischool);
  451. // }
  452. // else cutArea.Add(bischool);
  453. // }
  454. // else schools.Add(bischool);
  455. //}
  456. #endregion
  457. }
  458. else return Ok(new { state = 1, message = "创校信息为空" });
  459. if (upSc.Count > 1)
  460. await _dingDing.SendBotMsg($"BI,{_option.Location} \n 批量建校信息:{noticeDD}", GroupNames.成都开发測試群組);
  461. else if (upSc.Count == 1)
  462. await _dingDing.SendBotMsg($"BI,{_option.Location} \n 单个建校信息:{noticeDD}", GroupNames.成都开发測試群組);
  463. ////v2通知
  464. //Teacher targetTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{_tmdId}", new PartitionKey($"Base"));
  465. //_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);
  466. //保存操作记录
  467. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-batchAdd", stringBuilder?.ToString(), _dingDing, httpContext: HttpContext);
  468. if (schools.Count == foundSchools.biSchools.Count || userScs.Count == foundSchools.biSchools.Count)
  469. return Ok(new { state = RespondCode.CreateFailed, message = "已有部分学校批量创建成功;学校已经重复/学校信息有误!请检查学校信息!", schools, userScs });
  470. else
  471. {
  472. if (schools.Count > 0 || userScs.Count > 0 || cutArea.Count > 0)
  473. return Ok(new { state = RespondCode.Created, message = "已有部分学校批量创建成功;学校已经重复/学校信息有误/区域已在研修不能加区!请检查学校信息!", schools, userScs, cutArea });
  474. else
  475. return Ok(new { state = RespondCode.Ok, message = "批量创校已全部完成", scInfos });
  476. }
  477. }
  478. catch (Exception ex)
  479. {
  480. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/batch-school \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  481. return BadRequest();
  482. }
  483. }
  484. /// <summary>
  485. /// 依据学校编号查询学校信息;若是没有传学校编号,则查询所有学校信息 //已对接
  486. /// </summary>
  487. /// <param name="jsonElement"></param>
  488. /// <returns></returns>
  489. [ProducesDefaultResponseType]
  490. [HttpPost("get-schoolsinfo")]
  491. public async Task<IActionResult> GetSchoolsInfo(JsonElement jsonElement)
  492. {
  493. try
  494. {
  495. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  496. jsonElement.TryGetProperty("role", out JsonElement role);
  497. jsonElement.TryGetProperty("scId", out JsonElement scId);
  498. jsonElement.TryGetProperty("name", out JsonElement name);
  499. jsonElement.TryGetProperty("order", out JsonElement order);
  500. jsonElement.TryGetProperty("province", out JsonElement province);
  501. jsonElement.TryGetProperty("city", out JsonElement city);
  502. jsonElement.TryGetProperty("dist", out JsonElement dist);
  503. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  504. var cosmosClient = _azureCosmos.GetCosmosClient();
  505. ////分开部署,就不需要,一站多用时,取消注释
  506. //if ($"{site}".Equals(BIConst.Global))
  507. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  508. int scCnt = 0;
  509. int? pageSize = 100; //默认不指定返回大小
  510. string continuationToken = string.Empty; //返给前端分页token
  511. string pageToken = default;//接受前端的分页Tolen
  512. bool iscontinuation = false;//是否需要进行分页查询,默认不分页
  513. List<AssistSchool> schoolAssists = new(); //返回学校列表集合
  514. List<string> schoolIds = new();
  515. 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 ");
  516. StringBuilder scCntSql = new($"select value(count(c.id)) from c");
  517. if (jsonElement.TryGetProperty("pageSize", out JsonElement jsonPageSize))
  518. {
  519. if (!jsonPageSize.ValueKind.Equals(JsonValueKind.Undefined) && !jsonPageSize.ValueKind.Equals(JsonValueKind.Null) && jsonPageSize.TryGetInt32(out int tempPageSize))
  520. pageSize = tempPageSize;
  521. }
  522. if (pageSize != null && pageSize.Value > 0)
  523. iscontinuation = true;
  524. if (jsonElement.TryGetProperty("contToken", out JsonElement ContToken))
  525. pageToken = ContToken.GetString();
  526. if (!string.IsNullOrEmpty($"{scId}") && string.IsNullOrEmpty($"{name}"))
  527. {
  528. stringBuilder.Append($" where c.id='{scId}'");
  529. scCntSql.Append($" where c.id='{scId}'");
  530. }
  531. if (string.IsNullOrEmpty($"{scId}") && !string.IsNullOrEmpty($"{name}"))
  532. {
  533. stringBuilder.Append($" where Contains(c.name,'{name}')");
  534. scCntSql.Append($" where Contains(c.name,'{name}')");
  535. }
  536. if (!string.IsNullOrEmpty($"{province}") && string.IsNullOrEmpty($"{city}") && string.IsNullOrEmpty($"{dist}"))
  537. {
  538. stringBuilder.Append($" where Contains(c.province,'{province}')");
  539. scCntSql.Append($" where Contains(c.province,'{province}')");
  540. }
  541. if (!string.IsNullOrEmpty($"{city}") && !string.IsNullOrEmpty($"{city}") && string.IsNullOrEmpty($"{dist}"))
  542. {
  543. stringBuilder.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}')");
  544. scCntSql.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}')");
  545. }
  546. if (!string.IsNullOrEmpty($"{dist}") && !string.IsNullOrEmpty($"{city}") && !string.IsNullOrEmpty($"{dist}"))
  547. {
  548. stringBuilder.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}') and Contains(c.dist,'{dist}')");
  549. scCntSql.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}') and Contains(c.dist,'{dist}')");
  550. }
  551. if ($"{order}".Equals("desc"))
  552. stringBuilder.Append(" order by c.createTime desc");
  553. if (!string.IsNullOrEmpty($"{tmdId}"))
  554. {
  555. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", roles: !string.IsNullOrEmpty($"{role}") ? $"{role}" : "assist", isMany: true);
  556. string scsSql = BICommonWay.ManyScSql("c.id", schoolIds);
  557. scCntSql.Append($" where {scsSql}");
  558. scCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", scCntSql.ToString(), "Base");
  559. foreach (var id in schoolIds)
  560. {
  561. 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}'");
  562. if ($"{order}".Equals("desc"))
  563. sqlTxt.Append(" order by c.createTime desc");
  564. else
  565. sqlTxt.Append(" order by c.createTime asc");
  566. await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<AssistSchool>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  567. {
  568. schoolAssists.Add(itemSchool);
  569. }
  570. }
  571. }
  572. else
  573. {
  574. scCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", scCntSql.ToString(), "Base");
  575. await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), continuationToken: pageToken, requestOptions: new QueryRequestOptions() { MaxItemCount = pageSize, PartitionKey = new PartitionKey("Base") }))
  576. {
  577. using var json = await JsonDocument.ParseAsync(itemSchool.ContentStream);
  578. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt16() > 0)
  579. {
  580. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  581. {
  582. schoolAssists.Add(obj.ToObject<AssistSchool>());
  583. }
  584. if (iscontinuation)
  585. {
  586. continuationToken = itemSchool.GetContinuationToken();
  587. break;
  588. }
  589. }
  590. }
  591. }
  592. //if (schoolIds.Count > 0)
  593. //{
  594. // scCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", scCntSql.ToString(), "Base");
  595. // foreach (var id in schoolIds)
  596. // {
  597. // 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}'");
  598. // if ($"{order}".Equals("desc"))
  599. // sqlTxt.Append(" order by c.createTime desc");
  600. // await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<AssistSchool>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  601. // {
  602. // schoolAssists.Add(itemSchool);
  603. // }
  604. // }
  605. //}
  606. //else
  607. //{
  608. // if (!string.IsNullOrEmpty($"{scId}") && string.IsNullOrEmpty($"{name}"))
  609. // {
  610. // stringBuilder.Append($" where c.id='{scId}'");
  611. // scCntSql.Append($" where c.id='{scId}'");
  612. // }
  613. // if (string.IsNullOrEmpty($"{scId}") && !string.IsNullOrEmpty($"{name}"))
  614. // {
  615. // stringBuilder.Append($" where Contains(c.name,'{name}')");
  616. // scCntSql.Append($" where Contains(c.name,'{name}')");
  617. // }
  618. // if (!string.IsNullOrEmpty($"{province}") && string.IsNullOrEmpty($"{city}") && string.IsNullOrEmpty($"{dist}"))
  619. // {
  620. // stringBuilder.Append($" where Contains(c.province,'{province}')");
  621. // scCntSql.Append($" where Contains(c.province,'{province}')");
  622. // }
  623. // if (!string.IsNullOrEmpty($"{city}") && !string.IsNullOrEmpty($"{city}") && string.IsNullOrEmpty($"{dist}"))
  624. // {
  625. // stringBuilder.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}')");
  626. // scCntSql.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}')");
  627. // }
  628. // if (!string.IsNullOrEmpty($"{dist}") && !string.IsNullOrEmpty($"{city}") && !string.IsNullOrEmpty($"{dist}"))
  629. // {
  630. // stringBuilder.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}') and Contains(c.dist,'{dist}')");
  631. // scCntSql.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}') and Contains(c.dist,'{dist}')");
  632. // }
  633. // if ($"{order}".Equals("desc"))
  634. // stringBuilder.Append(" order by c.createTime desc");
  635. // scCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", scCntSql.ToString(), "Base");
  636. // await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), continuationToken: pageToken, requestOptions: new QueryRequestOptions() { MaxItemCount = pageSize, PartitionKey = new PartitionKey("Base") }))
  637. // {
  638. // using var json = await JsonDocument.ParseAsync(itemSchool.ContentStream);
  639. // if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt16() > 0)
  640. // {
  641. // foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  642. // {
  643. // schoolAssists.Add(obj.ToObject<AssistSchool>());
  644. // }
  645. // if (iscontinuation)
  646. // {
  647. // continuationToken = itemSchool.GetContinuationToken();
  648. // break;
  649. // }
  650. // }
  651. // }
  652. //}
  653. foreach (var item in schoolAssists)
  654. {
  655. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(item.id, new PartitionKey("ProductSum"));
  656. if (response.Status == 200)
  657. {
  658. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  659. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  660. item.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  661. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  662. item.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  663. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  664. item.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  665. }
  666. item.assists = await CommonFind.FindSchoolRoles(cosmosClient, item.id, "assist");
  667. item.scAdmin = await CommonFind.FindSchoolRoles(cosmosClient, item.id, "admin");
  668. item.lessonCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c ", $"LessonRecord-{item.id}");
  669. }
  670. //schoolAssists.ForEach(async school =>
  671. //{
  672. // var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school.id, new PartitionKey("ProductSum"));
  673. // if (response.Status == 200)
  674. // {
  675. // using var json = await JsonDocument.ParseAsync(response.ContentStream);
  676. // if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  677. // {
  678. // school.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  679. // }
  680. // if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  681. // {
  682. // school.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  683. // }
  684. // if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  685. // {
  686. // school.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  687. // }
  688. // }
  689. // school.assists = await CommonFind.FindSchoolRoles(cosmosClient, school.id, "assist");
  690. // school.lessonCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c ", $"LessonRecord-{school.id}");
  691. //});
  692. return Ok(new { state = 200, scCnt, continuationToken, schoolAssists });
  693. }
  694. catch (Exception ex)
  695. {
  696. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/get-schoolsinfo \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  697. return BadRequest();
  698. }
  699. }
  700. /// <summary>
  701. /// 所有信息
  702. /// </summary>
  703. /// <param name="jsonElement"></param>
  704. /// <returns></returns>
  705. [ProducesDefaultResponseType]
  706. [HttpPost("get-allscinfo")]
  707. public async Task<IActionResult> GetAllScsInfo(JsonElement jsonElement)
  708. {
  709. try
  710. {
  711. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  712. jsonElement.TryGetProperty("role", out JsonElement role);
  713. jsonElement.TryGetProperty("scId", out JsonElement scId);
  714. jsonElement.TryGetProperty("name", out JsonElement name);
  715. jsonElement.TryGetProperty("order", out JsonElement order);
  716. jsonElement.TryGetProperty("province", out JsonElement province);
  717. jsonElement.TryGetProperty("city", out JsonElement city);
  718. jsonElement.TryGetProperty("dist", out JsonElement dist);
  719. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  720. var cosmosClient = _azureCosmos.GetCosmosClient();
  721. ////分开部署,就不需要,一站多用时,取消注释
  722. //if ($"{site}".Equals(BIConst.Global))
  723. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  724. int scCnt = 0;
  725. List<AssistSchool> schoolAssists = new(); //返回学校列表集合
  726. List<string> schoolIds = new();
  727. 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 ");
  728. StringBuilder scCntSql = new($"select value(count(c.id)) from c");
  729. if (!string.IsNullOrEmpty($"{scId}") && string.IsNullOrEmpty($"{name}"))
  730. {
  731. stringBuilder.Append($" where c.id='{scId}'");
  732. scCntSql.Append($" where c.id='{scId}'");
  733. }
  734. if (string.IsNullOrEmpty($"{scId}") && !string.IsNullOrEmpty($"{name}"))
  735. {
  736. stringBuilder.Append($" where Contains(c.name,'{name}')");
  737. scCntSql.Append($" where Contains(c.name,'{name}')");
  738. }
  739. if (!string.IsNullOrEmpty($"{province}") && string.IsNullOrEmpty($"{city}") && string.IsNullOrEmpty($"{dist}"))
  740. {
  741. stringBuilder.Append($" where Contains(c.province,'{province}')");
  742. scCntSql.Append($" where Contains(c.province,'{province}')");
  743. }
  744. if (!string.IsNullOrEmpty($"{city}") && !string.IsNullOrEmpty($"{city}") && string.IsNullOrEmpty($"{dist}"))
  745. {
  746. stringBuilder.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}')");
  747. scCntSql.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}')");
  748. }
  749. if (!string.IsNullOrEmpty($"{dist}") && !string.IsNullOrEmpty($"{city}") && !string.IsNullOrEmpty($"{dist}"))
  750. {
  751. stringBuilder.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}') and Contains(c.dist,'{dist}')");
  752. scCntSql.Append($" where Contains(c.province,'{province}') and Contains(c.city,'{city}') and Contains(c.dist,'{dist}')");
  753. }
  754. if (!string.IsNullOrEmpty($"{tmdId}"))
  755. {
  756. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", roles: !string.IsNullOrEmpty($"{role}") ? $"{role}" : "assist", isMany: true);
  757. string scsSql = BICommonWay.ManyScSql("c.id", schoolIds);
  758. scCntSql.Append($" where {scsSql}");
  759. scCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", scCntSql.ToString(), "Base");
  760. foreach (var id in schoolIds)
  761. {
  762. 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}'");
  763. if ($"{order}".Equals("desc"))
  764. sqlTxt.Append(" order by c.createTime desc");
  765. await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<AssistSchool>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  766. {
  767. schoolAssists.Add(itemSchool);
  768. }
  769. }
  770. }
  771. else
  772. {
  773. if ($"{order}".Equals("desc"))
  774. stringBuilder.Append(" order by c.createTime desc");
  775. scCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", scCntSql.ToString(), "Base");
  776. await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  777. {
  778. using var json = await JsonDocument.ParseAsync(itemSchool.ContentStream);
  779. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt16() > 0)
  780. {
  781. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  782. {
  783. schoolAssists.Add(obj.ToObject<AssistSchool>());
  784. }
  785. }
  786. }
  787. }
  788. foreach (var item in schoolAssists)
  789. {
  790. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(item.id, new PartitionKey("ProductSum"));
  791. if (response.Status == 200)
  792. {
  793. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  794. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  795. item.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  796. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  797. item.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  798. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  799. item.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  800. }
  801. item.assists = await CommonFind.FindSchoolRoles(cosmosClient, item.id, "assist");
  802. item.scAdmin = await CommonFind.FindSchoolRoles(cosmosClient, item.id, "admin");
  803. item.lessonCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c ", $"LessonRecord-{item.id}");
  804. }
  805. return Ok(new { state = 200, scCnt, schoolAssists });
  806. }
  807. catch (Exception ex)
  808. {
  809. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/get-allscinfo() \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  810. return BadRequest();
  811. }
  812. }
  813. /// <summary>
  814. /// 使用yieId 关键字 本地效率未测出
  815. /// </summary>
  816. /// <param name="cosmosClient"></param>
  817. /// <param name="schoolAssists"></param>
  818. /// <returns></returns>
  819. private async IAsyncEnumerable<List<AssistSchool>> GetSchools(CosmosClient cosmosClient, List<AssistSchool> schoolAssists)
  820. {
  821. List<AssistSchool> tempSchoolAssists = new();
  822. foreach (var temp in schoolAssists)
  823. {
  824. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(temp.id, new PartitionKey("ProductSum"));
  825. if (response.Status == 200)
  826. {
  827. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  828. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  829. {
  830. temp.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  831. }
  832. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  833. {
  834. temp.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  835. }
  836. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  837. {
  838. temp.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  839. }
  840. }
  841. temp.assists = await CommonFind.FindSchoolRoles(cosmosClient, temp.id, "assist");
  842. tempSchoolAssists.Add(temp);
  843. }
  844. yield return tempSchoolAssists;
  845. }
  846. /// <summary>
  847. /// 取得学校所有顾问列表
  848. /// </summary>
  849. /// <returns></returns>
  850. [ProducesDefaultResponseType]
  851. [HttpPost("get-schoolassist")]
  852. public async Task<IActionResult> GetSchoolAssist(JsonElement jsonElement)
  853. {
  854. try
  855. {
  856. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  857. string schoolId = (jsonElement.TryGetProperty("schoolId", out JsonElement _schoolId)) ? _schoolId.GetString() : string.Empty;
  858. Dictionary<string, List<Dictionary<string, string>>> haveSchoolManger = new();
  859. string managerWhereOption = (!string.IsNullOrWhiteSpace(schoolId)) ? $" AND c.code = 'Teacher-{schoolId}'" : string.Empty;
  860. //查询学校的顾问
  861. 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}";
  862. var cosmosClient = _azureCosmos.GetCosmosClient();
  863. //if ($"{site}".Equals(BIConst.Global))
  864. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  865. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: managerSql, requestOptions: new QueryRequestOptions() { }))
  866. {
  867. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  868. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  869. {
  870. string id = obj.GetProperty("id").GetString(); //管理员ID
  871. string name = obj.GetProperty("name").GetString(); //管理员姓名
  872. string tempSchoolId = obj.GetProperty("schoolId").GetString(); //学校ID
  873. Dictionary<string, string> managerDic = new();
  874. managerDic.Add("id", id);
  875. managerDic.Add("name", name);
  876. if (haveSchoolManger.ContainsKey(tempSchoolId))
  877. {
  878. haveSchoolManger[tempSchoolId].Add(managerDic);
  879. }
  880. else
  881. {
  882. List<Dictionary<string, string>> managerList = new List<Dictionary<string, string>>();
  883. managerList.Add(managerDic);
  884. haveSchoolManger.Add(tempSchoolId, managerList);
  885. }
  886. }
  887. }
  888. //管理模组学校
  889. List<string> baseModuleSchoos = new List<string>();
  890. string baseWhereOption = (!string.IsNullOrEmpty(schoolId)) ? $" and c.id='{schoolId}'" : string.Empty;
  891. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"select c.id from c join serviceProduct in c.service.product where serviceProduct.prodCode = 'IPDYZYLC' {baseWhereOption}", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Product") }))
  892. {
  893. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  894. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  895. {
  896. string tempSchoolId = obj.GetProperty("id").GetString(); //学校ID
  897. baseModuleSchoos.Add(tempSchoolId);
  898. }
  899. }
  900. //学校信息
  901. List<object> schools = new List<object>();
  902. string schoolWhereOption = (!string.IsNullOrEmpty(schoolId)) ? $" where c.id='{schoolId}'" : string.Empty;
  903. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"select c.id,c.name,c.period,c.schoolCode,c.region,c.province,c.city,c.picture from c {schoolWhereOption}", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  904. {
  905. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  906. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  907. {
  908. dynamic schoolExpando = new ExpandoObject();
  909. schoolExpando.id = obj.GetProperty("id").GetString();
  910. schoolExpando.name = obj.GetProperty("name").GetString();
  911. //schoolExpando.period = obj.GetProperty("period");
  912. schoolExpando.schoolCode = obj.GetProperty("schoolCode").GetString();
  913. schoolExpando.region = obj.GetProperty("region").GetString();
  914. schoolExpando.province = obj.GetProperty("province").GetString();
  915. schoolExpando.city = obj.GetProperty("city").GetString();
  916. schoolExpando.picture = obj.GetProperty("picture").GetString();
  917. if (haveSchoolManger.ContainsKey(schoolExpando.id))
  918. {
  919. schoolExpando.hasMarger = true;
  920. schoolExpando.managers = haveSchoolManger[schoolExpando.id];
  921. }
  922. else
  923. {
  924. schoolExpando.hasMarger = false;
  925. schoolExpando.managers = new List<object>();
  926. }
  927. schoolExpando.hasBaseModule = (baseModuleSchoos.Contains(schoolExpando.id)) ? true : false;
  928. schools.Add(schoolExpando);
  929. }
  930. }
  931. return Ok(new { state = 200, schools });
  932. }
  933. catch (Exception ex)
  934. {
  935. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/get-schools \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  936. return BadRequest();
  937. }
  938. }
  939. /// <summary>
  940. /// 修改学校信息和顾问信息 //已经对接
  941. /// </summary>
  942. /// <param name="jsonElement"></param>
  943. /// <returns></returns>
  944. [ProducesDefaultResponseType]
  945. [AuthToken(Roles = "admin,rdc")]
  946. [HttpPost("upd-schoolassist")]
  947. public async Task<IActionResult> UpdSchoolAssist(JsonElement jsonElement)
  948. {
  949. try
  950. {
  951. if (!jsonElement.TryGetProperty("schoolId", out JsonElement _schoolId)) return BadRequest();
  952. if (!jsonElement.TryGetProperty("name", out JsonElement schoolName)) return BadRequest();
  953. if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
  954. if (!jsonElement.TryGetProperty("standard", out JsonElement standard)) return BadRequest();
  955. //if (!jsonElement.TryGetProperty("period", out JsonElement period)) return BadRequest();
  956. if (!jsonElement.TryGetProperty("picture", out JsonElement picture)) return BadRequest();
  957. if (!jsonElement.TryGetProperty("size", out JsonElement size)) return BadRequest();
  958. if (!jsonElement.TryGetProperty("scale", out JsonElement scale)) return BadRequest();
  959. if (!jsonElement.TryGetProperty("type", out JsonElement _type)) return BadRequest();
  960. jsonElement.TryGetProperty("province", out JsonElement province);
  961. jsonElement.TryGetProperty("city", out JsonElement city);
  962. jsonElement.TryGetProperty("dist", out JsonElement dist);
  963. jsonElement.TryGetProperty("address", out JsonElement address);
  964. string code = (jsonElement.TryGetProperty("code", out JsonElement _code))? _code.GetString() : string.Empty;
  965. jsonElement.TryGetProperty("assist", out JsonElement assist);
  966. jsonElement.TryGetProperty("scaleVersion", out JsonElement scaleVersion);
  967. //手動追加商業模組的部分先封印,商業模組需要經過訂單系統下單控管。
  968. //List<string> modules = null ;
  969. //if (!jsonElement.TryGetProperty("modules ", out JsonElement _modules))
  970. //{
  971. // return BadRequest();
  972. //}
  973. //else {
  974. // modules= _modules.ToObject<List<string>>();
  975. //}
  976. List<IdInfo> idInfos = assist.ToObject<List<IdInfo>>();
  977. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  978. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  979. var cosmosClient = _azureCosmos.GetCosmosClient();
  980. var tableClient = _azureStorage.GetCloudTableClient();
  981. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  982. //if ($"{site}".Equals(BIConst.Global))
  983. //{
  984. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  985. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  986. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  987. //}
  988. //IES5 實體學校變更
  989. if (!code.Equals("VirtualBase"))
  990. {
  991. School tempShool = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{_schoolId}", new PartitionKey("Base"));
  992. if (tempShool != null)
  993. {
  994. List<Period> periods = new();
  995. string campusId = Guid.NewGuid().ToString();
  996. //periodS.ForEach(x =>
  997. //{
  998. // periods.Add(new Period { id = Guid.NewGuid().ToString(), name = x.ToString(), campusId = campusId });
  999. //});
  1000. //tempShool.period = periods;
  1001. //if (modules!=null) {
  1002. // tempShool.modules=modules;
  1003. //}
  1004. tempShool.size = !string.IsNullOrEmpty($"{size}") ? int.Parse($"{size}") : tempShool.size;
  1005. tempShool.scale = !string.IsNullOrEmpty($"{scale}") ? int.Parse($"{scale}") : tempShool.scale;
  1006. tempShool.picture = $"{picture}";
  1007. tempShool.type = int.Parse($"{_type}");
  1008. tempShool.name = $"{schoolName}";
  1009. tempShool.areaId = $"{areaId}";
  1010. tempShool.standard = $"{standard}";
  1011. tempShool.province = string.IsNullOrEmpty($"{province}") ? tempShool.province : $"{province}";
  1012. tempShool.city = string.IsNullOrEmpty($"{city}") ? tempShool.city : $"{city}";
  1013. tempShool.dist = string.IsNullOrEmpty($"{dist}") ? tempShool.dist : $"{dist}";
  1014. tempShool.address = string.IsNullOrEmpty($"{address}") ? tempShool.address : $"{address}";
  1015. //計算學校版本
  1016. List<SchoolProductSumData> services = new List<SchoolProductSumData>();
  1017. Azure.Response productSumResponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{_schoolId}", new PartitionKey("ProductSum"));
  1018. if (productSumResponse.Status == 200)
  1019. {
  1020. var doc = JsonDocument.Parse(productSumResponse.Content);
  1021. if (doc.RootElement.TryGetProperty("service", out JsonElement service))
  1022. {
  1023. services.AddRange(service.ToObject<List<SchoolProductSumData>>());
  1024. }
  1025. }
  1026. tempShool.edition = BISchoolService.calSchoolEdition(tempShool, services.Select(s => s.prodCode).ToList());
  1027. //tempShool.edition.scaleVersion = string.IsNullOrEmpty($"{scaleVersion}") ? tempShool.edition.scaleVersion : $"{scaleVersion}";
  1028. tempShool.edition.scaleVersion = ($"{scaleVersion}" == null) ? tempShool.edition.scaleVersion : $"{scaleVersion}";
  1029. //修改学校
  1030. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(tempShool, tempShool.id, new PartitionKey("Base"));
  1031. //创建学校信息中间件
  1032. await BIStats.SetSchoolBIRelation(cosmosClient, blobClient, tableClient, _dingDing, tempShool);
  1033. //修改学校教师关联的信息
  1034. string sql = $"SELECT distinct value(c) FROM c join A1 in c.schools where A1.schoolId='{tempShool.id}'";
  1035. List<Teacher> teachers = new();
  1036. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  1037. {
  1038. teachers.Add(item);
  1039. }
  1040. foreach (var item in teachers)
  1041. {
  1042. Teacher.TeacherSchool teacherSchool = item.schools.Find(x => x.schoolId.Equals(tempShool.id));
  1043. if (teacherSchool != null)
  1044. {
  1045. teacherSchool.name = tempShool.name;
  1046. teacherSchool.picture = tempShool.picture;
  1047. teacherSchool.areaId = tempShool.areaId;
  1048. }
  1049. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey($"Base"));
  1050. }
  1051. //学校信息中间件更新
  1052. BIRelation biRel = new();
  1053. var respRel = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(tempShool.id, new PartitionKey("BIRel"));
  1054. if (respRel.Status == 200)
  1055. {
  1056. using var fileJson = await JsonDocument.ParseAsync(respRel.ContentStream);
  1057. biRel = fileJson.ToObject<BIRelation>();
  1058. }
  1059. else
  1060. {
  1061. biRel.id = tempShool.id;
  1062. }
  1063. string aName = null;
  1064. if (!string.IsNullOrEmpty($"{tempShool.areaId}"))
  1065. {
  1066. aName = await CosmosQueryHelper.GetStr(cosmosClient, "Normal", $"select value(c.name) from c where c.id='{tempShool.areaId}'", "Base-Area");
  1067. }
  1068. biRel.name = tempShool.name;
  1069. biRel.picture = tempShool.picture;
  1070. biRel.region = tempShool.region;
  1071. biRel.province = tempShool.province;
  1072. biRel.city = tempShool.city;
  1073. biRel.dist = tempShool.dist;
  1074. biRel.address = tempShool.address;
  1075. biRel.areaId = tempShool.areaId;
  1076. biRel.size = tempShool.size;
  1077. biRel.scale = tempShool.scale;
  1078. biRel.upDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1079. biRel.areaName = aName;
  1080. biRel.edition = tempShool.edition;
  1081. if (idInfos.Count > 0)
  1082. {
  1083. foreach (var item in idInfos)
  1084. {
  1085. var tempAss = biRel.assists.Find(f => f.id.Equals(item.id));
  1086. if (tempAss == null)
  1087. biRel.assists.Add(item);
  1088. }
  1089. }
  1090. else
  1091. {
  1092. biRel.assists = idInfos;
  1093. }
  1094. if (respRel.Status == 200)
  1095. {
  1096. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<BIRelation>(biRel, biRel.id, new PartitionKey("BIRel"));
  1097. }
  1098. else
  1099. {
  1100. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<BIRelation>(biRel, new PartitionKey("BIRel"));
  1101. }
  1102. }
  1103. //保存操作记录
  1104. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", $"{_tmdName}【{_tmdId}】修改学校功能,修改的学校:{_schoolId},{_type},{picture},{size},{idInfos.ToArray()}", _dingDing, httpContext: HttpContext);
  1105. return Ok(new { state = 200 });
  1106. }
  1107. //IES5 虛擬學校變更
  1108. else
  1109. {
  1110. VirtualBase tempVirtual = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<VirtualBase>($"{_schoolId}", new PartitionKey("VirtualBase"));
  1111. if (tempVirtual != null)
  1112. {
  1113. tempVirtual.picture = $"{picture}";
  1114. tempVirtual.type = int.Parse($"{_type}");
  1115. tempVirtual.name = $"{schoolName}";
  1116. tempVirtual.areaId = $"{areaId}";
  1117. tempVirtual.standard = $"{standard}";
  1118. tempVirtual.province = string.IsNullOrEmpty($"{province}") ? tempVirtual.province : $"{province}";
  1119. tempVirtual.city = string.IsNullOrEmpty($"{city}") ? tempVirtual.city : $"{city}";
  1120. tempVirtual.dist = string.IsNullOrEmpty($"{dist}") ? tempVirtual.dist : $"{dist}";
  1121. tempVirtual.address = string.IsNullOrEmpty($"{address}") ? tempVirtual.address : $"{address}";
  1122. string aName = null;
  1123. if (!string.IsNullOrEmpty($"{tempVirtual.areaId}"))
  1124. {
  1125. aName = await CosmosQueryHelper.GetStr(cosmosClient, "Normal", $"select value(c.name) from c where c.id='{tempVirtual.areaId}'", "Base-Area");
  1126. }
  1127. tempVirtual.areaName = aName;
  1128. //修改学校
  1129. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<VirtualBase>(tempVirtual, tempVirtual.id, new PartitionKey("VirtualBase"));
  1130. }
  1131. // 保存操作记录
  1132. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", $"{_tmdName}【{_tmdId}】修改学校功能,修改的学校:{_schoolId},{_type},{picture},{size},{idInfos.ToArray()}", _dingDing, httpContext: HttpContext);
  1133. return Ok(new { state = 200 });
  1134. }
  1135. }
  1136. catch (Exception ex)
  1137. {
  1138. await _dingDing.SendBotMsg($"BI, {_option.Location} /batchschool/upd-schoolassist \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1139. return BadRequest();
  1140. }
  1141. }
  1142. /// <summary>
  1143. /// 查询区域的学校
  1144. /// </summary>
  1145. /// <param name="jsonElement"></param>
  1146. /// <returns></returns>
  1147. [ProducesDefaultResponseType]
  1148. [HttpPost("get-schooldist")]
  1149. public async Task<IActionResult> GetSchoolDist(JsonElement jsonElement)
  1150. {
  1151. try
  1152. {
  1153. if (!jsonElement.TryGetProperty("dist", out JsonElement _dist)) return BadRequest();
  1154. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  1155. var cosmosClient = _azureCosmos.GetCosmosClient();
  1156. //if ($"{site}".Equals(BIConst.Global))
  1157. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1158. string sqltxt = $"SELECT * FROM c where c.dist='{_dist}'";
  1159. List<School> schools = new List<School>();
  1160. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: sqltxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1161. {
  1162. schools.Add(item);
  1163. }
  1164. return Ok(new { state = 200, schools });
  1165. }
  1166. catch (Exception ex)
  1167. {
  1168. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/get-schooldist \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1169. return BadRequest();
  1170. }
  1171. }
  1172. /// <summary>
  1173. /// 分页学校和顾问信息
  1174. /// </summary>
  1175. /// <param name="jsonElement"></param>
  1176. /// <returns></returns>
  1177. [ProducesDefaultResponseType]
  1178. [HttpPost("get-schools")]
  1179. public async Task<IActionResult> GetSchools(JsonElement jsonElement)
  1180. {
  1181. //List<School> schools = new List<School>();
  1182. List<AssistSchool> schoolAssists = new List<AssistSchool>();
  1183. if (!jsonElement.TryGetProperty("endPosition", out JsonElement endPosition)) return BadRequest();
  1184. if (!jsonElement.TryGetProperty("pageSize", out JsonElement pageSize)) return BadRequest();
  1185. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  1186. var cosmosClient = _azureCosmos.GetCosmosClient();
  1187. //if ($"{site}".Equals(BIConst.Global))
  1188. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1189. string sqltxt = $"SELECT * FROM c order by c.id offset {endPosition} limit {pageSize}";
  1190. await foreach (var itemSchool in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: sqltxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1191. {
  1192. AssistSchool schoolAssist = new()
  1193. {
  1194. id = itemSchool.id,
  1195. code = itemSchool.code,
  1196. schoolCode = itemSchool.schoolCode,
  1197. name = itemSchool.name,
  1198. region = itemSchool.region,
  1199. province = itemSchool.province,
  1200. city = itemSchool.city,
  1201. dist = itemSchool.dist,
  1202. size = itemSchool.size,
  1203. address = itemSchool.address,
  1204. picture = itemSchool.picture,
  1205. type = itemSchool.type,
  1206. scale = itemSchool.scale,
  1207. areaId = itemSchool.areaId,
  1208. standard = itemSchool.standard
  1209. };
  1210. schoolAssist.assists = await CommonFind.FindSchoolRoles(cosmosClient, itemSchool.id, "assist");
  1211. schoolAssists.Add(schoolAssist);
  1212. }
  1213. return Ok(new { state = 200, schoolAssists });
  1214. }
  1215. /// <summary>
  1216. /// 创校前检查数据
  1217. /// </summary>
  1218. /// <param name="jsonElement"></param>
  1219. /// <returns></returns>
  1220. [ProducesDefaultResponseType]
  1221. [HttpPost("get-checlkexist")]
  1222. public async Task<IActionResult> GetCheckExist(JsonElement jsonElement)
  1223. {
  1224. if (!jsonElement.TryGetProperty("scNames", out JsonElement _scNames)) return BadRequest();
  1225. if (!jsonElement.TryGetProperty("accounts", out JsonElement _accounts)) return BadRequest();
  1226. if (!jsonElement.TryGetProperty("areaIds", out JsonElement _areaIds)) return BadRequest();
  1227. jsonElement.TryGetProperty("schools", out JsonElement schools);
  1228. var cosmosClient = _azureCosmos.GetCosmosClient();
  1229. List<CreateSchoolInfo> cSchools = new();
  1230. if (!string.IsNullOrEmpty($"{schools}"))
  1231. cSchools = schools.ToObject<List<CreateSchoolInfo>>();
  1232. List<string> scNames = _scNames.ToObject<List<string>>();
  1233. List<string> accounts = _accounts.ToObject<List<string>>();
  1234. List<string> areaIds = _areaIds.ToObject<List<string>>();
  1235. List<string> existScNames = new(); //存在的学校
  1236. List<string> noAccounts = new(); // 不存在的账户
  1237. List<string> noAreaIds = new(); //不存在的学区
  1238. List<string> synPro = new(); //已同步省平台
  1239. List<CreateSchoolInfo> createScInfo = new(); //学校简码信息
  1240. if (scNames.Count > 0)
  1241. {
  1242. foreach (var item in scNames)
  1243. {
  1244. //查询学校名称是否全字段匹配
  1245. await foreach (var sc in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: $"select value(c.name) from c where c.name='{item}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1246. {
  1247. existScNames.Add(item);
  1248. }
  1249. }
  1250. }
  1251. if (accounts.Count > 0)
  1252. {
  1253. var content = new StringContent(_accounts.ToString(), Encoding.UTF8, "application/json");
  1254. string json = await _coreAPIHttpService.GetUserInfos(content);
  1255. List<TmdUserinfo> tmdInfos = json.ToObject<List<TmdUserinfo>>();
  1256. accounts.ForEach(ac =>
  1257. {
  1258. TmdUserinfo noTmdInfo = null;
  1259. tmdInfos.ForEach(tmd =>
  1260. {
  1261. if (!string.IsNullOrEmpty(tmd.id))
  1262. if (tmd.id.Equals($"{ac}"))
  1263. noTmdInfo = tmd;
  1264. if (!string.IsNullOrEmpty(tmd.mobile))
  1265. if (tmd.mobile.Equals($"{ac}"))
  1266. noTmdInfo = tmd;
  1267. if (!string.IsNullOrEmpty(tmd.mail))
  1268. if (tmd.mail.Equals($"{ac}"))
  1269. noTmdInfo = tmd;
  1270. });
  1271. //noTmdInfo = tmdInfos.Find(f => f.id.Equals($"{ac}") || f.mail.Equals($"{ac}") || f.mobile.Equals($"{ac}"));
  1272. if (noTmdInfo == null)
  1273. noAccounts.Add(ac);
  1274. });
  1275. }
  1276. if (areaIds.Count > 0)
  1277. {
  1278. foreach (var item in areaIds)
  1279. {
  1280. //查询区是否存在
  1281. var respAreaId = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{item}", new PartitionKey("Base-Area"));
  1282. if (respAreaId.Status != 200)
  1283. {
  1284. noAreaIds.Add(item);
  1285. }
  1286. //查询去是否同步省平台
  1287. var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{item}", new PartitionKey("AreaSetting"));
  1288. if (responseSet.Status == 200)
  1289. {
  1290. using var fileJson = await JsonDocument.ParseAsync(responseSet.ContentStream);
  1291. AreaSetting delSet = fileJson.ToObject<AreaSetting>();
  1292. if (!string.IsNullOrEmpty(delSet.accessConfig))
  1293. synPro.Add(item);
  1294. }
  1295. }
  1296. }
  1297. foreach (var item in cSchools)
  1298. {
  1299. CreateSchoolInfo createSchoolInfo = item;
  1300. //生成学校ID
  1301. bool tempStaus = true;
  1302. do
  1303. {
  1304. createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  1305. var schoolStatu = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
  1306. if (schoolStatu.Status != 200) tempStaus = false;
  1307. else createSchoolInfo.createCount = createSchoolInfo.createCount >= 3 ? createSchoolInfo.createCount = 3 : createSchoolInfo.createCount += 1;
  1308. } while (tempStaus);
  1309. createScInfo.Add(createSchoolInfo);
  1310. }
  1311. if (existScNames.Count > 0 || noAccounts.Count > 0 || noAreaIds.Count > 0 || synPro.Count > 0)
  1312. return Ok(new { state = RespondCode.Created, existScNames, noAccounts, noAreaIds, synPro, createScInfo });
  1313. else
  1314. return Ok(new { state = RespondCode.Ok, createScInfo });
  1315. }
  1316. /// <summary>
  1317. /// 批量创校前检查数据
  1318. /// </summary>
  1319. /// <param name="jsonElement"></param>
  1320. /// <returns></returns>
  1321. [ProducesDefaultResponseType]
  1322. [HttpPost("get-checkexists")]
  1323. public async Task<IActionResult> GetCheckExists(JsonElement jsonElement)
  1324. {
  1325. if (!jsonElement.TryGetProperty("checkScs", out JsonElement checkScs)) return BadRequest();
  1326. List<BISchool> bISchools = checkScs.ToObject<List<BISchool>>();
  1327. var cosmosClient = _azureCosmos.GetCosmosClient();
  1328. List<BISchool> existScNames = new(); //存在的学校
  1329. List<BISchool> noAccounts = new(); // 不存在的账户
  1330. List<BISchool> noAreaIds = new(); //不存在的学区
  1331. List<BISchool> synPro = new(); //已同步省平台
  1332. List<BISchool> createScInfo = new(); //学校简码信息
  1333. foreach (BISchool bISchool in bISchools)
  1334. {
  1335. //查询学校名称是否全字段匹配
  1336. await foreach (var sc in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: $"select value(c.name) from c where c.name='{bISchool.name}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1337. {
  1338. existScNames.Add(bISchool);
  1339. }
  1340. var content = new StringContent(bISchool.admin.ToJsonString(), Encoding.UTF8, "application/json");
  1341. string json = await _coreAPIHttpService.GetUserInfos(content);
  1342. List<TmdUserinfo> tmdInfos = json.ToObject<List<TmdUserinfo>>();
  1343. bISchool.admin.ForEach(ac =>
  1344. {
  1345. TmdUserinfo noTmdInfo = null;
  1346. tmdInfos.ForEach(tmd =>
  1347. {
  1348. if (!string.IsNullOrEmpty(tmd.id))
  1349. if (tmd.id.Equals($"{ac}"))
  1350. noTmdInfo = tmd;
  1351. if (!string.IsNullOrEmpty(tmd.mobile))
  1352. if (tmd.mobile.Equals($"{ac}"))
  1353. noTmdInfo = tmd;
  1354. if (!string.IsNullOrEmpty(tmd.mail))
  1355. if (tmd.mail.Equals($"{ac}"))
  1356. noTmdInfo = tmd;
  1357. });
  1358. //noTmdInfo = tmdInfos.Find(f => f.id.Equals($"{ac}") || f.mail.Equals($"{ac}") || f.mobile.Equals($"{ac}"));
  1359. if (noTmdInfo == null)
  1360. noAccounts.Add(bISchool);
  1361. });
  1362. if (!string.IsNullOrEmpty(bISchool.areaId))
  1363. {
  1364. //查询区是否存在
  1365. var respAreaId = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{bISchool.areaId}", new PartitionKey("Base-Area"));
  1366. if (respAreaId.Status != 200)
  1367. {
  1368. noAreaIds.Add(bISchool);
  1369. }
  1370. //查询去是否同步省平台
  1371. var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{bISchool.areaId}", new PartitionKey("AreaSetting"));
  1372. if (responseSet.Status == 200)
  1373. {
  1374. using var fileJson = await JsonDocument.ParseAsync(responseSet.ContentStream);
  1375. AreaSetting delSet = fileJson.ToObject<AreaSetting>();
  1376. if (!string.IsNullOrEmpty(delSet.accessConfig))
  1377. synPro.Add(bISchool);
  1378. }
  1379. }
  1380. CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo()
  1381. {
  1382. province = bISchool.province,
  1383. id = "",
  1384. name = bISchool.name,
  1385. city = bISchool.city,
  1386. aname = "",
  1387. createCount = 0,
  1388. };
  1389. //生成学校ID
  1390. bool tempStaus = true;
  1391. do
  1392. {
  1393. createSchoolInfo = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  1394. var schoolStatu = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{createSchoolInfo.id}", new PartitionKey($"Base"));
  1395. if (schoolStatu.Status != 200) tempStaus = false;
  1396. else createSchoolInfo.createCount = createSchoolInfo.createCount >= 3 ? createSchoolInfo.createCount = 3 : createSchoolInfo.createCount += 1;
  1397. } while (tempStaus);
  1398. bISchool.id = createSchoolInfo.id;
  1399. createScInfo.Add(bISchool);
  1400. }
  1401. if (existScNames.Count > 0 || noAccounts.Count > 0 || noAreaIds.Count > 0 || synPro.Count > 0)
  1402. return Ok(new { state = RespondCode.Created, existScNames, noAccounts, noAreaIds, synPro, createScInfo });
  1403. else
  1404. return Ok(new { state = RespondCode.Ok, createScInfo });
  1405. }
  1406. /// <summary>
  1407. /// 添加多个学校添加多个管理员
  1408. /// </summary>
  1409. /// <param name="jsonElement"></param>
  1410. /// <returns></returns>
  1411. [ProducesDefaultResponseType]
  1412. [HttpPost("set-batchmanage")]
  1413. public async Task<IActionResult> SetBatchManage(JsonElement jsonElement)
  1414. {
  1415. if (!jsonElement.TryGetProperty("scIds", out JsonElement _scIds)) return BadRequest();
  1416. if (!jsonElement.TryGetProperty("manages", out JsonElement _manages)) return BadRequest();
  1417. var cosmosClient = _azureCosmos.GetCosmosClient();
  1418. List<string> scIds = _scIds.ToObject<List<string>>();
  1419. List<string> manages = _manages.ToObject<List<string>>();
  1420. List<ExistScManage> existScManages = new();
  1421. if (scIds.Count > 0 && manages.Count > 0)
  1422. {
  1423. foreach (var scId in scIds)
  1424. {
  1425. foreach (var msId in manages)
  1426. {
  1427. //不存在则在原来的基础上添加顾问角色
  1428. Teacher tempTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>($"{msId}", new PartitionKey("Base"));
  1429. if (tempTeacher != null)
  1430. {
  1431. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{msId}", new PartitionKey($"Teacher-{scId}"));
  1432. if (response.Status == 200)
  1433. {
  1434. using var tchJson = await JsonDocument.ParseAsync(response.ContentStream);
  1435. SchoolTeacher tchSc = tchJson.ToObject<SchoolTeacher>();
  1436. if (tchSc.roles.Contains("admin"))
  1437. {
  1438. tchSc.roles.Add("admin");
  1439. //添加顾问权限
  1440. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(tchSc, tchSc.id, new PartitionKey($"Teacher-{scId}"));
  1441. }
  1442. else
  1443. existScManages.Add(new ExistScManage() { scId = scId, tmdId = msId });
  1444. }
  1445. else
  1446. {
  1447. SchoolTeacher addSchoolTeacher = new()
  1448. {
  1449. id = tempTeacher.id,
  1450. code = $"Teacher-{scId}",
  1451. pk = "Teacher",
  1452. status = "join",
  1453. roles = new List<string>() { "admin" },
  1454. name = tempTeacher.name,
  1455. job = $"管理员",
  1456. size = 0,
  1457. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1458. };
  1459. var haveTeacher = tempTeacher.schools.Find(x => x.schoolId.Equals($"{scId}"));
  1460. if (haveTeacher == null)
  1461. {
  1462. School school = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<School>(scId, new PartitionKey("Base"));
  1463. //教师存在,在该教师信息中添加要管理的学校信息
  1464. 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() });
  1465. tempTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(tempTeacher, msId, new PartitionKey("Base"));
  1466. }
  1467. //添加学校学校管理员
  1468. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(addSchoolTeacher, new PartitionKey($"Teacher-{scId}"));
  1469. }
  1470. }
  1471. else
  1472. {
  1473. CoreUser coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{msId}" } }, _option.Location, _configuration);
  1474. Teacher teacher = new() { id = coreUser.id, name = coreUser.name, picture = coreUser.picture, pk = "Base", code = "Base", size = 1, createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() };
  1475. var responseSc = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(scId, new PartitionKey("Base"));
  1476. if (responseSc.Status == 200)
  1477. {
  1478. using var tchJson = await JsonDocument.ParseAsync(responseSc.ContentStream);
  1479. School scInfo = tchJson.ToObject<School>();
  1480. teacher.schools.Add(new() { schoolId = scInfo.id, name = scInfo.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = scInfo.picture, areaId = scInfo.areaId });
  1481. }
  1482. teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  1483. SchoolTeacher addSchoolTeacher = new()
  1484. {
  1485. id = coreUser.id,
  1486. code = $"Teacher-{scId}",
  1487. pk = "Teacher",
  1488. status = "join",
  1489. roles = new List<string>() { "admin" },
  1490. name = coreUser.name,
  1491. job = $"管理员",
  1492. size = 0,
  1493. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1494. };
  1495. //添加学校学校管理员
  1496. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(addSchoolTeacher, new PartitionKey($"Teacher-{scId}"));
  1497. }
  1498. }
  1499. }
  1500. }
  1501. if (existScManages.Count > 0)
  1502. return Ok(new { state = RespondCode.Created, existScManages });
  1503. else
  1504. return Ok(new { state = RespondCode.Ok });
  1505. }
  1506. /// <summary>
  1507. /// 批量设置学校集合中学校多个管理员
  1508. /// </summary>
  1509. /// <param name="jsonElement"></param>
  1510. /// <returns></returns>
  1511. [ProducesDefaultResponseType]
  1512. [AuthToken(Roles = "admin")]
  1513. [HttpPost("batch-scmanage")]
  1514. public async Task<IActionResult> BatchScManage(JsonElement jsonElement)
  1515. {
  1516. if (!jsonElement.TryGetProperty("scManages", out JsonElement _scManages)) return BadRequest();
  1517. var cosmosClient = _azureCosmos.GetCosmosClient();
  1518. List<ScManages> scManages = _scManages.ToObject<List<ScManages>>();
  1519. List<ScManages> error = new(); //异常数据
  1520. foreach (var item in scManages)
  1521. {
  1522. School school = new();
  1523. var resSc = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{item.id}", new PartitionKey("Base"));
  1524. if (resSc.Status == 200)
  1525. {
  1526. using var sJson = await JsonDocument.ParseAsync(resSc.ContentStream);
  1527. school = sJson.ToObject<School>();
  1528. //CoreUser coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"19940828843" } }, _option.Location, _configuration);
  1529. var content = new StringContent(item.mobiles.ToArray().ToJsonString(), Encoding.UTF8, "application/json");
  1530. string json = await _coreAPIHttpService.GetUserInfos(content);
  1531. List<TmdUserinfo> tmdInfos = json.ToObject<List<TmdUserinfo>>();
  1532. Teacher teacher = new();
  1533. foreach (var tmd in tmdInfos)
  1534. {
  1535. var respone = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync($"{tmd.id}", new PartitionKey("Base"));
  1536. if (respone.Status == 200)
  1537. {
  1538. using var tchJson = await JsonDocument.ParseAsync(respone.ContentStream);
  1539. teacher = tchJson.ToObject<Teacher>();
  1540. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{tmd.id}", new PartitionKey($"Teacher-{item.id}"));
  1541. if (response.Status == 200)
  1542. {
  1543. using var scTchJson = await JsonDocument.ParseAsync(response.ContentStream);
  1544. SchoolTeacher tchSc = scTchJson.ToObject<SchoolTeacher>();
  1545. if (tchSc.roles.Contains("admin"))
  1546. {
  1547. tchSc.roles.Add("admin");
  1548. //添加顾问权限
  1549. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(tchSc, tchSc.id, new PartitionKey($"Teacher-{item.id}"));
  1550. }
  1551. else
  1552. {
  1553. var exsitI = error.Find(f => f.id.Equals(item.id));
  1554. if (exsitI != null)
  1555. {
  1556. var replacts = error.Where(w => w.id.Equals(item.id)).FirstOrDefault();
  1557. replacts.mobiles.Add($"{item.id}");
  1558. }
  1559. else
  1560. error.Add(new ScManages { id = item.id, name = item.name, mobiles = new List<string>() { $"{tmd.id}" } });
  1561. }
  1562. }
  1563. else
  1564. {
  1565. SchoolTeacher addSchoolTeacher = new()
  1566. {
  1567. id = tmd.id,
  1568. code = $"Teacher-{item.id}",
  1569. pk = "Teacher",
  1570. status = "join",
  1571. roles = new List<string>() { "admin" },
  1572. name = tmd.name,
  1573. job = $"管理员",
  1574. size = 0,
  1575. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1576. };
  1577. var haveTeacher = teacher.schools.Find(x => x.schoolId.Equals($"{item.id}"));
  1578. if (haveTeacher == null)
  1579. {
  1580. //教师存在,在该教师信息中添加要管理的学校信息
  1581. 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() });
  1582. teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  1583. }
  1584. //添加学校学校顾问
  1585. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(addSchoolTeacher, new PartitionKey($"Teacher-{item.id}"));
  1586. }
  1587. }
  1588. else
  1589. {
  1590. teacher = new()
  1591. {
  1592. id = $"{tmd.id}",
  1593. name = $"{tmd.name}",
  1594. picture = $"{tmd.picture}",
  1595. pk = "Base",
  1596. code = "Base",
  1597. size = 1,
  1598. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  1599. 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 } }
  1600. };
  1601. teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  1602. SchoolTeacher addSchoolTeacher = new()
  1603. {
  1604. id = tmd.id,
  1605. code = $"Teacher-{item.id}",
  1606. pk = "Teacher",
  1607. status = "join",
  1608. roles = new List<string>() { "admin" },
  1609. name = tmd.name,
  1610. job = $"管理员",
  1611. size = 0,
  1612. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  1613. };
  1614. //添加学校学校管理员
  1615. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(addSchoolTeacher, new PartitionKey($"Teacher-{item.id}"));
  1616. }
  1617. }
  1618. }
  1619. else
  1620. error.Add(new ScManages { id = item.id, name = item.name, mobiles = new List<string>() });
  1621. }
  1622. return Ok(new { state = RespondCode.Ok, error });
  1623. }
  1624. /// <summary>
  1625. /// 根據地理位置搜尋學校基本訊息
  1626. /// </summary>
  1627. /// <param name="GenerateCouponRequest"></param>
  1628. /// <returns></returns>
  1629. //[AuthToken(Roles = "admin,rdc,assist,sales")]
  1630. [HttpPost("get-school-basic-info")]
  1631. public async Task<IActionResult> GetSchoolBasicInfo(SchoolDataRequest request)
  1632. {
  1633. try
  1634. {
  1635. string url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  1636. string AccessToken = await getCoreAccessToken();
  1637. var client = _http.CreateClient();
  1638. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
  1639. HttpResponseMessage response = await client.PostAsJsonAsync($"{url}/Service/SchoolData", request);
  1640. if (response.StatusCode == HttpStatusCode.OK)
  1641. {
  1642. string jsonStr = await response.Content.ReadAsStringAsync();
  1643. var options1 = new JsonSerializerOptions
  1644. {
  1645. Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
  1646. };
  1647. return Ok(jsonStr.ToObject<JsonElement>());
  1648. }
  1649. else
  1650. {
  1651. return BadRequest();
  1652. }
  1653. }
  1654. catch (Exception ex)
  1655. {
  1656. return BadRequest();
  1657. }
  1658. }
  1659. /// <summary>
  1660. /// 弱歸戶
  1661. /// </summary>
  1662. /// <param name="GenerateCouponRequest"></param>
  1663. /// <returns></returns>
  1664. //[AuthToken(Roles = "admin,rdc,assist,sales")]
  1665. [HttpPost("upd-user-schoolw")]
  1666. public async Task<IActionResult> UpdUserSchoolW(UpdateUserSchoolCodeWRequest request)
  1667. {
  1668. try
  1669. {
  1670. string url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  1671. string AccessToken = await getCoreAccessToken();
  1672. var client = _http.CreateClient();
  1673. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
  1674. HttpResponseMessage response = await client.PostAsJsonAsync($"{url}/Service/UpdateUserSchoolCodeW", request);
  1675. if (response.StatusCode == HttpStatusCode.OK)
  1676. {
  1677. string jsonStr = await response.Content.ReadAsStringAsync();
  1678. var options1 = new JsonSerializerOptions
  1679. {
  1680. Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
  1681. };
  1682. return Ok(jsonStr.ToObject<JsonElement>());
  1683. }
  1684. else
  1685. {
  1686. return BadRequest();
  1687. }
  1688. }
  1689. catch (Exception ex)
  1690. {
  1691. return BadRequest();
  1692. }
  1693. }
  1694. private async Task<string> getCoreAccessToken()
  1695. {
  1696. string AccessToken = "";
  1697. try
  1698. {
  1699. string Url = _configuration.GetValue<string>("HaBookAuth:CoreAPI") + "/oauth2/token";
  1700. string GrantType = "device";
  1701. string ClientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1702. string Secret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1703. var content = new { grant_type = GrantType, client_id = ClientID, client_secret = Secret };
  1704. var response = await _http.CreateClient().PostAsJsonAsync($"{Url}", content);
  1705. if (response.IsSuccessStatusCode)
  1706. {
  1707. string responseBody = response.Content.ReadAsStringAsync().Result;
  1708. using (JsonDocument document = JsonDocument.Parse(responseBody.ToString()))
  1709. {
  1710. if (document.RootElement.TryGetProperty("access_token", out JsonElement AccessTokenObj))
  1711. {
  1712. AccessToken = AccessTokenObj.ToString();
  1713. }
  1714. }
  1715. }
  1716. return AccessToken;
  1717. }
  1718. catch (Exception ex)
  1719. {
  1720. return AccessToken;
  1721. }
  1722. }
  1723. #region 预设学校基础信息 多语言
  1724. /// <summary>
  1725. /// 预设学校基础信息 多语言
  1726. /// </summary>
  1727. /// <param name="period"></param>
  1728. /// <param name="Language"></param>
  1729. /// <param name="campusId"></param>
  1730. /// <returns></returns>
  1731. public List<Period> PresetSchoolPeriod(List<PeriodType> period, string Language, string campusId)
  1732. {
  1733. var builder = $"{_environment.ContentRootPath}/JsonFile/Preset/LangSchoolConfig.json";
  1734. StreamReader streamReader = new(new FileStream(builder, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8);
  1735. StringBuilder stringBuilder = new();
  1736. string text;
  1737. while ((text = streamReader.ReadLine()) != null)
  1738. {
  1739. stringBuilder.Append(text.ToString());
  1740. }
  1741. streamReader.Close();
  1742. string input = stringBuilder.ToString();
  1743. List<SchoolConfig> schoolConfigs = input.ToObject<List<SchoolConfig>>();
  1744. SchoolConfig schoolConfig = schoolConfigs.Find(x => x.Lang.Contains($"{Language}"));
  1745. if (schoolConfig == null)
  1746. {
  1747. if (Language.Contains("en"))
  1748. schoolConfig = schoolConfigs.Find(x => x.Lang.Contains("en-US"));
  1749. else
  1750. schoolConfig = schoolConfigs.Find(x => x.Lang.Contains("zh-CN"));
  1751. }
  1752. List<Period> periods = new();
  1753. if (period.Count > 0)
  1754. {
  1755. period.ForEach(x =>
  1756. {
  1757. periods.Add(new Period
  1758. {
  1759. id = Guid.NewGuid().ToString(),
  1760. name = x.name,
  1761. campusId = campusId,
  1762. 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() },
  1763. 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() } },
  1764. subjects = new List<Subject>() {
  1765. new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[0].name,type=schoolConfig.PresetSubject[0].type },
  1766. new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[1].name,type=schoolConfig.PresetSubject[1].type },
  1767. new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[2].name,type=schoolConfig.PresetSubject[2].type }
  1768. },
  1769. grades = schoolConfig.grades,
  1770. analysis = new Analysis()
  1771. {
  1772. type = new List<ExamSimple>() { new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[0].name },
  1773. new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[1].name },
  1774. new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[2].name },
  1775. new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[3].name } },
  1776. income = schoolConfig.PresetExam[0].income,
  1777. eugenics = schoolConfig.PresetExam[0].eugenics,
  1778. touch = schoolConfig.PresetExam[0].touch
  1779. },
  1780. periodType = x.value
  1781. });
  1782. });
  1783. }
  1784. else
  1785. {
  1786. periods.Add(new Period
  1787. {
  1788. id = Guid.NewGuid().ToString(),
  1789. name = "默认学段",
  1790. campusId = campusId,
  1791. 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() },
  1792. 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() } },
  1793. subjects = new List<Subject>() {
  1794. new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[0].name,type=schoolConfig.PresetSubject[0].type },
  1795. new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[1].name,type=schoolConfig.PresetSubject[1].type },
  1796. new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[2].name,type=schoolConfig.PresetSubject[2].type }
  1797. },
  1798. grades = schoolConfig.grades,
  1799. analysis = new Analysis()
  1800. {
  1801. type = new List<ExamSimple>() { new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[0].name },
  1802. new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[1].name },
  1803. new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[2].name },
  1804. new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[3].name } },
  1805. income = schoolConfig.PresetExam[0].income,
  1806. eugenics = schoolConfig.PresetExam[0].eugenics,
  1807. touch = schoolConfig.PresetExam[0].touch
  1808. }
  1809. });
  1810. }
  1811. return periods;
  1812. }
  1813. #endregion
  1814. //public class SchoolAssist
  1815. //{
  1816. // public string id { get; set; }
  1817. // public string code { get; set; }
  1818. // public string schoolCode { get; set; }
  1819. // public string name { get; set; }
  1820. // public string region { get; set; }
  1821. // public string province { get; set; }
  1822. // public string city { get; set; }
  1823. // public string dist { get; set; }
  1824. // public int size { get; set; }
  1825. // public string address { get; set; }
  1826. // public string picture { get; set; }
  1827. // public int type { get; set; }
  1828. // public int scale { get; set; }
  1829. // public string standard { get; set; }
  1830. // public string areaId { get; set; }
  1831. // public List<SchoolTeacherRoles> assists { get; set; }
  1832. // public int serial { get; set; } //软体
  1833. // public int service { get; set; } //服务
  1834. // public int hard { get; set; } //硬体
  1835. // //public List<SchoolProductSumData> serial { get; set; } //软体
  1836. // //public List<SchoolProductSumData> service { get; set; } //服务
  1837. // //public List<SchoolProductSumDataHard> hard { get; set; } //硬体
  1838. //}
  1839. /// <summary>
  1840. /// 创建多个学校实体
  1841. /// </summary>
  1842. public record FoundSchools()
  1843. {
  1844. /// <summary>
  1845. /// 语系
  1846. /// </summary>
  1847. public string lang { get; set; }
  1848. /// <summary>
  1849. /// 站点
  1850. /// </summary>
  1851. public string site { get; set; }
  1852. /// <summary>
  1853. /// 批量创校的数据结构
  1854. /// </summary>
  1855. public List<BISchool> biSchools { get; set; } = new List<BISchool>();
  1856. }
  1857. /// <summary>
  1858. /// 批量创校的数据结构
  1859. /// </summary>
  1860. public record BISchool()
  1861. {
  1862. public string id { get; set; }
  1863. /// <summary>
  1864. /// 学校名称
  1865. /// </summary>
  1866. public string name { get; set; }
  1867. /// <summary>
  1868. /// 学校管理员
  1869. /// </summary>
  1870. public List<string> admin { get; set; }
  1871. /// <summary>
  1872. /// 学校的学段
  1873. /// </summary>
  1874. public List<PeriodType> period { get; set; }
  1875. /// <summary>
  1876. /// 学校空间大小
  1877. /// </summary>
  1878. public int size { get; set; }
  1879. /// <summary>
  1880. /// 地区
  1881. /// </summary>
  1882. public string region { get; set; }
  1883. /// <summary>
  1884. /// 省份
  1885. /// </summary>
  1886. public string province { get; set; }
  1887. /// <summary>
  1888. /// 城市
  1889. /// </summary>
  1890. public string city { get; set; }
  1891. /// <summary>
  1892. /// 县,区,郡
  1893. /// </summary>
  1894. public string dist { get; set; }
  1895. /// <summary>
  1896. /// 学校详细地址
  1897. /// </summary>
  1898. public string address { get; set; }
  1899. /// <summary>
  1900. /// 学校类型
  1901. /// </summary>
  1902. public int type { get; set; }
  1903. /// <summary>
  1904. /// 区域ID
  1905. /// </summary>
  1906. public string areaId { get; set; }
  1907. /// <summary>
  1908. /// 区域标准
  1909. /// </summary>
  1910. public string standard { get; set; }
  1911. /// <summary>
  1912. /// 規模版本
  1913. /// </summary>
  1914. public string scaleVersion { get; set; }
  1915. /// <summary>
  1916. /// 手动增加的模块 ["art"]
  1917. /// </summary>
  1918. //public List<string> modules { get; set; } = new List<string>();
  1919. }
  1920. /// <summary>
  1921. /// 学段类型和学段名称
  1922. /// </summary>
  1923. public record PeriodType
  1924. {
  1925. public string name { get; set; }
  1926. public string value { get; set; }
  1927. }
  1928. /// <summary>
  1929. /// 存在的学校
  1930. /// </summary>
  1931. public record ExistScManage
  1932. {
  1933. public string scId { get; set; }
  1934. public string tmdId { get; set; }
  1935. }
  1936. /// <summary>
  1937. /// 管理员
  1938. /// </summary>
  1939. public record ScManages
  1940. {
  1941. public string id { get; set; }
  1942. public string name { get; set; }
  1943. public List<string> mobiles { get; set; }
  1944. }
  1945. public record SchoolDataRequest
  1946. (
  1947. string countryId,
  1948. string provinceId,
  1949. string cityId,
  1950. string shortCode,
  1951. bool fullData = false
  1952. );
  1953. public record UpdateUserSchoolCodeWRequest
  1954. (
  1955. [Required] List<string> ids,
  1956. [Required] string schoolDocId
  1957. );
  1958. }
  1959. }