BatchSchoolController.cs 117 KB

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