SchoolController.cs 144 KB

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