SchoolController.cs 142 KB

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