BatchSchoolController.cs 116 KB

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