SchoolController.cs 125 KB

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