SchoolController.cs 147 KB

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