BatchSchoolController.cs 115 KB

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