SchoolController.cs 143 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606
  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<StartEndTime> 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.date };
  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. /// 学校简要信息
  1609. /// </summary>
  1610. /// <param name="jsonElement"></param>
  1611. /// <returns></returns>
  1612. [ProducesDefaultResponseType]
  1613. [HttpPost("get-schools")]
  1614. public async Task<IActionResult> GetSchools (JsonElement jsonElement)
  1615. {
  1616. List<ScBriefInfo> scBriefs = new();
  1617. var cosmosClient = _azureCosmos.GetCosmosClient();
  1618. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS,"School").GetItemQueryIterator<ScBriefInfo>(queryText:"select value(c) from c" ,requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("Base")}))
  1619. {
  1620. scBriefs.Add(item);
  1621. }
  1622. return Ok(new { state = RespondCode.Ok, scBriefs });
  1623. }
  1624. /// <summary>
  1625. /// 通过tmdID 账户查询学校专业和模组 //已对接
  1626. /// </summary>
  1627. /// <param name="jsonElement"></param>
  1628. /// <returns></returns>
  1629. [ProducesDefaultResponseType]
  1630. [HttpPost("get-proded")]
  1631. public async Task<IActionResult> GetProdEd(JsonElement jsonElement)
  1632. {
  1633. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  1634. jsonElement.TryGetProperty("role", out JsonElement role);
  1635. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1636. var cosmosClient = _azureCosmos.GetCosmosClient();
  1637. ////分开部署,就不需要,一站多用时,取消注释
  1638. //if ($"{site}".Equals(BIConst.Global))
  1639. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1640. int adCnt = 0;
  1641. int allCnt = 0;
  1642. List<ScProdEd> scInfos = new();
  1643. List<string> products = new();
  1644. //List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1645. List<string> schoolIds = new();
  1646. if (!string.IsNullOrEmpty($"{tmdId}"))
  1647. {
  1648. switch ($"{role}")
  1649. {
  1650. case "admin":
  1651. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", "admin");
  1652. break;
  1653. case "sales":
  1654. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}", "sales");
  1655. break;
  1656. default:
  1657. schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1658. break;
  1659. }
  1660. }
  1661. else
  1662. schoolIds = await CommonFind.GetValueSingle(cosmosClient, "School", "select value(c.id) from c", "Base");
  1663. if (schoolIds.Count > 0)
  1664. {
  1665. string scInfoSql = $"select c.id,c.name,c.code,c.picture,c.type,c.size,c.scale from c ";
  1666. string idSql = BICommonWay.ManyScSql("c.id", schoolIds);
  1667. scInfos = await CommonFind.GetObject<ScProdEd>(cosmosClient, "School", $"{scInfoSql} where {idSql}", "Base");
  1668. string serialSql = "SELECT value(count(ARRAY_LENGTH(c.deviceBound))) FROM c ";
  1669. string serialAllSql = "SELECT value(sum((c.deviceMax))) FROM c";
  1670. if (schoolIds.Count > 0)
  1671. {
  1672. foreach (var scProd in scInfos)
  1673. {
  1674. adCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", serialSql, $"Product-{scProd.id}");
  1675. allCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", serialAllSql, $"Product-{scProd.id}");
  1676. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(scProd.id, new PartitionKey("ProductSum"));
  1677. if (response.Status == 200)
  1678. {
  1679. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1680. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  1681. {
  1682. List<string> serials = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1683. scProd.serial = serials;
  1684. products.AddRange(serials);
  1685. }
  1686. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  1687. {
  1688. List<string> services = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1689. scProd.service = services;
  1690. products.AddRange(services);
  1691. }
  1692. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  1693. {
  1694. List<string> hards = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  1695. scProd.hard = hards;
  1696. products.AddRange(hards);
  1697. }
  1698. }
  1699. }
  1700. //scInfos.ForEach(async scProd =>
  1701. //{
  1702. // var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(scProd.id, new PartitionKey("ProductSum"));
  1703. // if (response.Status == 200)
  1704. // {
  1705. // using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1706. // if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  1707. // {
  1708. // scProd.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1709. // }
  1710. // if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  1711. // {
  1712. // scProd.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  1713. // }
  1714. // if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  1715. // {
  1716. // scProd.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  1717. // }
  1718. // }
  1719. //});
  1720. }
  1721. }
  1722. var productAn = products.GroupBy(g => g).Select(s => new { key = s.Key, cnt = s.ToList().Count }).ToList();
  1723. return Ok(new { state = RespondCode.Ok, allCnt, adCnt, scInfos, productAn });
  1724. }
  1725. /// <summary>
  1726. /// 通过学校Id查询详情 数据管理工具——查询工具
  1727. /// </summary>
  1728. /// <returns></returns>
  1729. [ProducesDefaultResponseType]
  1730. [HttpPost("get-info")]
  1731. public async Task<IActionResult> GetSchool(JsonElement jsonElement)
  1732. {
  1733. jsonElement.TryGetProperty("schoolId", out JsonElement schoolId);
  1734. jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1735. var cosmosClient = _azureCosmos.GetCosmosClient();
  1736. ////分开部署,就不需要,一站多用时,取消注释
  1737. //if ($"{site}".Equals(BIConst.Global))
  1738. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1739. StringBuilder sqlTxt = new("select * from c");
  1740. if (!string.IsNullOrEmpty($"{schoolId}"))
  1741. {
  1742. sqlTxt.Append($" where c.id='{schoolId}'");
  1743. }
  1744. List<School> schools = new();
  1745. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1746. {
  1747. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1748. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1749. {
  1750. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1751. {
  1752. schools.Add(obj.ToObject<School>());
  1753. }
  1754. }
  1755. }
  1756. return Ok(new { state = 200, schools });
  1757. }
  1758. /// <summary>
  1759. /// 依据区域Id查询区域空间统计
  1760. /// </summary>
  1761. /// <param name="jsonElement"></param>
  1762. /// <returns></returns>
  1763. [ProducesDefaultResponseType]
  1764. [HttpPost("get-spance")]
  1765. public async Task<IActionResult> GetAreaSpace(JsonElement jsonElement)
  1766. {
  1767. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  1768. jsonElement.TryGetProperty("schoolId", out JsonElement schoolId);
  1769. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1770. var cosmosClient = _azureCosmos.GetCosmosClient();
  1771. ////分开部署,就不需要,一站多用时,取消注释
  1772. //if ($"{site}".Equals(BIConst.Global))
  1773. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1774. long allSize = 0; //全部大小
  1775. int teacherSpace = 0; //学校分配给教师的空间
  1776. long useSize = 0; //已使用大小
  1777. Dictionary<string, double?> useSpaceInfo = new(); //学校使用详情
  1778. //查询区域所有学校
  1779. if (!string.IsNullOrEmpty($"{areaId}"))
  1780. {
  1781. List<string> schools = new();
  1782. schools = await CommonFind.FindScIds(cosmosClient, $"select value(c.id) from c where c.areaId='{areaId}'", "Base");
  1783. allSize = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(sum(c.size)) from c where c.areaId='{areaId}'", "Base"); //区域所有学校空间
  1784. foreach (var school in schools)
  1785. {
  1786. 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}") }))
  1787. {
  1788. var json = await JsonDocument.ParseAsync(item.ContentStream);
  1789. foreach (var elmt in json.RootElement.GetProperty("Documents").EnumerateArray())
  1790. {
  1791. if (elmt.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
  1792. {
  1793. teacherSpace += _size.GetInt32();
  1794. break;
  1795. }
  1796. }
  1797. }
  1798. long blobsize = 0;
  1799. RedisValue value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", $"{school}");
  1800. if (!value.IsNullOrEmpty)
  1801. {
  1802. JsonElement record = value.ToString().ToObject<JsonElement>();
  1803. if (record.TryGetInt64(out blobsize))
  1804. {
  1805. }
  1806. }
  1807. else
  1808. {
  1809. var storageClient = _azureStorage.GetBlobContainerClient("school");
  1810. var size = await storageClient.GetBlobsCatalogSize();
  1811. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{school}", size.Item1);
  1812. foreach (var key in size.Item2.Keys)
  1813. {
  1814. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Bolb:Catalog:{school}", key);
  1815. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Bolb:Catalog:school", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1816. }
  1817. useSize += size.Item1.Value;
  1818. useSpaceInfo = useSpaceInfo.Concat(size.Item2).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1819. //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 方式合并
  1820. }
  1821. SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{school}");
  1822. if (Scores != null)
  1823. {
  1824. Dictionary<string, double?> catalog = new();
  1825. foreach (var score in Scores)
  1826. {
  1827. double val = score.Score;
  1828. string key = score.Element.ToString();
  1829. catalog.Add(key, val);
  1830. }
  1831. useSpaceInfo = useSpaceInfo.Concat(catalog).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1832. }
  1833. else
  1834. {
  1835. var client = _azureStorage.GetBlobContainerClient("school");
  1836. var size = await client.GetBlobsCatalogSize();
  1837. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{school}", size.Item1);
  1838. foreach (var key in size.Item2.Keys)
  1839. {
  1840. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{school}", key);
  1841. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{school}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1842. }
  1843. useSize += size.Item1.Value;
  1844. useSpaceInfo = useSpaceInfo.Concat(size.Item2).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1845. }
  1846. }
  1847. }
  1848. //查询学校
  1849. if (!string.IsNullOrEmpty($"{schoolId}"))
  1850. {
  1851. allSize = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"SELECT value(c.size) FROM c where c.id='{schoolId}'", "Base");
  1852. teacherSpace = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"SELECT value(sum(c.size)) FROM c", $"Teacher-{schoolId}");
  1853. long blobsize = 0;
  1854. RedisValue value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", $"{schoolId}");
  1855. if (!value.IsNullOrEmpty)
  1856. {
  1857. JsonElement record = value.ToString().ToObject<JsonElement>();
  1858. if (record.TryGetInt64(out blobsize))
  1859. {
  1860. useSize = blobsize;
  1861. }
  1862. }
  1863. else
  1864. {
  1865. var storageClient = _azureStorage.GetBlobContainerClient("school");
  1866. var size = await storageClient.GetBlobsCatalogSize();
  1867. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{schoolId}", size.Item1);
  1868. foreach (var key in size.Item2.Keys)
  1869. {
  1870. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Bolb:Catalog:{schoolId}", key);
  1871. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Bolb:Catalog:school", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1872. }
  1873. useSpaceInfo = size.Item2;
  1874. }
  1875. Dictionary<string, double?> catalog = new();
  1876. SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{schoolId}");
  1877. if (Scores != null)
  1878. {
  1879. foreach (var score in Scores)
  1880. {
  1881. double val = score.Score;
  1882. string key = score.Element.ToString();
  1883. catalog.Add(key, val);
  1884. }
  1885. useSpaceInfo = catalog;
  1886. }
  1887. else
  1888. {
  1889. var client = _azureStorage.GetBlobContainerClient("school");
  1890. var size = await client.GetBlobsCatalogSize();
  1891. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{schoolId}", size.Item1);
  1892. foreach (var key in size.Item2.Keys)
  1893. {
  1894. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{schoolId}", key);
  1895. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{schoolId}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1896. }
  1897. useSize = size.Item1.Value;
  1898. useSpaceInfo = size.Item2;
  1899. }
  1900. }
  1901. return Ok(new { state = 200, allSize, useSize, teacherSpace, useSpaceInfo });
  1902. }
  1903. /// <summary>
  1904. /// 移交学校顾问
  1905. /// </summary>
  1906. /// <param name="jsonElement"></param>
  1907. /// <returns></returns>
  1908. [ProducesDefaultResponseType]
  1909. [HttpPost("get-shift")]
  1910. public async Task<IActionResult> GetShift(JsonElement jsonElement)
  1911. {
  1912. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  1913. if (!jsonElement.TryGetProperty("school", out JsonElement _school)) return BadRequest();
  1914. //if (!jsonElement.TryGetProperty("teacher", out JsonElement _teacher)) return BadRequest();
  1915. if (!jsonElement.TryGetProperty("shiftTeacher", out JsonElement _shiftTeacher)) return BadRequest();
  1916. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1917. var cosmosClient = _azureCosmos.GetCosmosClient();
  1918. var tableClient = _azureStorage.GetCloudTableClient();
  1919. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  1920. //if ($"{site}".Equals(BIConst.Global))
  1921. //{
  1922. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1923. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  1924. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  1925. //}
  1926. SchoolTeacher schoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<SchoolTeacher>($"{_tmdId}", new PartitionKey($"Teacher-{_school}"));
  1927. if (schoolTeacher.roles.IsNotEmpty() && schoolTeacher.roles.Contains("assist"))
  1928. {
  1929. schoolTeacher.roles.Remove("assist");
  1930. SchoolTeacher newSchoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<SchoolTeacher>($"{_shiftTeacher}", new PartitionKey($"Teacher-{_school}"));
  1931. if (!newSchoolTeacher.roles.Contains("assist"))
  1932. {
  1933. newSchoolTeacher.roles.Add("assist");
  1934. newSchoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(newSchoolTeacher, $"{_shiftTeacher}", new PartitionKey($"Teacher-{_school}"));
  1935. }
  1936. await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, $"{_tmdId}", new PartitionKey($"Teacher-{_school}"));
  1937. School schoolBase = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<School>($"{_school}", new PartitionKey($"Base"));
  1938. //发送消息实体
  1939. string shiftCode = "shift-assist";
  1940. Notification notification = new Notification
  1941. {
  1942. hubName = "hita",
  1943. type = "msg",
  1944. from = $"BI:{_option.Location}:{_school}",
  1945. to = new List<string> { $"{_shiftTeacher}" },
  1946. label = $"{shiftCode}_school",
  1947. body = new { location = _option.Location, biz = shiftCode, tmdid = $"{_tmdId}", tmdname = $"{_tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  1948. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  1949. };
  1950. if (notification != null)
  1951. {
  1952. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  1953. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1954. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1955. var location = _option.Location;
  1956. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);//站内发送消息
  1957. }
  1958. //保存操作记录
  1959. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "schoolTeacher-add", $"{_tmdName}【{_tmdId}】移交顾问给{newSchoolTeacher.name}【{newSchoolTeacher.id}】", _dingDing, httpContext: HttpContext);
  1960. return Ok(new { state = 200 });
  1961. }
  1962. else { return Ok(new { status = 201, msg = $"{_tmdName}【{_tmdId}】账号不是顾问" }); }
  1963. }
  1964. /// <summary>
  1965. /// 管理员所管理的学校信息
  1966. /// </summary>
  1967. /// <param name="jsonElement"></param>
  1968. /// <returns></returns>
  1969. [ProducesDefaultResponseType]
  1970. [HttpPost("get-managescs")]
  1971. public async Task<IActionResult> GetManageSclist(JsonElement jsonElement)
  1972. {
  1973. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  1974. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  1975. var cosmosClient = _azureCosmos.GetCosmosClient();
  1976. List<ManageScInfo> mScInfos = new();
  1977. List<ManageScInfo> noScInfos = new();
  1978. List<string> scIds = new();
  1979. 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}'";
  1980. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: mScSql, requestOptions: new QueryRequestOptions() { }))
  1981. {
  1982. scIds.Add(item);
  1983. }
  1984. if (scIds.Count > 0)
  1985. {
  1986. string scInfoSql = $"select c.id,c.name,c.code,c.picture,c.region,c.province,c.city,c.dist,c.areaId from c ";
  1987. string idSql = BICommonWay.ManyScSql("c.id", scIds);
  1988. string scSql = $"{scInfoSql} where {idSql}";
  1989. if (!string.IsNullOrEmpty($"{areaId}"))
  1990. {
  1991. scSql = $"{scInfoSql} where {idSql} and c.areaId='{areaId}'";
  1992. }
  1993. mScInfos = await CommonFind.GetObject<ManageScInfo>(cosmosClient, "School", scSql, "Base");
  1994. }
  1995. if (!string.IsNullOrEmpty($"{areaId}"))
  1996. {
  1997. 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}'";
  1998. List<ManageScInfo> areaAllScInfos = await CommonFind.GetObject<ManageScInfo>(cosmosClient, "School", noScInfoSql, "Base");
  1999. noScInfos = areaAllScInfos.Where(w => !mScInfos.Any(a => a.id == w.id)).ToList();
  2000. //noScInfos = areaAllScInfos.Except(mScInfos).ToList();
  2001. }
  2002. return Ok(new { state = RespondCode.Ok, mScInfos, noScInfos });
  2003. }
  2004. /// <summary>
  2005. /// 查询学校简单信息
  2006. /// </summary>
  2007. /// <param name="jsonElement"></param>
  2008. /// <returns></returns>
  2009. [ProducesDefaultResponseType]
  2010. [HttpPost("get-scsimple")]
  2011. public async Task<IActionResult> GetScSimple(JsonElement jsonElement)
  2012. {
  2013. var cosmosClient = _azureCosmos.GetCosmosClient();
  2014. jsonElement.TryGetProperty("scName", out JsonElement scName);
  2015. StringBuilder scSql = new("select c.id,c.name,c.picture,c.createTime from c");
  2016. if (!string.IsNullOrEmpty($"{scName}"))
  2017. scSql.Append($" where c.name='{scName}'");
  2018. List<ScSimple> scSimple = new();
  2019. await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ScSimple>(queryText: scSql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  2020. {
  2021. scSimple.Add(itemSchool);
  2022. }
  2023. return Ok(new { state = RespondCode.Ok, scSimple });
  2024. }
  2025. /// <summary>
  2026. /// 添加新学段的学校
  2027. /// </summary>
  2028. /// <param name="jsonElement"></param>
  2029. /// <returns></returns>
  2030. [ProducesDefaultResponseType]
  2031. [HttpPost("set-allscperiod")]
  2032. public async Task<IActionResult> SetAllScPeriod(JsonElement jsonElement)
  2033. {
  2034. jsonElement.TryGetProperty("Language", out JsonElement Language);
  2035. jsonElement.TryGetProperty("scId", out JsonElement scId);
  2036. jsonElement.TryGetProperty("periodName", out JsonElement periodName);
  2037. var cosmosClient = _azureCosmos.GetCosmosClient();
  2038. var builder = $"{_environment.ContentRootPath}/JsonFile/Preset/LangSchoolConfig.json";
  2039. StreamReader streamReader = new(new FileStream(builder, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8);
  2040. StringBuilder stringBuilder = new();
  2041. string text;
  2042. string scName = "默认学段";
  2043. while ((text = streamReader.ReadLine()) != null)
  2044. {
  2045. stringBuilder.Append(text.ToString());
  2046. }
  2047. streamReader.Close();
  2048. string input = stringBuilder.ToString();
  2049. List<SchoolConfig> schoolConfigs = input.ToObject<List<SchoolConfig>>();
  2050. SchoolConfig schoolConfig = null;
  2051. if (!string.IsNullOrEmpty($"{Language}"))
  2052. schoolConfig = schoolConfigs.Find(x => x.Lang.Contains($"{Language}"));
  2053. if (schoolConfig == null)
  2054. {
  2055. if ($"{Language}".Contains("en"))
  2056. schoolConfig = schoolConfigs.Find(x => x.Lang.Contains("en-US"));
  2057. else
  2058. schoolConfig = schoolConfigs.Find(x => x.Lang.Contains("zh-CN"));
  2059. }
  2060. string campusId = Guid.NewGuid().ToString();
  2061. StringBuilder noPeriodScSql = new("SELECT value(c) FROM c ");
  2062. List<School> allSc = new();
  2063. if (!string.IsNullOrEmpty($"{scId}"))
  2064. noPeriodScSql.Append($" where c.id='{scId}'");
  2065. else
  2066. noPeriodScSql.Append($" where c.code='Base' and c.period=[]");
  2067. if (!string.IsNullOrEmpty($"{periodName}"))
  2068. scName = $"{periodName}";
  2069. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(noPeriodScSql.ToString(),requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("Base")}))
  2070. {
  2071. allSc.Add(item);
  2072. }
  2073. foreach (var school in allSc)
  2074. {
  2075. if (school.campuses.Count > 0)
  2076. campusId = school.campuses.Select(x => x.id).FirstOrDefault().ToString();
  2077. school.period.Add(new Period
  2078. {
  2079. id = Guid.NewGuid().ToString(),
  2080. name = scName,
  2081. campusId = campusId,
  2082. 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() },
  2083. 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() } },
  2084. subjects = new List<Subject>() {
  2085. new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[0].name,type=schoolConfig.PresetSubject[0].type },
  2086. new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[1].name,type=schoolConfig.PresetSubject[1].type },
  2087. new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[2].name,type=schoolConfig.PresetSubject[2].type }
  2088. },
  2089. grades = schoolConfig.grades,
  2090. analysis = new Analysis()
  2091. {
  2092. type = new List<ExamSimple>() { new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[0].name },
  2093. new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[1].name },
  2094. new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[2].name },
  2095. new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[3].name } },
  2096. income = schoolConfig.PresetExam[0].income,
  2097. eugenics = schoolConfig.PresetExam[0].eugenics,
  2098. touch = schoolConfig.PresetExam[0].touch
  2099. }
  2100. });
  2101. if (!school.campuses.Select(x => x.id).Contains(campusId))
  2102. school.campuses.Add(new Campus { name = school.name, id = campusId });
  2103. School rSchool = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, school.id, new PartitionKey("Base"));
  2104. }
  2105. return Ok(new { state = RespondCode.Ok });
  2106. }
  2107. /// <summary>
  2108. /// 设置学校学段
  2109. /// </summary>
  2110. /// <param name="jsonElement"></param>
  2111. /// <returns></returns>
  2112. [ProducesDefaultResponseType]
  2113. [HttpPost("set-scperiod")]
  2114. public async Task<IActionResult> SetScPeriod(JsonElement jsonElement)
  2115. {
  2116. if (!jsonElement.TryGetProperty("scId", out JsonElement scId)) return BadRequest();
  2117. jsonElement.TryGetProperty("Language", out JsonElement Language);
  2118. var cosmosClient = _azureCosmos.GetCosmosClient();
  2119. var builder = $"{_environment.ContentRootPath}/JsonFile/Preset/LangSchoolConfig.json";
  2120. StreamReader streamReader = new(new FileStream(builder, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8);
  2121. StringBuilder stringBuilder = new();
  2122. string text;
  2123. while ((text = streamReader.ReadLine()) != null)
  2124. {
  2125. stringBuilder.Append(text.ToString());
  2126. }
  2127. streamReader.Close();
  2128. string input = stringBuilder.ToString();
  2129. List<SchoolConfig> schoolConfigs = input.ToObject<List<SchoolConfig>>();
  2130. SchoolConfig schoolConfig = null;
  2131. if (!string.IsNullOrEmpty($"{Language}"))
  2132. schoolConfig = schoolConfigs.Find(x => x.Lang.Contains($"{Language}"));
  2133. if (schoolConfig == null)
  2134. {
  2135. if ($"{Language}".Contains("en"))
  2136. schoolConfig = schoolConfigs.Find(x => x.Lang.Contains("en-US"));
  2137. else
  2138. schoolConfig = schoolConfigs.Find(x => x.Lang.Contains("zh-CN"));
  2139. }
  2140. string campusId = Guid.NewGuid().ToString();
  2141. School school = null;
  2142. school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{scId}", new PartitionKey("Base"));
  2143. if (school != null)
  2144. {
  2145. school.period.Add(new Period
  2146. {
  2147. id = Guid.NewGuid().ToString(),
  2148. name = "默认学段",
  2149. campusId = campusId,
  2150. 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() },
  2151. 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() } },
  2152. subjects = new List<Subject>() {
  2153. new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[0].name,type=schoolConfig.PresetSubject[0].type },
  2154. new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[1].name,type=schoolConfig.PresetSubject[1].type },
  2155. new Subject { id=Guid.NewGuid().ToString(),name=schoolConfig.PresetSubject[2].name,type=schoolConfig.PresetSubject[2].type }
  2156. },
  2157. grades = schoolConfig.grades,
  2158. analysis = new Analysis()
  2159. {
  2160. type = new List<ExamSimple>() { new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[0].name },
  2161. new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[1].name },
  2162. new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[2].name },
  2163. new ExamSimple { id = Guid.NewGuid().ToString(), name = schoolConfig.PresetExam[0].type[3].name } },
  2164. income = schoolConfig.PresetExam[0].income,
  2165. eugenics = schoolConfig.PresetExam[0].eugenics,
  2166. touch = schoolConfig.PresetExam[0].touch
  2167. }
  2168. });
  2169. school.campuses.Add(new Campus { name = school.name, id = campusId });
  2170. }
  2171. school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, school.id, new PartitionKey("Base"));
  2172. return Ok(new { state = RespondCode.Ok, school });
  2173. }
  2174. #region 购买记录
  2175. /// <summary>
  2176. /// 取得CoreBB學校訂單履歷資訊 暂时这样处理
  2177. /// </summary>
  2178. /// <param name="request"></param>
  2179. /// <returns></returns>
  2180. private async Task<List<object>> GetOrderHisFromCoreBBAsync(string schoolCode)
  2181. {
  2182. List<object> result = new List<object>();
  2183. try
  2184. {
  2185. string url = _configuration.GetValue<string>("HaBookAuth:CoreBBAPI") + "/ies5/get-school-order";
  2186. string AccessToken = await getCoreAccessToken();
  2187. _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
  2188. string paramJson = JsonConvert.SerializeObject(new { school_code = schoolCode });
  2189. var content = new StringContent(paramJson, Encoding.UTF8, "application/json");
  2190. HttpResponseMessage responseMessage = await _httpClient.PostAsync(url, content);
  2191. if (responseMessage.StatusCode == HttpStatusCode.OK)
  2192. {
  2193. string responseBody = responseMessage.Content.ReadAsStringAsync().Result;
  2194. result = System.Text.Json.JsonSerializer.Deserialize<List<object>>(responseBody.ToString());
  2195. }
  2196. return result;
  2197. }
  2198. catch (Exception ex)
  2199. {
  2200. return result;
  2201. }
  2202. }
  2203. private async Task<string> getCoreAccessToken()
  2204. {
  2205. string AccessToken = "";
  2206. try
  2207. {
  2208. string Url = _configuration.GetValue<string>("HaBookAuth:CoreAPI") + "/oauth2/token";
  2209. string GrantType = "device";
  2210. string ClientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  2211. string Secret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  2212. var content = new { grant_type = GrantType, client_id = ClientID, client_secret = Secret };
  2213. var response = await _httpClient.PostAsJsonAsync($"{Url}", content);
  2214. if (response.IsSuccessStatusCode)
  2215. {
  2216. string responseBody = response.Content.ReadAsStringAsync().Result;
  2217. using (JsonDocument document = JsonDocument.Parse(responseBody.ToString()))
  2218. {
  2219. if (document.RootElement.TryGetProperty("access_token", out JsonElement AccessTokenObj))
  2220. {
  2221. AccessToken = AccessTokenObj.ToString();
  2222. }
  2223. }
  2224. }
  2225. return AccessToken;
  2226. }
  2227. catch (Exception ex)
  2228. {
  2229. return AccessToken;
  2230. }
  2231. }
  2232. #endregion
  2233. #region 顾问学校统计返回值
  2234. public record ScRankCnt : SchoolBase
  2235. {
  2236. public int openCnt { get; set; }
  2237. public int lessCnt { get; set; }
  2238. public int interCnt { get; set; }
  2239. public int actCnt { get; set; }
  2240. }
  2241. public record SchoolBase
  2242. {
  2243. public string id { get; set; }
  2244. public string code { get; set; }
  2245. public string name { get; set; }
  2246. public string picture { get; set; }
  2247. }
  2248. #endregion
  2249. /// <summary>
  2250. /// 未加入区域的学校
  2251. /// </summary>
  2252. public record NotAreaSchool
  2253. {
  2254. public string id { get; set; }
  2255. public string name { get; set; }
  2256. public string schoolCode { get; set; }
  2257. public string picture { get; set; }
  2258. public List<string> period { get; set; }
  2259. public string province { get; set; }
  2260. public string city { get; set; }
  2261. public string dist { get; set; } = "";
  2262. public string areaId { get; set; } = "";
  2263. public string standard { get; set; } = "";
  2264. public List<SchoolArea> areas { get; set; } = new List<SchoolArea>();
  2265. }
  2266. /// <summary>
  2267. /// 学校空间使用情况
  2268. /// </summary>
  2269. public record SchoolSpace
  2270. {
  2271. public string id { get; set; }
  2272. public string name { get; set; }
  2273. public Space space { get; set; }
  2274. }
  2275. /// <summary>
  2276. /// 空间
  2277. /// </summary>
  2278. public record Space
  2279. {
  2280. /// <summary>
  2281. /// 已使用空间
  2282. /// </summary>
  2283. public long useSize { get; set; }
  2284. /// <summary>
  2285. /// 分配教师空间
  2286. /// </summary>
  2287. public long tSize { get; set; }
  2288. /// <summary>
  2289. /// 空间类型
  2290. /// </summary>
  2291. public Dictionary<string, double?> catalogSize { get; set; }
  2292. }
  2293. public record ScSimple
  2294. {
  2295. public string id { get; set; }
  2296. public string name { get; set; }
  2297. public string picture { get; set; }
  2298. public long createTime { get; set; }
  2299. }
  2300. public record DelSchoolRel
  2301. {
  2302. public string id { get; set; }
  2303. public string code { get; set; }
  2304. /// <summary>
  2305. /// 未删除的类型 1 学校 2教师 3学生
  2306. /// </summary>
  2307. public int type { get; set; }
  2308. public int status { get; set; }
  2309. }
  2310. }
  2311. }