SchoolController.cs 114 KB

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