SchoolController.cs 138 KB

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