BatchSchoolController.cs 116 KB

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