SchoolController.cs 112 KB

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