SchoolController.cs 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238
  1. using Azure.Cosmos;
  2. using Azure.Storage.Blobs;
  3. using HTEXLib.COMM.Helpers;
  4. using MathNet.Numerics.LinearAlgebra;
  5. using MathNet.Numerics.LinearAlgebra.Double;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.AspNetCore.Mvc;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.Options;
  10. using Newtonsoft.Json;
  11. using StackExchange.Redis;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Net.Http;
  17. using System.Net.Http.Headers;
  18. using System.Net.Http.Json;
  19. using System.Text;
  20. using System.Text.Json;
  21. using System.Threading.Tasks;
  22. using TEAMModelBI.Filter;
  23. using TEAMModelBI.Models;
  24. using TEAMModelBI.Tool;
  25. using TEAMModelBI.Tool.CosmosBank;
  26. using TEAMModelBI.Tool.Extension;
  27. using TEAMModelOS.Models;
  28. using TEAMModelOS.SDK;
  29. using TEAMModelOS.SDK.Context.BI;
  30. using TEAMModelOS.SDK.Context.Constant;
  31. using TEAMModelOS.SDK.DI;
  32. using TEAMModelOS.SDK.DI.CoreAPI;
  33. using TEAMModelOS.SDK.Extension;
  34. using TEAMModelOS.SDK.Models;
  35. using TEAMModelOS.SDK.Models.Cosmos.BI;
  36. using TEAMModelOS.SDK.Models.Cosmos.Common;
  37. using TEAMModelOS.SDK.Models.Service.BI;
  38. using static TEAMModelBI.Controllers.BISchool.SchoolController;
  39. namespace TEAMModelBI.Controllers.BISchool
  40. {
  41. [Route("schoolcheck")]
  42. [ApiController]
  43. public class SchoolController : ControllerBase
  44. {
  45. private readonly AzureCosmosFactory _azureCosmos;
  46. private readonly DingDing _dingDing;
  47. private readonly Option _option;
  48. private readonly AzureStorageFactory _azureStorage;
  49. private readonly AzureRedisFactory _azureRedis;
  50. private readonly IConfiguration _configuration;
  51. private readonly NotificationService _notificationService;
  52. private readonly CoreAPIHttpService _coreAPIHttpService;
  53. private readonly HttpClient _httpClient;
  54. public SchoolController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, AzureRedisFactory azureRedis, IConfiguration configuration, NotificationService notificationService, CoreAPIHttpService coreAPIHttpService, HttpClient httpClient)
  55. {
  56. _azureCosmos = azureCosmos;
  57. _dingDing = dingDing;
  58. _azureStorage = azureStorage;
  59. _option = option?.Value;
  60. _azureRedis = azureRedis;
  61. _configuration = configuration;
  62. _notificationService = notificationService;
  63. _coreAPIHttpService = coreAPIHttpService;
  64. _httpClient = httpClient;
  65. }
  66. /// <summary>
  67. /// 查询未加入区域的学校 //已对接
  68. /// </summary>
  69. /// <returns></returns>
  70. [ProducesDefaultResponseType]
  71. [HttpPost("get-notarea")]
  72. public async Task<IActionResult> GetNotAreaSchool(JsonElement jsonElement)
  73. {
  74. try
  75. {
  76. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  77. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  78. var cosmosClient = _azureCosmos.GetCosmosClient();
  79. ////分开部署,就不需要,一站多用时,取消注释
  80. //if ($"{site}".Equals(BIConst.Global))
  81. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  82. //默认不指定返回大小
  83. int? pageSize = null;
  84. string continuationToken = string.Empty;
  85. string pageToken = default;
  86. if (jsonElement.TryGetProperty("pageSize", out JsonElement jsonPageSize))
  87. {
  88. if (!jsonPageSize.ValueKind.Equals(JsonValueKind.Undefined) && !jsonPageSize.ValueKind.Equals(JsonValueKind.Null) && jsonPageSize.TryGetInt32(out int tempPageSize))
  89. {
  90. pageSize = tempPageSize;
  91. }
  92. }
  93. //是否需要进行分页查询,默认不分页
  94. bool iscontinuation = false;
  95. if (pageSize != null && pageSize.Value > 0)
  96. {
  97. iscontinuation = true;
  98. }
  99. if (jsonElement.TryGetProperty("contToken", out JsonElement ContToken))
  100. {
  101. pageToken = ContToken.GetString();
  102. }
  103. StringBuilder sqltxt = new($"SELECT c.id,c.name,c.schoolCode,c.province,c.city,c.dist,c.picture,c.period,c.areaId,c.standard,c.manyAreas FROM c");
  104. if (!string.IsNullOrEmpty($"{areaId}"))
  105. {
  106. sqltxt.Append($" WHERE c.areaId !='{areaId}'");
  107. }
  108. else
  109. {
  110. sqltxt.Append($" WHERE c.areaId ='' and c.standard = ''");
  111. }
  112. List<NotAreaSchool> tempNotAreaSchools = new();
  113. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: sqltxt.ToString(), continuationToken: pageToken, requestOptions: new QueryRequestOptions() { MaxItemCount = pageSize, PartitionKey = new PartitionKey("Base") }))
  114. {
  115. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  116. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  117. {
  118. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  119. {
  120. NotAreaSchool notAreaSchool = new()
  121. {
  122. id = obj.GetProperty("id").GetString(),
  123. name = obj.GetProperty("name").GetString(),
  124. schoolCode = obj.GetProperty("schoolCode").GetString(),
  125. picture = obj.GetProperty("picture").GetString(),
  126. period = obj.GetProperty("period").ToObject<List<Period>>().Select(x => x.name).ToList(),
  127. province = obj.GetProperty("province").GetString(),
  128. city = obj.GetProperty("city").GetString(),
  129. dist = obj.GetProperty("dist").GetString(),
  130. areaId = obj.GetProperty("areaId").GetString(),
  131. standard = obj.GetProperty("standard").GetString()
  132. };
  133. try
  134. {
  135. notAreaSchool.areas = obj.GetProperty("manyAreas").ToObject<List<SchoolArea>>();
  136. }
  137. catch { }
  138. tempNotAreaSchools.Add(notAreaSchool);
  139. }
  140. if (iscontinuation)
  141. {
  142. continuationToken = item.GetContinuationToken();
  143. break;
  144. }
  145. }
  146. }
  147. List<NotAreaSchool> notAreaSchools = new();
  148. tempNotAreaSchools.ForEach(nas =>
  149. {
  150. if (nas.areas == null)
  151. notAreaSchools.Add(nas);
  152. else
  153. {
  154. var not = nas.areas.Find(f => f.areaId == $"{areaId}");
  155. if (not == null)
  156. notAreaSchools.Add(nas);
  157. }
  158. });
  159. //if (!string.IsNullOrEmpty($"{areaId}"))
  160. // notAreaSchools = notAreaSchools.Select(na => new NotAreaSchool { id = na.id, name = na.name, schoolCode = na.schoolCode, picture = na.picture, period = na.period, province = na.province, city = na.city = na.city, dist = na.dist, manyAreas = new List<ManyArea> { na.manyAreas.Find(m => m.areaId != $"{areaId}") } }).ToList();
  161. return Ok(new { state = 200, continuationToken, pageSize, notAreaSchools });
  162. }
  163. catch (Exception ex)
  164. {
  165. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/get-notarea \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  166. return BadRequest();
  167. }
  168. }
  169. /// <summary>
  170. /// 学校加入区 //已对接
  171. /// </summary>
  172. /// <param name="jsonElement"></param>
  173. /// <returns></returns>
  174. [ProducesDefaultResponseType]
  175. [AuthToken(Roles = "admin,rdc,assist,sales")]
  176. [HttpPost("set-schooljoinarea")]
  177. public async Task<IActionResult> SetSchoolJoinArea(JsonElement jsonElement)
  178. {
  179. try
  180. {
  181. if (!jsonElement.TryGetProperty("standard", out JsonElement standard)) return BadRequest();
  182. if (!jsonElement.TryGetProperty("schoolCode", out JsonElement _schoolCode)) return BadRequest();
  183. if (!jsonElement.TryGetProperty("areaId", out JsonElement _areaId)) return BadRequest();
  184. jsonElement.TryGetProperty("areaName", out JsonElement areaName);
  185. jsonElement.TryGetProperty("isDefault", out JsonElement isDefault);
  186. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  187. var isManyArea = false;
  188. if (!string.IsNullOrEmpty($"{isDefault}"))
  189. {
  190. isManyArea = true;
  191. }
  192. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  193. List<string> schoolCodes = _schoolCode.ToObject<List<string>>();
  194. StringBuilder msg = new($"{_tmdName}【{_tmdId}】操作学校加入区域功能,加入的区域:{standard},学校ID:{string.Join("|", schoolCodes.ToArray())}");
  195. var cosmosClient = _azureCosmos.GetCosmosClient();
  196. var tableClient = _azureStorage.GetCloudTableClient();
  197. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  198. ////分开部署,就不需要,一站多用时,取消注释
  199. //if ($"{site}".Equals(BIConst.Global))
  200. //{
  201. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  202. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  203. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  204. //}
  205. var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{_areaId}", new PartitionKey("AreaSetting"));
  206. if (responseSet.Status == 200)
  207. {
  208. using var fileJson = await JsonDocument.ParseAsync(responseSet.ContentStream);
  209. AreaSetting delSet = fileJson.ToObject<AreaSetting>();
  210. if (!string.IsNullOrEmpty(delSet.accessConfig))
  211. return Ok(new { state = 401, msg = "区域已经规定了,不能切换能能力" });
  212. }
  213. if (schoolCodes.Count > 0)
  214. {
  215. foreach (var tempCode in schoolCodes)
  216. {
  217. School school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(tempCode, new PartitionKey("Base"));
  218. if (school != null)
  219. {
  220. if (isManyArea)
  221. {
  222. if (school.areas == null)
  223. school.areas = new List<SchoolArea>() { new SchoolArea() { areaId = $"{_areaId}", name = $"{areaName}", status = "join" } };
  224. else
  225. {
  226. var marea = school.areas.Find(ma => ma.areaId == $"{_areaId}");
  227. if (marea == null)
  228. school.areas.Add(new SchoolArea() { areaId = $"{_areaId}", name = $"{areaName}", status = $"join" });
  229. }
  230. }
  231. school.standard = $"{standard}";
  232. school.areaId = $"{_areaId}";
  233. msg.Append($"{school.name}【{school.id}】学校移除多区域的名单:");
  234. List<Teacher> teachers = new();
  235. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Teacher>(queryText: $"SELECT value(c) FROM c join s in c.schools where s.schoolId ='{school.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  236. {
  237. teachers.Add(item);
  238. }
  239. foreach (var item in teachers)
  240. {
  241. msg.Append($"{item.name}[{item.id}]");
  242. var tchSchool = item.schools.Find(f => f.schoolId.Equals($"{school.id}"));
  243. if (tchSchool == null)
  244. {
  245. Teacher.TeacherSchool teacherSchool = new() { schoolId = school.id, name = school.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = school.picture, areaId = school.areaId };
  246. item.schools.Add(teacherSchool);
  247. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(item, item.id, new PartitionKey("Base"));
  248. }
  249. }
  250. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, school.id, new PartitionKey(school.code));
  251. }
  252. }
  253. }
  254. //保存操作记录
  255. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", msg.ToString(), _dingDing, httpContext: HttpContext);
  256. return Ok(new { state = 200 });
  257. }
  258. catch (Exception ex)
  259. {
  260. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/set-schooljoinarea \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  261. return BadRequest();
  262. }
  263. }
  264. /// <summary>
  265. /// 依据学校编号查询学校信息 //已对接
  266. /// </summary>
  267. /// <param name="jsonElement"></param>
  268. /// <returns></returns>
  269. [HttpPost("get-schoolid")]
  270. public async Task<IActionResult> GetSchoolId(JsonElement jsonElement)
  271. {
  272. try
  273. {
  274. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  275. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  276. var cosmosClient = _azureCosmos.GetCosmosClient();
  277. ////分开部署,就不需要,一站多用时,取消注释
  278. //if ($"{site}".Equals(BIConst.Global))
  279. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  280. AssistSchool schoolAssists = new(); //返回学校列表集合
  281. string sqlTxt = $"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,c.period,c.campuses from c where c.id='{schoolId}'";
  282. await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<AssistSchool>(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  283. {
  284. schoolAssists = itemSchool;
  285. }
  286. if (schoolAssists.id != null)
  287. {
  288. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(schoolAssists.id, new PartitionKey("ProductSum"));
  289. if (response.Status == 200)
  290. {
  291. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  292. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  293. {
  294. schoolAssists.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  295. }
  296. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  297. {
  298. schoolAssists.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  299. }
  300. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  301. {
  302. schoolAssists.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  303. }
  304. }
  305. schoolAssists.assists = await CommonFind.FindSchoolRoles(cosmosClient, schoolAssists.id, "assist");
  306. schoolAssists.lessonCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c ", $"LessonRecord-{schoolAssists.id}");
  307. return Ok(new { state = 200, schoolAssists });
  308. }
  309. else return Ok(new { state = 404, msg = "未找到该学校!" });
  310. }
  311. catch (Exception ex)
  312. {
  313. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/get-schoolid \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  314. return BadRequest();
  315. }
  316. }
  317. /// <summary>
  318. /// 修改学校信息 //已对接
  319. /// </summary>
  320. /// <param name="school"></param>
  321. /// <returns></returns>
  322. [ProducesDefaultResponseType]
  323. [AuthToken(Roles = "admin,rdc,assist,sales")]
  324. [HttpPost("upd-school")]
  325. public async Task<IActionResult> UpdSchool(School school, [FromHeader] string site)
  326. {
  327. try
  328. {
  329. School schoolInfo = new School();
  330. var cosmosClient = _azureCosmos.GetCosmosClient();
  331. var tableClient = _azureStorage.GetCloudTableClient();
  332. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  333. if ($"{site}".Equals(BIConst.Global))
  334. {
  335. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  336. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  337. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  338. }
  339. string _auth = HttpContext.GetXAuth("AuthToken");
  340. var (tmdId, tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(_auth, _option);
  341. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school.id, new PartitionKey($"Base"));
  342. if (response.Status == 200)
  343. {
  344. string sql = $"SELECT distinct value(c) FROM c join A1 in c.schools where A1.schoolId='{school.id}'";
  345. List<Teacher> teachers = new();
  346. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Teacher>(sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  347. {
  348. teachers.Add(item);
  349. }
  350. foreach (var item in teachers)
  351. {
  352. Teacher.TeacherSchool teacherSchool = item.schools.Find(x => x.schoolId.Equals(school.id));
  353. if (teacherSchool != null)
  354. {
  355. teacherSchool.name = school.name;
  356. teacherSchool.picture = school.picture;
  357. teacherSchool.areaId = school.areaId;
  358. }
  359. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey($"Base"));
  360. }
  361. schoolInfo = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<School>(school, school.id, new PartitionKey($"Base"));
  362. //保存操作记录
  363. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", $"{tmdName}【{tmdId}】修改学校信息,学校和ID:{school.name}【{school.id}】", _dingDing, httpContext: HttpContext);
  364. }
  365. else return Ok(new { state = 400, message = "请求错误!" });
  366. return Ok(new { state = 200, schoolInfo });
  367. }
  368. catch (Exception ex)
  369. {
  370. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/upd-school \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  371. return BadRequest();
  372. }
  373. }
  374. /// <summary>
  375. /// 顾问学校空间使用情况
  376. /// </summary>
  377. /// <param name="jsonElement"></param>
  378. /// <returns></returns>
  379. [ProducesDefaultResponseType]
  380. [HttpPost("get-assistspace")]
  381. public async Task<IActionResult> GetAssistSchoolSpace(JsonElement jsonElement)
  382. {
  383. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  384. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  385. var cosmosClient = _azureCosmos.GetCosmosClient();
  386. ////分开部署,就不需要,一站多用时,取消注释
  387. //if ($"{site}".Equals(BIConst.Global))
  388. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  389. List<string> schools = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  390. List<SchoolSpace> schoolSpaces = new();
  391. foreach (var sid in schools)
  392. {
  393. School school = new();
  394. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(sid, new PartitionKey("Base"));
  395. if (response.Status == 200)
  396. {
  397. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  398. school = json.ToObject<School>();
  399. }
  400. long teach = 0;
  401. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"SELECT sum(c.size) as size FROM c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{sid}") }))
  402. {
  403. var json = await JsonDocument.ParseAsync(item.ContentStream);
  404. foreach (var elmt in json.RootElement.GetProperty("Documents").EnumerateArray())
  405. {
  406. if (elmt.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
  407. {
  408. teach = _size.GetInt32();
  409. break;
  410. }
  411. }
  412. }
  413. SchoolSpace schoolSpace = new() { id = sid, name = school != null ? school.name : sid };
  414. Space space = new Space();
  415. long blobsize = 0; //使用大小
  416. RedisValue value = default;
  417. value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", sid);
  418. if (value != default && !value.IsNullOrEmpty)
  419. {
  420. JsonElement record = value.ToString().ToObject<JsonElement>();
  421. if (record.TryGetInt64(out blobsize))
  422. {
  423. }
  424. }
  425. else
  426. {
  427. var client = _azureStorage.GetBlobContainerClient(sid);
  428. var size = await client.GetBlobsCatalogSize();
  429. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", sid, size.Item1);
  430. foreach (var key in size.Item2.Keys)
  431. {
  432. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{sid}", key);
  433. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{sid}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  434. }
  435. space.useSize = (long)size.Item1; space.tSize = teach; space.catalogSize = size.Item2;
  436. schoolSpace.space = space;
  437. schoolSpaces.Add(schoolSpace);
  438. continue;
  439. }
  440. Dictionary<string, double?> catalog = new Dictionary<string, double?>();
  441. SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{sid}");
  442. if (Scores != null)
  443. {
  444. foreach (var score in Scores)
  445. {
  446. double val = score.Score;
  447. string key = score.Element.ToString();
  448. catalog.Add(key, val);
  449. }
  450. space.useSize = blobsize; space.tSize = teach; space.catalogSize = catalog;
  451. schoolSpace.space = space;
  452. schoolSpaces.Add(schoolSpace);
  453. continue;
  454. }
  455. else
  456. {
  457. var client = _azureStorage.GetBlobContainerClient(sid);
  458. var size = await client.GetBlobsCatalogSize();
  459. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", sid, size.Item1);
  460. foreach (var key in size.Item2.Keys)
  461. {
  462. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{sid}", key);
  463. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{sid}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  464. }
  465. space.useSize = (long)size.Item1;
  466. space.tSize = teach;
  467. space.catalogSize = size.Item2;
  468. schoolSpace.space = space;
  469. schoolSpaces.Add(schoolSpace);
  470. continue;
  471. }
  472. }
  473. return Ok(new { state = 200, schoolSpaces });
  474. }
  475. /// <summary>
  476. /// 修改顾问学校 //已经对接
  477. /// </summary>
  478. /// <param name="jsonElement"></param>
  479. /// <returns></returns>
  480. [ProducesDefaultResponseType]
  481. [AuthToken(Roles = "admin,rdc")]
  482. [HttpPost("set-aistschool")]
  483. public async Task<IActionResult> SetAssistSchool(JsonElement jsonElement)
  484. {
  485. try
  486. {
  487. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement parKey)) return BadRequest();
  488. jsonElement.TryGetProperty("userId", out JsonElement userId);
  489. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  490. if (!jsonElement.TryGetProperty("schoolIds", out JsonElement jsSchoolIds)) return BadRequest();
  491. if (!jsonElement.TryGetProperty("busy", out JsonElement busy)) return BadRequest();
  492. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  493. List<string> schoolIds = jsSchoolIds.ToObject<List<string>>();
  494. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  495. var cosmosClient = _azureCosmos.GetCosmosClient();
  496. string divide = _option.Location;
  497. ////分开部署,就不需要,一站多用时,取消注释
  498. //if ($"{site}".Equals(BIConst.Global))
  499. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  500. Dictionary<string, object> dic = new() { { "PartitionKey", $"{parKey}" } };
  501. if (!string.IsNullOrEmpty($"{userId}"))
  502. {
  503. dic.Add("userId", $"{userId}");
  504. }
  505. if (string.IsNullOrEmpty($"{userId}") && string.IsNullOrEmpty($"{tmdId}"))
  506. {
  507. return Ok(new { state = 400, msg = "钉钉账户或醍摩豆账户需要至少要传一个!" });
  508. }
  509. Dictionary<string, List<string>> noSchools = new();
  510. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  511. List<DingDingUserInfo> updUsers = new();
  512. if (ddUserInfoList.Count > 0)
  513. {
  514. foreach (var ddInfo in ddUserInfoList)
  515. {
  516. if (schoolIds.Count > 0)
  517. {
  518. if (string.IsNullOrEmpty(ddInfo.tmdId))
  519. {
  520. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{ddInfo.mobile}" } }, _option.Location, _configuration);
  521. if (coreUser != null && coreUser.id != null)
  522. {
  523. ddInfo.tmdId = coreUser.id;
  524. ddInfo.tmdName = coreUser.name;
  525. ddInfo.tmdMobile = coreUser.mobile;
  526. ddInfo.picture = coreUser.picture;
  527. ddInfo.mail = coreUser.mail;
  528. }
  529. else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  530. //List<string> moblie = new() { $"{ddInfo.mobile}" };
  531. //var content = new StringContent(moblie.ToJsonString(), Encoding.UTF8, "application/json");
  532. //string json = await _coreAPIHttpService.GetUserInfos(content);
  533. //if (!string.IsNullOrEmpty(json))
  534. //{
  535. // List<JsonElement> json_id = json.ToObject<List<JsonElement>>();
  536. // foreach (var tmd in json_id)
  537. // {
  538. // ddInfo.tmdId = tmd.GetProperty("id").ToString();
  539. // ddInfo.tmdName = tmd.GetProperty("name").ToString();
  540. // ddInfo.tmdMobile = tmd.GetProperty("mobile").ToString();
  541. // ddInfo.picture = tmd.GetProperty("picture").ToString();
  542. // ddInfo.mail = tmd.GetProperty("mail").ToString();
  543. // }
  544. //}
  545. //else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  546. }
  547. List<string> noSchool = await SchoolWay.SchoolAdviser(cosmosClient, ddInfo, schoolIds, $"{busy}");
  548. if (noSchool.Count > 0)
  549. {
  550. noSchools.Add(ddInfo.tmdId, noSchool);
  551. }
  552. }
  553. List<string> userSchoolAdv = new(ddInfo.schoolIds.Split("|", StringSplitOptions.RemoveEmptyEntries));
  554. if ($"{busy}".Equals("add"))
  555. {
  556. userSchoolAdv.AddRange(schoolIds);
  557. ddInfo.schoolIds = userSchoolAdv.Count > 0 ? string.Join("|", userSchoolAdv) : "";
  558. }
  559. if ($"{busy}".Equals("del"))
  560. {
  561. var temp = userSchoolAdv.Where(p => !schoolIds.Any(x => x == p)).ToList();
  562. ddInfo.schoolIds = temp.Count > 0 ? string.Join("|", temp) : "";
  563. }
  564. updUsers.Add(ddInfo);
  565. }
  566. }
  567. updUsers = await table.SaveOrUpdateAll(updUsers);
  568. if (noSchools.Count > 0)
  569. return Ok(new { state = 201, recUsers = updUsers, noSchools });
  570. else
  571. return Ok(new { state = 200, recUsers = updUsers });
  572. }
  573. catch (Exception ex)
  574. {
  575. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/set-aistschool \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  576. return BadRequest();
  577. }
  578. }
  579. /// <summary>
  580. /// 依据学校ID查学校管理员信息 //已对接
  581. /// </summary>
  582. /// <param name="jsonElement"></param>
  583. /// <returns></returns>
  584. [ProducesDefaultResponseType]
  585. [HttpPost("get-scmanage")]
  586. public async Task<IActionResult> GetSchoolManage(JsonElement jsonElement)
  587. {
  588. if (!jsonElement.TryGetProperty("scId", out JsonElement scId)) return BadRequest();
  589. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  590. var cosmosClient = _azureCosmos.GetCosmosClient();
  591. ////分开部署,就不需要,一站多用时,取消注释
  592. //if ($"{site}".Equals(BIConst.Global))
  593. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  594. List<BaseInfo> scManages = new();
  595. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<BaseInfo>(queryText: $"select c.id,c.name,c.picture from c where ARRAY_CONTAINS(c.roles,'admin',true) and c.code='Teacher-{scId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{scId}") }))
  596. {
  597. scManages.Add(item);
  598. }
  599. return Ok(new { state = RespondCode.Ok, scManages });
  600. }
  601. /// <summary>
  602. /// 设置学校管理员 //已对接
  603. /// </summary>
  604. /// <param name="jsonElement"></param>
  605. /// <returns></returns>
  606. [ProducesDefaultResponseType]
  607. [AuthToken(Roles = "admin,rdc")]
  608. [HttpPost("set-manage")]
  609. public async Task<IActionResult> SetSchoolManage(JsonElement jsonElement)
  610. {
  611. try
  612. {
  613. var (_tmdId, _tmdName, _, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  614. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  615. if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
  616. jsonElement.TryGetProperty("tmdPic", out JsonElement picture);
  617. if (!jsonElement.TryGetProperty("scId", out JsonElement schoolId)) return BadRequest();
  618. if (!jsonElement.TryGetProperty("scName", out JsonElement schoolName)) return BadRequest();
  619. jsonElement.TryGetProperty("scAreaId", out JsonElement scAreaId);
  620. jsonElement.TryGetProperty("scPic", out JsonElement scpicture);
  621. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  622. var cosmosClient = _azureCosmos.GetCosmosClient();
  623. var tableClient = _azureStorage.GetCloudTableClient();
  624. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  625. ////分开部署,就不需要,一站多用时,取消注释
  626. //if ($"{site}".Equals(BIConst.Global))
  627. //{
  628. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  629. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  630. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  631. //}
  632. StringBuilder strMsg = new($"{_tmdName}【{_tmdId}】账户将{tmdName}【{tmdId}】");
  633. string areaId = null;
  634. if (string.IsNullOrEmpty($"{scAreaId}"))
  635. {
  636. var resScInfo = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{schoolId}", new PartitionKey("Base"));
  637. if (resScInfo.Status == 200)
  638. {
  639. using var tchJson = await JsonDocument.ParseAsync(resScInfo.ContentStream);
  640. School scInfo = tchJson.ToObject<School>();
  641. areaId = scInfo.areaId;
  642. }else areaId = $"{scAreaId}";
  643. }
  644. else { areaId = $"{scAreaId}"; }
  645. Teacher teacher = new();
  646. SchoolTeacher schoolTeacher = new();
  647. var resTeacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Base"));
  648. if (resTeacher.Status == 200)
  649. {
  650. using var tchJson = await JsonDocument.ParseAsync(resTeacher.ContentStream);
  651. teacher = tchJson.ToObject<Teacher>();
  652. var existArea = teacher.schools.Find(f => f.schoolId.Equals($"{schoolId}"));
  653. if (existArea == null)
  654. {
  655. teacher.schools.Add(new Teacher.TeacherSchool { schoolId = $"{schoolId}", name = $"{schoolName}", status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = string.IsNullOrEmpty($"{scpicture}") ? "" : $"{scpicture}", areaId = areaId });
  656. teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  657. strMsg.Append($"账户基础信息添加学校,{schoolName}【{schoolId}】;");
  658. }
  659. }
  660. else
  661. {
  662. teacher.id = $"{tmdId}";
  663. teacher.name = $"{tmdName}";
  664. teacher.picture = string.IsNullOrEmpty($"{picture}") ? "" : $"{picture}";
  665. teacher.pk = "Base";
  666. teacher.code = "Base";
  667. teacher.size = 1;
  668. teacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  669. //教师存在,在该教师信息中添加要管理的学校信息
  670. teacher.schools.Add(new Teacher.TeacherSchool { schoolId = $"{schoolId}", name = $"{schoolName}", status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = string.IsNullOrEmpty($"{scpicture}") ? "" : $"{scpicture}", areaId = areaId });
  671. teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  672. strMsg.Append($"添加基础信息,并添加学校,{schoolName}【{schoolId}】;");
  673. }
  674. if (teacher != null)
  675. {
  676. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Teacher-{schoolId}"));
  677. if (response.Status == 200)
  678. {
  679. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  680. schoolTeacher = json.ToObject<SchoolTeacher>();
  681. if (!schoolTeacher.roles.Contains("admin"))
  682. {
  683. schoolTeacher.roles.Add("admin");
  684. schoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, schoolTeacher.id, new PartitionKey($"Teacher-{schoolId}"));
  685. strMsg.Append($"并设置管理员,学校信息{schoolName}【{schoolId}】");
  686. }
  687. else
  688. return Ok(new { state = RespondCode.Conflict, schoolTeacher = "已经是该校的管理人员" });
  689. }
  690. else
  691. {
  692. schoolTeacher = new()
  693. {
  694. id = $"{tmdId}",
  695. code = $"Teacher-{schoolId}",
  696. roles = new List<string> { "admin", "teacher" },
  697. job = "管理员",
  698. name = $"{tmdName}",
  699. picture = string.IsNullOrEmpty($"{picture}") ? "" : $"{picture}",
  700. status = "join",
  701. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  702. pk = "Teacher",
  703. ttl = -1
  704. };
  705. schoolTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey($"Teacher-{schoolId}"));
  706. strMsg.Append($"并新建学校管理员,学校信息{schoolName}【{schoolId}】");
  707. }
  708. }
  709. //保存操作记录
  710. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "schoolTeacher-add", strMsg.ToString(), _dingDing, httpContext: HttpContext);
  711. return Ok(new { state = RespondCode.Ok, teacher, schoolTeacher });
  712. }
  713. catch (Exception ex)
  714. {
  715. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/set-schoolme \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  716. return BadRequest();
  717. }
  718. }
  719. /// <summary>
  720. /// 移除学校管理员 //已对接
  721. /// </summary>
  722. /// <param name="jsonElement"></param>
  723. /// <returns></returns>
  724. [ProducesDefaultResponseType]
  725. [AuthToken(Roles = "admin,rdc")]
  726. [HttpPost("del-manage")]
  727. public async Task<IActionResult> DelSchoolManage(JsonElement jsonElement)
  728. {
  729. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  730. if (!jsonElement.TryGetProperty("scIds", out JsonElement _scIds)) return BadRequest();
  731. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  732. List<string> scIds = _scIds.ToObject<List<string>>();
  733. var cosmosClient = _azureCosmos.GetCosmosClient();
  734. ////分开部署,就不需要,一站多用时,取消注释
  735. //if ($"{site}".Equals(BIConst.Global))
  736. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  737. List<string> existScId = new();
  738. SchoolTeacher scTeacher = null;
  739. foreach (var scId in scIds)
  740. {
  741. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Teacher-{scId}"));
  742. if (response.Status == 200)
  743. {
  744. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  745. scTeacher = json.ToObject<SchoolTeacher>();
  746. if (scTeacher.roles.Contains("admin"))
  747. {
  748. scTeacher.roles.Remove("admin");
  749. scTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(scTeacher, scTeacher.id, new PartitionKey($"Teacher-{scId}"));
  750. }
  751. else
  752. existScId.Add(scId);
  753. }
  754. else
  755. existScId.Add(scId);
  756. }
  757. return Ok(new { state = RespondCode.Ok, existScId });
  758. }
  759. /// <summary>
  760. /// 一个账户设置多个学校的管理员
  761. /// </summary>
  762. /// <param name="jsonElement"></param>
  763. /// <returns></returns>
  764. [ProducesDefaultResponseType]
  765. [AuthToken(Roles = "admin,rdc")]
  766. [HttpPost("set-batchmageage")]
  767. public async Task<IActionResult> SetBatchScManage(JsonElement jsonElement)
  768. {
  769. try
  770. {
  771. var (_tmdId, _tmdName, _, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  772. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  773. if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
  774. jsonElement.TryGetProperty("tmdPic", out JsonElement picture);
  775. if (!jsonElement.TryGetProperty("scSimplles", out JsonElement scSimplles)) return BadRequest();
  776. List<BatchScManage> schools = scSimplles.ToObject<List<BatchScManage>>();
  777. List<BatchScManage> existManageSc = new();
  778. Teacher teacher = new();
  779. StringBuilder msg = new($"{_tmdName}[{_tmdId}]设置账号:");
  780. var cosmosClient = _azureCosmos.GetCosmosClient();
  781. var tableClient = _azureStorage.GetCloudTableClient();
  782. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  783. if (schools.Count > 0)
  784. {
  785. var resTeacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Base"));
  786. if (resTeacher.Status == 200)
  787. {
  788. using var tchJson = await JsonDocument.ParseAsync(resTeacher.ContentStream);
  789. teacher = tchJson.ToObject<Teacher>();
  790. }
  791. else
  792. {
  793. teacher.id = $"{tmdId}";
  794. teacher.name = $"{tmdName}";
  795. teacher.picture = string.IsNullOrEmpty($"{picture}") ? "" : $"{picture}";
  796. teacher.pk = "Base";
  797. teacher.code = "Base";
  798. teacher.size = 1;
  799. teacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  800. }
  801. msg.Append($"{teacher.name}[{teacher.id}]设置学校管理员;学校信息:");
  802. foreach (var school in schools)
  803. {
  804. SchoolTeacher schoolTeacher = null;
  805. var existArea = teacher.schools.Find(f => f.schoolId.Equals($"{school.id}"));
  806. if (existArea == null)
  807. {
  808. teacher.schools.Add(new Teacher.TeacherSchool { schoolId = $"{school.id}", name = $"{school.id}", status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = string.IsNullOrEmpty($"{school.picture}") ? "" : $"{school.picture}", areaId = string.IsNullOrEmpty($"{school.areaId}") ? "" : $"{school.areaId}" });
  809. }
  810. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Teacher-{school.id}"));
  811. if (response.Status == 200)
  812. {
  813. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  814. schoolTeacher = json.ToObject<SchoolTeacher>();
  815. if (!schoolTeacher.roles.Contains("admin"))
  816. {
  817. schoolTeacher.roles.Add("admin");
  818. schoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, schoolTeacher.id, new PartitionKey($"Teacher-{school.id}"));
  819. }
  820. else
  821. existManageSc.Add(school);
  822. }
  823. else
  824. {
  825. schoolTeacher = new()
  826. {
  827. id = $"{tmdId}",
  828. code = $"Teacher-{school.id}",
  829. roles = new List<string> { "admin", "teacher" },
  830. job = "管理员",
  831. name = $"{tmdName}",
  832. picture = string.IsNullOrEmpty($"{picture}") ? "" : $"{picture}",
  833. status = "join",
  834. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  835. pk = "Teacher",
  836. ttl = -1
  837. };
  838. schoolTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey($"Teacher-{school.id}"));
  839. }
  840. msg.Append($"{school.name}[{school.id}]");
  841. }
  842. if(resTeacher.Status == 200)
  843. teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  844. else
  845. teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  846. }
  847. //保存操作记录
  848. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "schoolTeacher-add", msg.ToString(), _dingDing, httpContext: HttpContext);
  849. return Ok(new { state = RespondCode.Ok, teacher });
  850. }
  851. catch (Exception ex)
  852. {
  853. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/set-batchmageage \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  854. return BadRequest();
  855. }
  856. }
  857. /// <summary>
  858. /// 删除学校、学校相关的教师、学生 //已对接
  859. /// </summary>
  860. /// <param name="jsonElement"></param>
  861. /// <returns></returns>
  862. [ProducesDefaultResponseType]
  863. [AuthToken(Roles = "admin,rdc")]
  864. [HttpPost("set-del")]
  865. public async Task<IActionResult> DelSchool(JsonElement jsonElement)
  866. {
  867. try
  868. {
  869. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  870. List<string> schools = schoolId.ToObject<List<string>>();
  871. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  872. string _auth = HttpContext.GetXAuth("AuthToken");
  873. var (tmdId, tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(_auth, _option);
  874. var cosmosClient = _azureCosmos.GetCosmosClient();
  875. var tableClient = _azureStorage.GetCloudTableClient();
  876. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  877. ////分开部署,就不需要,一站多用时,取消注释
  878. //if ($"{site}".Equals(BIConst.Global))
  879. //{
  880. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  881. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  882. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  883. //}
  884. StringBuilder msg = new();
  885. List<DelSchoolRel> delSchoolRels = new();
  886. foreach (var tempId in schools)
  887. {
  888. List<string> scTchIds = new();
  889. List<string> scStuIds = new();
  890. string scTecSql = $"select value(c.id) from c where ARRAY_LENGTH(c.roles) > 0 and c.status = 'join'";
  891. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scTecSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{tempId}") }))
  892. {
  893. scTchIds.Add(item);
  894. }
  895. string scStuSql = $"select value(c.id) from c";
  896. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Student").GetItemQueryIterator<string>(queryText: scStuSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{tempId}") }))
  897. {
  898. scStuIds.Add(item);
  899. }
  900. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{tempId}", new PartitionKey($"Base"));
  901. if (response.Status == 204)
  902. msg.AppendLine($"{tmdName}【{tmdId}】删除学校,删除状态:{response.Status},删除ID:{tempId}");
  903. else
  904. delSchoolRels.Add(new DelSchoolRel() { id = $"{tempId}", code = "Base", type = 1, status = response.Status });
  905. foreach (var item in scTchIds)
  906. {
  907. //学校教师信息
  908. var tchRespnse = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{item}", new PartitionKey($"Teacher-{tempId}"));
  909. if (tchRespnse.Status == 204)
  910. msg.AppendLine($"删除教师,删除状态:{tchRespnse.Status},删除ID:{item}");
  911. else
  912. delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Teacher-{tempId}", type = 2, status = response.Status });
  913. //教师基础信息
  914. var tchBaseResponse = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{item}", new PartitionKey("Base"));
  915. if (tchBaseResponse.Status == 200)
  916. {
  917. using var json = await JsonDocument.ParseAsync(tchBaseResponse.ContentStream);
  918. Teacher teacher = json.ToObject<Teacher>();
  919. var tempSc = teacher.schools.Find(f => f.schoolId.Equals($"{tempId}"));
  920. if (tempSc != null)
  921. {
  922. teacher.schools.Remove(tempSc);
  923. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  924. }
  925. }
  926. else
  927. delSchoolRels.Add(new DelSchoolRel { id = $"{item}", code = "Base", type = 2, status = response.Status });
  928. }
  929. //删除学校学生
  930. foreach (var item in scStuIds)
  931. {
  932. var stuRespnse = await cosmosClient.GetContainer("TEAMModelOS", "Student").DeleteItemStreamAsync($"{item}", new PartitionKey($"Base-{tempId}"));
  933. if (stuRespnse.Status == 204)
  934. msg.AppendLine($"删除学生,删除状态:{stuRespnse.Status},删除ID:{item}");
  935. else
  936. delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Base-{tempId}", type = 3, status = response.Status });
  937. }
  938. }
  939. //string scTecSql = $"select value(c.id) from c where ARRAY_LENGTH(c.roles) > 0 and c.status = 'join'";
  940. //await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scTecSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{schoolId}") }))
  941. //{
  942. // scTchIds.Add(item);
  943. //}
  944. //string scStuSql = $"select value(c.id) from c";
  945. //await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scStuSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  946. //{
  947. // scStuIds.Add(item);
  948. //}
  949. //var response = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{schoolId}", new PartitionKey($"Base"));
  950. //if (response.Status == 204)
  951. // msg.AppendLine($"{tmdName}【{tmdId}】删除学校,删除状态:{response.Status},删除ID:{schoolId}");
  952. //else
  953. // delSchoolRels.Add(new DelSchoolRel() { id = $"{schoolId}", code = "Base", type = 1, status = response.Status });
  954. //foreach (var item in scTchIds)
  955. //{
  956. // var tchRespnse = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{item}", new PartitionKey($"Teacher-{schoolId}"));
  957. // if (tchRespnse.Status == 204)
  958. // msg.AppendLine($"删除教师,删除状态:{tchRespnse.Status},删除ID:{item}");
  959. // else
  960. // delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Teacher-{schoolId}", type = 2, status = response.Status });
  961. //}
  962. //foreach (var item in scStuIds)
  963. //{
  964. // var stuRespnse = await cosmosClient.GetContainer("TEAMModelOS", "Student").DeleteItemStreamAsync($"{item}", new PartitionKey($"Base-{schoolId}"));
  965. // if (stuRespnse.Status == 204)
  966. // msg.AppendLine($"删除学生,删除状态:{stuRespnse.Status},删除ID:{item}");
  967. // else
  968. // delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Base-{schoolId}", type = 3, status = response.Status });
  969. //}
  970. //保存操作记录
  971. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "set-del", msg.ToString(), _dingDing, httpContext: HttpContext);
  972. if (delSchoolRels.Count > 0)
  973. return Ok(new { state = 201, delSchoolRels });
  974. else
  975. return Ok(new { state = 200 });
  976. }
  977. catch (Exception ex)
  978. {
  979. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/set-del \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  980. return BadRequest();
  981. }
  982. }
  983. /// <summary>
  984. /// 依据学校统计 //已对接
  985. /// </summary>
  986. /// <param name="jsonElement"></param>
  987. /// <returns></returns>
  988. [ProducesDefaultResponseType]
  989. [HttpPost("get-schoolcnt")]
  990. public async Task<IActionResult> GetSchoolCnt(JsonElement jsonElement)
  991. {
  992. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  993. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  994. var cosmosClient = _azureCosmos.GetCosmosClient();
  995. ////分开部署,就不需要,一站多用时,取消注释
  996. //if ($"{site}".Equals(BIConst.Global))
  997. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  998. DateTimeOffset dtime = DateTimeOffset.UtcNow;
  999. var (weekS, weekE) = TimeHelper.GetStartOrEnd(dtime, "week");
  1000. var (lastWeekS, lastWeekE) = TimeHelper.GetStartOrEnd(dtime, "lastweek");
  1001. var (termS, termE) = TimeHelper.GetStartOrEnd(dtime, "term");
  1002. var (lastTermS, lastTermE) = TimeHelper.GetStartOrEnd(dtime, "lastterm");
  1003. var (yearS, yearE) = TimeHelper.GetStartOrEnd(dtime, "year");
  1004. var (lastYearS, lastYearE) = TimeHelper.GetStartOrEnd(dtime, "lastYear");
  1005. int tecCnt = 0;// 教师数量
  1006. int classCnt = 0; //班级
  1007. int stuCnt = 0; //学生
  1008. int roomCnt = 0; //智慧教室
  1009. int lesCnt = 0; //课例总数
  1010. int weekLesCnt = 0; //本周课例
  1011. int lastWeekLesCnt = 0; //上周课例
  1012. int weekACTCnt = 0; //本周活动
  1013. int lastWeekACTCnt = 0; //上周活动
  1014. int termLesCnt = 0; //本学期课例
  1015. int lastTermLesCnt = 0; //上学学期课例
  1016. int termACTCnt = 0; //本学期活动
  1017. int lastTermActCnt = 0; //上学学期活动
  1018. int yearLesCnt = 0; //今年课例
  1019. int lastYearLesCnt = 0; //去年课例
  1020. int yearACTCnt = 0; //今年活动
  1021. int lastYearACTCnt = 0; //去年活动
  1022. SchoolInfo schoolInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolInfo>($"{schoolId}", new PartitionKey("Base"));
  1023. if (schoolInfo != null)
  1024. {
  1025. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(schoolInfo.id, new PartitionKey("ProductSum"));
  1026. if (response.Status == 200)
  1027. {
  1028. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1029. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  1030. {
  1031. schoolInfo.serial = serial.ToObject<List<ProductSumInfos>>();
  1032. }
  1033. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  1034. {
  1035. schoolInfo.service = service.ToObject<List<ProductSumInfos>>();
  1036. }
  1037. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  1038. {
  1039. schoolInfo.hard = hard.ToObject<List<SchoolProductSumDataHard>>();
  1040. }
  1041. }
  1042. schoolInfo.assists = await CommonFind.FindSchoolRoles(cosmosClient, schoolInfo.id, "assist");
  1043. string currencySql = "select value(count(c.id)) from c";
  1044. tecCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"Teacher-{schoolInfo.id}"); // 教师数量
  1045. classCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"Class-{schoolInfo.id}"); //班级
  1046. stuCnt = await CommonFind.GetSqlValueCount(cosmosClient, "Student", currencySql, $"Base-{schoolInfo.id}"); //学生
  1047. roomCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"Room-{schoolInfo.id}"); //智慧教室
  1048. lesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"LessonRecord-{schoolInfo.id}"); //课例总数
  1049. weekLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {weekS} and c.startTime<= {weekE}", $"LessonRecord-{schoolInfo.id}"); //本周课例
  1050. lastWeekLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {lastWeekS} and c.startTime<= {lastWeekE}", $"LessonRecord-{schoolInfo.id}"); //上周课例
  1051. termLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {termS} and c.startTime <= {termE}", $"LessonRecord-{schoolInfo.id}"); //本学期课例
  1052. lastTermLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {lastTermS} and c.startTime <= {lastTermE}", $"LessonRecord-{schoolInfo.id}"); //上学学期课例
  1053. yearLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {yearS} and c.startTime <= {yearE}", $"LessonRecord-{schoolInfo.id}"); //今年课例
  1054. lastYearLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {lastYearS} and c.startTime <= {lastYearE}", $"LessonRecord-{schoolInfo.id}"); //去年课例
  1055. int ACTCnt = 0; //活动
  1056. foreach (var type in StaticValue.activityTypes)
  1057. {
  1058. ACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}'");
  1059. weekACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {weekS} and c.createTime <= {weekE} "); //本周活动
  1060. lastWeekACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {lastWeekS} and c.createTime <= {lastWeekE} "); //上周活动
  1061. termACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {termS} and c.createTime <= {termE}", $"LessonRecord-{schoolInfo.id}"); //本学期活动
  1062. lastTermActCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {lastTermS} and c.createTime <= {lastTermE}", $"LessonRecord-{schoolInfo.id}"); //上学学期活动
  1063. yearACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {yearS} and c.createTime <= {yearE}", $"LessonRecord-{schoolInfo.id}"); //今年活动
  1064. lastYearACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {lastYearS} and c.createTime <= {lastYearE}", $"LessonRecord-{schoolInfo.id}"); //去年活动
  1065. }
  1066. //取得購買紀錄
  1067. List<object> order = await GetOrderHisFromCoreBBAsync(schoolId.GetString());
  1068. return Ok(new { state = RespondCode.Ok, tecCnt, classCnt, stuCnt, roomCnt, lesCnt, weekLesCnt, lastWeekLesCnt, weekACTCnt, lastWeekACTCnt, termLesCnt, lastTermLesCnt, termACTCnt, lastTermActCnt, yearLesCnt, lastYearLesCnt, yearACTCnt, lastYearACTCnt, schoolInfo, ACTCnt, buy = new { yearS, yearE, lastYearS, lastYearE, order } });
  1069. }
  1070. else
  1071. return Ok(new { state = RespondCode.NotFound, msg = "未找到该学校信息!" });
  1072. }
  1073. /// <summary>
  1074. /// 通过学校Id 统计学校信息 //已对接
  1075. /// </summary>
  1076. /// <param name="jsonElement"></param>
  1077. /// <returns></returns>
  1078. [ProducesDefaultResponseType]
  1079. [HttpPost("get-analyse")]
  1080. public async Task<IActionResult> GetAnalyse(JsonElement jsonElement)
  1081. {
  1082. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  1083. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1084. var cosmosClient = _azureCosmos.GetCosmosClient();
  1085. ////分开部署,就不需要,一站多用时,取消注释
  1086. //if ($"{site}".Equals(BIConst.Global))
  1087. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1088. RecSchool recSchool = new();
  1089. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{schoolId}", new PartitionKey("Base"));
  1090. if (response.Status == 200)
  1091. {
  1092. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1093. recSchool = json.ToObject<RecSchool>();
  1094. }
  1095. else return Ok(new { state = RespondCode.NotFound, msg = "未找到该学校" });
  1096. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1097. var (days, daye) = TimeHelper.GetStartOrEnd(dateTime);
  1098. var (lastDays, lastDaye) = TimeHelper.GetStartOrEnd(dateTime.AddDays(-1));
  1099. var (years, yeare) = TimeHelper.GetStartOrEnd(dateTime, "year");
  1100. var (lastYears, lastYeare) = TimeHelper.GetStartOrEnd(dateTime, "lastYear");
  1101. int tchCnt = 0; //教师数量
  1102. int stuCnt = 0; //学校数量
  1103. int roomCnt = 0; //智慧教室数量
  1104. int lessAllCant = 0; //课例总数
  1105. int lessLastdayCnt = 0; //昨天的课例
  1106. int lessDayCnt = 0; //今天的课例
  1107. int lessLastYearCnt = 0; //去年的课例
  1108. int lessYearCnt = 0; //今年的课例
  1109. double allInterCnt = 0; //所有互动
  1110. double lastDayInterCnt = 0; // 昨天课例互动
  1111. double interCnt = 0; // 今天课例互动
  1112. double lastYearInterCnt = 0; // 去年课例互动
  1113. double yearInterCnt = 0; // 今年课例互动
  1114. int allActCnt = 0; //所有活动
  1115. int lastActCnt = 0; //昨天活动
  1116. int actCnt = 0; //今天活动
  1117. int lastYearActCnt = 0; //去年活动
  1118. int yearActCnt = 0; //今年活动
  1119. string commSql = "select value(count(c.id)) from c ";
  1120. tchCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", commSql, $"Teacher-{schoolId}");
  1121. stuCnt = await CommonFind.GetSqlValueCount(cosmosClient, "Student", commSql, $"Base-{schoolId}");
  1122. roomCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", commSql, $"Room-{schoolId}");
  1123. lessAllCant = await CommonFind.GetSqlValueCount(cosmosClient, "School", commSql, $"LessonRecord-{schoolId}");
  1124. string lessCode = $"LessonRecord-{schoolId}";
  1125. string lessLastdaySql = $"{commSql} where c.startTime >= {lastDays} and c.startTime <= {lastDaye} ";
  1126. lessLastdayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastdaySql, lessCode);
  1127. string lessDaySql = $"{commSql} where c.startTime >= {days} and c.startTime <= {daye} ";
  1128. lessDayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessDaySql, lessCode);
  1129. string lessLastYarSql = $"{commSql} where c.startTime >= {lastYears} and c.startTime <= {lastYeare} ";
  1130. lessLastYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastYarSql, lessCode);
  1131. string lessYearSql = $"{commSql} where c.startTime >= {years} and c.startTime <= {yeare} ";
  1132. lessYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessYearSql, lessCode);
  1133. //课例互动
  1134. string strInterSql = $"select value(sum(c.clientInteractionAverge)) from c";
  1135. allInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", strInterSql, lessCode);
  1136. string lastdayInterSql = $"{strInterSql} where c.startTime >= { lastDays} and c.startTime <= {lastDays} ";
  1137. lastDayInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", lastdayInterSql, lessCode);
  1138. string dayInterSql = $"{strInterSql} where c.startTime >= { days} and c.startTime <= {daye} ";
  1139. interCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", dayInterSql, lessCode);
  1140. string lastYarInterSql = $"{strInterSql} where c.startTime >= { lastYears} and c.startTime <= {lastYeare} ";
  1141. lastYearInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", lastYarInterSql, lessCode);
  1142. string yearInterSql = $"{strInterSql} where c.startTime >= { years} and c.startTime <= {yeare} ";
  1143. yearInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", yearInterSql, lessCode);
  1144. //活动
  1145. allActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: $"and c.school='{schoolId}'");
  1146. string lastActSql = $" and c.school='{schoolId}' and c.createTime >= {lastDays} and c.createTime <= {lastDays}";
  1147. lastActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: lastActSql);
  1148. string actSql = $" and c.school='{schoolId}' and c.createTime >= {days} and c.createTime <= {daye}";
  1149. actCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actSql);
  1150. string lastYearActSql = $" and c.school='{schoolId}' and c.createTime >= {lastYears} and c.createTime <= {lastYeare}";
  1151. lastYearActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: lastYearActSql);
  1152. string yearActSql = $" and c.school='{schoolId}' and c.createTime >= {years} and c.createTime <= {yeare}";
  1153. yearActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: yearActSql);
  1154. return Ok(new { state = 200, recSchool, tchCnt, stuCnt, roomCnt, lessAllCant, lessLastdayCnt, lessDayCnt, lessLastYearCnt, lessYearCnt, allInterCnt, lastDayInterCnt, interCnt, lastYearInterCnt, yearInterCnt, allActCnt, lastActCnt, actCnt, lastYearActCnt, yearActCnt });
  1155. }
  1156. /// <summary>
  1157. /// 学校每周课例趋势 //已对接
  1158. /// </summary>
  1159. /// <param name="jsonElement"></param>
  1160. /// <returns></returns>
  1161. [ProducesDefaultResponseType]
  1162. [HttpPost("get-schooldate")]
  1163. public async Task<IActionResult> GetSchoolDate(JsonElement jsonElement)
  1164. {
  1165. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  1166. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1167. var cosmosClient = _azureCosmos.GetCosmosClient();
  1168. ////分开部署,就不需要,一站多用时,取消注释
  1169. //if ($"{site}".Equals(BIConst.Global))
  1170. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1171. List<double> weekTrend = new();
  1172. int year = DateTimeOffset.UtcNow.Year;
  1173. int dayOfweek = (int)DateTimeOffset.Parse($"{year}-1-1").DayOfWeek;
  1174. int currentTime = DateTimeOffset.UtcNow.DayOfYear / 7 + 1;
  1175. int currentTime1 = DateTimeOffset.UtcNow.DayOfYear / 7;
  1176. //获取当前学期所有的课程记录
  1177. List<LessAnalyse> records = new List<LessAnalyse>();
  1178. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<LessAnalyse>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{schoolId}") }))
  1179. {
  1180. records.Add(item);
  1181. }
  1182. List<(string name, string periodId, int count)> grades = LessonStatisWay.GetGradeCount(records);
  1183. var subs = records.GroupBy(x => x.subjectId).Where(w => !string.IsNullOrEmpty(w.Key)).Select(y => new { key = y.Key, count = y.ToList().Count }).ToList();
  1184. var gradeCnt = grades.Select(x => new { x.name, x.periodId, value = x.count });
  1185. var subCnt = subs.Select(x => new { name = x.key, value = x.count });
  1186. List<LessonCount> scount = new();
  1187. List<LessonCount> tcount = new();
  1188. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<LessonCount>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{schoolId}-{year}") }))
  1189. {
  1190. scount.Add(item);
  1191. }
  1192. List<string> teacIds = await CommonFind.FindRolesId(cosmosClient, new List<string>() { $"{schoolId}" });
  1193. foreach (var tId in teacIds)
  1194. {
  1195. var sqlTxtt = $"select value(c) from c where c.id='{tId}'";
  1196. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<LessonCount>(queryText: sqlTxtt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{year}") }))
  1197. {
  1198. tcount.Add(item);
  1199. }
  1200. }
  1201. int days = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? days = 366 : days = 365;
  1202. List<List<double>> lessons = new();
  1203. if (scount.Count > 0)
  1204. {
  1205. foreach (LessonCount item in scount)
  1206. {
  1207. lessons.Add(item.beginCount);
  1208. }
  1209. }
  1210. if (tcount.Count > 0)
  1211. {
  1212. foreach (LessonCount item in tcount)
  1213. {
  1214. lessons.Add(item.beginCount);
  1215. }
  1216. }
  1217. if (lessons.Count > 0)
  1218. {
  1219. var bmatrix = DenseMatrix.OfColumns(lessons);
  1220. //开学第一周周内开课
  1221. if (dayOfweek == 0)
  1222. {
  1223. dayOfweek = 7;
  1224. }
  1225. //第一周多少天
  1226. var dd = 7 - dayOfweek + 1;
  1227. //一年有几周
  1228. int sweeks = days / 7;
  1229. //查询天数
  1230. int dayYear = 0;
  1231. if (currentTime > 0)
  1232. {
  1233. for (int i = 0; i <= currentTime; i++)
  1234. {
  1235. if (i == 0)
  1236. {
  1237. var bsum = bmatrix.SubMatrix(dayYear, dd, 0, bmatrix.ColumnCount).ColumnSums().Sum();
  1238. dayYear += dd;
  1239. //weeks.Add(i, bsum);
  1240. weekTrend.Add(bsum);
  1241. }
  1242. else
  1243. {
  1244. var bsum = bmatrix.SubMatrix(dayYear, 7, 0, bmatrix.ColumnCount).ColumnSums().Sum();
  1245. dayYear += 7;
  1246. //weeks.Add(i, bsum);
  1247. weekTrend.Add(bsum);
  1248. }
  1249. }
  1250. }
  1251. //最后一周是否有余
  1252. int stary = days - dayYear;
  1253. if (stary > 0 && stary < 7)
  1254. {
  1255. var bsum = bmatrix.SubMatrix(dayYear, stary - 1, 0, bmatrix.ColumnCount).ColumnSums().Sum();
  1256. //weeks.Add((sweeks + 1), bsum);
  1257. weekTrend.Add(bsum);
  1258. }
  1259. }
  1260. return Ok(new { state = 200, gradeCnt, subCnt, weekTrend });
  1261. }
  1262. /// <summary>
  1263. /// 顾问学校基础统计、以及排行 //已对接
  1264. /// </summary>
  1265. /// <param name="jsonElement"></param>
  1266. /// <returns></returns>
  1267. [ProducesDefaultResponseType]
  1268. [HttpPost("get-assisscbase")]
  1269. public async Task<IActionResult> GetAssistSchoolCnt(JsonElement jsonElement)
  1270. {
  1271. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  1272. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1273. var cosmosClient = _azureCosmos.GetCosmosClient();
  1274. ////分开部署,就不需要,一站多用时,取消注释
  1275. //if ($"{site}".Equals(BIConst.Global))
  1276. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1277. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1278. int scAllCnt = 0; //学校
  1279. int tchAllCnt = 0; //教师数量
  1280. int tchMonthCnt = 0; //教师本月新增
  1281. int stuAllCnt = 0; //所有学校学生
  1282. int lessAllCnt = 0; //课例总数
  1283. int lessMthCnt = 0; //本月新增
  1284. List<ScRankCnt> scRankCnts = new(); //学校开课、上传, 课例排名
  1285. var (start, end) = TimeHelper.GetStartOrEnd(dateTime, "month");
  1286. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1287. if (schoolIds.Count > 0)
  1288. {
  1289. string scIdSql = BICommonWay.ManyScSql("c.schoolId", schoolIds);
  1290. string stuSql = $"select value(count(c.id)) from c where {scIdSql}";
  1291. stuAllCnt = await CommonFind.GetSqlValueCount(cosmosClient, "Student", stuSql);
  1292. string scSql = BICommonWay.ManyScSql("c.school", schoolIds);
  1293. string lessMoSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and {scSql} and c.startTime >= {start} and c.startTime <= {end}";
  1294. lessMthCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessMoSql);
  1295. List<SchoolBase> scInfos = new();
  1296. string scInfoSql = $"select c.id,c.name,c.code,c.picture from c ";
  1297. string idSql = BICommonWay.ManyScSql("c.id", schoolIds);
  1298. scInfos = await CommonFind.GetObject<SchoolBase>(cosmosClient, "School", $"{scInfoSql} where {idSql}", "Base");
  1299. List<string> tchMonIds = new();
  1300. foreach (var item in scInfos)
  1301. {
  1302. ScRankCnt lessRankCnt = new() { id = item.id, name = item.name, code = item.code, picture = item.picture };
  1303. string tchSql = $"select value(count(c.id)) from c where array_contains(c.roles,'teacher',true) and c.createTime >= {start} and c.createTime <= {end}";
  1304. tchMonthCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", tchSql, $"Teacher-{item.id}");
  1305. string tchAllSql = $"select value(count(c.id)) from c where ARRAY_CONTAINS(c.roles,'teacher',true) and c.status = 'join'";
  1306. tchAllCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", tchAllSql, $"Teacher-{item.id}");
  1307. string lessALLSql = "select value(count(c.id)) from c where c.pk='LessonRecord'";
  1308. lessAllCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", lessALLSql, $"LessonRecord-{item.id}");
  1309. string lessUpSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and c.upload = 0";
  1310. lessRankCnt.openCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessMoSql, $"LessonRecord-{item.id}");
  1311. string lessSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and c.upload = 1";
  1312. lessRankCnt.lessCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessSql, $"LessonRecord-{item.id}");
  1313. string interactSql = $"select value(sum(c.clientInteractionCount)) from c where c.pk='LessonRecord'";
  1314. lessRankCnt.interCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", interactSql, $"LessonRecord-{item.id}");
  1315. string actSql = $" and c.school='{item.id}'";
  1316. lessRankCnt.actCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actSql);
  1317. scRankCnts.Add(lessRankCnt);
  1318. }
  1319. scAllCnt = schoolIds.Count();
  1320. tchMonthCnt = tchMonIds.Distinct().Count();
  1321. }
  1322. return Ok(new { state = RespondCode.Ok, scAllCnt, tchAllCnt, tchMonthCnt, stuAllCnt, lessAllCnt, lessMthCnt, scRankCnts });
  1323. }
  1324. /// <summary>
  1325. /// 一年学校和多个学校的课例、互动、活动统计分析 //已对接
  1326. /// </summary>
  1327. /// <param name="jsonElement"></param>
  1328. /// <returns></returns>
  1329. [ProducesDefaultResponseType]
  1330. [HttpPost("get-assissc")]
  1331. public async Task<IActionResult> GetAssisSc(JsonElement jsonElement)
  1332. {
  1333. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  1334. jsonElement.TryGetProperty("schoolId", out JsonElement schooId);
  1335. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  1336. var cosmosClient = _azureCosmos.GetCosmosClient();
  1337. //if ($"{site}".Equals(BIConst.Global))
  1338. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1339. List<YearCnt> yearCnts = new(); //当前的课例,活动,互动统计
  1340. string strSql = "SELECT value(count(c.id)) FROM c where c.pk='LessonRecord'";
  1341. string scSql = null;
  1342. if (!string.IsNullOrEmpty($"{tmdId}") && string.IsNullOrEmpty($"{schooId}"))
  1343. {
  1344. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1345. if (schoolIds.Count == 0) return Ok(new { state = RespondCode.Ok, yearCnts, });
  1346. scSql = BICommonWay.ManyScSql("c.school", schoolIds);
  1347. }
  1348. if (!string.IsNullOrEmpty($"{schooId}") && string.IsNullOrEmpty($"{tmdId}"))
  1349. scSql = $"c.school = '{schooId}'";
  1350. if ((string.IsNullOrEmpty($"{tmdId}") && string.IsNullOrEmpty($"{schooId}")) || (!string.IsNullOrEmpty($"{tmdId}") && !string.IsNullOrEmpty($"{schooId}")))
  1351. return Ok(new { state = RespondCode.ParamsError, msg = "参数错误" });
  1352. List<MonthStartEnd> mthStartEnds = await TimeHelper.GetYearSataMthCtMth(DateTimeOffset.UtcNow);
  1353. if (mthStartEnds.Count > 0)
  1354. {
  1355. foreach (var item in mthStartEnds)
  1356. {
  1357. YearCnt yearCnt = new() { name = item.yearMonth };
  1358. string selessSql = $"{strSql} and {scSql.ToString()} and c.startTime >= { item.start} and c.startTime <= {item.end}";
  1359. yearCnt.lessCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", selessSql);
  1360. string interactSql = $"select value(sum(c.clientInteractionAverge)) from c where c.pk='LessonRecord' and {scSql} and c.startTime >= { item.start} and c.startTime <= {item.end}";
  1361. yearCnt.interCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", interactSql);
  1362. string mthActSql = $"and {scSql} and c.createTime >= {item.start} and c.createTime <= {item.end}";
  1363. yearCnt.actCnt = await ActivityWay.GetCnt(cosmosClient, condSql: mthActSql);
  1364. yearCnts.Add(yearCnt);
  1365. }
  1366. }
  1367. return Ok(new { state = RespondCode.Ok, yearCnts, });
  1368. }
  1369. /// <summary>
  1370. /// 顾问学校统计 //已对接
  1371. /// </summary>
  1372. /// <param name="jsonElement"></param>
  1373. /// <returns></returns>
  1374. [ProducesDefaultResponseType]
  1375. [HttpPost("get-assissccnt")]
  1376. public async Task<IActionResult> GetAssisScCnt(JsonElement jsonElement)
  1377. {
  1378. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  1379. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  1380. var cosmosClient = _azureCosmos.GetCosmosClient();
  1381. //if ($"{site}".Equals(BIConst.Global))
  1382. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1383. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1384. var (days, daye) = TimeHelper.GetStartOrEnd(dateTime);
  1385. var (lastDays, lastDaye) = TimeHelper.GetStartOrEnd(dateTime.AddDays(-1));
  1386. var (years, yeare) = TimeHelper.GetStartOrEnd(dateTime, "year");
  1387. var (lastYears, lastYeare) = TimeHelper.GetStartOrEnd(dateTime, "lastYear");
  1388. int lessAll = 0; //所以课例
  1389. int lessLastdayCnt = 0; //昨天的课例
  1390. int lessDayCnt = 0; //今天的课例
  1391. int lessLastYearCnt = 0; //去年的课例
  1392. int lessYearCnt = 0; //今年的课例
  1393. double interAll = 0; //所有互动总数
  1394. double lastDayInterCnt = 0; // 昨天课例互动
  1395. double interCnt = 0; // 今天课例互动
  1396. double lastYearInterCnt = 0; // 去年课例互动
  1397. double yearInterCnt = 0; // 今年课例互动
  1398. int actAllCnt = 0; //所有活动
  1399. int lastActCnt = 0; //昨天活动
  1400. int actCnt = 0; //今天活动
  1401. int lastYearActCnt = 0; //去年活动
  1402. int yearActCnt = 0; //今年活动
  1403. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1404. if (schoolIds.Count > 0)
  1405. {
  1406. string scSql = BICommonWay.ManyScSql("c.school", schoolIds);
  1407. string strSql = "SELECT value(count(c.id)) FROM c where c.pk='LessonRecord'";
  1408. //课例
  1409. lessAll = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{strSql} and {scSql}");
  1410. string lessLastdaySql = $"{strSql} and {scSql} and c.startTime >= { lastDays} and c.startTime <= {lastDaye} ";
  1411. lessLastdayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastdaySql);
  1412. string lessDaySql = $"{strSql} and {scSql} and c.startTime >= { days} and c.startTime <= {daye} ";
  1413. lessDayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessDaySql);
  1414. string lessLastYarSql = $"{strSql} and {scSql} and c.startTime >= { lastYears} and c.startTime <= {lastYeare} ";
  1415. lessLastYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastYarSql);
  1416. string lessYearSql = $"{strSql} and {scSql} and c.startTime >= { years} and c.startTime <= {yeare} ";
  1417. lessYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessYearSql);
  1418. //课例互动
  1419. string strInterSql = $"select value(sum(c.clientInteractionCount)) from c where c.pk='LessonRecord' and {scSql}";
  1420. interAll = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", strInterSql);
  1421. string lastdayInterSql = $"{strInterSql} and c.startTime >= { lastDays} and c.startTime <= {lastDaye} ";
  1422. lastDayInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", lastdayInterSql);
  1423. string dayInterSql = $"{strInterSql} and c.startTime >= { days} and c.startTime <= {daye} ";
  1424. interCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", dayInterSql);
  1425. string lastYarInterSql = $"{strInterSql} and c.startTime >= { lastYears} and c.startTime <= {lastYeare} ";
  1426. lastYearInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", lastYarInterSql);
  1427. string yearInterSql = $"{strInterSql} and c.startTime >= { years} and c.startTime <= {yeare} ";
  1428. yearInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", yearInterSql);
  1429. //活动
  1430. string actAllSql = $"and {scSql} ";
  1431. actAllCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actAllSql);
  1432. string lastActSql = $"and {scSql} and c.createTime >= {lastDays} and c.createTime <= {lastDaye}";
  1433. lastActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: lastActSql);
  1434. string actSql = $"and {scSql} and c.createTime >= {days} and c.createTime <= {daye}";
  1435. actCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actSql);
  1436. string lastYearActSql = $" and {scSql} and c.createTime >= {lastYears} and c.createTime <= {lastYeare}";
  1437. lastYearActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: lastYearActSql);
  1438. string yearActSql = $"and {scSql} and c.createTime >= {years} and c.createTime <= {yeare}";
  1439. yearActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: yearActSql);
  1440. }
  1441. return Ok(new { state = RespondCode.Ok, lessAll, lessLastdayCnt, lessDayCnt, lessLastYearCnt, lessYearCnt, interAll, lastDayInterCnt, interCnt, lastYearInterCnt, yearInterCnt, actAllCnt, lastActCnt, actCnt, lastYearActCnt, yearActCnt });
  1442. }
  1443. /// <summary>
  1444. /// 查询学校基础信息,和学校年级、科目数据统计 //已对接
  1445. /// </summary>
  1446. /// <param name="jsonElement"></param>
  1447. /// <returns></returns>
  1448. [ProducesDefaultResponseType]
  1449. [HttpPost("get-ratio")]
  1450. public async Task<IActionResult> GetRatio(JsonElement jsonElement)
  1451. {
  1452. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  1453. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1454. var cosmosClient = _azureCosmos.GetCosmosClient();
  1455. ////分开部署,就不需要,一站多用时,取消注释
  1456. //if ($"{site}".Equals(BIConst.Global))
  1457. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1458. AnSchool school = new(); //学校基础基础信息
  1459. int serial = 0; //学校软体数量
  1460. int service = 0; //学校服务数量
  1461. int hard = 0; //学校硬件数量
  1462. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{schoolId}", new PartitionKey("Base"));
  1463. if (response.Status == 200)
  1464. {
  1465. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1466. school = json.ToObject<AnSchool>();
  1467. }
  1468. else return Ok(new { state = RespondCode.NotFound, msg = "未找到该学校" });
  1469. List<LessAnalyse> lessAnalyses = new();
  1470. await foreach (var lessItem in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<LessAnalyse>(queryText: "select c.id,c.code,c.periodId,c.subjectId,c.grade from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{school.id}") }))
  1471. {
  1472. lessAnalyses.Add(lessItem);
  1473. }
  1474. List<(string name, string periodId, int count)> grades = LessonStatisWay.GetGradeCount(lessAnalyses);
  1475. var subs = lessAnalyses.GroupBy(x => x.subjectId).Where(y => !string.IsNullOrEmpty(y.Key)).Select(y => new { key = y.Key, count = y.ToList().Count }).ToList();
  1476. var gradeCnt = grades.Select(x => new { x.name, x.periodId,value = x.count });
  1477. var subCnt = subs.Select(x => new { name = x.key, value = x.count });
  1478. var responseProduct = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school.id, new PartitionKey("ProductSum"));
  1479. if (responseProduct.Status == 200)
  1480. {
  1481. using var json = await JsonDocument.ParseAsync(responseProduct.ContentStream);
  1482. if (json.RootElement.TryGetProperty("serial", out JsonElement _serial) && !_serial.ValueKind.Equals(JsonValueKind.Null))
  1483. {
  1484. serial = _serial.ToObject<List<SchoolProductSumData>>().Count;//.Select(x => x.prodCode).ToList();
  1485. }
  1486. if (json.RootElement.TryGetProperty("service", out JsonElement _service) && !_service.ValueKind.Equals(JsonValueKind.Null))
  1487. {
  1488. service = _service.ToObject<List<SchoolProductSumData>>().Count;//.Select(x => x.prodCode).ToList();
  1489. }
  1490. if (json.RootElement.TryGetProperty("hard", out JsonElement _hard) && !_hard.ValueKind.Equals(JsonValueKind.Null))
  1491. {
  1492. hard = _hard.ToObject<List<SchoolProductSumDataHard>>().Count();//.Select(x => x.prodCode).ToList();
  1493. }
  1494. }
  1495. return Ok(new { state = RespondCode.Ok, school, gradeCnt, subCnt, serial, service, hard });
  1496. }
  1497. /// <summary>
  1498. /// 通过tmdID 账户查询学校专业和模组 //已对接
  1499. /// </summary>
  1500. /// <param name="jsonElement"></param>
  1501. /// <returns></returns>
  1502. [ProducesDefaultResponseType]
  1503. [HttpPost("get-proded")]
  1504. public async Task<IActionResult> GetProdEd(JsonElement jsonElement)
  1505. {
  1506. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return Ok(new { state = RespondCode.ParamsError, nsg = "参数错误" });
  1507. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1508. var cosmosClient = _azureCosmos.GetCosmosClient();
  1509. ////分开部署,就不需要,一站多用时,取消注释
  1510. //if ($"{site}".Equals(BIConst.Global))
  1511. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1512. int adCnt = 0;
  1513. int allCnt = 0;
  1514. List<ScProdEd> scInfos = new();
  1515. List<string> products = new();
  1516. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1517. if (schoolIds.Count > 0)
  1518. {
  1519. string scInfoSql = $"select c.id,c.name,c.code,c.picture,c.type,c.size,c.scale from c ";
  1520. string idSql = BICommonWay.ManyScSql("c.id", schoolIds);
  1521. scInfos = await CommonFind.GetObject<ScProdEd>(cosmosClient, "School", $"{scInfoSql} where {idSql}", "Base");
  1522. string serialSql = "SELECT value(count(ARRAY_LENGTH(c.deviceBound))) FROM c ";
  1523. string serialAllSql = "SELECT value(sum((c.deviceMax))) FROM c";
  1524. if (schoolIds.Count > 0)
  1525. {
  1526. foreach (var scProd in scInfos)
  1527. {
  1528. adCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", serialSql, $"Product-{scProd.id}");
  1529. allCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", serialAllSql, $"Product-{scProd.id}");
  1530. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(scProd.id, new PartitionKey("ProductSum"));
  1531. if (response.Status == 200)
  1532. {
  1533. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1534. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  1535. {
  1536. List<string> serials = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1537. scProd.serial = serials;
  1538. products.AddRange(serials);
  1539. }
  1540. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  1541. {
  1542. List<string> services = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1543. scProd.service = services;
  1544. products.AddRange(services);
  1545. }
  1546. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  1547. {
  1548. List<string> hards = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  1549. scProd.hard = hards;
  1550. products.AddRange(hards);
  1551. }
  1552. }
  1553. }
  1554. //scInfos.ForEach(async scProd =>
  1555. //{
  1556. // var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(scProd.id, new PartitionKey("ProductSum"));
  1557. // if (response.Status == 200)
  1558. // {
  1559. // using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1560. // if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  1561. // {
  1562. // scProd.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1563. // }
  1564. // if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  1565. // {
  1566. // scProd.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1567. // }
  1568. // if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  1569. // {
  1570. // scProd.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  1571. // }
  1572. // }
  1573. //});
  1574. }
  1575. }
  1576. var productAn = products.GroupBy(g => g).Select(s => new { key = s.Key, cnt = s.ToList().Count }).ToList();
  1577. return Ok(new { state = RespondCode.Ok, allCnt, adCnt, scInfos, productAn });
  1578. }
  1579. /// <summary>
  1580. /// 通过学校Id查询详情 数据管理工具——查询工具
  1581. /// </summary>
  1582. /// <returns></returns>
  1583. [ProducesDefaultResponseType]
  1584. [HttpPost("get-info")]
  1585. public async Task<IActionResult> GetSchool(JsonElement jsonElement)
  1586. {
  1587. jsonElement.TryGetProperty("schoolId", out JsonElement schoolId);
  1588. jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1589. var cosmosClient = _azureCosmos.GetCosmosClient();
  1590. ////分开部署,就不需要,一站多用时,取消注释
  1591. //if ($"{site}".Equals(BIConst.Global))
  1592. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1593. StringBuilder sqlTxt = new("select * from c");
  1594. if (!string.IsNullOrEmpty($"{schoolId}"))
  1595. {
  1596. sqlTxt.Append($" where c.id='{schoolId}'");
  1597. }
  1598. List<School> schools = new();
  1599. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1600. {
  1601. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1602. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1603. {
  1604. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1605. {
  1606. schools.Add(obj.ToObject<School>());
  1607. }
  1608. }
  1609. }
  1610. return Ok(new { state = 200, schools });
  1611. }
  1612. /// <summary>
  1613. /// 依据区域Id查询区域空间统计
  1614. /// </summary>
  1615. /// <param name="jsonElement"></param>
  1616. /// <returns></returns>
  1617. [ProducesDefaultResponseType]
  1618. [HttpPost("get-spance")]
  1619. public async Task<IActionResult> GetAreaSpace(JsonElement jsonElement)
  1620. {
  1621. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  1622. jsonElement.TryGetProperty("schoolId", out JsonElement schoolId);
  1623. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1624. var cosmosClient = _azureCosmos.GetCosmosClient();
  1625. ////分开部署,就不需要,一站多用时,取消注释
  1626. //if ($"{site}".Equals(BIConst.Global))
  1627. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1628. long allSize = 0; //全部大小
  1629. int teacherSpace = 0; //学校分配给教师的空间
  1630. long useSize = 0; //已使用大小
  1631. Dictionary<string, double?> useSpaceInfo = new(); //学校使用详情
  1632. //查询区域所有学校
  1633. if (!string.IsNullOrEmpty($"{areaId}"))
  1634. {
  1635. List<string> schools = new();
  1636. schools = await CommonFind.FindSchoolIds(cosmosClient, $"select c.id from c where c.areaId='{areaId}'", "Base");
  1637. allSize = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(sum(c.size)) from c where c.areaId='{areaId}'", "Base"); //区域所有学校空间
  1638. foreach (var school in schools)
  1639. {
  1640. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"SELECT sum(c.size) as size FROM c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
  1641. {
  1642. var json = await JsonDocument.ParseAsync(item.ContentStream);
  1643. foreach (var elmt in json.RootElement.GetProperty("Documents").EnumerateArray())
  1644. {
  1645. if (elmt.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
  1646. {
  1647. teacherSpace += _size.GetInt32();
  1648. break;
  1649. }
  1650. }
  1651. }
  1652. long blobsize = 0;
  1653. RedisValue value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", $"{school}");
  1654. if (!value.IsNullOrEmpty)
  1655. {
  1656. JsonElement record = value.ToString().ToObject<JsonElement>();
  1657. if (record.TryGetInt64(out blobsize))
  1658. {
  1659. }
  1660. }
  1661. else
  1662. {
  1663. var storageClient = _azureStorage.GetBlobContainerClient("school");
  1664. var size = await storageClient.GetBlobsCatalogSize();
  1665. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{school}", size.Item1);
  1666. foreach (var key in size.Item2.Keys)
  1667. {
  1668. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Bolb:Catalog:{school}", key);
  1669. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Bolb:Catalog:school", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1670. }
  1671. useSize += size.Item1.Value;
  1672. useSpaceInfo = useSpaceInfo.Concat(size.Item2).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1673. //useSpaceInfo = (from e in useSpaceInfo.Concat(size.Item2) group e by e.Key into g select new { Name = g.Key, value = g.Sum(kvp => kvp.Value) }).ToDictionary(item => item.Name, item => item.value); //linq 方式合并
  1674. }
  1675. SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{school}");
  1676. if (Scores != null)
  1677. {
  1678. Dictionary<string, double?> catalog = new();
  1679. foreach (var score in Scores)
  1680. {
  1681. double val = score.Score;
  1682. string key = score.Element.ToString();
  1683. catalog.Add(key, val);
  1684. }
  1685. useSpaceInfo = useSpaceInfo.Concat(catalog).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1686. }
  1687. else
  1688. {
  1689. var client = _azureStorage.GetBlobContainerClient("school");
  1690. var size = await client.GetBlobsCatalogSize();
  1691. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{school}", size.Item1);
  1692. foreach (var key in size.Item2.Keys)
  1693. {
  1694. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{school}", key);
  1695. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{school}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1696. }
  1697. useSize += size.Item1.Value;
  1698. useSpaceInfo = useSpaceInfo.Concat(size.Item2).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1699. }
  1700. }
  1701. }
  1702. //查询学校
  1703. if (!string.IsNullOrEmpty($"{schoolId}"))
  1704. {
  1705. allSize = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"SELECT value(c.size) FROM c where c.id='{schoolId}'", "Base");
  1706. teacherSpace = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"SELECT value(sum(c.size)) FROM c", $"Teacher-{schoolId}");
  1707. long blobsize = 0;
  1708. RedisValue value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", $"{schoolId}");
  1709. if (!value.IsNullOrEmpty)
  1710. {
  1711. JsonElement record = value.ToString().ToObject<JsonElement>();
  1712. if (record.TryGetInt64(out blobsize))
  1713. {
  1714. useSize = blobsize;
  1715. }
  1716. }
  1717. else
  1718. {
  1719. var storageClient = _azureStorage.GetBlobContainerClient("school");
  1720. var size = await storageClient.GetBlobsCatalogSize();
  1721. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{schoolId}", size.Item1);
  1722. foreach (var key in size.Item2.Keys)
  1723. {
  1724. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Bolb:Catalog:{schoolId}", key);
  1725. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Bolb:Catalog:school", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1726. }
  1727. useSpaceInfo = size.Item2;
  1728. }
  1729. Dictionary<string, double?> catalog = new();
  1730. SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{schoolId}");
  1731. if (Scores != null)
  1732. {
  1733. foreach (var score in Scores)
  1734. {
  1735. double val = score.Score;
  1736. string key = score.Element.ToString();
  1737. catalog.Add(key, val);
  1738. }
  1739. useSpaceInfo = catalog;
  1740. }
  1741. else
  1742. {
  1743. var client = _azureStorage.GetBlobContainerClient("school");
  1744. var size = await client.GetBlobsCatalogSize();
  1745. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{schoolId}", size.Item1);
  1746. foreach (var key in size.Item2.Keys)
  1747. {
  1748. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{schoolId}", key);
  1749. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{schoolId}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1750. }
  1751. useSize = size.Item1.Value;
  1752. useSpaceInfo = size.Item2;
  1753. }
  1754. }
  1755. return Ok(new { state = 200, allSize, useSize, teacherSpace, useSpaceInfo });
  1756. }
  1757. /// <summary>
  1758. /// 移交学校顾问
  1759. /// </summary>
  1760. /// <param name="jsonElement"></param>
  1761. /// <returns></returns>
  1762. [ProducesDefaultResponseType]
  1763. [HttpPost("get-shift")]
  1764. public async Task<IActionResult> GetShift(JsonElement jsonElement)
  1765. {
  1766. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  1767. if (!jsonElement.TryGetProperty("school", out JsonElement _school)) return BadRequest();
  1768. //if (!jsonElement.TryGetProperty("teacher", out JsonElement _teacher)) return BadRequest();
  1769. if (!jsonElement.TryGetProperty("shiftTeacher", out JsonElement _shiftTeacher)) return BadRequest();
  1770. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1771. var cosmosClient = _azureCosmos.GetCosmosClient();
  1772. var tableClient = _azureStorage.GetCloudTableClient();
  1773. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  1774. //if ($"{site}".Equals(BIConst.Global))
  1775. //{
  1776. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1777. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  1778. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  1779. //}
  1780. SchoolTeacher schoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<SchoolTeacher>($"{_tmdId}", new PartitionKey($"Teacher-{_school}"));
  1781. if (schoolTeacher.roles.IsNotEmpty() && schoolTeacher.roles.Contains("assist"))
  1782. {
  1783. schoolTeacher.roles.Remove("assist");
  1784. SchoolTeacher newSchoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<SchoolTeacher>($"{_shiftTeacher}", new PartitionKey($"Teacher-{_school}"));
  1785. if (!newSchoolTeacher.roles.Contains("assist"))
  1786. {
  1787. newSchoolTeacher.roles.Add("assist");
  1788. newSchoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(newSchoolTeacher, $"{_shiftTeacher}", new PartitionKey($"Teacher-{_school}"));
  1789. }
  1790. await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, $"{_tmdId}", new PartitionKey($"Teacher-{_school}"));
  1791. School schoolBase = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<School>($"{_school}", new PartitionKey($"Base"));
  1792. //发送消息实体
  1793. string shiftCode = "shift-assist";
  1794. Notification notification = new Notification
  1795. {
  1796. hubName = "hita",
  1797. type = "msg",
  1798. from = $"BI:{_option.Location}:{_school}",
  1799. to = new List<string> { $"{_shiftTeacher}" },
  1800. label = $"{shiftCode}_school",
  1801. body = new { location = _option.Location, biz = shiftCode, tmdid = $"{_tmdId}", tmdname = $"{_tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  1802. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1803. };
  1804. if (notification != null)
  1805. {
  1806. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1807. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1808. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1809. var location = _option.Location;
  1810. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);//站内发送消息
  1811. }
  1812. //保存操作记录
  1813. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "schoolTeacher-add", $"{_tmdName}【{_tmdId}】移交顾问给{newSchoolTeacher.name}【{newSchoolTeacher.id}】", _dingDing, httpContext: HttpContext);
  1814. return Ok(new { state = 200 });
  1815. }
  1816. else { return Ok(new { status = 201, msg = $"{_tmdName}【{_tmdId}】账号不是顾问" }); }
  1817. }
  1818. /// <summary>
  1819. /// 管理员所管理的学校信息
  1820. /// </summary>
  1821. /// <param name="jsonElement"></param>
  1822. /// <returns></returns>
  1823. [HttpPost("get-managescs")]
  1824. public async Task<IActionResult> GetManageSclist(JsonElement jsonElement)
  1825. {
  1826. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  1827. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  1828. var cosmosClient = _azureCosmos.GetCosmosClient();
  1829. List<ManageScInfo> mScInfos = new();
  1830. List<string> scIds = new();
  1831. string mScSql = $"SELECT value(REPLACE(c.code, 'Teacher-', '')) FROM c where array_contains(c.roles,'admin',true) and c.pk='Teacher' and c.id='{tmdId}'";
  1832. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: mScSql, requestOptions: new QueryRequestOptions() { }))
  1833. {
  1834. scIds.Add(item);
  1835. }
  1836. if (scIds.Count > 0)
  1837. {
  1838. string scInfoSql = $"select c.id,c.name,c.code,c.picture,c.region,c.province,c.city,c.dist,c.areaId from c ";
  1839. string idSql = BICommonWay.ManyScSql("c.id", scIds);
  1840. string scSql = $"{scInfoSql} where {idSql}";
  1841. if (!string.IsNullOrEmpty($"{areaId}"))
  1842. {
  1843. scSql = $"{scInfoSql} where {idSql} and c.areaId='{areaId}'";
  1844. }
  1845. mScInfos = await CommonFind.GetObject<ManageScInfo>(cosmosClient, "School", scSql, "Base");
  1846. }
  1847. return Ok(new { state = RespondCode.Ok, mScInfos });
  1848. }
  1849. #region 购买记录
  1850. /// <summary>
  1851. /// 取得CoreBB學校訂單履歷資訊 暂时这样处理
  1852. /// </summary>
  1853. /// <param name="request"></param>
  1854. /// <returns></returns>
  1855. private async Task<List<object>> GetOrderHisFromCoreBBAsync(string schoolCode)
  1856. {
  1857. List<object> result = new List<object>();
  1858. try
  1859. {
  1860. string url = _configuration.GetValue<string>("HaBookAuth:CoreBBAPI") + "/ies5/get-school-order";
  1861. string AccessToken = await getCoreAccessToken();
  1862. _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
  1863. string paramJson = JsonConvert.SerializeObject(new { school_code = schoolCode });
  1864. var content = new StringContent(paramJson, Encoding.UTF8, "application/json");
  1865. HttpResponseMessage responseMessage = await _httpClient.PostAsync(url, content);
  1866. if (responseMessage.StatusCode == HttpStatusCode.OK)
  1867. {
  1868. string responseBody = responseMessage.Content.ReadAsStringAsync().Result;
  1869. result = System.Text.Json.JsonSerializer.Deserialize<List<object>>(responseBody.ToString());
  1870. }
  1871. return result;
  1872. }
  1873. catch (Exception ex)
  1874. {
  1875. return result;
  1876. }
  1877. }
  1878. private async Task<string> getCoreAccessToken()
  1879. {
  1880. string AccessToken = "";
  1881. try
  1882. {
  1883. string Url = _configuration.GetValue<string>("HaBookAuth:CoreAPI") + "/oauth2/token";
  1884. string GrantType = "device";
  1885. string ClientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1886. string Secret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1887. var content = new { grant_type = GrantType, client_id = ClientID, client_secret = Secret };
  1888. var response = await _httpClient.PostAsJsonAsync($"{Url}", content);
  1889. if (response.IsSuccessStatusCode)
  1890. {
  1891. string responseBody = response.Content.ReadAsStringAsync().Result;
  1892. using (JsonDocument document = JsonDocument.Parse(responseBody.ToString()))
  1893. {
  1894. if (document.RootElement.TryGetProperty("access_token", out JsonElement AccessTokenObj))
  1895. {
  1896. AccessToken = AccessTokenObj.ToString();
  1897. }
  1898. }
  1899. }
  1900. return AccessToken;
  1901. }
  1902. catch (Exception ex)
  1903. {
  1904. return AccessToken;
  1905. }
  1906. }
  1907. #endregion
  1908. #region 顾问学校统计返回值
  1909. public record ScRankCnt : SchoolBase
  1910. {
  1911. public int openCnt { get; set; }
  1912. public int lessCnt { get; set; }
  1913. public int interCnt { get; set; }
  1914. public int actCnt { get; set; }
  1915. }
  1916. public record SchoolBase
  1917. {
  1918. public string id { get; set; }
  1919. public string code { get; set; }
  1920. public string name { get; set; }
  1921. public string picture { get; set; }
  1922. }
  1923. #endregion
  1924. /// <summary>
  1925. /// 未加入区域的学校
  1926. /// </summary>
  1927. public record NotAreaSchool
  1928. {
  1929. public string id { get; set; }
  1930. public string name { get; set; }
  1931. public string schoolCode { get; set; }
  1932. public string picture { get; set; }
  1933. public List<string> period { get; set; }
  1934. public string province { get; set; }
  1935. public string city { get; set; }
  1936. public string dist { get; set; }
  1937. public string areaId { get; set; }
  1938. public string standard { get; set; }
  1939. public List<SchoolArea> areas { get; set; } = new List<SchoolArea>();
  1940. }
  1941. /// <summary>
  1942. /// 学校空间使用情况
  1943. /// </summary>
  1944. public record SchoolSpace
  1945. {
  1946. public string id { get; set; }
  1947. public string name { get; set; }
  1948. public Space space { get; set; }
  1949. }
  1950. /// <summary>
  1951. /// 空间
  1952. /// </summary>
  1953. public record Space
  1954. {
  1955. /// <summary>
  1956. /// 已使用空间
  1957. /// </summary>
  1958. public long useSize { get; set; }
  1959. /// <summary>
  1960. /// 分配教师空间
  1961. /// </summary>
  1962. public long tSize { get; set; }
  1963. /// <summary>
  1964. /// 空间类型
  1965. /// </summary>
  1966. public Dictionary<string, double?> catalogSize { get; set; }
  1967. }
  1968. public record DelSchoolRel
  1969. {
  1970. public string id { get; set; }
  1971. public string code { get; set; }
  1972. /// <summary>
  1973. /// 未删除的类型 1 学校 2教师 3学生
  1974. /// </summary>
  1975. public int type { get; set; }
  1976. public int status { get; set; }
  1977. }
  1978. }
  1979. }