BatchSchoolController.cs 103 KB

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