SchoolController.cs 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858
  1. using Azure.Cosmos;
  2. using HTEXLib.COMM.Helpers;
  3. using MathNet.Numerics.LinearAlgebra;
  4. using MathNet.Numerics.LinearAlgebra.Double;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.AspNetCore.Mvc;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.Options;
  9. using StackExchange.Redis;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Net.Http;
  14. using System.Text;
  15. using System.Text.Json;
  16. using System.Threading.Tasks;
  17. using TEAMModelBI.DI.BIAzureStorage;
  18. using TEAMModelBI.Filter;
  19. using TEAMModelBI.Models;
  20. using TEAMModelBI.Tool;
  21. using TEAMModelBI.Tool.CosmosBank;
  22. using TEAMModelBI.Tool.Extension;
  23. using TEAMModelOS.Models;
  24. using TEAMModelOS.SDK;
  25. using TEAMModelOS.SDK.Context.BI;
  26. using TEAMModelOS.SDK.Context.Constant;
  27. using TEAMModelOS.SDK.DI;
  28. using TEAMModelOS.SDK.Extension;
  29. using TEAMModelOS.SDK.Models;
  30. using TEAMModelOS.SDK.Models.Cosmos.BI;
  31. using TEAMModelOS.SDK.Models.Cosmos.Common;
  32. using TEAMModelOS.SDK.Models.Service;
  33. using TEAMModelOS.SDK.Models.Service.BI;
  34. namespace TEAMModelBI.Controllers.BISchool
  35. {
  36. [Route("schoolcheck")]
  37. [ApiController]
  38. public class SchoolController : ControllerBase
  39. {
  40. private readonly AzureCosmosFactory _azureCosmos;
  41. private readonly DingDing _dingDing;
  42. private readonly Option _option;
  43. private readonly AzureStorageFactory _azureStorage;
  44. private readonly AzureRedisFactory _azureRedis;
  45. private readonly IConfiguration _configuration;
  46. private readonly NotificationService _notificationService;
  47. private readonly CoreAPIHttpService _coreAPIHttpService;
  48. public SchoolController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, AzureRedisFactory azureRedis, IConfiguration configuration, NotificationService notificationService, CoreAPIHttpService coreAPIHttpService)
  49. {
  50. _azureCosmos = azureCosmos;
  51. _dingDing = dingDing;
  52. _azureStorage = azureStorage;
  53. _option = option?.Value;
  54. _azureRedis = azureRedis;
  55. _configuration = configuration;
  56. _notificationService = notificationService;
  57. _coreAPIHttpService = coreAPIHttpService;
  58. }
  59. /// <summary>
  60. /// 查询未加入区域的学校
  61. /// </summary>
  62. /// <returns></returns>
  63. [ProducesDefaultResponseType]
  64. [HttpPost("get-notarea")]
  65. public async Task<IActionResult> GetNotAreaSchool(JsonElement jsonElement)
  66. {
  67. try
  68. {
  69. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  70. jsonElement.TryGetProperty("site", out JsonElement site);
  71. var cosmosClient = _azureCosmos.GetCosmosClient();
  72. if ($"{site}".Equals(BIConst.Global))
  73. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  74. //默认不指定返回大小
  75. int? pageSize = null;
  76. string continuationToken = string.Empty;
  77. string pageToken = default;
  78. if (jsonElement.TryGetProperty("pageSize", out JsonElement jsonPageSize))
  79. {
  80. if (!jsonPageSize.ValueKind.Equals(JsonValueKind.Undefined) && !jsonPageSize.ValueKind.Equals(JsonValueKind.Null) && jsonPageSize.TryGetInt32(out int tempPageSize))
  81. {
  82. pageSize = tempPageSize;
  83. }
  84. }
  85. //是否需要进行分页查询,默认不分页
  86. bool iscontinuation = false;
  87. if (pageSize != null && pageSize.Value > 0)
  88. {
  89. iscontinuation = true;
  90. }
  91. if (jsonElement.TryGetProperty("contToken", out JsonElement ContToken))
  92. {
  93. pageToken = ContToken.GetString();
  94. }
  95. StringBuilder sqltxt = new($"SELECT c.id,c.name,c.schoolCode,c.province,c.city,c.dist,c.picture,c.period,c.areaId,c.standard,c.manyAreas FROM c");
  96. if (!string.IsNullOrEmpty($"{areaId}"))
  97. {
  98. sqltxt.Append($" WHERE c.areaId !='{areaId}'");
  99. }
  100. else
  101. {
  102. sqltxt.Append($" WHERE c.areaId ='' and c.standard = ''");
  103. }
  104. List<NotAreaSchool> tempNotAreaSchools = new();
  105. 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") }))
  106. {
  107. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  108. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  109. {
  110. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  111. {
  112. //List<string> temp0 = obj.GetProperty("period").ToObject<List<Period>>().Select(x=>x.name).ToList();
  113. NotAreaSchool notAreaSchool = new NotAreaSchool()
  114. {
  115. id = obj.GetProperty("id").GetString(),
  116. name = obj.GetProperty("name").GetString(),
  117. schoolCode = obj.GetProperty("schoolCode").GetString(),
  118. picture = obj.GetProperty("picture").GetString(),
  119. period = obj.GetProperty("period").ToObject<List<Period>>().Select(x => x.name).ToList(),
  120. province = obj.GetProperty("province").GetString(),
  121. city = obj.GetProperty("city").GetString(),
  122. dist = obj.GetProperty("dist").GetString(),
  123. areaId = obj.GetProperty("areaId").GetString(),
  124. standard = obj.GetProperty("standard").GetString()
  125. };
  126. try
  127. {
  128. notAreaSchool.areas = obj.GetProperty("manyAreas").ToObject<List<SchoolArea>>();
  129. }
  130. catch { }
  131. tempNotAreaSchools.Add(notAreaSchool);
  132. }
  133. if (iscontinuation)
  134. {
  135. continuationToken = item.GetContinuationToken();
  136. break;
  137. }
  138. }
  139. }
  140. List<NotAreaSchool> notAreaSchools = new List<NotAreaSchool>();
  141. tempNotAreaSchools.ForEach(nas =>
  142. {
  143. if (nas.areas == null)
  144. notAreaSchools.Add(nas);
  145. else
  146. {
  147. var not = nas.areas.Find(f => f.areaId == $"{areaId}");
  148. if (not == null)
  149. notAreaSchools.Add(nas);
  150. }
  151. });
  152. //if (!string.IsNullOrEmpty($"{areaId}"))
  153. // 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();
  154. return Ok(new { state = 200, continuationToken, pageSize, notAreaSchools });
  155. }
  156. catch (Exception ex)
  157. {
  158. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/get-notarea \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  159. return BadRequest();
  160. }
  161. }
  162. /// <summary>
  163. /// 学校加入区
  164. /// </summary>
  165. /// <param name="jsonElement"></param>
  166. /// <returns></returns>
  167. [ProducesDefaultResponseType]
  168. [AuthToken(Roles = "admin,rdc,assist,sales")]
  169. [HttpPost("set-schooljoinarea")]
  170. public async Task<IActionResult> SetSchoolJoinArea(JsonElement jsonElement)
  171. {
  172. try
  173. {
  174. if (!jsonElement.TryGetProperty("standard", out JsonElement standard)) return BadRequest();
  175. if (!jsonElement.TryGetProperty("schoolCode", out JsonElement _schoolCode)) return BadRequest();
  176. if (!jsonElement.TryGetProperty("areaId", out JsonElement _areaId)) return BadRequest();
  177. jsonElement.TryGetProperty("areaName", out JsonElement areaName);
  178. jsonElement.TryGetProperty("isDefault", out JsonElement isDefault);
  179. jsonElement.TryGetProperty("site", out JsonElement site);
  180. var isManyArea = false;
  181. if (!string.IsNullOrEmpty($"{isDefault}"))
  182. {
  183. isManyArea = true;
  184. }
  185. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  186. List<string> schoolCodes = _schoolCode.ToObject<List<string>>();
  187. StringBuilder msg = new($"{_tmdName}【{_tmdId}】操作学校加入区域功能,加入的区域:{standard},学校ID:{string.Join("|", schoolCodes.ToArray())}");
  188. var cosmosClient = _azureCosmos.GetCosmosClient();
  189. var tableClient = _azureStorage.GetCloudTableClient();
  190. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  191. if ($"{site}".Equals(BIConst.Global))
  192. {
  193. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  194. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  195. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  196. }
  197. var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{_areaId}", new PartitionKey("AreaSetting"));
  198. if (responseSet.Status == 200)
  199. {
  200. using var fileJson = await JsonDocument.ParseAsync(responseSet.ContentStream);
  201. AreaSetting delSet = fileJson.ToObject<AreaSetting>();
  202. if (!string.IsNullOrEmpty(delSet.accessConfig))
  203. return Ok(new { state = 401, msg = "区域已经规定了,不能切换能能力" });
  204. }
  205. if (schoolCodes.Count > 0)
  206. {
  207. foreach (var tempCode in schoolCodes)
  208. {
  209. School school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(tempCode, new PartitionKey("Base"));
  210. if (school != null)
  211. {
  212. if (isManyArea)
  213. {
  214. if (school.areas == null)
  215. school.areas = new List<SchoolArea>() { new SchoolArea() { areaId = $"{_areaId}", name =$"{areaName}", status = "join" } };
  216. else
  217. {
  218. var marea = school.areas.Find(ma => ma.areaId == $"{_areaId}");
  219. if (marea == null)
  220. school.areas.Add(new SchoolArea() { areaId = $"{_areaId}", name = $"{areaName}", status = $"join" });
  221. }
  222. }
  223. school.standard = $"{standard}";
  224. school.areaId = $"{_areaId}";
  225. msg.Append($"{school.name}【{school.id}】学校移除多区域的名单:");
  226. List<Teacher> teachers = new();
  227. 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") }))
  228. {
  229. teachers.Add(item);
  230. }
  231. foreach (var item in teachers)
  232. {
  233. msg.Append($"{item.name}[{item.id}]");
  234. var tchSchool = item.schools.Find(f => f.schoolId.Equals($"{school.id}") && f.areaId.Equals($"{_areaId}"));
  235. if (tchSchool == null)
  236. {
  237. Teacher.TeacherSchool teacherSchool = new() { schoolId = school.id, name = school.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = school.picture, areaId = school.areaId };
  238. item.schools.Add(teacherSchool);
  239. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(item, item.id, new PartitionKey("Base"));
  240. }
  241. }
  242. await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, school.id, new PartitionKey(school.code));
  243. }
  244. }
  245. }
  246. //保存操作记录
  247. //await _azureStorage.SaveBILog("school-update", $"{_tmdName}【{_tmdId}】操作学校加入区域功能,加入的区域:{standard},学校ID:{string.Join("|", schoolCodes.ToArray())}", _dingDing, httpContext: HttpContext);
  248. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", msg.ToString(), _dingDing, httpContext: HttpContext);
  249. return Ok(new { state = 200 });
  250. }
  251. catch (Exception ex)
  252. {
  253. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/set-schooljoinarea \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  254. return BadRequest();
  255. }
  256. }
  257. /// <summary>
  258. /// 依据醍摩豆账户查询顾问管理学校的基础信息
  259. /// </summary>
  260. /// <param name="jsonElement"></param>
  261. /// <returns></returns>
  262. [HttpPost("get-assistschool")]
  263. public async Task<IActionResult> GetAssistSchool(JsonElement jsonElement)
  264. {
  265. try
  266. {
  267. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  268. jsonElement.TryGetProperty("site", out JsonElement site);
  269. List<object> schools = new List<object>();
  270. var cosmosClient = _azureCosmos.GetCosmosClient();
  271. if ($"{site}".Equals(BIConst.Global))
  272. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  273. //List<string> schoolIds = new List<string>();
  274. //string sqlTxt = $"SELECT DISTINCT REPLACE(c.code, 'Teacher-', '') AS schoolId FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS(c.roles, 'assist', true) AND c.id='{tmdId}' ";
  275. //await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { }))
  276. //{
  277. // using var json = await JsonDocument.ParseAsync(item.ContentStream);
  278. // foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  279. // {
  280. // schoolIds.Add(obj.GetProperty("schoolId").GetString());
  281. // }
  282. //}
  283. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  284. foreach (var item in schoolIds)
  285. {
  286. await foreach (var itemBase in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"select c.id,c.code,c.name,c.picture,c.region,c.province,c.city,c.dist from c where c.id='{item}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  287. {
  288. var json = await JsonDocument.ParseAsync(itemBase.ContentStream);
  289. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  290. {
  291. schools.Add(obj.ToObject<object>());
  292. }
  293. }
  294. }
  295. return Ok(new { state = 200, schools });
  296. }
  297. catch (Exception ex)
  298. {
  299. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/get-assustschool \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  300. return BadRequest();
  301. }
  302. }
  303. /// <summary>
  304. /// 依据学校编号查询学校信息
  305. /// </summary>
  306. /// <param name="jsonElement"></param>
  307. /// <returns></returns>
  308. [HttpPost("get-schoolid")]
  309. public async Task<IActionResult> GetSchoolId(JsonElement jsonElement)
  310. {
  311. try
  312. {
  313. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  314. jsonElement.TryGetProperty("site", out JsonElement site);
  315. var cosmosClient = _azureCosmos.GetCosmosClient();
  316. if ($"{site}".Equals(BIConst.Global))
  317. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  318. AssistSchool schoolAssists = new(); //返回学校列表集合
  319. 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 from c where c.id='{schoolId}'";
  320. await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<AssistSchool>(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  321. {
  322. //schoolAssists.Add(itemSchool);
  323. schoolAssists = itemSchool;
  324. //school = itemSchool;
  325. }
  326. if (schoolAssists.id != null)
  327. {
  328. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(schoolAssists.id, new PartitionKey("ProductSum"));
  329. if (response.Status == 200)
  330. {
  331. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  332. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  333. {
  334. schoolAssists.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  335. }
  336. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  337. {
  338. schoolAssists.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  339. }
  340. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  341. {
  342. schoolAssists.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  343. }
  344. }
  345. schoolAssists.assists = await CommonFind.FindSchoolRoles(cosmosClient, schoolAssists.id, "assist");
  346. schoolAssists.lessonCount = await CommonFind.FindTotals(cosmosClient, $"select count(c.id) as totals from c ", "School", $"LessonRecord-{schoolAssists.id}");
  347. return Ok(new { state = 200, schoolAssists });
  348. }
  349. else return Ok(new { state = 404, msg = "未找到该学校!" });
  350. }
  351. catch (Exception ex)
  352. {
  353. await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/get-schoolid \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  354. return BadRequest();
  355. }
  356. }
  357. /// <summary>
  358. /// 修改学校信息
  359. /// </summary>
  360. /// <param name="school"></param>
  361. /// <returns></returns>
  362. [ProducesDefaultResponseType]
  363. [AuthToken(Roles = "admin,rdc,assist,sales")]
  364. [HttpPost("upd-school")]
  365. public async Task<IActionResult> UpdSchool(School school, [FromHeader] string site)
  366. {
  367. try
  368. {
  369. School schoolInfo = new School();
  370. var cosmosClient = _azureCosmos.GetCosmosClient();
  371. var tableClient = _azureStorage.GetCloudTableClient();
  372. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  373. if ($"{site}".Equals(BIConst.Global))
  374. {
  375. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  376. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  377. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  378. }
  379. string _auth = HttpContext.GetXAuth("AuthToken");
  380. //var (tmdId, tmdName) = HttpJwtAnalysis.JwtXAuth(_auth, _option);
  381. var (tmdId, tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(_auth, _option);
  382. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school.id, new PartitionKey($"Base"));
  383. if (response.Status == 200)
  384. {
  385. string sql = $"SELECT distinct value(c) FROM c join A1 in c.schools where A1.schoolId='{school.id}'";
  386. List<Teacher> teachers = new List<Teacher>();
  387. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Teacher>(sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  388. {
  389. teachers.Add(item);
  390. }
  391. foreach (var item in teachers)
  392. {
  393. Teacher.TeacherSchool teacherSchool = item.schools.Find(x => x.schoolId.Equals(school.id));
  394. if (teacherSchool != null)
  395. {
  396. teacherSchool.name = school.name;
  397. teacherSchool.picture = school.picture;
  398. teacherSchool.areaId = school.areaId;
  399. }
  400. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey($"Base"));
  401. }
  402. schoolInfo = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<School>(school, school.id, new PartitionKey($"Base"));
  403. //保存操作记录
  404. //await _azureStorage.SaveBILog("school-update", $"{tmdName}【{tmdId}】修改学校信息,学校和ID:{school.name}【{school.id}】", _dingDing, httpContext: HttpContext);
  405. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", $"{tmdName}【{tmdId}】修改学校信息,学校和ID:{school.name}【{school.id}】", _dingDing, httpContext: HttpContext);
  406. }
  407. else return Ok(new { state = 400, message = "请求错误!" });
  408. return Ok(new { state = 200, schoolInfo });
  409. //School tempShool = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(replaceSchool.school.id, new PartitionKey("Base"));
  410. //if (tempShool != null)
  411. //{
  412. // List<Teacher> teachers = new List<Teacher>();
  413. // string sqltxt = $"select distinct value(c) from c join a1 in c.schools where a1.schoolId='{replaceSchool.school.id}'";
  414. // await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sqltxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  415. // {
  416. // teachers.Add(item);
  417. // }
  418. // foreach (var item in teachers)
  419. // {
  420. // Teacher.TeacherSchool teacherSchool = item.schools.Find(x => x.schoolId.Equals(replaceSchool.school.id));
  421. // if (teacherSchool != null)
  422. // {
  423. // teacherSchool.name = replaceSchool.school.name;
  424. // teacherSchool.picture = replaceSchool.school.picture;
  425. // teacherSchool.areaId = replaceSchool.school.areaId;
  426. // }
  427. // await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey("Base"));
  428. // }
  429. // schoolInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(replaceSchool.school, replaceSchool.school.id, new PartitionKey("Base"));
  430. // //保存操作记录
  431. // await _azureStorage.SaveBILog("school-update", $"{replaceSchool.tmdName}【{replaceSchool.tmdId}】修改学校信息,学校和ID:{replaceSchool.school.name}【{replaceSchool.school.id}】", _dingDing, httpContext: HttpContext);
  432. // return Ok(new { state = 200, schoolInfo });
  433. //}
  434. //else return Ok(new { state = 400, message = "请求错误!" });
  435. }
  436. catch (Exception ex)
  437. {
  438. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/upd-school \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  439. return BadRequest();
  440. }
  441. }
  442. /// <summary>
  443. /// 顾问学校空间使用情况
  444. /// </summary>
  445. /// <param name="jsonElement"></param>
  446. /// <returns></returns>
  447. [HttpPost("get-assistspace")]
  448. public async Task<IActionResult> GetAssistSchoolSpace(JsonElement jsonElement)
  449. {
  450. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  451. jsonElement.TryGetProperty("site", out JsonElement site);
  452. var cosmosClient = _azureCosmos.GetCosmosClient();
  453. if ($"{site}".Equals(BIConst.Global))
  454. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  455. List<string> schools = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  456. List<SchoolSpace> schoolSpaces = new();
  457. foreach (var sid in schools)
  458. {
  459. School school = new();
  460. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(sid, new PartitionKey("Base"));
  461. if (response.Status == 200)
  462. {
  463. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  464. school = json.ToObject<School>();
  465. }
  466. long teach = 0;
  467. 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}") }))
  468. {
  469. var json = await JsonDocument.ParseAsync(item.ContentStream);
  470. foreach (var elmt in json.RootElement.GetProperty("Documents").EnumerateArray())
  471. {
  472. if (elmt.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
  473. {
  474. teach = _size.GetInt32();
  475. break;
  476. }
  477. }
  478. }
  479. SchoolSpace schoolSpace = new() { id = sid, name = school != null ? school.name : sid };
  480. Space space = new Space();
  481. long blobsize = 0; //使用大小
  482. RedisValue value = default;
  483. value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", sid);
  484. if (value != default && !value.IsNullOrEmpty)
  485. {
  486. JsonElement record = value.ToString().ToObject<JsonElement>();
  487. if (record.TryGetInt64(out blobsize))
  488. {
  489. }
  490. }
  491. else
  492. {
  493. var client = _azureStorage.GetBlobContainerClient(sid);
  494. var size = await client.GetBlobsCatalogSize();
  495. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", sid, size.Item1);
  496. foreach (var key in size.Item2.Keys)
  497. {
  498. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{sid}", key);
  499. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{sid}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  500. }
  501. space.useSize = (long)size.Item1; space.tSize = teach; space.catalogSize = size.Item2;
  502. schoolSpace.space = space;
  503. schoolSpaces.Add(schoolSpace);
  504. continue;
  505. }
  506. Dictionary<string, double?> catalog = new Dictionary<string, double?>();
  507. SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{sid}");
  508. if (Scores != null)
  509. {
  510. foreach (var score in Scores)
  511. {
  512. double val = score.Score;
  513. string key = score.Element.ToString();
  514. catalog.Add(key, val);
  515. }
  516. space.useSize = blobsize; space.tSize = teach; space.catalogSize = catalog;
  517. schoolSpace.space = space;
  518. schoolSpaces.Add(schoolSpace);
  519. continue;
  520. }
  521. else
  522. {
  523. var client = _azureStorage.GetBlobContainerClient(sid);
  524. var size = await client.GetBlobsCatalogSize();
  525. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", sid, size.Item1);
  526. foreach (var key in size.Item2.Keys)
  527. {
  528. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{sid}", key);
  529. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{sid}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  530. }
  531. space.useSize = (long)size.Item1;
  532. space.tSize = teach;
  533. space.catalogSize = size.Item2;
  534. schoolSpace.space = space;
  535. schoolSpaces.Add(schoolSpace);
  536. continue;
  537. }
  538. }
  539. return Ok(new { state = 200, schoolSpaces });
  540. }
  541. /// <summary>
  542. /// 移交学校顾问
  543. /// </summary>
  544. /// <param name="jsonElement"></param>
  545. /// <returns></returns>
  546. [HttpPost("get-shift")]
  547. public async Task<IActionResult> GetShift(JsonElement jsonElement)
  548. {
  549. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  550. if (!jsonElement.TryGetProperty("school", out JsonElement _school)) return BadRequest();
  551. //if (!jsonElement.TryGetProperty("teacher", out JsonElement _teacher)) return BadRequest();
  552. if (!jsonElement.TryGetProperty("shiftTeacher", out JsonElement _shiftTeacher)) return BadRequest();
  553. jsonElement.TryGetProperty("site", out JsonElement site);
  554. var cosmosClient = _azureCosmos.GetCosmosClient();
  555. var tableClient = _azureStorage.GetCloudTableClient();
  556. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  557. if ($"{site}".Equals(BIConst.Global))
  558. {
  559. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  560. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  561. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  562. }
  563. SchoolTeacher schoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<SchoolTeacher>($"{_tmdId}", new PartitionKey($"Teacher-{_school}"));
  564. if (schoolTeacher.roles.IsNotEmpty() && schoolTeacher.roles.Contains("assist"))
  565. {
  566. schoolTeacher.roles.Remove("assist");
  567. SchoolTeacher newSchoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<SchoolTeacher>($"{_shiftTeacher}", new PartitionKey($"Teacher-{_school}"));
  568. if (!newSchoolTeacher.roles.Contains("assist"))
  569. {
  570. newSchoolTeacher.roles.Add("assist");
  571. newSchoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(newSchoolTeacher, $"{_shiftTeacher}", new PartitionKey($"Teacher-{_school}"));
  572. }
  573. await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, $"{_tmdId}", new PartitionKey($"Teacher-{_school}"));
  574. School schoolBase = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<School>($"{_school}", new PartitionKey($"Base"));
  575. //发送消息实体
  576. string shiftCode = "shift-assist";
  577. Notification notification = new Notification
  578. {
  579. hubName = "hita",
  580. type = "msg",
  581. from = $"BI:{_option.Location}:{_school}",
  582. to = new List<string> { $"{_shiftTeacher}" },
  583. label = $"{shiftCode}_school",
  584. body = new { location = _option.Location, biz = shiftCode, tmdid = $"{_tmdId}", tmdname = $"{_tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  585. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  586. };
  587. if (notification != null)
  588. {
  589. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  590. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  591. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  592. var location = _option.Location;
  593. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);//站内发送消息
  594. }
  595. //保存操作记录
  596. //await _azureStorage.SaveBILog("schoolTeacher-add", $"{_tmdName}【{_tmdId}】移交顾问给{newSchoolTeacher.name}【{newSchoolTeacher.id}】", _dingDing, httpContext: HttpContext);
  597. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "schoolTeacher-add", $"{_tmdName}【{_tmdId}】移交顾问给{newSchoolTeacher.name}【{newSchoolTeacher.id}】", _dingDing, httpContext: HttpContext);
  598. return Ok(new { state = 200 });
  599. }
  600. else { return Ok(new { status = 201, msg = $"{_tmdName}【{_tmdId}】账号不是顾问" }); }
  601. }
  602. /// <summary>
  603. /// 修改顾问学校
  604. /// </summary>
  605. /// <param name="jsonElement"></param>
  606. /// <returns></returns>
  607. [ProducesDefaultResponseType]
  608. [AuthToken(Roles = "admin,rdc")]
  609. [HttpPost("set-aistschool")]
  610. public async Task<IActionResult> SetAssistSchool(JsonElement jsonElement)
  611. {
  612. try
  613. {
  614. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement parKey)) return BadRequest();
  615. jsonElement.TryGetProperty("userId", out JsonElement userId);
  616. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  617. if (!jsonElement.TryGetProperty("schoolIds", out JsonElement jsSchoolIds)) return BadRequest();
  618. if (!jsonElement.TryGetProperty("busy", out JsonElement busy)) return BadRequest();
  619. jsonElement.TryGetProperty("site", out JsonElement site);
  620. List<string> schoolIds = jsSchoolIds.ToObject<List<string>>();
  621. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  622. var cosmosClient = _azureCosmos.GetCosmosClient();
  623. string divide = _option.Location;
  624. if ($"{site}".Equals(BIConst.Global))
  625. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  626. Dictionary<string, object> dic = new() { { "PartitionKey", $"{parKey}" } };
  627. if (!string.IsNullOrEmpty($"{userId}"))
  628. {
  629. dic.Add("userId", $"{userId}");
  630. }
  631. if (string.IsNullOrEmpty($"{userId}") && string.IsNullOrEmpty($"{tmdId}"))
  632. {
  633. return Ok(new { state = 400, msg = "钉钉账户或醍摩豆账户需要至少要传一个!" });
  634. }
  635. Dictionary<string, List<string>> noSchools = new();
  636. List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
  637. List<DingDingUserInfo> updUsers = new();
  638. if (ddUserInfoList.Count > 0)
  639. {
  640. foreach (var ddInfo in ddUserInfoList)
  641. {
  642. if (schoolIds.Count > 0)
  643. {
  644. if (string.IsNullOrEmpty(ddInfo.tmdId))
  645. {
  646. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{ddInfo.mobile}" } }, _option.Location, _configuration);
  647. if (coreUser != null && coreUser.id != null)
  648. {
  649. ddInfo.tmdId = coreUser.id;
  650. ddInfo.tmdName = coreUser.name;
  651. ddInfo.tmdMobile = coreUser.mobile;
  652. ddInfo.picture = coreUser.picture;
  653. ddInfo.mail = coreUser.mail;
  654. }
  655. else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  656. //List<string> moblie = new() { $"{ddInfo.mobile}" };
  657. //var content = new StringContent(moblie.ToJsonString(), Encoding.UTF8, "application/json");
  658. //string json = await _coreAPIHttpService.GetUserInfos(content);
  659. //if (!string.IsNullOrEmpty(json))
  660. //{
  661. // List<JsonElement> json_id = json.ToObject<List<JsonElement>>();
  662. // foreach (var tmd in json_id)
  663. // {
  664. // ddInfo.tmdId = tmd.GetProperty("id").ToString();
  665. // ddInfo.tmdName = tmd.GetProperty("name").ToString();
  666. // ddInfo.tmdMobile = tmd.GetProperty("mobile").ToString();
  667. // ddInfo.picture = tmd.GetProperty("picture").ToString();
  668. // ddInfo.mail = tmd.GetProperty("mail").ToString();
  669. // }
  670. //}
  671. //else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  672. }
  673. List<string> noSchool = await SchoolWay.SchoolAdviser(cosmosClient, ddInfo, schoolIds, $"{busy}");
  674. if (noSchool.Count > 0)
  675. {
  676. noSchools.Add(ddInfo.tmdId, noSchool);
  677. }
  678. }
  679. List<string> userSchoolAdv = new(ddInfo.schoolIds.Split("|", StringSplitOptions.RemoveEmptyEntries));
  680. if ($"{busy}".Equals("add"))
  681. {
  682. userSchoolAdv.AddRange(schoolIds);
  683. ddInfo.schoolIds = userSchoolAdv.Count > 0 ? string.Join("|", userSchoolAdv) : "";
  684. }
  685. if ($"{busy}".Equals("del"))
  686. {
  687. var temp = userSchoolAdv.Where(p => !schoolIds.Any(x => x == p)).ToList();
  688. ddInfo.schoolIds = temp.Count > 0 ? string.Join("|", temp) : "";
  689. }
  690. updUsers.Add(ddInfo);
  691. }
  692. }
  693. updUsers = await table.SaveOrUpdateAll(updUsers);
  694. if (noSchools.Count > 0)
  695. return Ok(new { state = 201, recUsers = updUsers, noSchools });
  696. else
  697. return Ok(new { state = 200, recUsers = updUsers });
  698. }
  699. catch (Exception ex)
  700. {
  701. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/set-aistschool \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  702. return BadRequest();
  703. }
  704. }
  705. /// <summary>
  706. /// 依据学校ID查学校管理员信息
  707. /// </summary>
  708. /// <param name="jsonElement"></param>
  709. /// <returns></returns>
  710. [HttpPost("get-scmanage")]
  711. public async Task<IActionResult> GetSchoolManage(JsonElement jsonElement)
  712. {
  713. if (!jsonElement.TryGetProperty("scId", out JsonElement scId)) return BadRequest();
  714. jsonElement.TryGetProperty("site", out JsonElement site);
  715. var cosmosClient = _azureCosmos.GetCosmosClient();
  716. if ($"{site}".Equals(BIConst.Global))
  717. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  718. List<ManageMember> scManages = new();
  719. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ManageMember>(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}")}))
  720. {
  721. scManages.Add(item);
  722. }
  723. return Ok(new { state = RespondCode.Ok, scManages });
  724. }
  725. /// <summary>
  726. /// 设置学校管理员
  727. /// </summary>
  728. /// <param name="jsonElement"></param>
  729. /// <returns></returns>
  730. [ProducesDefaultResponseType]
  731. [AuthToken(Roles = "admin,rdc")]
  732. [HttpPost("set-manage")]
  733. public async Task<IActionResult> SetSchoolManage(JsonElement jsonElement)
  734. {
  735. try
  736. {
  737. var (_tmdId, _tmdName, _, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  738. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  739. if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
  740. jsonElement.TryGetProperty("tmdPic", out JsonElement picture);
  741. if (!jsonElement.TryGetProperty("scId", out JsonElement schoolId)) return BadRequest();
  742. if (!jsonElement.TryGetProperty("scName", out JsonElement schoolName)) return BadRequest();
  743. jsonElement.TryGetProperty("scPic", out JsonElement scpicture);
  744. jsonElement.TryGetProperty("site", out JsonElement site);
  745. var cosmosClient = _azureCosmos.GetCosmosClient();
  746. var tableClient = _azureStorage.GetCloudTableClient();
  747. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  748. if ($"{site}".Equals(BIConst.Global))
  749. {
  750. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  751. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  752. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  753. }
  754. StringBuilder strMsg = new($"{_tmdName}【{_tmdId}】账户将{tmdName}【{tmdId}】");
  755. Teacher teacher = null;
  756. SchoolTeacher schoolTeacher = null;
  757. var resTeacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Base"));
  758. if (resTeacher.Status == 200)
  759. {
  760. using var tchJson = await JsonDocument.ParseAsync(resTeacher.ContentStream);
  761. teacher = tchJson.ToObject<Teacher>();
  762. var existArea = teacher.schools.Find(f => f.schoolId.Equals($"{schoolId}"));
  763. if (existArea == null)
  764. {
  765. teacher.schools.Add(new Teacher.TeacherSchool { schoolId = $"{schoolId}", name = $"{schoolName}", status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = string.IsNullOrEmpty($"{scpicture}") ? "" : $"{scpicture}", areaId = "" });
  766. teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  767. strMsg.Append($"账户基础信息添加学校,");
  768. }
  769. }
  770. else
  771. {
  772. teacher.id = $"{tmdId}";
  773. teacher.name = $"{tmdName}";
  774. teacher.picture = string.IsNullOrEmpty($"{picture}") ? "" : $"{picture}";
  775. teacher.pk = "Base";
  776. teacher.code = "Base";
  777. teacher.size = 1;
  778. teacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  779. //教师存在,在该教师信息中添加要管理的学校信息
  780. teacher.schools.Add(new Teacher.TeacherSchool { schoolId = $"{schoolId}", name = $"{schoolName}", status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = string.IsNullOrEmpty($"{scpicture}") ? "" : $"{scpicture}", areaId = "" });
  781. teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  782. strMsg.Append($"添加基础信息,并添加学校");
  783. }
  784. if (teacher != null)
  785. {
  786. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Teacher-{schoolId}"));
  787. if (response.Status == 200)
  788. {
  789. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  790. schoolTeacher = json.ToObject<SchoolTeacher>();
  791. if (!schoolTeacher.roles.Contains("admin"))
  792. {
  793. schoolTeacher.roles.Add("admin");
  794. schoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, schoolTeacher.id, new PartitionKey($"Teacher-{schoolId}"));
  795. strMsg.Append($"设置管理员,学校信息{schoolName}【{schoolId}】");
  796. }
  797. else
  798. return Ok(new { state = RespondCode.Conflict, schoolTeacher = "已经是该校的管理人员" });
  799. }
  800. else
  801. {
  802. schoolTeacher = new()
  803. {
  804. id = $"{tmdId}",
  805. code = $"Teacher-{schoolId}",
  806. roles = new List<string> { "admin", "teacher" },
  807. job = "管理员",
  808. name = $"{tmdName}",
  809. picture = string.IsNullOrEmpty($"{picture}") ? "" : $"{picture}",
  810. status = "join",
  811. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  812. pk = "Teacher",
  813. ttl = -1
  814. };
  815. schoolTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey($"Teacher-{schoolId}"));
  816. strMsg.Append($"新建学校管理员,学校信息{schoolName}【{schoolId}】");
  817. }
  818. }
  819. //保存操作记录
  820. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "schoolTeacher-add", $"{_tmdName}【{_tmdId}】账户创建{tmdName}【{tmdName}】账户,并设学校管理员。学校ID:{schoolId}。", _dingDing, httpContext: HttpContext);
  821. return Ok(new { state = RespondCode.Ok, teacher, schoolTeacher });
  822. }
  823. catch (Exception ex)
  824. {
  825. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/set-schoolme \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  826. return BadRequest();
  827. }
  828. }
  829. /// <summary>
  830. /// 移除学校管理员
  831. /// </summary>
  832. /// <param name="jsonElement"></param>
  833. /// <returns></returns>
  834. [ProducesDefaultResponseType]
  835. [AuthToken(Roles = "admin,rdc")]
  836. [HttpPost("del-manage")]
  837. public async Task<IActionResult> DelSchoolManage(JsonElement jsonElement)
  838. {
  839. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  840. if (!jsonElement.TryGetProperty("scId", out JsonElement scId)) return BadRequest();
  841. jsonElement.TryGetProperty("site", out JsonElement site);
  842. var cosmosClient = _azureCosmos.GetCosmosClient();
  843. if ($"{site}".Equals(BIConst.Global))
  844. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  845. SchoolTeacher scTeacher = null;
  846. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Teacher-{scId}"));
  847. if (response.Status == 200)
  848. {
  849. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  850. scTeacher = json.ToObject<SchoolTeacher>();
  851. if (scTeacher.roles.Contains("admin"))
  852. {
  853. scTeacher.roles.Remove("admin");
  854. scTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(scTeacher, scTeacher.id, new PartitionKey($"Teacher-{scId}"));
  855. }
  856. else
  857. return Ok(new { state = RespondCode.NotFound, msg = "该账户不是管理员" });
  858. }
  859. else
  860. return Ok(new { state = RespondCode.NotFound,msg="未找到醍摩豆管理员信息" });
  861. return Ok(new { state = RespondCode.Ok , scTeacher });
  862. }
  863. /// <summary>
  864. /// 删除学校、学校相关的教师、学生
  865. /// </summary>
  866. /// <param name="jsonElement"></param>
  867. /// <returns></returns>
  868. [ProducesDefaultResponseType]
  869. [AuthToken(Roles = "admin,rdc")]
  870. [HttpPost("set-del")]
  871. public async Task<IActionResult> DelSchool(JsonElement jsonElement)
  872. {
  873. try
  874. {
  875. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  876. List<string> schools = schoolId.ToObject<List<string>>();
  877. jsonElement.TryGetProperty("site", out JsonElement site);
  878. string _auth = HttpContext.GetXAuth("AuthToken");
  879. var (tmdId, tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(_auth, _option);
  880. var cosmosClient = _azureCosmos.GetCosmosClient();
  881. var tableClient = _azureStorage.GetCloudTableClient();
  882. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  883. if ($"{site}".Equals(BIConst.Global))
  884. {
  885. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  886. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  887. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  888. }
  889. StringBuilder msg = new();
  890. List<DelSchoolRel> delSchoolRels = new();
  891. foreach (var tempId in schools)
  892. {
  893. List<string> scTchIds = new();
  894. List<string> scStuIds = new();
  895. string scTecSql = $"select value(c.id) from c where ARRAY_LENGTH(c.roles) > 0 and c.status = 'join'";
  896. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scTecSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{tempId}") }))
  897. {
  898. scTchIds.Add(item);
  899. }
  900. string scStuSql = $"select value(c.id) from c";
  901. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Student").GetItemQueryIterator<string>(queryText: scStuSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{tempId}") }))
  902. {
  903. scStuIds.Add(item);
  904. }
  905. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{tempId}", new PartitionKey($"Base"));
  906. if (response.Status == 204)
  907. msg.AppendLine($"{tmdName}【{tmdId}】删除学校,删除状态:{response.Status},删除ID:{tempId}");
  908. else
  909. delSchoolRels.Add(new DelSchoolRel() { id = $"{tempId}", code = "Base", type = 1, status = response.Status });
  910. foreach (var item in scTchIds)
  911. {
  912. var tchRespnse = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{item}", new PartitionKey($"Teacher-{tempId}"));
  913. if (tchRespnse.Status == 204)
  914. msg.AppendLine($"删除教师,删除状态:{tchRespnse.Status},删除ID:{item}");
  915. else
  916. delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Teacher-{tempId}", type = 2, status = response.Status });
  917. }
  918. foreach (var item in scStuIds)
  919. {
  920. var stuRespnse = await cosmosClient.GetContainer("TEAMModelOS", "Student").DeleteItemStreamAsync($"{item}", new PartitionKey($"Base-{tempId}"));
  921. if (stuRespnse.Status == 204)
  922. msg.AppendLine($"删除学生,删除状态:{stuRespnse.Status},删除ID:{item}");
  923. else
  924. delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Base-{tempId}", type = 3, status = response.Status });
  925. }
  926. }
  927. //string scTecSql = $"select value(c.id) from c where ARRAY_LENGTH(c.roles) > 0 and c.status = 'join'";
  928. //await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scTecSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{schoolId}") }))
  929. //{
  930. // scTchIds.Add(item);
  931. //}
  932. //string scStuSql = $"select value(c.id) from c";
  933. //await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scStuSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  934. //{
  935. // scStuIds.Add(item);
  936. //}
  937. //var response = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{schoolId}", new PartitionKey($"Base"));
  938. //if (response.Status == 204)
  939. // msg.AppendLine($"{tmdName}【{tmdId}】删除学校,删除状态:{response.Status},删除ID:{schoolId}");
  940. //else
  941. // delSchoolRels.Add(new DelSchoolRel() { id = $"{schoolId}", code = "Base", type = 1, status = response.Status });
  942. //foreach (var item in scTchIds)
  943. //{
  944. // var tchRespnse = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{item}", new PartitionKey($"Teacher-{schoolId}"));
  945. // if (tchRespnse.Status == 204)
  946. // msg.AppendLine($"删除教师,删除状态:{tchRespnse.Status},删除ID:{item}");
  947. // else
  948. // delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Teacher-{schoolId}", type = 2, status = response.Status });
  949. //}
  950. //foreach (var item in scStuIds)
  951. //{
  952. // var stuRespnse = await cosmosClient.GetContainer("TEAMModelOS", "Student").DeleteItemStreamAsync($"{item}", new PartitionKey($"Base-{schoolId}"));
  953. // if (stuRespnse.Status == 204)
  954. // msg.AppendLine($"删除学生,删除状态:{stuRespnse.Status},删除ID:{item}");
  955. // else
  956. // delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Base-{schoolId}", type = 3, status = response.Status });
  957. //}
  958. //保存操作记录
  959. //await _azureStorage.SaveBILog("set-del", msg.ToString(), _dingDing, httpContext: HttpContext);
  960. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "set-del", msg.ToString(), _dingDing, httpContext: HttpContext);
  961. if (delSchoolRels.Count > 0)
  962. return Ok(new { state = 201, delSchoolRels });
  963. else
  964. return Ok(new { state = 200 });
  965. }
  966. catch (Exception ex)
  967. {
  968. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/set-del \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  969. return BadRequest();
  970. }
  971. }
  972. /// <summary>
  973. /// 查询所有学校 第三方开放平台关联学校显示所有学校
  974. /// </summary>
  975. /// <param name="jsonElement"></param>
  976. /// <returns></returns>
  977. [HttpPost("get-applyschools")]
  978. public async Task<IActionResult> GetApplySchools(JsonElement jsonElement)
  979. {
  980. jsonElement.TryGetProperty("site", out JsonElement site);
  981. var cosmosClient = _azureCosmos.GetCosmosClient();
  982. var tableClient = _azureStorage.GetCloudTableClient();
  983. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  984. if ($"{site}".Equals(BIConst.Global))
  985. {
  986. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  987. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  988. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  989. }
  990. List<ApplySchool> applySchools = new();
  991. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ApplySchool>(queryText: "select c.id,c.code,c.name,c.picture from c",requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("Base")}))
  992. {
  993. applySchools.Add(item);
  994. }
  995. return Ok(new { state = 200, applySchools });
  996. }
  997. /// <summary>
  998. /// 通过学校Id查询详情 数据管理工具——查询工具
  999. /// </summary>
  1000. /// <returns></returns>
  1001. [HttpPost("get-info")]
  1002. public async Task<IActionResult> GetSchool(JsonElement jsonElement)
  1003. {
  1004. jsonElement.TryGetProperty("schoolId", out JsonElement schoolId);
  1005. jsonElement.TryGetProperty("site", out JsonElement site);
  1006. var cosmosClient = _azureCosmos.GetCosmosClient();
  1007. if ($"{site}".Equals(BIConst.Global))
  1008. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1009. StringBuilder sqlTxt = new StringBuilder("select * from c");
  1010. if (!string.IsNullOrEmpty($"{schoolId}"))
  1011. {
  1012. sqlTxt.Append($" where c.id='{schoolId}'");
  1013. }
  1014. List<School> schools = new();
  1015. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1016. {
  1017. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  1018. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1019. {
  1020. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1021. {
  1022. schools.Add(obj.ToObject<School>());
  1023. }
  1024. }
  1025. }
  1026. return Ok(new { state = 200, schools });
  1027. }
  1028. /// <summary>
  1029. /// 依据区域Id查询区域空间统计
  1030. /// </summary>
  1031. /// <param name="jsonElement"></param>
  1032. /// <returns></returns>
  1033. [ProducesDefaultResponseType]
  1034. [HttpPost("get-spance")]
  1035. public async Task<IActionResult> GetAreaSpace(JsonElement jsonElement)
  1036. {
  1037. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  1038. jsonElement.TryGetProperty("schoolId", out JsonElement schoolId);
  1039. jsonElement.TryGetProperty("site", out JsonElement site);
  1040. var cosmosClient = _azureCosmos.GetCosmosClient();
  1041. if ($"{site}".Equals(BIConst.Global))
  1042. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1043. long allSize = 0; //全部大小
  1044. int teacherSpace = 0; //学校分配给教师的空间
  1045. long useSize = 0; //已使用大小
  1046. Dictionary<string, double?> useSpaceInfo = new(); //学校使用详情
  1047. //查询区域所有学校
  1048. if (!string.IsNullOrEmpty($"{areaId}"))
  1049. {
  1050. List<string> schools = new();
  1051. schools = await CommonFind.FindSchoolIds(cosmosClient, $"select c.id from c where c.areaId='{areaId}'", "Base");
  1052. allSize = await CommonFind.FindTotals(cosmosClient, $"select sum(c.size) as totals from c where c.areaId='{areaId}'", new List<string> { "School" }); //区域所有学校空间
  1053. foreach (var school in schools)
  1054. {
  1055. 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}") }))
  1056. {
  1057. var json = await JsonDocument.ParseAsync(item.ContentStream);
  1058. foreach (var elmt in json.RootElement.GetProperty("Documents").EnumerateArray())
  1059. {
  1060. if (elmt.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
  1061. {
  1062. teacherSpace += _size.GetInt32();
  1063. break;
  1064. }
  1065. }
  1066. }
  1067. long blobsize = 0;
  1068. RedisValue value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", $"{school}");
  1069. if (!value.IsNullOrEmpty)
  1070. {
  1071. JsonElement record = value.ToString().ToObject<JsonElement>();
  1072. if (record.TryGetInt64(out blobsize))
  1073. {
  1074. }
  1075. }
  1076. else
  1077. {
  1078. var storageClient = _azureStorage.GetBlobContainerClient("school");
  1079. var size = await storageClient.GetBlobsCatalogSize();
  1080. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{school}", size.Item1);
  1081. foreach (var key in size.Item2.Keys)
  1082. {
  1083. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Bolb:Catalog:{school}", key);
  1084. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Bolb:Catalog:school", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1085. }
  1086. useSize += size.Item1.Value;
  1087. useSpaceInfo = useSpaceInfo.Concat(size.Item2).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1088. //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 方式合并
  1089. }
  1090. SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{school}");
  1091. if (Scores != null)
  1092. {
  1093. Dictionary<string, double?> catalog = new();
  1094. foreach (var score in Scores)
  1095. {
  1096. double val = score.Score;
  1097. string key = score.Element.ToString();
  1098. catalog.Add(key, val);
  1099. }
  1100. useSpaceInfo = useSpaceInfo.Concat(catalog).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1101. //useSpaceInfo = (from e in useSpaceInfo.Concat(catalog) 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 方式合并
  1102. }
  1103. else
  1104. {
  1105. var client = _azureStorage.GetBlobContainerClient("school");
  1106. var size = await client.GetBlobsCatalogSize();
  1107. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{school}", size.Item1);
  1108. foreach (var key in size.Item2.Keys)
  1109. {
  1110. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{school}", key);
  1111. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{school}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1112. }
  1113. useSize += size.Item1.Value;
  1114. useSpaceInfo = useSpaceInfo.Concat(size.Item2).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1115. //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 方式合并
  1116. }
  1117. }
  1118. }
  1119. //查询学校
  1120. if (!string.IsNullOrEmpty($"{schoolId}"))
  1121. {
  1122. allSize = await CommonFind.FindTotals(cosmosClient, $"SELECT c.size as totals FROM c where c.id='{schoolId}'", "School", "Base");
  1123. teacherSpace = await CommonFind.FindTotals(cosmosClient, $"SELECT sum(c.size) as totals FROM c", "School", $"Teacher-{schoolId}");
  1124. long blobsize = 0;
  1125. RedisValue value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", $"{schoolId}");
  1126. if (!value.IsNullOrEmpty)
  1127. {
  1128. JsonElement record = value.ToString().ToObject<JsonElement>();
  1129. if (record.TryGetInt64(out blobsize))
  1130. {
  1131. useSize = blobsize;
  1132. }
  1133. }
  1134. else
  1135. {
  1136. var storageClient = _azureStorage.GetBlobContainerClient("school");
  1137. var size = await storageClient.GetBlobsCatalogSize();
  1138. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{schoolId}", size.Item1);
  1139. foreach (var key in size.Item2.Keys)
  1140. {
  1141. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Bolb:Catalog:{schoolId}", key);
  1142. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Bolb:Catalog:school", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1143. }
  1144. useSpaceInfo = size.Item2;
  1145. }
  1146. Dictionary<string, double?> catalog = new();
  1147. SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{schoolId}");
  1148. if (Scores != null)
  1149. {
  1150. foreach (var score in Scores)
  1151. {
  1152. double val = score.Score;
  1153. string key = score.Element.ToString();
  1154. catalog.Add(key, val);
  1155. }
  1156. useSpaceInfo = catalog;
  1157. }
  1158. else
  1159. {
  1160. var client = _azureStorage.GetBlobContainerClient("school");
  1161. var size = await client.GetBlobsCatalogSize();
  1162. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{schoolId}", size.Item1);
  1163. foreach (var key in size.Item2.Keys)
  1164. {
  1165. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{schoolId}", key);
  1166. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{schoolId}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  1167. }
  1168. useSize = size.Item1.Value;
  1169. useSpaceInfo = size.Item2;
  1170. }
  1171. }
  1172. return Ok(new { state = 200, allSize, useSize, teacherSpace, useSpaceInfo });
  1173. }
  1174. /// <summary>
  1175. /// 依据学校统计
  1176. /// </summary>
  1177. /// <param name="jsonElement"></param>
  1178. /// <returns></returns>
  1179. [HttpPost("get-schoolcnt")]
  1180. public async Task<IActionResult> GetSchoolCnt(JsonElement jsonElement)
  1181. {
  1182. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  1183. jsonElement.TryGetProperty("site", out JsonElement site);
  1184. var cosmosClient = _azureCosmos.GetCosmosClient();
  1185. if ($"{site}".Equals(BIConst.Global))
  1186. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1187. DateTimeOffset dtime = DateTimeOffset.UtcNow;
  1188. var (weekS, weekE) = TimeHelper.GetStartOrEnd(dtime, "week");
  1189. var (lastWeekS, lastWeekE) = TimeHelper.GetStartOrEnd(dtime, "lastweek");
  1190. var (termS, termE) = TimeHelper.GetStartOrEnd(dtime, "term");
  1191. var (lastTermS, lastTermE) = TimeHelper.GetStartOrEnd(dtime, "lastterm");
  1192. var (yearS, yearE) = TimeHelper.GetStartOrEnd(dtime, "year");
  1193. var (lastYearS, lastYearE) = TimeHelper.GetStartOrEnd(dtime, "lastYear");
  1194. int tecCnt = 0;// 教师数量
  1195. int classCnt = 0; //班级
  1196. int stuCnt = 0; //学生
  1197. int roomCnt = 0; //智慧教室
  1198. int lesCnt = 0; //课例总数
  1199. int weekLesCnt = 0; //本周课例
  1200. int lastWeekLesCnt = 0; //上周课例
  1201. int weekACTCnt = 0; //本周活动
  1202. int lastWeekACTCnt = 0; //上周活动
  1203. int termLesCnt = 0; //本学期课例
  1204. int lastTermLesCnt = 0; //上学学期课例
  1205. int termACTCnt = 0; //本学期活动
  1206. int lastTermActCnt = 0; //上学学期活动
  1207. int yearLesCnt = 0; //今年课例
  1208. int lastYearLesCnt = 0; //去年课例
  1209. int yearACTCnt = 0; //今年课例
  1210. int lastYearACTCnt = 0; //去年课例
  1211. SchoolInfo schoolInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolInfo>($"{schoolId}", new PartitionKey("Base"));
  1212. if (schoolInfo != null)
  1213. {
  1214. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(schoolInfo.id, new PartitionKey("ProductSum"));
  1215. if (response.Status == 200)
  1216. {
  1217. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1218. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  1219. {
  1220. schoolInfo.serial = serial.ToObject<List<ProductSumInfos>>();
  1221. }
  1222. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  1223. {
  1224. schoolInfo.service = service.ToObject<List<ProductSumInfos>>();
  1225. }
  1226. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  1227. {
  1228. schoolInfo.hard = hard.ToObject<List<SchoolProductSumDataHard>>();
  1229. }
  1230. }
  1231. schoolInfo.assists = await CommonFind.FindSchoolRoles(cosmosClient, schoolInfo.id, "assist");
  1232. string currencySql = "select value(count(c.id)) from c";
  1233. //schoolInfo.lessonCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"LessonRecord-{schoolInfo.id}");
  1234. tecCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"Teacher-{schoolInfo.id}"); // 教师数量
  1235. classCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"Class-{schoolInfo.id}"); //班级
  1236. stuCnt = await CommonFind.GetSqlValueCount(cosmosClient, "Student", currencySql, $"Base-{schoolInfo.id}"); //学生
  1237. roomCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"Room-{schoolInfo.id}"); //智慧教室
  1238. lesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"LessonRecord-{schoolInfo.id}"); //课例总数
  1239. weekLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {weekS} and c.startTime<= {weekE}", $"LessonRecord-{schoolInfo.id}"); //本周课例
  1240. lastWeekLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {lastWeekS} and c.startTime<= {lastWeekE}", $"LessonRecord-{schoolInfo.id}"); //上周课例
  1241. termLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {termS} and c.startTime <= {termE}", $"LessonRecord-{schoolInfo.id}"); //本学期课例
  1242. lastTermLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {lastTermS} and c.startTime <= {lastTermE}", $"LessonRecord-{schoolInfo.id}"); //上学学期课例
  1243. yearLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {yearS} and c.startTime <= {yearE}", $"LessonRecord-{schoolInfo.id}"); //今年课例
  1244. lastYearLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {lastYearS} and c.startTime <= {lastYearE}", $"LessonRecord-{schoolInfo.id}"); //去年课例
  1245. int ACTCnt = 0; //活动
  1246. foreach (var type in StaticValue.activityTypes)
  1247. {
  1248. ACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}'");
  1249. weekACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {weekS} and c.createTime <= {weekE} "); //本周活动
  1250. lastWeekACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {lastWeekS} and c.createTime <= {lastWeekE} "); //上周活动
  1251. 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}"); //本学期活动
  1252. 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}"); //上学学期活动
  1253. 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}"); //今年活动
  1254. 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}"); //去年活动
  1255. }
  1256. return Ok(new { state = 200, tecCnt, classCnt, stuCnt, roomCnt, lesCnt, weekLesCnt, lastWeekLesCnt, weekACTCnt, lastWeekACTCnt, termLesCnt, lastTermLesCnt, termACTCnt, lastTermActCnt, yearLesCnt, lastYearLesCnt, yearACTCnt, lastYearACTCnt, schoolInfo, ACTCnt });
  1257. }
  1258. else
  1259. return Ok(new { state = 404, msg = "未找到该学校信息!" });
  1260. }
  1261. /// <summary>
  1262. /// 学校每周课例趋势
  1263. /// </summary>
  1264. /// <param name="jsonElement"></param>
  1265. /// <returns></returns>
  1266. [HttpPost("get-schooldate")]
  1267. public async Task<IActionResult> GetSchoolDate(JsonElement jsonElement)
  1268. {
  1269. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  1270. jsonElement.TryGetProperty("site", out JsonElement site);
  1271. var cosmosClient = _azureCosmos.GetCosmosClient();
  1272. if ($"{site}".Equals(BIConst.Global))
  1273. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1274. List<double> weekTrend = new();
  1275. int year = DateTimeOffset.UtcNow.Year;
  1276. int dayOfweek = (int)DateTimeOffset.Parse($"{year}-1-1").DayOfWeek;
  1277. int currentTime = DateTimeOffset.UtcNow.DayOfYear / 7 + 1;
  1278. int currentTime1 = DateTimeOffset.UtcNow.DayOfYear / 7;
  1279. //获取当前学期所有的课程记录
  1280. List<LessonRecord> records = new List<LessonRecord>();
  1281. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<LessonRecord>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{schoolId}") }))
  1282. {
  1283. records.Add(item);
  1284. }
  1285. List<(string name, int count)> grades = getGradeCount(records);
  1286. var subs = records.GroupBy(x => x.subjectId).Select(y => new { key = y.Key, count = y.ToList().Count }).ToList();
  1287. var gradeCnt = grades.Select(x => new { x.name, value = x.count });
  1288. var subCnt = subs.Select(x => new { name = x.key, value = x.count });
  1289. List<LessonCount> scount = new();
  1290. List<LessonCount> tcount = new();
  1291. 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}") }))
  1292. {
  1293. scount.Add(item);
  1294. }
  1295. List<string> teacIds = await CommonFind.FindRolesId(cosmosClient, new List<string>() { $"{schoolId}" });
  1296. foreach (var tId in teacIds)
  1297. {
  1298. var sqlTxtt = $"select value(c) from c where c.id='{tId}'";
  1299. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<LessonCount>(queryText: sqlTxtt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{year}") }))
  1300. {
  1301. tcount.Add(item);
  1302. }
  1303. }
  1304. int days = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? days = 366 : days = 365;
  1305. List<List<double>> lessons = new();
  1306. if (scount.Count > 0)
  1307. {
  1308. foreach (LessonCount item in scount)
  1309. {
  1310. lessons.Add(item.beginCount);
  1311. }
  1312. }
  1313. if (tcount.Count > 0)
  1314. {
  1315. foreach (LessonCount item in tcount)
  1316. {
  1317. lessons.Add(item.beginCount);
  1318. }
  1319. }
  1320. if (lessons.Count > 0)
  1321. {
  1322. var bmatrix = DenseMatrix.OfColumns(lessons);
  1323. //开学第一周周内开课
  1324. if (dayOfweek == 0)
  1325. {
  1326. dayOfweek = 7;
  1327. }
  1328. //第一周多少天
  1329. var dd = 7 - dayOfweek + 1;
  1330. //一年有几周
  1331. int sweeks = days / 7;
  1332. //查询天数
  1333. int dayYear = 0;
  1334. if (currentTime > 0)
  1335. {
  1336. for (int i = 0; i <= currentTime; i++)
  1337. {
  1338. if (i == 0)
  1339. {
  1340. var bsum = bmatrix.SubMatrix(dayYear, dd, 0, bmatrix.ColumnCount).ColumnSums().Sum();
  1341. dayYear += dd;
  1342. //weeks.Add(i, bsum);
  1343. weekTrend.Add(bsum);
  1344. }
  1345. else
  1346. {
  1347. var bsum = bmatrix.SubMatrix(dayYear, 7, 0, bmatrix.ColumnCount).ColumnSums().Sum();
  1348. dayYear += 7;
  1349. //weeks.Add(i, bsum);
  1350. weekTrend.Add(bsum);
  1351. }
  1352. }
  1353. }
  1354. //最后一周是否有余
  1355. int stary = days - dayYear;
  1356. if (stary > 0 && stary < 7)
  1357. {
  1358. var bsum = bmatrix.SubMatrix(dayYear, stary - 1, 0, bmatrix.ColumnCount).ColumnSums().Sum();
  1359. //weeks.Add((sweeks + 1), bsum);
  1360. weekTrend.Add(bsum);
  1361. }
  1362. }
  1363. return Ok(new { state = 200, gradeCnt, subCnt, weekTrend });
  1364. }
  1365. /// <summary>
  1366. /// 顾问学校基础统计、以及排行
  1367. /// </summary>
  1368. /// <param name="jsonElement"></param>
  1369. /// <returns></returns>
  1370. [ProducesDefaultResponseType]
  1371. [HttpPost("get-assisscbase")]
  1372. public async Task<IActionResult> GetAssistSchoolCnt(JsonElement jsonElement)
  1373. {
  1374. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  1375. jsonElement.TryGetProperty("site", out JsonElement site);
  1376. var cosmosClient = _azureCosmos.GetCosmosClient();
  1377. if ($"{site}".Equals(BIConst.Global))
  1378. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1379. DateTimeOffset dateTime = DateTimeOffset.UtcNow ;
  1380. int scAllCnt = 0; //学校
  1381. int tchAllCnt = 0; //教师数量
  1382. int tchMonthCnt = 0; //教师本月新增
  1383. int stuAllCnt = 0; //所有学校学生
  1384. int lessAllCnt = 0; //课例总数
  1385. int lessMthCnt = 0; //本月新增
  1386. List<ScRankCnt> scRankCnts = new(); //学校开课、上传, 课例排名
  1387. var (start, end) = TimeHelper.GetStartOrEnd(dateTime, "month");
  1388. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1389. string scIdSql = BICommonWay.ManyScSql("schoolId", schoolIds);
  1390. string stuSql = $"select value(count(c.id)) from c where {scIdSql}";
  1391. stuAllCnt = await CommonFind.GetSqlValueCount(cosmosClient, "Student", stuSql);
  1392. string scSql = BICommonWay.ManyScSql("school", schoolIds);
  1393. string lessMoSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and {scSql} and c.startTime >= {start} and c.startTime <= {end}";
  1394. lessMthCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessMoSql);
  1395. List<SchoolBase> scInfos = new();
  1396. string scInfoSql = $"select c.id,c.name,c.code,c.picture from c ";
  1397. scInfos = await CommonFind.GetObject<SchoolBase>(cosmosClient, "School", scInfoSql, "Base",schoolIds);
  1398. List<string> tchMonIds = new();
  1399. foreach (var item in scInfos)
  1400. {
  1401. ScRankCnt lessRankCnt = new() { id = item.id, name = item.name, code = item.code, picture = item.picture };
  1402. string tchSql = $"select value(count(c.id)) from c where array_contains(c.roles,'teacher',true) and c.createTime >= {start} and c.createTime <= {end}";
  1403. tchMonthCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", tchSql, $"Teacher-{item.id}");
  1404. string tchAllSql = $"select value(count(c.id)) from c where ARRAY_CONTAINS(c.roles,'teacher',true) and c.status = 'join'";
  1405. tchAllCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", tchAllSql, $"Teacher-{item.id}");
  1406. string lessALLSql = "select value(count(c.id)) from c where c.pk='LessonRecord'";
  1407. lessAllCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", lessALLSql, $"LessonRecord-{item.id}");
  1408. string lessUpSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and c.upload = 0";
  1409. lessRankCnt.openCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessMoSql, $"LessonRecord-{item.id}");
  1410. string lessSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and c.upload = 1";
  1411. lessRankCnt.lessCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessSql, $"LessonRecord-{item.id}");
  1412. string interactSql = $"select value(sum(c.clientInteractionCount)) from c where c.pk='LessonRecord'";
  1413. lessRankCnt.interCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", interactSql, $"LessonRecord-{item.id}");
  1414. string actSql = $" and c.school='{item.id}'";
  1415. lessRankCnt.actCnt = await ActivityWay.GetCnt(cosmosClient, actSql);
  1416. scRankCnts.Add(lessRankCnt);
  1417. }
  1418. scAllCnt = schoolIds.Count();
  1419. tchMonthCnt = tchMonIds.Distinct().Count();
  1420. return Ok(new { state = RespondCode.Ok, scAllCnt, tchAllCnt, tchMonthCnt, stuAllCnt, lessAllCnt, lessMthCnt, scRankCnts });
  1421. }
  1422. /// <summary>
  1423. /// 顾问所有学校一年的统计
  1424. /// </summary>
  1425. /// <param name="jsonElement"></param>
  1426. /// <returns></returns>
  1427. [ProducesDefaultResponseType]
  1428. [HttpPost("get-assissc")]
  1429. public async Task<IActionResult> GetAssisSc(JsonElement jsonElement)
  1430. {
  1431. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  1432. jsonElement.TryGetProperty("site", out JsonElement site);
  1433. var cosmosClient = _azureCosmos.GetCosmosClient();
  1434. if ($"{site}".Equals(BIConst.Global))
  1435. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1436. List <YearCnt> yearCnts = new(); //当前的课例,活动,互动统计
  1437. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1438. string strSql = "SELECT value(count(c.id)) FROM c where c.pk='LessonRecord'";
  1439. string scSql = BICommonWay.ManyScSql("school", schoolIds);
  1440. List<MonthStartEnd> mthStartEnds = await TimeHelper.GetYearSataMthCtMth(DateTimeOffset.UtcNow);
  1441. if (mthStartEnds.Count > 0)
  1442. {
  1443. foreach (var item in mthStartEnds)
  1444. {
  1445. YearCnt yearCnt = new() { name = item.yearMonth };
  1446. string selessSql = $"{strSql} and {scSql.ToString()} and c.startTime >= { item.start} and c.startTime <= {item.end}";
  1447. yearCnt.lessCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", selessSql);
  1448. 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}";
  1449. yearCnt.interCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", interactSql);
  1450. string mthActSql = $" and {scSql} and c.createTime >= {item.start} and c.createTime <= {item.end}";
  1451. yearCnt.actCnt = await ActivityWay.GetCnt(cosmosClient, mthActSql);
  1452. yearCnts.Add(yearCnt);
  1453. }
  1454. }
  1455. return Ok(new { state = RespondCode.Ok, yearCnts, });
  1456. }
  1457. /// <summary>
  1458. /// 顾问学校统计
  1459. /// </summary>
  1460. /// <param name="jsonElement"></param>
  1461. /// <returns></returns>
  1462. [ProducesDefaultResponseType]
  1463. [HttpPost("get-assissccnt")]
  1464. public async Task<IActionResult> GetAssisScCnt(JsonElement jsonElement)
  1465. {
  1466. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  1467. jsonElement.TryGetProperty("site", out JsonElement site);
  1468. var cosmosClient = _azureCosmos.GetCosmosClient();
  1469. if ($"{site}".Equals(BIConst.Global))
  1470. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1471. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1472. var (days, daye) = TimeHelper.GetStartOrEnd(dateTime);
  1473. var (lastDays, lastDaye) = TimeHelper.GetStartOrEnd(dateTime.AddDays(-1));
  1474. var (years, yeare) = TimeHelper.GetStartOrEnd(dateTime, "year");
  1475. var (lastYears, lastYeare) = TimeHelper.GetStartOrEnd(dateTime, "lastYear");
  1476. int lessAll = 0; //所以课例
  1477. int lessLastdayCnt = 0; //昨天的课例
  1478. int lessDayCnt = 0; //今天的课例
  1479. int lessLastYarCnt = 0; //去年的课例
  1480. int lessYearCnt = 0; //去年的课例
  1481. int interAll = 0; //所有互动总数
  1482. int lastDayInterCnt = 0; // 昨天课例互动
  1483. int interCnt = 0; // 今天课例互动
  1484. int lastYarInterCnt = 0; // 去年课例互动
  1485. int yearInterCnt = 0; // 今年课例互动
  1486. int actAllCnt = 0; //所有活动
  1487. int lastActCnt = 0; //昨天活动
  1488. int actCnt = 0; //今天活动
  1489. int lastYearActCn = 0; //去年活动
  1490. int yearActCn = 0; //今年活动
  1491. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  1492. string scSql = BICommonWay.ManyScSql("school", schoolIds);
  1493. string strSql = "SELECT value(count(c.id)) FROM c where c.pk='LessonRecord'";
  1494. //课例
  1495. lessAll = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{strSql} and {scSql}");
  1496. string lessLastdaySql = $"{strSql} and {scSql} and c.startTime >= { lastDays} and c.startTime <= {lastDays} ";
  1497. lessLastdayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastdaySql);
  1498. string lessDaySql = $"{strSql} and {scSql} and c.startTime >= { days} and c.startTime <= {daye} ";
  1499. lessDayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessDaySql);
  1500. string lessLastYarSql = $"{strSql} and {scSql} and c.startTime >= { lastYears} and c.startTime <= {lastYeare} ";
  1501. lessLastYarCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastYarSql);
  1502. string lessYearSql = $"{strSql} and {scSql} and c.startTime >= { years} and c.startTime <= {yeare} ";
  1503. lessYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessYearSql);
  1504. //课例互动
  1505. string strInterSql = $"select value(sum(c.clientInteractionAverge)) from c where c.pk='LessonRecord' and {scSql}";
  1506. interAll = await CommonFind.GetSqlValueCount(cosmosClient, "School", strInterSql);
  1507. string lastdayInterSql = $"{strInterSql} and c.startTime >= { lastDays} and c.startTime <= {lastDays} ";
  1508. lastDayInterCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lastdayInterSql);
  1509. string dayInterSql = $"{strInterSql} and c.startTime >= { days} and c.startTime <= {daye} ";
  1510. interCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", dayInterSql);
  1511. string lastYarInterSql = $"{strInterSql} and c.startTime >= { lastYears} and c.startTime <= {lastYeare} ";
  1512. lastYarInterCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lastYarInterSql);
  1513. string yearInterSql = $"{strInterSql} and c.startTime >= { years} and c.startTime <= {yeare} ";
  1514. yearInterCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", yearInterSql);
  1515. //活动
  1516. string actAllSql = $" and {scSql} ";
  1517. actAllCnt = await ActivityWay.GetCnt(cosmosClient, actAllSql);
  1518. string lastActSql = $" and {scSql} and c.createTime >= {lastDays} and c.createTime <= {lastDays}";
  1519. lastActCnt = await ActivityWay.GetCnt(cosmosClient, lastActSql);
  1520. string actSql = $" and {scSql} and c.createTime >= {days} and c.createTime <= {daye}";
  1521. actCnt = await ActivityWay.GetCnt(cosmosClient, actSql);
  1522. string lastYearActSql = $" and {scSql} and c.createTime >= {lastYears} and c.createTime <= {lastYeare}";
  1523. lastYearActCn = await ActivityWay.GetCnt(cosmosClient, lastYearActSql);
  1524. string yearActSql = $" and {scSql} and c.createTime >= {years} and c.createTime <= {yeare}";
  1525. yearActCn = await ActivityWay.GetCnt(cosmosClient, yearActSql);
  1526. return Ok(new { state = RespondCode.Ok, lessAll, lessLastdayCnt, lessDayCnt, lessLastYarCnt, lessYearCnt, interAll, lastDayInterCnt, interCnt, lastYarInterCnt, yearInterCnt, actAllCnt, lastActCnt, actCnt, lastYearActCn, yearActCn });
  1527. }
  1528. /// <summary>
  1529. /// 依据年级统计
  1530. /// </summary>
  1531. /// <param name="records"></param>
  1532. /// <returns></returns>
  1533. private List<(string name, int count)> getGradeCount(List<LessonRecord> records)
  1534. {
  1535. List<string> grades = new();
  1536. List<(string name, int count)> gCount = new();
  1537. foreach (var record in records)
  1538. {
  1539. foreach (string gId in record.grade)
  1540. {
  1541. if (!grades.Contains(gId))
  1542. {
  1543. grades.Add(gId);
  1544. }
  1545. }
  1546. }
  1547. foreach (var gId in grades)
  1548. {
  1549. var c = records.Where(r => r.grade.Contains(gId)).Count();
  1550. gCount.Add((gId, c));
  1551. }
  1552. return gCount;
  1553. }
  1554. #region 顾问学校统计返回值
  1555. public record ScRankCnt : SchoolBase
  1556. {
  1557. public int openCnt { get; set; }
  1558. public int lessCnt { get; set; }
  1559. public int interCnt { get; set; }
  1560. public int actCnt { get; set; }
  1561. }
  1562. public record YearCnt
  1563. {
  1564. public string name { get; set; }
  1565. public int lessCnt { get; set; }
  1566. public int interCnt { get; set; }
  1567. public int actCnt { get; set; }
  1568. }
  1569. public record SchoolBase
  1570. {
  1571. public string id { get; set; }
  1572. public string code { get; set; }
  1573. public string name { get; set; }
  1574. public string picture { get; set; }
  1575. }
  1576. #endregion
  1577. public record ApplySchool
  1578. {
  1579. public string id { get; set; }
  1580. public string code { get; set; }
  1581. public string name { get; set; }
  1582. public string picture { get; set; }
  1583. }
  1584. /// <summary>
  1585. /// 未加入区域的学校
  1586. /// </summary>
  1587. public record NotAreaSchool
  1588. {
  1589. public string id { get; set; }
  1590. public string name { get; set; }
  1591. public string schoolCode { get; set; }
  1592. public string picture { get; set; }
  1593. public List<string> period { get; set; }
  1594. public string province { get; set; }
  1595. public string city { get; set; }
  1596. public string dist { get; set; }
  1597. public string areaId { get; set; }
  1598. public string standard { get; set; }
  1599. public List<SchoolArea> areas { get; set; } = new List<SchoolArea>();
  1600. }
  1601. /// <summary>
  1602. /// 学校空间使用情况
  1603. /// </summary>
  1604. public record SchoolSpace
  1605. {
  1606. public string id { get; set; }
  1607. public string name { get; set; }
  1608. public Space space { get; set; }
  1609. }
  1610. /// <summary>
  1611. /// 空间
  1612. /// </summary>
  1613. public record Space
  1614. {
  1615. /// <summary>
  1616. /// 已使用空间
  1617. /// </summary>
  1618. public long useSize { get; set; }
  1619. /// <summary>
  1620. /// 分配教师空间
  1621. /// </summary>
  1622. public long tSize { get; set; }
  1623. /// <summary>
  1624. /// 空间类型
  1625. /// </summary>
  1626. public Dictionary<string, double?> catalogSize { get; set; }
  1627. }
  1628. public record DelSchoolRel
  1629. {
  1630. public string id { get; set; }
  1631. public string code { get; set; }
  1632. /// <summary>
  1633. /// 未删除的类型 1 学校 2教师 3学生
  1634. /// </summary>
  1635. public int type { get; set; }
  1636. public int status { get; set; }
  1637. }
  1638. }
  1639. }