BatchSchoolController.cs 122 KB

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