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