SchoolController.cs 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430
  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.pk='School' and (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. schoolTeacher.roles.Add("admin");
  726. schoolTeacher.status = "join";
  727. schoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, schoolTeacher.id, new PartitionKey($"Teacher-{schoolId}"));
  728. strMsg.Append($"并设置管理员,学校信息{schoolName}【{schoolId}】");
  729. }
  730. else
  731. return Ok(new { state = RespondCode.Conflict, schoolTeacher = "已经是该校的管理人员" });
  732. }
  733. else
  734. {
  735. schoolTeacher = new()
  736. {
  737. id = $"{tmdId}",
  738. code = $"Teacher-{schoolId}",
  739. roles = new List<string> { "admin" },
  740. job = "管理员",
  741. name = $"{tmdName}",
  742. picture = string.IsNullOrEmpty($"{picture}") ? "" : $"{picture}",
  743. status = "join",
  744. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  745. pk = "Teacher",
  746. ttl = -1
  747. };
  748. schoolTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey($"Teacher-{schoolId}"));
  749. strMsg.Append($"并新建学校管理员,学校信息{schoolName}【{schoolId}】");
  750. }
  751. }
  752. //保存操作记录
  753. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "schoolTeacher-add", strMsg.ToString(), _dingDing, httpContext: HttpContext);
  754. return Ok(new { state = RespondCode.Ok, teacher, schoolTeacher });
  755. }
  756. catch (Exception ex)
  757. {
  758. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/set-schoolme \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  759. return BadRequest();
  760. }
  761. }
  762. /// <summary>
  763. /// 移除学校管理员 //已对接
  764. /// </summary>
  765. /// <param name="jsonElement"></param>
  766. /// <returns></returns>
  767. [ProducesDefaultResponseType]
  768. [AuthToken(Roles = "admin,rdc")]
  769. [HttpPost("del-manage")]
  770. public async Task<IActionResult> DelSchoolManage(JsonElement jsonElement)
  771. {
  772. var (_tmdId, _tmdName, _, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  773. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  774. if (!jsonElement.TryGetProperty("scIds", out JsonElement _scIds)) return BadRequest();
  775. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  776. List<string> scIds = _scIds.ToObject<List<string>>();
  777. var cosmosClient = _azureCosmos.GetCosmosClient();
  778. var tableClient = _azureStorage.GetCloudTableClient();
  779. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  780. ////分开部署,就不需要,一站多用时,取消注释
  781. //if ($"{site}".Equals(BIConst.Global))
  782. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  783. List<string> existScId = new();
  784. StringBuilder strMsg = new($"{_tmdName}【{_tmdId}】管理员账户将{tmdId}的账户移除学校:");
  785. SchoolTeacher scTeacher = null;
  786. foreach (var scId in scIds)
  787. {
  788. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Teacher-{scId}"));
  789. if (response.Status == 200)
  790. {
  791. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  792. scTeacher = json.ToObject<SchoolTeacher>();
  793. if (scTeacher.roles.Contains("admin"))
  794. {
  795. scTeacher.roles.Remove("admin");
  796. strMsg.Append($"{scId},");
  797. scTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(scTeacher, scTeacher.id, new PartitionKey($"Teacher-{scId}"));
  798. }
  799. else
  800. existScId.Add(scId);
  801. }
  802. else
  803. existScId.Add(scId);
  804. }
  805. //保存操作记录
  806. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "schoolTeacher-updatee", strMsg.ToString(), _dingDing, httpContext: HttpContext);
  807. return Ok(new { state = RespondCode.Ok, existScId });
  808. }
  809. /// <summary>
  810. /// 一个账户设置多个学校的管理员
  811. /// </summary>
  812. /// <param name="jsonElement"></param>
  813. /// <returns></returns>
  814. [ProducesDefaultResponseType]
  815. [AuthToken(Roles = "admin,rdc")]
  816. [HttpPost("set-batchmageage")]
  817. public async Task<IActionResult> SetBatchScManage(JsonElement jsonElement)
  818. {
  819. try
  820. {
  821. var (_tmdId, _tmdName, _, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  822. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  823. if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
  824. jsonElement.TryGetProperty("tmdPic", out JsonElement picture);
  825. if (!jsonElement.TryGetProperty("scSimplles", out JsonElement scSimplles)) return BadRequest();
  826. List<BatchScManage> schools = scSimplles.ToObject<List<BatchScManage>>();
  827. List<BatchScManage> existManageSc = new();
  828. Teacher teacher = new();
  829. StringBuilder msg = new($"{_tmdName}[{_tmdId}]设置账号:");
  830. var cosmosClient = _azureCosmos.GetCosmosClient();
  831. var tableClient = _azureStorage.GetCloudTableClient();
  832. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  833. if (schools.Count > 0)
  834. {
  835. var resTeacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Base"));
  836. if (resTeacher.Status == 200)
  837. {
  838. using var tchJson = await JsonDocument.ParseAsync(resTeacher.ContentStream);
  839. teacher = tchJson.ToObject<Teacher>();
  840. }
  841. else
  842. {
  843. teacher.id = $"{tmdId}";
  844. teacher.name = $"{tmdName}";
  845. teacher.picture = string.IsNullOrEmpty($"{picture}") ? "" : $"{picture}";
  846. teacher.pk = "Base";
  847. teacher.code = "Base";
  848. teacher.size = 1;
  849. teacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  850. }
  851. msg.Append($"{teacher.name}[{teacher.id}]设置学校管理员;学校信息:");
  852. foreach (var school in schools)
  853. {
  854. SchoolTeacher schoolTeacher = null;
  855. var existSchool = teacher.schools.Find(f => f.schoolId.Equals($"{school.id}"));
  856. if (existSchool == null)
  857. {
  858. 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}" });
  859. }
  860. else
  861. existSchool.name = school.name;
  862. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Teacher-{school.id}"));
  863. if (response.Status == 200)
  864. {
  865. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  866. schoolTeacher = json.ToObject<SchoolTeacher>();
  867. if (!schoolTeacher.roles.Contains("admin"))
  868. {
  869. schoolTeacher.roles.Add("admin");
  870. schoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, schoolTeacher.id, new PartitionKey($"Teacher-{school.id}"));
  871. }
  872. else
  873. existManageSc.Add(school);
  874. }
  875. else
  876. {
  877. schoolTeacher = new()
  878. {
  879. id = $"{tmdId}",
  880. code = $"Teacher-{school.id}",
  881. roles = new List<string> { "admin" },
  882. job = "管理员",
  883. name = $"{tmdName}",
  884. picture = string.IsNullOrEmpty($"{picture}") ? "" : $"{picture}",
  885. status = "join",
  886. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  887. pk = "Teacher",
  888. ttl = -1
  889. };
  890. schoolTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey($"Teacher-{school.id}"));
  891. }
  892. msg.Append($"{school.name}[{school.id}]");
  893. }
  894. if (resTeacher.Status == 200)
  895. teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  896. else
  897. teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  898. }
  899. //保存操作记录
  900. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "schoolTeacher-add", msg.ToString(), _dingDing, httpContext: HttpContext);
  901. return Ok(new { state = RespondCode.Ok, teacher });
  902. }
  903. catch (Exception ex)
  904. {
  905. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/set-batchmageage \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  906. return BadRequest();
  907. }
  908. }
  909. /// <summary>
  910. /// 删除学校、学校相关的教师、学生 //已对接
  911. /// </summary>
  912. /// <param name="jsonElement"></param>
  913. /// <returns></returns>
  914. [ProducesDefaultResponseType]
  915. [AuthToken(Roles = "admin,rdc")]
  916. [HttpPost("set-del")]
  917. public async Task<IActionResult> DelSchool(JsonElement jsonElement)
  918. {
  919. try
  920. {
  921. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  922. List<string> schools = schoolId.ToObject<List<string>>();
  923. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  924. string _auth = HttpContext.GetXAuth("AuthToken");
  925. var (tmdId, tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(_auth, _option);
  926. var cosmosClient = _azureCosmos.GetCosmosClient();
  927. var tableClient = _azureStorage.GetCloudTableClient();
  928. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  929. ////分开部署,就不需要,一站多用时,取消注释
  930. //if ($"{site}".Equals(BIConst.Global))
  931. //{
  932. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  933. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  934. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  935. //}
  936. StringBuilder msg = new();
  937. List<DelSchoolRel> delSchoolRels = new();
  938. foreach (var tempId in schools)
  939. {
  940. List<string> scTchIds = new();
  941. List<string> scStuIds = new();
  942. string scTecSql = $"select value(c.id) from c where ARRAY_LENGTH(c.roles) > 0 and c.status = 'join'";
  943. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scTecSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{tempId}") }))
  944. {
  945. scTchIds.Add(item);
  946. }
  947. string scStuSql = $"select value(c.id) from c";
  948. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Student").GetItemQueryIterator<string>(queryText: scStuSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{tempId}") }))
  949. {
  950. scStuIds.Add(item);
  951. }
  952. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{tempId}", new PartitionKey($"Base"));
  953. if (response.Status == 204)
  954. msg.AppendLine($"{tmdName}【{tmdId}】删除学校,删除状态:{response.Status},删除ID:{tempId}");
  955. else
  956. delSchoolRels.Add(new DelSchoolRel() { id = $"{tempId}", code = "Base", type = 1, status = response.Status });
  957. //删除学校信息中间
  958. var resBiRel = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{tempId}", new PartitionKey($"BIRel"));
  959. if (response.Status == 204)
  960. msg.AppendLine($"{tmdName}【{tmdId}】删除学校信息中间件,删除状态:{response.Status},删除ID:{tempId}");
  961. else
  962. delSchoolRels.Add(new DelSchoolRel() { id = $"{tempId}", code = "Base", type = 1, status = response.Status });
  963. foreach (var item in scTchIds)
  964. {
  965. //学校教师信息
  966. var tchRespnse = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{item}", new PartitionKey($"Teacher-{tempId}"));
  967. if (tchRespnse.Status == 204)
  968. msg.AppendLine($"删除教师,删除状态:{tchRespnse.Status},删除ID:{item}");
  969. else
  970. delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Teacher-{tempId}", type = 2, status = response.Status });
  971. //教师基础信息
  972. var tchBaseResponse = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{item}", new PartitionKey("Base"));
  973. if (tchBaseResponse.Status == 200)
  974. {
  975. using var json = await JsonDocument.ParseAsync(tchBaseResponse.ContentStream);
  976. Teacher teacher = json.ToObject<Teacher>();
  977. var tempSc = teacher.schools.Find(f => f.schoolId.Equals($"{tempId}"));
  978. if (tempSc != null)
  979. {
  980. teacher.schools.Remove(tempSc);
  981. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  982. }
  983. }
  984. else
  985. delSchoolRels.Add(new DelSchoolRel { id = $"{item}", code = "Base", type = 2, status = response.Status });
  986. }
  987. //删除学校学生
  988. foreach (var item in scStuIds)
  989. {
  990. var stuRespnse = await cosmosClient.GetContainer("TEAMModelOS", "Student").DeleteItemStreamAsync($"{item}", new PartitionKey($"Base-{tempId}"));
  991. if (stuRespnse.Status == 204)
  992. msg.AppendLine($"删除学生,删除状态:{stuRespnse.Status},删除ID:{item}");
  993. else
  994. delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Base-{tempId}", type = 3, status = response.Status });
  995. }
  996. }
  997. //string scTecSql = $"select value(c.id) from c where ARRAY_LENGTH(c.roles) > 0 and c.status = 'join'";
  998. //await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scTecSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{schoolId}") }))
  999. //{
  1000. // scTchIds.Add(item);
  1001. //}
  1002. //string scStuSql = $"select value(c.id) from c";
  1003. //await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scStuSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  1004. //{
  1005. // scStuIds.Add(item);
  1006. //}
  1007. //var response = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{schoolId}", new PartitionKey($"Base"));
  1008. //if (response.Status == 204)
  1009. // msg.AppendLine($"{tmdName}【{tmdId}】删除学校,删除状态:{response.Status},删除ID:{schoolId}");
  1010. //else
  1011. // delSchoolRels.Add(new DelSchoolRel() { id = $"{schoolId}", code = "Base", type = 1, status = response.Status });
  1012. //foreach (var item in scTchIds)
  1013. //{
  1014. // var tchRespnse = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{item}", new PartitionKey($"Teacher-{schoolId}"));
  1015. // if (tchRespnse.Status == 204)
  1016. // msg.AppendLine($"删除教师,删除状态:{tchRespnse.Status},删除ID:{item}");
  1017. // else
  1018. // delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Teacher-{schoolId}", type = 2, status = response.Status });
  1019. //}
  1020. //foreach (var item in scStuIds)
  1021. //{
  1022. // var stuRespnse = await cosmosClient.GetContainer("TEAMModelOS", "Student").DeleteItemStreamAsync($"{item}", new PartitionKey($"Base-{schoolId}"));
  1023. // if (stuRespnse.Status == 204)
  1024. // msg.AppendLine($"删除学生,删除状态:{stuRespnse.Status},删除ID:{item}");
  1025. // else
  1026. // delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Base-{schoolId}", type = 3, status = response.Status });
  1027. //}
  1028. //保存操作记录
  1029. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "set-del", msg.ToString(), _dingDing, httpContext: HttpContext);
  1030. if (delSchoolRels.Count > 0)
  1031. return Ok(new { state = 201, delSchoolRels });
  1032. else
  1033. return Ok(new { state = 200 });
  1034. }
  1035. catch (Exception ex)
  1036. {
  1037. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/set-del \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  1038. return BadRequest();
  1039. }
  1040. }
  1041. /// <summary>
  1042. /// 依据学校统计 //已对接
  1043. /// </summary>
  1044. /// <param name="jsonElement"></param>
  1045. /// <returns></returns>
  1046. [ProducesDefaultResponseType]
  1047. [HttpPost("get-schoolcnt")]
  1048. public async Task<IActionResult> GetSchoolCnt(JsonElement jsonElement)
  1049. {
  1050. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  1051. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1052. var cosmosClient = _azureCosmos.GetCosmosClient();
  1053. ////分开部署,就不需要,一站多用时,取消注释
  1054. //if ($"{site}".Equals(BIConst.Global))
  1055. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1056. DateTimeOffset dtime = DateTimeOffset.UtcNow;
  1057. var (weekS, weekE) = TimeHelper.GetStartOrEnd(dtime, "week");
  1058. var (lastWeekS, lastWeekE) = TimeHelper.GetStartOrEnd(dtime, "lastweek");
  1059. var (termS, termE) = TimeHelper.GetStartOrEnd(dtime, "term");
  1060. var (lastTermS, lastTermE) = TimeHelper.GetStartOrEnd(dtime, "lastterm");
  1061. var (yearS, yearE) = TimeHelper.GetStartOrEnd(dtime, "year");
  1062. var (lastYearS, lastYearE) = TimeHelper.GetStartOrEnd(dtime, "lastYear");
  1063. int tecCnt = 0;// 教师数量
  1064. int classCnt = 0; //班级
  1065. int stuCnt = 0; //学生
  1066. int roomCnt = 0; //智慧教室
  1067. int lesCnt = 0; //课例总数
  1068. int weekLesCnt = 0; //本周课例
  1069. int lastWeekLesCnt = 0; //上周课例
  1070. int weekACTCnt = 0; //本周活动
  1071. int lastWeekACTCnt = 0; //上周活动
  1072. int termLesCnt = 0; //本学期课例
  1073. int lastTermLesCnt = 0; //上学学期课例
  1074. int termACTCnt = 0; //本学期活动
  1075. int lastTermActCnt = 0; //上学学期活动
  1076. int yearLesCnt = 0; //今年课例
  1077. int lastYearLesCnt = 0; //去年课例
  1078. int yearACTCnt = 0; //今年活动
  1079. int lastYearACTCnt = 0; //去年活动
  1080. SchoolInfo schoolInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolInfo>($"{schoolId}", new PartitionKey("Base"));
  1081. if (schoolInfo != null)
  1082. {
  1083. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(schoolInfo.id, new PartitionKey("ProductSum"));
  1084. if (response.Status == 200)
  1085. {
  1086. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1087. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  1088. schoolInfo.serial = serial.ToObject<List<ProductSumInfos>>();
  1089. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  1090. schoolInfo.service = service.ToObject<List<ProductSumInfos>>();
  1091. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  1092. schoolInfo.hard = hard.ToObject<List<SchoolProductSumDataHard>>();
  1093. }
  1094. schoolInfo.assists = await CommonFind.FindSchoolRoles(cosmosClient, schoolInfo.id, "assist");
  1095. string currencySql = "select value(count(c.id)) from c";
  1096. tecCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"Teacher-{schoolInfo.id}"); // 教师数量
  1097. classCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"Class-{schoolInfo.id}"); //班级
  1098. stuCnt = await CommonFind.GetSqlValueCount(cosmosClient, "Student", currencySql, $"Base-{schoolInfo.id}"); //学生
  1099. roomCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"Room-{schoolInfo.id}"); //智慧教室
  1100. lesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"LessonRecord-{schoolInfo.id}"); //课例总数
  1101. weekLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {weekS} and c.startTime<= {weekE}", $"LessonRecord-{schoolInfo.id}"); //本周课例
  1102. lastWeekLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {lastWeekS} and c.startTime<= {lastWeekE}", $"LessonRecord-{schoolInfo.id}"); //上周课例
  1103. termLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {termS} and c.startTime <= {termE}", $"LessonRecord-{schoolInfo.id}"); //本学期课例
  1104. lastTermLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {lastTermS} and c.startTime <= {lastTermE}", $"LessonRecord-{schoolInfo.id}"); //上学学期课例
  1105. yearLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {yearS} and c.startTime <= {yearE}", $"LessonRecord-{schoolInfo.id}"); //今年课例
  1106. lastYearLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {lastYearS} and c.startTime <= {lastYearE}", $"LessonRecord-{schoolInfo.id}"); //去年课例
  1107. int ACTCnt = 0; //活动
  1108. foreach (var type in StaticValue.activityTypes)
  1109. {
  1110. ACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}'");
  1111. weekACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {weekS} and c.createTime <= {weekE} "); //本周活动
  1112. lastWeekACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {lastWeekS} and c.createTime <= {lastWeekE} "); //上周活动
  1113. 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}"); //本学期活动
  1114. 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}"); //上学学期活动
  1115. 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}"); //今年活动
  1116. 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}"); //去年活动
  1117. }
  1118. //取得購買紀錄
  1119. List<object> order = await GetOrderHisFromCoreBBAsync(schoolId.GetString());
  1120. 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 } });
  1121. }
  1122. else
  1123. return Ok(new { state = RespondCode.NotFound, msg = "未找到该学校信息!" });
  1124. }
  1125. /// <summary>
  1126. /// 通过学校Id 统计学校信息 //已对接
  1127. /// </summary>
  1128. /// <param name="jsonElement"></param>
  1129. /// <returns></returns>
  1130. [ProducesDefaultResponseType]
  1131. [HttpPost("get-analyse")]
  1132. public async Task<IActionResult> GetAnalyse(JsonElement jsonElement)
  1133. {
  1134. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  1135. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1136. var cosmosClient = _azureCosmos.GetCosmosClient();
  1137. ////分开部署,就不需要,一站多用时,取消注释
  1138. //if ($"{site}".Equals(BIConst.Global))
  1139. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1140. RecSchool recSchool = new();
  1141. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{schoolId}", new PartitionKey("Base"));
  1142. if (response.Status == 200)
  1143. {
  1144. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1145. recSchool = json.ToObject<RecSchool>();
  1146. }
  1147. else return Ok(new { state = RespondCode.NotFound, msg = "未找到该学校" });
  1148. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1149. var (days, daye) = TimeHelper.GetStartOrEnd(dateTime);
  1150. var (lastDays, lastDaye) = TimeHelper.GetStartOrEnd(dateTime.AddDays(-1));
  1151. var (years, yeare) = TimeHelper.GetStartOrEnd(dateTime, "year");
  1152. var (lastYears, lastYeare) = TimeHelper.GetStartOrEnd(dateTime, "lastYear");
  1153. int tchCnt = 0; //教师数量
  1154. int stuCnt = 0; //学校数量
  1155. int roomCnt = 0; //智慧教室数量
  1156. int lessAllCant = 0; //课例总数
  1157. int lessLastdayCnt = 0; //昨天的课例
  1158. int lessDayCnt = 0; //今天的课例
  1159. int lessLastYearCnt = 0; //去年的课例
  1160. int lessYearCnt = 0; //今年的课例
  1161. double allInterCnt = 0; //所有互动
  1162. double lastDayInterCnt = 0; // 昨天课例互动
  1163. double interCnt = 0; // 今天课例互动
  1164. double lastYearInterCnt = 0; // 去年课例互动
  1165. double yearInterCnt = 0; // 今年课例互动
  1166. int allActCnt = 0; //所有活动
  1167. int lastActCnt = 0; //昨天活动
  1168. int actCnt = 0; //今天活动
  1169. int lastYearActCnt = 0; //去年活动
  1170. int yearActCnt = 0; //今年活动
  1171. string commSql = "select value(count(c.id)) from c ";
  1172. tchCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", commSql, $"Teacher-{schoolId}");
  1173. stuCnt = await CommonFind.GetSqlValueCount(cosmosClient, "Student", commSql, $"Base-{schoolId}");
  1174. roomCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", commSql, $"Room-{schoolId}");
  1175. lessAllCant = await CommonFind.GetSqlValueCount(cosmosClient, "School", commSql, $"LessonRecord-{schoolId}");
  1176. string lessCode = $"LessonRecord-{schoolId}";
  1177. string lessLastdaySql = $"{commSql} where c.startTime >= {lastDays} and c.startTime <= {lastDaye} ";
  1178. lessLastdayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastdaySql, lessCode);
  1179. string lessDaySql = $"{commSql} where c.startTime >= {days} and c.startTime <= {daye} ";
  1180. lessDayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessDaySql, lessCode);
  1181. string lessLastYarSql = $"{commSql} where c.startTime >= {lastYears} and c.startTime <= {lastYeare} ";
  1182. lessLastYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastYarSql, lessCode);
  1183. string lessYearSql = $"{commSql} where c.startTime >= {years} and c.startTime <= {yeare} ";
  1184. lessYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessYearSql, lessCode);
  1185. //课例互动
  1186. string strInterSql = $"select value(sum(c.clientInteractionAverge)) from c";
  1187. allInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", strInterSql, lessCode);
  1188. string lastdayInterSql = $"{strInterSql} where c.startTime >= {lastDays} and c.startTime <= {lastDays} ";
  1189. lastDayInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", lastdayInterSql, lessCode);
  1190. string dayInterSql = $"{strInterSql} where c.startTime >= {days} and c.startTime <= {daye} ";
  1191. interCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", dayInterSql, lessCode);
  1192. string lastYarInterSql = $"{strInterSql} where c.startTime >= {lastYears} and c.startTime <= {lastYeare} ";
  1193. lastYearInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", lastYarInterSql, lessCode);
  1194. string yearInterSql = $"{strInterSql} where c.startTime >= {years} and c.startTime <= {yeare} ";
  1195. yearInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", yearInterSql, lessCode);
  1196. //活动
  1197. allActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: $"and c.school='{schoolId}'");
  1198. string lastActSql = $" and c.school='{schoolId}' and c.createTime >= {lastDays} and c.createTime <= {lastDays}";
  1199. lastActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: lastActSql);
  1200. string actSql = $" and c.school='{schoolId}' and c.createTime >= {days} and c.createTime <= {daye}";
  1201. actCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actSql);
  1202. string lastYearActSql = $" and c.school='{schoolId}' and c.createTime >= {lastYears} and c.createTime <= {lastYeare}";
  1203. lastYearActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: lastYearActSql);
  1204. string yearActSql = $" and c.school='{schoolId}' and c.createTime >= {years} and c.createTime <= {yeare}";
  1205. yearActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: yearActSql);
  1206. return Ok(new { state = 200, recSchool, tchCnt, stuCnt, roomCnt, lessAllCant, lessLastdayCnt, lessDayCnt, lessLastYearCnt, lessYearCnt, allInterCnt, lastDayInterCnt, interCnt, lastYearInterCnt, yearInterCnt, allActCnt, lastActCnt, actCnt, lastYearActCnt, yearActCnt });
  1207. }
  1208. /// <summary>
  1209. /// 学校每周课例趋势 //已对接
  1210. /// </summary>
  1211. /// <param name="jsonElement"></param>
  1212. /// <returns></returns>
  1213. [ProducesDefaultResponseType]
  1214. [HttpPost("get-schooldate")]
  1215. public async Task<IActionResult> GetSchoolDate(JsonElement jsonElement)
  1216. {
  1217. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  1218. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1219. var cosmosClient = _azureCosmos.GetCosmosClient();
  1220. ////分开部署,就不需要,一站多用时,取消注释
  1221. //if ($"{site}".Equals(BIConst.Global))
  1222. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1223. List<double> weekTrend = new();
  1224. int year = DateTimeOffset.UtcNow.Year;
  1225. int dayOfweek = (int)DateTimeOffset.Parse($"{year}-1-1").DayOfWeek;
  1226. int currentTime = DateTimeOffset.UtcNow.DayOfYear / 7 + 1;
  1227. int currentTime1 = DateTimeOffset.UtcNow.DayOfYear / 7;
  1228. //获取当前学期所有的课程记录
  1229. List<LessAnalyse> records = new List<LessAnalyse>();
  1230. 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}") }))
  1231. {
  1232. records.Add(item);
  1233. }
  1234. List<(string name, string periodId, int count)> grades = LessonStatisWay.GetGradeCount(records);
  1235. var subs = records.GroupBy(x => x.subjectId).Where(w => !string.IsNullOrEmpty(w.Key)).Select(y => new { key = y.Key, count = y.ToList().Count }).ToList();
  1236. var gradeCnt = grades.Select(x => new { x.name, x.periodId, value = x.count });
  1237. var subCnt = subs.Select(x => new { name = x.key, value = x.count });
  1238. List<LessonCount> scount = new();
  1239. List<LessonCount> tcount = new();
  1240. 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}") }))
  1241. {
  1242. scount.Add(item);
  1243. }
  1244. List<string> teacIds = await CommonFind.FindRolesId(cosmosClient, new List<string>() { $"{schoolId}" });
  1245. foreach (var tId in teacIds)
  1246. {
  1247. var sqlTxtt = $"select value(c) from c where c.id='{tId}'";
  1248. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<LessonCount>(queryText: sqlTxtt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{year}") }))
  1249. {
  1250. tcount.Add(item);
  1251. }
  1252. }
  1253. int days = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? days = 366 : days = 365;
  1254. List<List<double>> lessons = new();
  1255. if (scount.Count > 0)
  1256. {
  1257. foreach (LessonCount item in scount)
  1258. {
  1259. lessons.Add(item.beginCount);
  1260. }
  1261. }
  1262. if (tcount.Count > 0)
  1263. {
  1264. foreach (LessonCount item in tcount)
  1265. {
  1266. lessons.Add(item.beginCount);
  1267. }
  1268. }
  1269. if (lessons.Count > 0)
  1270. {
  1271. var bmatrix = DenseMatrix.OfColumns(lessons);
  1272. //开学第一周周内开课
  1273. if (dayOfweek == 0)
  1274. {
  1275. dayOfweek = 7;
  1276. }
  1277. //第一周多少天
  1278. var dd = 7 - dayOfweek + 1;
  1279. //一年有几周
  1280. int sweeks = days / 7;
  1281. //查询天数
  1282. int dayYear = 0;
  1283. if (currentTime > 0)
  1284. {
  1285. for (int i = 0; i <= currentTime; i++)
  1286. {
  1287. if (i == 0)
  1288. {
  1289. var bsum = bmatrix.SubMatrix(dayYear, dd, 0, bmatrix.ColumnCount).ColumnSums().Sum();
  1290. dayYear += dd;
  1291. //weeks.Add(i, bsum);
  1292. weekTrend.Add(bsum);
  1293. }
  1294. else
  1295. {
  1296. var bsum = bmatrix.SubMatrix(dayYear, 7, 0, bmatrix.ColumnCount).ColumnSums().Sum();
  1297. dayYear += 7;
  1298. //weeks.Add(i, bsum);
  1299. weekTrend.Add(bsum);
  1300. }
  1301. }
  1302. }
  1303. //最后一周是否有余
  1304. int stary = days - dayYear;
  1305. if (stary > 0 && stary < 7)
  1306. {
  1307. var bsum = bmatrix.SubMatrix(dayYear, stary - 1, 0, bmatrix.ColumnCount).ColumnSums().Sum();
  1308. //weeks.Add((sweeks + 1), bsum);
  1309. weekTrend.Add(bsum);
  1310. }
  1311. }
  1312. return Ok(new { state = 200, gradeCnt, subCnt, weekTrend });
  1313. }
  1314. /// <summary>
  1315. /// 顾问学校基础统计、以及排行 //已对接
  1316. /// </summary>
  1317. /// <param name="jsonElement"></param>
  1318. /// <returns></returns>
  1319. [ProducesDefaultResponseType]
  1320. [HttpPost("get-assisscbase")]
  1321. public async Task<IActionResult> GetAssistSchoolCnt(JsonElement jsonElement)
  1322. {
  1323. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  1324. jsonElement.TryGetProperty("role", out JsonElement role);
  1325. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1326. var cosmosClient = _azureCosmos.GetCosmosClient();
  1327. ////分开部署,就不需要,一站多用时,取消注释
  1328. //if ($"{site}".Equals(BIConst.Global))
  1329. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1330. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1331. int scAllCnt = 0; //学校
  1332. int tchAllCnt = 0; //教师数量
  1333. int tchMonthCnt = 0; //教师本月新增
  1334. int stuAllCnt = 0; //所有学校学生
  1335. int lessAllCnt = 0; //课例总数
  1336. int lessMthCnt = 0; //本月新增
  1337. List<ScRankCnt> scRankCnts = new(); //学校开课、上传, 课例排名
  1338. var (start, end) = TimeHelper.GetStartOrEnd(dateTime, "month");
  1339. List<string> schoolIds = new();
  1340. if (!string.IsNullOrEmpty($"{tmdId}"))
  1341. {
  1342. switch ($"{role}")
  1343. {
  1344. case "admin":
  1345. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", "admin");
  1346. break;
  1347. case "sales":
  1348. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", "sales");
  1349. break;
  1350. default:
  1351. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1352. break;
  1353. }
  1354. }
  1355. else
  1356. schoolIds = await CommonFind.GetValueSingle(cosmosClient, "School", "select value(c.id) from c", "Base");
  1357. if (schoolIds.Count > 0)
  1358. {
  1359. string scIdSql = BICommonWay.ManyScSql("c.schoolId", schoolIds);
  1360. string stuSql = $"select value(count(c.id)) from c where {scIdSql}";
  1361. stuAllCnt = await CommonFind.GetSqlValueCount(cosmosClient, "Student", stuSql);
  1362. string scSql = BICommonWay.ManyScSql("c.school", schoolIds);
  1363. string lessMoSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and {scSql} and c.startTime >= {start} and c.startTime <= {end}";
  1364. lessMthCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessMoSql);
  1365. List<SchoolBase> scInfos = new();
  1366. string scInfoSql = $"select c.id,c.name,c.code,c.picture from c ";
  1367. string idSql = BICommonWay.ManyScSql("c.id", schoolIds);
  1368. scInfos = await CommonFind.GetObject<SchoolBase>(cosmosClient, "School", $"{scInfoSql} where {idSql}", "Base");
  1369. List<string> tchMonIds = new();
  1370. foreach (var item in scInfos)
  1371. {
  1372. ScRankCnt lessRankCnt = new() { id = item.id, name = item.name, code = item.code, picture = item.picture };
  1373. string tchSql = $"select value(count(c.id)) from c where array_contains(c.roles,'teacher',true) and c.createTime >= {start} and c.createTime <= {end}";
  1374. tchMonthCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", tchSql, $"Teacher-{item.id}");
  1375. string tchAllSql = $"select value(count(c.id)) from c where ARRAY_CONTAINS(c.roles,'teacher',true) and c.status = 'join'";
  1376. tchAllCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", tchAllSql, $"Teacher-{item.id}");
  1377. string lessALLSql = $"select value(count(c.id)) from c where c.pk='LessonRecord'";
  1378. lessAllCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", lessALLSql, $"LessonRecord-{item.id}");
  1379. string lessUpSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and c.upload = 0";
  1380. lessRankCnt.openCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessUpSql, $"LessonRecord-{item.id}");
  1381. string lessSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and c.upload = 1";
  1382. lessRankCnt.lessCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessSql, $"LessonRecord-{item.id}");
  1383. string interactSql = $"select value(sum(c.clientInteractionCount)) from c where c.pk='LessonRecord'";
  1384. lessRankCnt.interCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", interactSql, $"LessonRecord-{item.id}");
  1385. string actSql = $" and c.school='{item.id}'";
  1386. lessRankCnt.actCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actSql);
  1387. scRankCnts.Add(lessRankCnt);
  1388. }
  1389. scAllCnt = schoolIds.Count();
  1390. tchMonthCnt = tchMonIds.Distinct().Count();
  1391. }
  1392. return Ok(new { state = RespondCode.Ok, scAllCnt, tchAllCnt, tchMonthCnt, stuAllCnt, lessAllCnt, lessMthCnt, scRankCnts });
  1393. }
  1394. /// <summary>
  1395. /// 一年学校和多个学校的课例、互动、活动统计分析 //已对接
  1396. /// </summary>
  1397. /// <param name="jsonElement"></param>
  1398. /// <returns></returns>
  1399. [ProducesDefaultResponseType]
  1400. [HttpPost("get-assissc")]
  1401. public async Task<IActionResult> GetAssisSc(JsonElement jsonElement)
  1402. {
  1403. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  1404. jsonElement.TryGetProperty("role", out JsonElement role);
  1405. jsonElement.TryGetProperty("schoolId", out JsonElement schooId);
  1406. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  1407. var cosmosClient = _azureCosmos.GetCosmosClient();
  1408. //if ($"{site}".Equals(BIConst.Global))
  1409. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1410. List<YearCnt> yearCnts = new(); //当前的课例,活动,互动统计
  1411. List<string> schoolIds = new();
  1412. string strSql = "SELECT value(count(c.id)) FROM c where c.pk='LessonRecord'";
  1413. string scSql = null;
  1414. if (!string.IsNullOrEmpty($"{tmdId}") && string.IsNullOrEmpty($"{schooId}"))
  1415. {
  1416. //List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1417. if (!string.IsNullOrEmpty($"{tmdId}"))
  1418. {
  1419. switch ($"{role}")
  1420. {
  1421. case "admin":
  1422. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", "admin");
  1423. scSql = BICommonWay.ManyScSql("c.school", schoolIds);
  1424. break;
  1425. case "sales":
  1426. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", "sales");
  1427. scSql = BICommonWay.ManyScSql("c.school", schoolIds);
  1428. break;
  1429. default:
  1430. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1431. scSql = BICommonWay.ManyScSql("c.school", schoolIds);
  1432. break;
  1433. }
  1434. }
  1435. }
  1436. else if (!string.IsNullOrEmpty($"{schooId}") && string.IsNullOrEmpty($"{tmdId}"))
  1437. scSql = $"c.school = '{schooId}'";
  1438. else
  1439. {
  1440. schoolIds = await CommonFind.GetValueSingle(cosmosClient, "School", "select value(c.id) from c", "Base");
  1441. if (schoolIds.Count == 0)
  1442. return Ok(new { state = RespondCode.Ok, yearCnts, });
  1443. else
  1444. scSql = BICommonWay.ManyScSql("c.school", schoolIds);
  1445. }
  1446. //if ((string.IsNullOrEmpty($"{tmdId}") && string.IsNullOrEmpty($"{schooId}")) || (!string.IsNullOrEmpty($"{tmdId}") && !string.IsNullOrEmpty($"{schooId}")))
  1447. List<StartEndTime> mthStartEnds = await TimeHelper.GetYearSataMthCtMth(DateTimeOffset.UtcNow);
  1448. if (mthStartEnds.Count > 0)
  1449. {
  1450. foreach (var item in mthStartEnds)
  1451. {
  1452. YearCnt yearCnt = new() { name = item.date };
  1453. string selessSql = $"{strSql} and {scSql.ToString()} and c.startTime >= {item.start} and c.startTime <= {item.end}";
  1454. yearCnt.lessCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", selessSql);
  1455. 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}";
  1456. //double iCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", interactSql);
  1457. yearCnt.interCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", interactSql);
  1458. string mthActSql = $"and {scSql} and c.createTime >= {item.start} and c.createTime <= {item.end}";
  1459. yearCnt.actCnt = await ActivityWay.GetCnt(cosmosClient, condSql: mthActSql);
  1460. yearCnts.Add(yearCnt);
  1461. }
  1462. }
  1463. return Ok(new { state = RespondCode.Ok, yearCnts, });
  1464. }
  1465. /// <summary>
  1466. /// 顾问学校统计 //已对接
  1467. /// </summary>
  1468. /// <param name="jsonElement"></param>
  1469. /// <returns></returns>
  1470. [ProducesDefaultResponseType]
  1471. [HttpPost("get-assissccnt")]
  1472. public async Task<IActionResult> GetAssisScCnt(JsonElement jsonElement)
  1473. {
  1474. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  1475. jsonElement.TryGetProperty("role", out JsonElement role);
  1476. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  1477. var cosmosClient = _azureCosmos.GetCosmosClient();
  1478. //if ($"{site}".Equals(BIConst.Global))
  1479. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1480. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1481. var (days, daye) = TimeHelper.GetStartOrEnd(dateTime);
  1482. var (lastDays, lastDaye) = TimeHelper.GetStartOrEnd(dateTime.AddDays(-1));
  1483. var (years, yeare) = TimeHelper.GetStartOrEnd(dateTime, "year");
  1484. var (lastYears, lastYeare) = TimeHelper.GetStartOrEnd(dateTime, "lastYear");
  1485. int lessAll = 0; //所以课例
  1486. int lessLastdayCnt = 0; //昨天的课例
  1487. int lessDayCnt = 0; //今天的课例
  1488. int lessLastYearCnt = 0; //去年的课例
  1489. int lessYearCnt = 0; //今年的课例
  1490. double interAll = 0; //所有互动总数
  1491. double lastDayInterCnt = 0; // 昨天课例互动
  1492. double interCnt = 0; // 今天课例互动
  1493. double lastYearInterCnt = 0; // 去年课例互动
  1494. double yearInterCnt = 0; // 今年课例互动
  1495. int actAllCnt = 0; //所有活动
  1496. int lastActCnt = 0; //昨天活动
  1497. int actCnt = 0; //今天活动
  1498. int lastYearActCnt = 0; //去年活动
  1499. int yearActCnt = 0; //今年活动
  1500. List<string> schoolIds = new();
  1501. if (!string.IsNullOrEmpty($"{tmdId}"))
  1502. {
  1503. switch ($"{role}")
  1504. {
  1505. case "admin":
  1506. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", "admin");
  1507. break;
  1508. case "sales":
  1509. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", "sales");
  1510. //scSql = BICommonWay.ManyScSql("c.school", schoolIds);
  1511. break;
  1512. default:
  1513. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1514. break;
  1515. }
  1516. }
  1517. else
  1518. schoolIds = await CommonFind.GetValueSingle(cosmosClient, "School", "select value(c.id) from c", "Base");
  1519. if (schoolIds.Count > 0)
  1520. {
  1521. string scSql = BICommonWay.ManyScSql("c.school", schoolIds);
  1522. string strSql = "SELECT value(count(c.id)) FROM c where c.pk='LessonRecord'";
  1523. //课例
  1524. lessAll = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{strSql} and {scSql}");
  1525. string lessLastdaySql = $"{strSql} and {scSql} and c.startTime >= {lastDays} and c.startTime <= {lastDaye} ";
  1526. lessLastdayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastdaySql);
  1527. string lessDaySql = $"{strSql} and {scSql} and c.startTime >= {days} and c.startTime <= {daye} ";
  1528. lessDayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessDaySql);
  1529. string lessLastYarSql = $"{strSql} and {scSql} and c.startTime >= {lastYears} and c.startTime <= {lastYeare} ";
  1530. lessLastYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastYarSql);
  1531. string lessYearSql = $"{strSql} and {scSql} and c.startTime >= {years} and c.startTime <= {yeare} ";
  1532. lessYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessYearSql);
  1533. //课例互动
  1534. string strInterSql = $"select value(sum(c.clientInteractionCount)) from c where c.pk='LessonRecord' and {scSql}";
  1535. interAll = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", strInterSql);
  1536. string lastdayInterSql = $"{strInterSql} and c.startTime >= {lastDays} and c.startTime <= {lastDaye} ";
  1537. lastDayInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", lastdayInterSql);
  1538. string dayInterSql = $"{strInterSql} and c.startTime >= {days} and c.startTime <= {daye} ";
  1539. interCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", dayInterSql);
  1540. string lastYarInterSql = $"{strInterSql} and c.startTime >= {lastYears} and c.startTime <= {lastYeare} ";
  1541. lastYearInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", lastYarInterSql);
  1542. string yearInterSql = $"{strInterSql} and c.startTime >= {years} and c.startTime <= {yeare} ";
  1543. yearInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", yearInterSql);
  1544. //活动
  1545. string actAllSql = $"and {scSql} ";
  1546. actAllCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actAllSql);
  1547. string lastActSql = $"and {scSql} and c.createTime >= {lastDays} and c.createTime <= {lastDaye}";
  1548. lastActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: lastActSql);
  1549. string actSql = $"and {scSql} and c.createTime >= {days} and c.createTime <= {daye}";
  1550. actCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actSql);
  1551. string lastYearActSql = $" and {scSql} and c.createTime >= {lastYears} and c.createTime <= {lastYeare}";
  1552. lastYearActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: lastYearActSql);
  1553. string yearActSql = $"and {scSql} and c.createTime >= {years} and c.createTime <= {yeare}";
  1554. yearActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: yearActSql);
  1555. }
  1556. return Ok(new { state = RespondCode.Ok, lessAll, lessLastdayCnt, lessDayCnt, lessLastYearCnt, lessYearCnt, interAll, lastDayInterCnt, interCnt, lastYearInterCnt, yearInterCnt, actAllCnt, lastActCnt, actCnt, lastYearActCnt, yearActCnt });
  1557. }
  1558. /// <summary>
  1559. /// 查询学校基础信息,和学校年级、科目数据统计 //已对接
  1560. /// </summary>
  1561. /// <param name="jsonElement"></param>
  1562. /// <returns></returns>
  1563. [ProducesDefaultResponseType]
  1564. [HttpPost("get-ratio")]
  1565. public async Task<IActionResult> GetRatio(JsonElement jsonElement)
  1566. {
  1567. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  1568. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1569. var cosmosClient = _azureCosmos.GetCosmosClient();
  1570. ////分开部署,就不需要,一站多用时,取消注释
  1571. //if ($"{site}".Equals(BIConst.Global))
  1572. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1573. AnSchool school = new(); //学校基础基础信息
  1574. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{schoolId}", new PartitionKey("Base"));
  1575. if (response.Status == 200)
  1576. {
  1577. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1578. school = json.ToObject<AnSchool>();
  1579. }
  1580. else return Ok(new { state = RespondCode.NotFound, msg = "未找到该学校" });
  1581. List<LessAnalyse> lessAnalyses = new();
  1582. 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}") }))
  1583. {
  1584. lessAnalyses.Add(lessItem);
  1585. }
  1586. List<(string name, string periodId, int count)> grades = LessonStatisWay.GetGradeCount(lessAnalyses);
  1587. var subs = lessAnalyses.GroupBy(x => x.subjectId).Where(y => !string.IsNullOrEmpty(y.Key)).Select(y => new { key = y.Key, count = y.ToList().Count }).ToList();
  1588. var gradeCnt = grades.Select(x => new { x.name, x.periodId, value = x.count });
  1589. var subCnt = subs.Select(x => new { name = x.key, value = x.count });
  1590. var responseProduct = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school.id, new PartitionKey("ProductSum"));
  1591. if (responseProduct.Status == 200)
  1592. {
  1593. using var json = await JsonDocument.ParseAsync(responseProduct.ContentStream);
  1594. if (json.RootElement.TryGetProperty("serial", out JsonElement _serial) && !_serial.ValueKind.Equals(JsonValueKind.Null))
  1595. {
  1596. school.serial = _serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1597. }
  1598. if (json.RootElement.TryGetProperty("service", out JsonElement _service) && !_service.ValueKind.Equals(JsonValueKind.Null))
  1599. {
  1600. school.service = _service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1601. }
  1602. if (json.RootElement.TryGetProperty("hard", out JsonElement _hard) && !_hard.ValueKind.Equals(JsonValueKind.Null))
  1603. {
  1604. school.hard = _hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  1605. }
  1606. }
  1607. return Ok(new { state = RespondCode.Ok, school, gradeCnt, subCnt });
  1608. }
  1609. /// <summary>
  1610. /// 学校简要信息
  1611. /// </summary>
  1612. /// <param name="jsonElement"></param>
  1613. /// <returns></returns>
  1614. [ProducesDefaultResponseType]
  1615. [HttpPost("get-schools")]
  1616. public async Task<IActionResult> GetSchools (JsonElement jsonElement)
  1617. {
  1618. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  1619. List<ScBriefInfo> scBriefs = new();
  1620. var cosmosClient = _azureCosmos.GetCosmosClient();
  1621. StringBuilder sql = new("select c.id,c.name,c.picture,c.areaId,c.size,c.period from c ");
  1622. if (!string.IsNullOrEmpty($"{areaId}"))
  1623. sql.Append($" where c.areaId = '{areaId}'");
  1624. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS,"School").GetItemQueryIterator<ScBriefInfo>(queryText: sql.ToString(), requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("Base")}))
  1625. {
  1626. scBriefs.Add(item);
  1627. }
  1628. return Ok(new { state = RespondCode.Ok, scBriefs });
  1629. }
  1630. /// <summary>
  1631. /// 通过tmdID 账户查询学校专业和模组 //已对接
  1632. /// </summary>
  1633. /// <param name="jsonElement"></param>
  1634. /// <returns></returns>
  1635. [ProducesDefaultResponseType]
  1636. [HttpPost("get-proded")]
  1637. public async Task<IActionResult> GetProdEd(JsonElement jsonElement)
  1638. {
  1639. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  1640. jsonElement.TryGetProperty("role", out JsonElement role);
  1641. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1642. var cosmosClient = _azureCosmos.GetCosmosClient();
  1643. ////分开部署,就不需要,一站多用时,取消注释
  1644. //if ($"{site}".Equals(BIConst.Global))
  1645. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1646. int adCnt = 0;
  1647. int allCnt = 0;
  1648. List<ScProdEd> scInfos = new();
  1649. List<string> products = new();
  1650. //List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1651. List<string> schoolIds = new();
  1652. if (!string.IsNullOrEmpty($"{tmdId}"))
  1653. {
  1654. switch ($"{role}")
  1655. {
  1656. case "admin":
  1657. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", "admin");
  1658. break;
  1659. case "sales":
  1660. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", "sales");
  1661. break;
  1662. default:
  1663. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1664. break;
  1665. }
  1666. }
  1667. else
  1668. schoolIds = await CommonFind.GetValueSingle(cosmosClient, "School", "select value(c.id) from c", "Base");
  1669. if (schoolIds.Count > 0)
  1670. {
  1671. string scInfoSql = $"select c.id,c.name,c.code,c.picture,c.type,c.size,c.scale from c ";
  1672. string idSql = BICommonWay.ManyScSql("c.id", schoolIds);
  1673. scInfos = await CommonFind.GetObject<ScProdEd>(cosmosClient, "School", $"{scInfoSql} where {idSql}", "Base");
  1674. string serialSql = "SELECT value(count(ARRAY_LENGTH(c.deviceBound))) FROM c ";
  1675. string serialAllSql = "SELECT value(sum((c.deviceMax))) FROM c";
  1676. if (schoolIds.Count > 0)
  1677. {
  1678. foreach (var scProd in scInfos)
  1679. {
  1680. adCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", serialSql, $"Product-{scProd.id}");
  1681. allCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", serialAllSql, $"Product-{scProd.id}");
  1682. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(scProd.id, new PartitionKey("ProductSum"));
  1683. if (response.Status == 200)
  1684. {
  1685. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1686. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  1687. {
  1688. List<string> serials = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1689. scProd.serial = serials;
  1690. products.AddRange(serials);
  1691. }
  1692. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  1693. {
  1694. List<string> services = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1695. scProd.service = services;
  1696. products.AddRange(services);
  1697. }
  1698. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  1699. {
  1700. List<string> hards = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  1701. scProd.hard = hards;
  1702. products.AddRange(hards);
  1703. }
  1704. }
  1705. }
  1706. //scInfos.ForEach(async scProd =>
  1707. //{
  1708. // var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(scProd.id, new PartitionKey("ProductSum"));
  1709. // if (response.Status == 200)
  1710. // {
  1711. // using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1712. // if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  1713. // {
  1714. // scProd.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1715. // }
  1716. // if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  1717. // {
  1718. // scProd.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1719. // }
  1720. // if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  1721. // {
  1722. // scProd.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  1723. // }
  1724. // }
  1725. //});
  1726. }
  1727. }
  1728. var productAn = products.GroupBy(g => g).Select(s => new { key = s.Key, cnt = s.ToList().Count }).ToList();
  1729. return Ok(new { state = RespondCode.Ok, allCnt, adCnt, scInfos, productAn });
  1730. }
  1731. /// <summary>
  1732. /// 通过学校Id查询详情 数据管理工具——查询工具
  1733. /// </summary>
  1734. /// <returns></returns>
  1735. [ProducesDefaultResponseType]
  1736. [HttpPost("get-info")]
  1737. public async Task<IActionResult> GetSchool(JsonElement jsonElement)
  1738. {
  1739. jsonElement.TryGetProperty("schoolId", out JsonElement schoolId);
  1740. jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1741. var cosmosClient = _azureCosmos.GetCosmosClient();
  1742. ////分开部署,就不需要,一站多用时,取消注释
  1743. //if ($"{site}".Equals(BIConst.Global))
  1744. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1745. StringBuilder sqlTxt = new("select * from c");
  1746. if (!string.IsNullOrEmpty($"{schoolId}"))
  1747. {
  1748. sqlTxt.Append($" where c.id='{schoolId}'");
  1749. }
  1750. List<School> schools = new();
  1751. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1752. {
  1753. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1754. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1755. {
  1756. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1757. {
  1758. schools.Add(obj.ToObject<School>());
  1759. }
  1760. }
  1761. }
  1762. return Ok(new { state = 200, schools });
  1763. }
  1764. /// <summary>
  1765. /// 依据区域Id查询区域空间统计
  1766. /// </summary>
  1767. /// <param name="jsonElement"></param>
  1768. /// <returns></returns>
  1769. [ProducesDefaultResponseType]
  1770. [HttpPost("get-spance")]
  1771. public async Task<IActionResult> GetAreaSpace(JsonElement jsonElement)
  1772. {
  1773. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  1774. jsonElement.TryGetProperty("schoolId", out JsonElement schoolId);
  1775. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1776. var cosmosClient = _azureCosmos.GetCosmosClient();
  1777. ////分开部署,就不需要,一站多用时,取消注释
  1778. //if ($"{site}".Equals(BIConst.Global))
  1779. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1780. long allSize = 0; //全部大小
  1781. int teacherSpace = 0; //学校分配给教师的空间
  1782. long useSize = 0; //已使用大小
  1783. Dictionary<string, double?> useSpaceInfo = new(); //学校使用详情
  1784. //查询区域所有学校
  1785. if (!string.IsNullOrEmpty($"{areaId}"))
  1786. {
  1787. List<string> schools = new();
  1788. schools = await CommonFind.FindScIds(cosmosClient, $"select value(c.id) from c where c.areaId='{areaId}'", "Base");
  1789. allSize = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(sum(c.size)) from c where c.areaId='{areaId}'", "Base"); //区域所有学校空间
  1790. foreach (var school in schools)
  1791. {
  1792. 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}") }))
  1793. {
  1794. var json = await JsonDocument.ParseAsync(item.ContentStream);
  1795. foreach (var elmt in json.RootElement.GetProperty("Documents").EnumerateArray())
  1796. {
  1797. if (elmt.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
  1798. {
  1799. teacherSpace += _size.GetInt32();
  1800. break;
  1801. }
  1802. }
  1803. }
  1804. long blobsize = 0;
  1805. RedisValue value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", $"{school}");
  1806. if (!value.IsNullOrEmpty)
  1807. {
  1808. JsonElement record = value.ToString().ToObject<JsonElement>();
  1809. if (record.TryGetInt64(out blobsize))
  1810. {
  1811. }
  1812. }
  1813. else
  1814. {
  1815. var storageClient = _azureStorage.GetBlobContainerClient("school");
  1816. var size = await storageClient.GetBlobsCatalogSize();
  1817. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{school}", size.Item1);
  1818. foreach (var key in size.Item2.Keys)
  1819. {
  1820. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Bolb:Catalog:{school}", key);
  1821. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Bolb:Catalog:school", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1822. }
  1823. useSize += size.Item1.Value;
  1824. useSpaceInfo = useSpaceInfo.Concat(size.Item2).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1825. //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 方式合并
  1826. }
  1827. SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{school}");
  1828. if (Scores != null)
  1829. {
  1830. Dictionary<string, double?> catalog = new();
  1831. foreach (var score in Scores)
  1832. {
  1833. double val = score.Score;
  1834. string key = score.Element.ToString();
  1835. catalog.Add(key, val);
  1836. }
  1837. useSpaceInfo = useSpaceInfo.Concat(catalog).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1838. }
  1839. else
  1840. {
  1841. var client = _azureStorage.GetBlobContainerClient("school");
  1842. var size = await client.GetBlobsCatalogSize();
  1843. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{school}", size.Item1);
  1844. foreach (var key in size.Item2.Keys)
  1845. {
  1846. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{school}", key);
  1847. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{school}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1848. }
  1849. useSize += size.Item1.Value;
  1850. useSpaceInfo = useSpaceInfo.Concat(size.Item2).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1851. }
  1852. }
  1853. }
  1854. //查询学校
  1855. if (!string.IsNullOrEmpty($"{schoolId}"))
  1856. {
  1857. allSize = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"SELECT value(c.size) FROM c where c.id='{schoolId}'", "Base");
  1858. teacherSpace = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"SELECT value(sum(c.size)) FROM c", $"Teacher-{schoolId}");
  1859. long blobsize = 0;
  1860. RedisValue value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", $"{schoolId}");
  1861. if (!value.IsNullOrEmpty)
  1862. {
  1863. JsonElement record = value.ToString().ToObject<JsonElement>();
  1864. if (record.TryGetInt64(out blobsize))
  1865. {
  1866. useSize = blobsize;
  1867. }
  1868. }
  1869. else
  1870. {
  1871. var storageClient = _azureStorage.GetBlobContainerClient("school");
  1872. var size = await storageClient.GetBlobsCatalogSize();
  1873. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{schoolId}", size.Item1);
  1874. foreach (var key in size.Item2.Keys)
  1875. {
  1876. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Bolb:Catalog:{schoolId}", key);
  1877. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Bolb:Catalog:school", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1878. }
  1879. useSpaceInfo = size.Item2;
  1880. }
  1881. Dictionary<string, double?> catalog = new();
  1882. SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{schoolId}");
  1883. if (Scores != null)
  1884. {
  1885. foreach (var score in Scores)
  1886. {
  1887. double val = score.Score;
  1888. string key = score.Element.ToString();
  1889. catalog.Add(key, val);
  1890. }
  1891. useSpaceInfo = catalog;
  1892. }
  1893. else
  1894. {
  1895. var client = _azureStorage.GetBlobContainerClient("school");
  1896. var size = await client.GetBlobsCatalogSize();
  1897. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{schoolId}", size.Item1);
  1898. foreach (var key in size.Item2.Keys)
  1899. {
  1900. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{schoolId}", key);
  1901. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{schoolId}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1902. }
  1903. useSize = size.Item1.Value;
  1904. useSpaceInfo = size.Item2;
  1905. }
  1906. }
  1907. return Ok(new { state = 200, allSize, useSize, teacherSpace, useSpaceInfo });
  1908. }
  1909. /// <summary>
  1910. /// 移交学校顾问
  1911. /// </summary>
  1912. /// <param name="jsonElement"></param>
  1913. /// <returns></returns>
  1914. [ProducesDefaultResponseType]
  1915. [HttpPost("get-shift")]
  1916. public async Task<IActionResult> GetShift(JsonElement jsonElement)
  1917. {
  1918. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  1919. if (!jsonElement.TryGetProperty("school", out JsonElement _school)) return BadRequest();
  1920. //if (!jsonElement.TryGetProperty("teacher", out JsonElement _teacher)) return BadRequest();
  1921. if (!jsonElement.TryGetProperty("shiftTeacher", out JsonElement _shiftTeacher)) return BadRequest();
  1922. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1923. var cosmosClient = _azureCosmos.GetCosmosClient();
  1924. var tableClient = _azureStorage.GetCloudTableClient();
  1925. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  1926. //if ($"{site}".Equals(BIConst.Global))
  1927. //{
  1928. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1929. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  1930. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  1931. //}
  1932. SchoolTeacher schoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<SchoolTeacher>($"{_tmdId}", new PartitionKey($"Teacher-{_school}"));
  1933. if (schoolTeacher.roles.IsNotEmpty() && schoolTeacher.roles.Contains("assist"))
  1934. {
  1935. schoolTeacher.roles.Remove("assist");
  1936. SchoolTeacher newSchoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<SchoolTeacher>($"{_shiftTeacher}", new PartitionKey($"Teacher-{_school}"));
  1937. if (!newSchoolTeacher.roles.Contains("assist"))
  1938. {
  1939. newSchoolTeacher.roles.Add("assist");
  1940. newSchoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(newSchoolTeacher, $"{_shiftTeacher}", new PartitionKey($"Teacher-{_school}"));
  1941. }
  1942. await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, $"{_tmdId}", new PartitionKey($"Teacher-{_school}"));
  1943. School schoolBase = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<School>($"{_school}", new PartitionKey($"Base"));
  1944. //发送消息实体
  1945. string shiftCode = "shift-assist";
  1946. //保存操作记录
  1947. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "schoolTeacher-add", $"{_tmdName}【{_tmdId}】移交顾问给{newSchoolTeacher.name}【{newSchoolTeacher.id}】", _dingDing, httpContext: HttpContext);
  1948. return Ok(new { state = 200 });
  1949. }
  1950. else { return Ok(new { status = 201, msg = $"{_tmdName}【{_tmdId}】账号不是顾问" }); }
  1951. }
  1952. /// <summary>
  1953. /// 管理员所管理的学校信息
  1954. /// </summary>
  1955. /// <param name="jsonElement"></param>
  1956. /// <returns></returns>
  1957. [ProducesDefaultResponseType]
  1958. [HttpPost("get-managescs")]
  1959. public async Task<IActionResult> GetManageSclist(JsonElement jsonElement)
  1960. {
  1961. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  1962. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  1963. var cosmosClient = _azureCosmos.GetCosmosClient();
  1964. List<ManageScInfo> mScInfos = new();
  1965. List<ManageScInfo> noScInfos = new();
  1966. List<string> scIds = new();
  1967. 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}'";
  1968. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: mScSql, requestOptions: new QueryRequestOptions() { }))
  1969. {
  1970. scIds.Add(item);
  1971. }
  1972. if (scIds.Count > 0)
  1973. {
  1974. string scInfoSql = $"select c.id,c.name,c.code,c.picture,c.region,c.province,c.city,c.dist,c.areaId from c ";
  1975. string idSql = BICommonWay.ManyScSql("c.id", scIds);
  1976. string scSql = $"{scInfoSql} where {idSql}";
  1977. if (!string.IsNullOrEmpty($"{areaId}"))
  1978. {
  1979. scSql = $"{scInfoSql} where {idSql} and c.areaId='{areaId}'";
  1980. }
  1981. mScInfos = await CommonFind.GetObject<ManageScInfo>(cosmosClient, "School", scSql, "Base");
  1982. }
  1983. if (!string.IsNullOrEmpty($"{areaId}"))
  1984. {
  1985. 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}'";
  1986. List<ManageScInfo> areaAllScInfos = await CommonFind.GetObject<ManageScInfo>(cosmosClient, "School", noScInfoSql, "Base");
  1987. noScInfos = areaAllScInfos.Where(w => !mScInfos.Any(a => a.id == w.id)).ToList();
  1988. //noScInfos = areaAllScInfos.Except(mScInfos).ToList();
  1989. }
  1990. return Ok(new { state = RespondCode.Ok, mScInfos, noScInfos });
  1991. }
  1992. /// <summary>
  1993. /// 查询学校简单信息
  1994. /// </summary>
  1995. /// <param name="jsonElement"></param>
  1996. /// <returns></returns>
  1997. [ProducesDefaultResponseType]
  1998. [HttpPost("get-scsimple")]
  1999. public async Task<IActionResult> GetScSimple(JsonElement jsonElement)
  2000. {
  2001. var cosmosClient = _azureCosmos.GetCosmosClient();
  2002. jsonElement.TryGetProperty("scName", out JsonElement scName);
  2003. StringBuilder scSql = new("select c.id,c.name,c.picture,c.createTime from c");
  2004. if (!string.IsNullOrEmpty($"{scName}"))
  2005. scSql.Append($" where c.name='{scName}'");
  2006. List<ScSimple> scSimple = new();
  2007. await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ScSimple>(queryText: scSql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  2008. {
  2009. scSimple.Add(itemSchool);
  2010. }
  2011. return Ok(new { state = RespondCode.Ok, scSimple });
  2012. }
  2013. #region 购买记录
  2014. /// <summary>
  2015. /// 取得CoreBB學校訂單履歷資訊 暂时这样处理
  2016. /// </summary>
  2017. /// <param name="request"></param>
  2018. /// <returns></returns>
  2019. private async Task<List<object>> GetOrderHisFromCoreBBAsync(string schoolCode)
  2020. {
  2021. List<object> result = new List<object>();
  2022. try
  2023. {
  2024. string url = _configuration.GetValue<string>("HaBookAuth:CoreBBAPI") + "/ies5/get-school-order";
  2025. string AccessToken = await getCoreAccessToken();
  2026. var client = _httpClient.CreateClient();
  2027. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
  2028. string paramJson = JsonConvert.SerializeObject(new { school_code = schoolCode });
  2029. var content = new StringContent(paramJson, Encoding.UTF8, "application/json");
  2030. HttpResponseMessage responseMessage = await client.PostAsync(url, content);
  2031. if (responseMessage.StatusCode == HttpStatusCode.OK)
  2032. {
  2033. string responseBody = responseMessage.Content.ReadAsStringAsync().Result;
  2034. result = System.Text.Json.JsonSerializer.Deserialize<List<object>>(responseBody.ToString());
  2035. }
  2036. return result;
  2037. }
  2038. catch (Exception ex)
  2039. {
  2040. return result;
  2041. }
  2042. }
  2043. private async Task<string> getCoreAccessToken()
  2044. {
  2045. string AccessToken = "";
  2046. try
  2047. {
  2048. string Url = _configuration.GetValue<string>("HaBookAuth:CoreAPI") + "/oauth2/token";
  2049. string GrantType = "device";
  2050. string ClientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  2051. string Secret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  2052. var content = new { grant_type = GrantType, client_id = ClientID, client_secret = Secret };
  2053. var response = await _httpClient.CreateClient().PostAsJsonAsync($"{Url}", content);
  2054. if (response.IsSuccessStatusCode)
  2055. {
  2056. string responseBody = response.Content.ReadAsStringAsync().Result;
  2057. using (JsonDocument document = JsonDocument.Parse(responseBody.ToString()))
  2058. {
  2059. if (document.RootElement.TryGetProperty("access_token", out JsonElement AccessTokenObj))
  2060. {
  2061. AccessToken = AccessTokenObj.ToString();
  2062. }
  2063. }
  2064. }
  2065. return AccessToken;
  2066. }
  2067. catch (Exception ex)
  2068. {
  2069. return AccessToken;
  2070. }
  2071. }
  2072. #endregion
  2073. #region 顾问学校统计返回值
  2074. public record ScRankCnt : SchoolBase
  2075. {
  2076. public int openCnt { get; set; }
  2077. public int lessCnt { get; set; }
  2078. public int interCnt { get; set; }
  2079. public int actCnt { get; set; }
  2080. }
  2081. public record SchoolBase
  2082. {
  2083. public string id { get; set; }
  2084. public string code { get; set; }
  2085. public string name { get; set; }
  2086. public string picture { get; set; }
  2087. }
  2088. #endregion
  2089. /// <summary>
  2090. /// 未加入区域的学校
  2091. /// </summary>
  2092. public record NotAreaSchool
  2093. {
  2094. public string id { get; set; }
  2095. public string name { get; set; }
  2096. public string schoolCode { get; set; }
  2097. public string picture { get; set; }
  2098. public List<string> period { get; set; }
  2099. public string province { get; set; }
  2100. public string city { get; set; }
  2101. public string dist { get; set; } = "";
  2102. public string areaId { get; set; } = "";
  2103. public string standard { get; set; } = "";
  2104. public List<SchoolArea> areas { get; set; } = new List<SchoolArea>();
  2105. }
  2106. /// <summary>
  2107. /// 学校空间使用情况
  2108. /// </summary>
  2109. public record SchoolSpace
  2110. {
  2111. public string id { get; set; }
  2112. public string name { get; set; }
  2113. public Space space { get; set; }
  2114. }
  2115. /// <summary>
  2116. /// 空间
  2117. /// </summary>
  2118. public record Space
  2119. {
  2120. /// <summary>
  2121. /// 已使用空间
  2122. /// </summary>
  2123. public long useSize { get; set; }
  2124. /// <summary>
  2125. /// 分配教师空间
  2126. /// </summary>
  2127. public long tSize { get; set; }
  2128. /// <summary>
  2129. /// 空间类型
  2130. /// </summary>
  2131. public Dictionary<string, double?> catalogSize { get; set; }
  2132. }
  2133. public record ScSimple
  2134. {
  2135. public string id { get; set; }
  2136. public string name { get; set; }
  2137. public string picture { get; set; }
  2138. public long createTime { get; set; }
  2139. }
  2140. public record DelSchoolRel
  2141. {
  2142. public string id { get; set; }
  2143. public string code { get; set; }
  2144. /// <summary>
  2145. /// 未删除的类型 1 学校 2教师 3学生
  2146. /// </summary>
  2147. public int type { get; set; }
  2148. public int status { get; set; }
  2149. }
  2150. }
  2151. }