SchoolController.cs 138 KB

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