SchoolController.cs 137 KB

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