BatchSchoolController.cs 97 KB

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