SchoolController.cs 152 KB

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