SchoolController.cs 137 KB

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