SchoolController.cs 138 KB

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