SchoolController.cs 128 KB

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