SchoolController.cs 142 KB

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