SchoolController.cs 152 KB

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