BatchSchoolController.cs 94 KB

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