SchoolController.cs 134 KB

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