SchoolController.cs 142 KB

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