SchoolController.cs 115 KB

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