SchoolController.cs 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  1. using Azure.Core;
  2. using Microsoft.Azure.Cosmos;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Options;
  5. using Pipelines.Sockets.Unofficial.Arenas;
  6. using StackExchange.Redis;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Text.Json;
  12. using System.Threading.Tasks;
  13. using TEAMModelBI.Models;
  14. using TEAMModelBI.Tool;
  15. using TEAMModelBI.Tool.CosmosBank;
  16. using TEAMModelOS.Models;
  17. using TEAMModelOS.SDK.Context.Constant;
  18. using TEAMModelOS.SDK.DI;
  19. using TEAMModelOS.SDK.Extension;
  20. using TEAMModelOS.SDK.Models;
  21. using TEAMModelOS.SDK.Models.Cosmos.BI;
  22. using TEAMModelOS.SDK.Models.Cosmos.BI.BISchool;
  23. using TEAMModelOS.SDK.Models.Service.BI;
  24. using TEAMModelOS.SDK.Models.Service.BIStatsWay;
  25. using LessonStats = TEAMModelOS.SDK.Models.Cosmos.BI.LessonStats;
  26. namespace TEAMModelBI.Controllers.Census
  27. {
  28. [Route("school")]
  29. [ApiController]
  30. public class SchoolController : ControllerBase
  31. {
  32. private readonly AzureCosmosFactory _azureCosmos;
  33. private readonly AzureStorageFactory _azureStorage;
  34. private readonly DingDing _dingDing;
  35. private readonly Option _option;
  36. private readonly HttpTrigger _httpTrigger;
  37. private readonly AzureRedisFactory _azureRedis;
  38. public SchoolController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, HttpTrigger httpTrigger, AzureRedisFactory azureRedis)
  39. {
  40. _azureCosmos = azureCosmos;
  41. _azureStorage = azureStorage;
  42. _dingDing = dingDing;
  43. _option = option?.Value;
  44. _httpTrigger = httpTrigger;
  45. _azureRedis = azureRedis;
  46. }
  47. /// <summary>
  48. /// 统计所有分析:基础、课例、活动、资源
  49. /// </summary>
  50. /// <param name="jsonElement"></param>
  51. /// <returns></returns>
  52. [ProducesDefaultResponseType]
  53. [HttpPost("get-all")]
  54. public async Task<IActionResult> GetAll(JsonElement jsonElement)
  55. {
  56. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  57. var cosmosClient = _azureCosmos.GetCosmosClient();
  58. //////分开部署,就不需要,一站多用时,取消注释
  59. //if ($"{site}".Equals(BIConst.Global))
  60. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  61. long schoolCount = 0; //学校数量
  62. int tecCount = 0; //教师数量
  63. int stuCount = 0; //学生数量
  64. long roomCount = 0; //教室数量
  65. long wisdomRoomCount = 0; //智慧教室数量
  66. long allClassCount = 0; //所有班级
  67. long allLessCount = 0; //所有课例
  68. long lastYearLessCount = 0; //去年课例
  69. long yearLessCount = 0;//今年课例
  70. long lastWeekLessCount = 0; //上周课例
  71. long weekLessCount = 0; //本周课例
  72. long lastTermLessCount = 0; //上学期课例
  73. long termLessCount = 0; //本学期课例
  74. long allActivityCount = 0; //所有活动
  75. long lastActivityCount = 0; //去年活动
  76. long activityCount = 0; //今年活动
  77. long lastWeekActivitCount = 0; //上周活动
  78. long weekActivitCount = 0; //本周活动
  79. long lastTermActivitCount = 0; //上学期活动
  80. long TermActivitCount = 0; //本学期学期活动
  81. long rercCount = 0; //所有资源数量
  82. long weekRercCount = 0; //本周资源数量
  83. long lastWeekRercCount = 0; //上周资源数量
  84. long lastTermRercCount = 0; //上学期资源
  85. long termRercCount = 0; //本学期资源
  86. long lastYearRercCount = 0; //去年资源
  87. long yearRercCount = 0; //去年资源
  88. var (lastYearStart, lastYearEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.Parse($"{DateTimeOffset.UtcNow.Year - 1}-1-1"), "year"); //计算去年开始/结束时间
  89. var (yearStart, yearEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "year"); //计算今年开始/结束时间
  90. var (lastWeekStart, lastWeekEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastweek"); //计算上周开始/结束时间
  91. var (weekStart, weekEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "week"); //计算本周开始/结束时间
  92. var (lastTermStart, lastTermEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastterm"); //计算上学期开始/结束时间
  93. var (termStart, termEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "term"); //计算本学期开始/结束时间
  94. schoolCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", "select value(count(c.id)) from c", "Base"); //所有学校数量
  95. tecCount = await CommonFind.GetSqlValueCount(cosmosClient, "Teacher", "select value(count(c.id)) from c", "Base"); //所有教师数量
  96. stuCount = await CommonFind.GetSqlValueCount(cosmosClient, "Student", "select value(count(c.id)) from c", "Base"); //所有学生数量
  97. allClassCount = await CommonFind.GetSqlValueCount(cosmosClient, new List<string>() { "School" }, "select count(c.id) totals from c where c.pk = 'Class'"); //所有班级数量
  98. roomCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", "select value(count(c.id)) from c where c.pk = 'Room'"); //所有教室数量
  99. wisdomRoomCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", "select value(count(c.id)) from c where c.pk = 'Room' and c.serial != null"); //智慧教室数量
  100. List<string> containers = new() { "School", "Teacher" };
  101. string lessSqlTxt = "select value(count(c.id)) from c where c.pk='LessonRecord' and c.startTime>={0} and c.startTime<={1}";
  102. allLessCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, $"select count(c.id) as totals from c where c.pk='LessonRecord'");//所有课例
  103. lastYearLessCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, string.Format(lessSqlTxt, lastYearStart, lastYearEnd)); //去年课例
  104. yearLessCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, string.Format(lessSqlTxt, yearStart, yearEnd)); //今年课例
  105. lastWeekLessCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, string.Format(lessSqlTxt, lastWeekStart, lastWeekEnd)); //上周课例
  106. weekLessCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, string.Format(lessSqlTxt, weekStart, weekEnd)); //本周课例
  107. lastTermLessCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, string.Format(lessSqlTxt, lastTermStart, lastTermEnd)); //上学期课例
  108. termLessCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, string.Format(lessSqlTxt, termStart, termEnd)); //上学期课例
  109. string typeSqlTxt = "select value(count(c.id)) from c where c.pk='{0}' and c.createTime >={1} and c.createTime<= {2}";
  110. foreach (var type in StaticValue.activityTypes)
  111. {
  112. allActivityCount += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"select value(count(c.id)) from c where c.pk='{type}' ");//所有活动
  113. lastActivityCount += await CommonFind.GetSqlValueCount(cosmosClient, "Common", string.Format(typeSqlTxt, type, lastYearStart, lastYearEnd)); //去年活动
  114. activityCount += await CommonFind.GetSqlValueCount(cosmosClient, "Common", string.Format(typeSqlTxt, type, yearStart, yearEnd)); //今年活动
  115. lastWeekActivitCount += await CommonFind.GetSqlValueCount(cosmosClient, "Common", string.Format(typeSqlTxt, type, lastWeekStart, lastWeekEnd)); //上周活动
  116. weekActivitCount += await CommonFind.GetSqlValueCount(cosmosClient, "Common", string.Format(typeSqlTxt, type, weekStart, weekEnd)); //本周活动
  117. lastTermActivitCount += await CommonFind.GetSqlValueCount(cosmosClient, "Common", string.Format(typeSqlTxt, type, lastTermStart, lastTermEnd)); //上学期活动
  118. TermActivitCount += await CommonFind.GetSqlValueCount(cosmosClient, "Common", string.Format(typeSqlTxt, type, termStart, termEnd)); //本学期学期活动
  119. }
  120. string bloblSqlTxt = "select value(count(c.id)) from c where c.pk='Bloblog' and c.time>={0} and c.time<={1}";
  121. rercCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, "select value(count(c.id)) from c where c.pk='Bloblog'"); //所有资源
  122. lastWeekRercCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, string.Format(bloblSqlTxt, lastWeekStart, lastWeekEnd)); //上周资源
  123. weekRercCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, string.Format(bloblSqlTxt, weekStart, weekEnd)); //本周资源
  124. lastTermRercCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, string.Format(bloblSqlTxt, lastTermStart, lastTermEnd)); //上学期资源
  125. termRercCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, string.Format(bloblSqlTxt, termStart, termEnd)); //这学期资源
  126. lastYearRercCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, string.Format(bloblSqlTxt, lastYearStart, lastYearEnd)); //去年资源
  127. yearRercCount = await CommonFind.GetSqlValueCount(cosmosClient, containers, string.Format(bloblSqlTxt, yearStart, yearEnd)); //今年资源
  128. return Ok(new { state = 200, schoolCount, tecCount, stuCount, allClassCount, roomCount, wisdomRoomCount, allLessCount, lastYearLessCount, yearLessCount, lastWeekLessCount, weekLessCount, lastTermLessCount, termLessCount, allActivityCount, lastActivityCount, activityCount, lastWeekActivitCount, weekActivitCount, lastTermActivitCount, TermActivitCount, rercCount, lastWeekRercCount, weekRercCount, lastTermRercCount, termRercCount, lastYearRercCount, yearRercCount });
  129. }
  130. /// <summary>
  131. /// 查询顾问相关的学校统计数据
  132. /// </summary>
  133. /// <param name="jsonElement"></param>
  134. /// <returns></returns>
  135. [ProducesDefaultResponseType]
  136. [HttpPost("get-assist")]
  137. public async Task<IActionResult> GetAssistStatis(JsonElement jsonElement)
  138. {
  139. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  140. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  141. int tecCount = 0; //教师数量
  142. int stuCount = 0; //学校数量
  143. int classCount = 0; //班级数量
  144. int roomCount = 0; //智慧教师数量
  145. int allLessonCount = 0; //课例数量
  146. int lastWeekLessCount = 0;// 上周课例数
  147. int weekLessCount = 0; //本周课例
  148. int lastTermLessCount = 0;// 上学期课例数
  149. int termLessCount = 0; //本学期课例
  150. int lastYearLessCount = 0; //去年课例
  151. int yearLessCount = 0; //今年课例
  152. int allBloblog = 0; //学校资源
  153. int lastYearBloblog = 0; //去年学校资源
  154. int yearBloblog = 0; //今年学校资源
  155. long allActivity = 0; //学校所有活动
  156. long lastYearActivity = 0; //去年学校所有活动
  157. long yearActivity = 0; //今年学校所有活动
  158. long lastWeekActivity = 0; //上周学校所有活动
  159. long weekActivity = 0; //本周学校所有活动
  160. var cosmosClient = _azureCosmos.GetCosmosClient();
  161. ////分开部署,就不需要,一站多用时,取消注释
  162. //if ($"{site}".Equals(BIConst.Global))
  163. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  164. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  165. var (lastWeekStart, lastWeekEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastweek"); //计算上周开始/结束时间
  166. var (weekStart, weekEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "week"); //计算本周开始/结束时间
  167. var (lastTermStart, lastTermEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastterm"); //计算上学期开始/结束时间
  168. var (termStart, termEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "term"); //计算本学期开始/结束时间
  169. var (lastYearStart, lastYearEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.Parse($"{DateTimeOffset.UtcNow.Year - 1}-1-1"), "year"); //计算去年开始/结束时间
  170. var (yearStart, yearEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "year"); //计算今年开始/结束时间
  171. string unifySqlTxt = "select value(count(c.id)) from c";
  172. string unifyTimeSql = "select value(count(c.id)) from c where c.startTime>={0} and c.startTime<={1}";
  173. string blobTimeSql = "select value(count(c.id)) from c where c.time>={0} and c.time<={1}";
  174. List<RecSchoolDate> recSchoolDates = new();
  175. foreach (var itemId in schoolIds)
  176. {
  177. School school = new();
  178. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(itemId, new PartitionKey("Base"));
  179. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  180. {
  181. using var json = await JsonDocument.ParseAsync(response.Content);
  182. school = json.ToObject<School>();
  183. }
  184. tecCount += await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c where ARRAY_CONTAINS(c.roles,'teacher',true) and c.status = 'join'", $"Teacher-{itemId}");
  185. stuCount += await CommonFind.GetSqlValueCount(cosmosClient, "Student", unifySqlTxt, $"Base-{itemId}");
  186. classCount += await CommonFind.GetSqlValueCount(cosmosClient, "School", unifySqlTxt, $"Class-{itemId}");
  187. roomCount += await CommonFind.GetSqlValueCount(cosmosClient, "School", unifySqlTxt, $"Room-{itemId}");
  188. //学校所有课例
  189. int tempLessCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", unifySqlTxt, $"LessonRecord-{itemId}");
  190. lastWeekLessCount += await CommonFind.GetSqlValueCount(cosmosClient, "School", string.Format(unifyTimeSql, lastWeekStart, lastWeekEnd), $"LessonRecord-{itemId}");
  191. weekLessCount += await CommonFind.GetSqlValueCount(cosmosClient, "School", string.Format(unifyTimeSql, weekStart, weekEnd), $"LessonRecord-{itemId}");
  192. lastTermLessCount += await CommonFind.GetSqlValueCount(cosmosClient, "School", string.Format(unifyTimeSql, lastTermStart, lastTermEnd), $"LessonRecord-{itemId}");
  193. termLessCount += await CommonFind.GetSqlValueCount(cosmosClient, "School", string.Format(unifyTimeSql, termStart, termEnd), $"LessonRecord-{itemId}");
  194. lastYearLessCount += await CommonFind.GetSqlValueCount(cosmosClient, "School", string.Format(unifyTimeSql, lastYearStart, lastYearEnd), $"LessonRecord-{itemId}");
  195. yearLessCount += await CommonFind.GetSqlValueCount(cosmosClient, "School", string.Format(unifyTimeSql, yearStart, yearEnd), $"LessonRecord-{itemId}");
  196. //学校资源
  197. int tempBloblog = await CommonFind.GetSqlValueCount(cosmosClient, "School", unifySqlTxt, $"Bloblog-{itemId}");
  198. lastYearBloblog += await CommonFind.GetSqlValueCount(cosmosClient, "School", string.Format(blobTimeSql, lastYearStart, lastYearEnd), $"Bloblog-{itemId}");
  199. yearBloblog += await CommonFind.GetSqlValueCount(cosmosClient, "School", string.Format(blobTimeSql, yearStart, yearEnd), $"Bloblog-{itemId}");
  200. //学校活动
  201. long tempallActivity = 0;
  202. //统计活动
  203. foreach (var type in StaticValue.activityTypes)
  204. {
  205. string sqlTime = "SELECT value(count(c.id)) FROM c where c.pk = '{0}' and c.school = '{1}' and c.createTime>={2} and c.createTime<={3}";
  206. tempallActivity += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"SELECT value(count(c.id)) FROM c where c.pk = '{type}' and c.school = '{itemId}'");
  207. lastYearActivity += await CommonFind.GetSqlValueCount(cosmosClient, "Common", string.Format(sqlTime, type, itemId, lastYearStart, lastYearEnd));
  208. yearActivity += await CommonFind.GetSqlValueCount(cosmosClient, "Common", string.Format(sqlTime, type, itemId, yearStart, yearEnd));
  209. lastWeekActivity += await CommonFind.GetSqlValueCount(cosmosClient, "Common", string.Format(sqlTime, type, itemId, lastWeekStart, lastWeekEnd));
  210. weekActivity += await CommonFind.GetSqlValueCount(cosmosClient, "Common", string.Format(sqlTime, type, itemId, weekStart, weekEnd));
  211. }
  212. allLessonCount += tempLessCount;
  213. allActivity += tempallActivity;
  214. allBloblog += tempBloblog;
  215. recSchoolDates.Add(new RecSchoolDate() { id = school.id, name = school.name, dataCount = (tempLessCount + tempallActivity + tempBloblog) });
  216. }
  217. return Ok(new { state = 200, schoolCount = schoolIds.Count, tecCount, stuCount, classCount, roomCount, allLessonCount, lastWeekLessCount, weekLessCount, lastTermLessCount, termLessCount, lastYearLessCount, yearLessCount, allBloblog, lastYearBloblog, yearBloblog, allActivity, lastYearActivity, yearActivity, lastWeekActivity, weekActivity, recSchoolDates });
  218. }
  219. /// <summary>
  220. /// 依据学校Id统计学校分析
  221. /// </summary>
  222. /// <param name="jsonElement"></param>
  223. /// <returns></returns>
  224. [ProducesDefaultResponseType]
  225. [HttpPost("get-idstatis")]
  226. public async Task<IActionResult> GetIdStatis(JsonElement jsonElement)
  227. {
  228. if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
  229. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  230. int tecCount = 0; //学校教师数量
  231. int stuCount = 0; //学校学生数量
  232. int classCount = 0; //班级数量
  233. int roomCount = 0; //教室教师数量
  234. long allLessCount = 0; //课例总数
  235. int lastWeekLess = 0; //上周的总数
  236. int weekLess = 0; //本周的总数
  237. int lastTermLess = 0; //上学期的总数
  238. int termLess = 0; //本学期的总数
  239. int lessYearLess = 0; //去年的总数
  240. int yearLess = 0; //去年的总数
  241. int allActivity = 0; //学校所有活动
  242. int lastYearActivity = 0; //去年学校所有活动
  243. int yearActivity = 0; //今年学校所有活动
  244. int lastWeekActivity = 0; //上周学校所有活动
  245. int weekActivity = 0; //本周学校所有活动
  246. int allBlob = 0; //所有资源
  247. int lastYearBlob = 0; //去年的资源
  248. int yearBlob = 0; //去年的资源
  249. var cosmosClient = _azureCosmos.GetCosmosClient();
  250. ////分开部署,就不需要,一站多用时,取消注释
  251. //if ($"{site}".Equals(BIConst.Global))
  252. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  253. var (lastWeekStart, lastWeekEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastweek"); //计算上周开始/结束时间
  254. var (weekStart, weekEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "week"); //计算本周开始/结束时间
  255. var (lastTermStart, lastTermEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastterm"); //计算上学期开始/结束时间
  256. var (termStart, termEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "term"); //计算本学期开始/结束时间
  257. var (lastYearStart, lastYearEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.Parse($"{DateTimeOffset.UtcNow.Year - 1}-1-1"), "year"); //计算去年开始/结束时间
  258. var (yearStart, yearEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "year"); //计算今年开始/结束时间
  259. tecCount = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Teacher-{schoolId}", "SELECT value(count(c.id)) FROM c WHERE ARRAY_CONTAINS(c.roles, 'teacher', true) AND c.status = 'join'");
  260. stuCount = await JointlySingleQuery.GetValueInt(cosmosClient, "Student", $"Base-{schoolId}");
  261. classCount = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Class-{schoolId}");
  262. roomCount = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Room-{schoolId}");
  263. string unifyTimeSql = "select value(count(c.id)) from c where c.startTime>={0} and c.startTime<={1}";
  264. allLessCount = await LessonStatisWay.GetSchoolIdLessonCount(cosmosClient, $"{schoolId}");
  265. lastWeekLess = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"LessonRecord-{schoolId}", string.Format(unifyTimeSql, lastWeekStart, lastWeekEnd));
  266. weekLess = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"LessonRecord-{schoolId}", string.Format(unifyTimeSql, weekStart, lastWeekEnd));
  267. lastTermLess = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"LessonRecord-{schoolId}", string.Format(unifyTimeSql, lastTermStart, lastTermEnd));
  268. termLess = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"LessonRecord-{schoolId}", string.Format(unifyTimeSql, termStart, termEnd));
  269. lessYearLess = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"LessonRecord-{schoolId}", string.Format(unifyTimeSql, lastYearStart, lastYearEnd));
  270. yearLess = await JointlySingleQuery.GetValueInt(cosmosClient, "School", string.Format(unifyTimeSql, yearStart, yearEnd), $"LessonRecord-{schoolId}");
  271. //统计活动
  272. foreach (var type in StaticValue.activityTypes)
  273. {
  274. string sqlTime = "select value(count(c.id)) from c where c.pk = '{0}' and c.school = '{1}' and c.createTime>={2} and c.createTime<={3}";
  275. allActivity += await JointlySingleQuery.GetValueInt(cosmosClient, "Common", $"{type}-{schoolId}", $"select value(count(c.id)) from c where c.pk = '{type}' and c.school = '{schoolId}'");
  276. lastYearActivity += await JointlySingleQuery.GetValueInt(cosmosClient, "Common", $"{type}-{schoolId}", string.Format(sqlTime, type, schoolId, lastYearStart, lastYearEnd));
  277. yearActivity += await JointlySingleQuery.GetValueInt(cosmosClient, "Common", $"{type}-{schoolId}", string.Format(sqlTime, type, schoolId, yearStart, yearEnd));
  278. lastWeekActivity += await JointlySingleQuery.GetValueInt(cosmosClient, "Common", $"{type}-{schoolId}", string.Format(sqlTime, type, schoolId, lastWeekStart, lastWeekEnd));
  279. weekActivity += await JointlySingleQuery.GetValueInt(cosmosClient, "Common", $"{type}-{schoolId}", string.Format(sqlTime, type, schoolId, weekStart, weekEnd));
  280. }
  281. //学校资源
  282. string blobTimeSql = "select value(count(c.id)) from c where c.time>={0} and c.time<={1}";
  283. allBlob = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Bloblog-{schoolId}");
  284. lastYearBlob = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Bloblog-{schoolId}", string.Format(blobTimeSql, lastYearStart, lastYearEnd));
  285. yearBlob = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Bloblog-{schoolId}", string.Format(blobTimeSql, yearStart, yearEnd));
  286. //获取所有的课程记录
  287. List<LessonRecord> records = new();
  288. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<LessonRecord>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{schoolId}") }))
  289. {
  290. records.Add(item);
  291. }
  292. List<(string name, int count)> gradeCount = new();
  293. if (records.Count > 0)
  294. {
  295. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{schoolId}", new PartitionKey($"Base"));
  296. School sc = new();
  297. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  298. {
  299. using var json = await JsonDocument.ParseAsync(response.Content);
  300. sc = json.ToObject<School>();
  301. }
  302. List<string> grades = new();
  303. foreach (var item in records)
  304. {
  305. foreach (string gId in item.grade)
  306. {
  307. if (!grades.Contains(gId))
  308. {
  309. grades.Add(gId);
  310. }
  311. }
  312. }
  313. foreach (var gId in grades)
  314. {
  315. var c = records.Where(r => r.grade.Contains(gId)).Count();
  316. gradeCount.Add((gId, c));
  317. }
  318. }
  319. return Ok(new { state = 200, tecCount, stuCount, classCount, roomCount, allLessCount, lastWeekLess, weekLess, lastTermLess, termLess, lessYearLess, yearLess, allActivity, lastYearActivity, yearActivity, lastWeekActivity, weekActivity, allBlob, lastYearBlob, yearBlob });
  320. }
  321. /// <summary>
  322. /// 未区域学校统计
  323. /// </summary>
  324. /// <param name="jsonElement"></param>
  325. /// <returns></returns>
  326. [ProducesDefaultResponseType]
  327. [HttpPost("get-noarea")]
  328. public async Task<IActionResult> GetNoAreaCnt(JsonElement jsonElement)
  329. {
  330. var cosmosClient = _azureCosmos.GetCosmosClient();
  331. int tLessCnt = 0; //课例
  332. int tActCnt = 0; //活动
  333. List<string> scIds = new(); //学校id集合
  334. string scIdSql = "select value(c.id) from c where c.areaId=null or c.areaId=''";
  335. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<string>(queryText: scIdSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  336. {
  337. scIds.Add(item);
  338. }
  339. string comSql = BICommonWay.ManyScSql("c.school", scIds);
  340. string lesSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and {comSql}";
  341. tLessCnt = await CommonFind.GetSqlValueCount(cosmosClient, new List<string>() { "School", "Teacher" }, lesSql);
  342. comSql = BICommonWay.ManyScSql(" and c.school", scIds);
  343. tActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: comSql);
  344. return Ok(new { state = 200, scCnt = scIds.Count(), tLessCnt, tActCnt });
  345. }
  346. /// <summary>
  347. /// 未加区的学校统计
  348. /// </summary>
  349. /// <param name="jsonElement"></param>
  350. /// <returns></returns>
  351. [ProducesDefaultResponseType]
  352. [HttpPost("get-noareasc")]
  353. public async Task<IActionResult> GetNoAareaScCnt(JsonElement jsonElement)
  354. {
  355. var cosmosClient = _azureCosmos.GetCosmosClient();
  356. var tableClient = _azureStorage.GetCloudTableClient();
  357. var table = tableClient.GetTableReference("BIDDUserInfo");
  358. var (dayS, dayE) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow);
  359. var (weekS, weekE) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "week");
  360. var (monthS, monthE) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "month");
  361. var (termS, termE) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "term");
  362. List<AreaAssist> areaAssists = new(); //顾问信息
  363. int tchCnt = 0; //所有区级老师
  364. int stuCnt = 0; //所有区级学生
  365. int tLessCnt = 0; //课例数量
  366. int tActCnt = 0; //活动数量
  367. HashSet<string> tchIds = new();
  368. List<string> scIds = new(); //学校id集合
  369. string scIdSql = "select value(c.id) from c where c.areaId=null or c.areaId=''";
  370. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<string>(queryText: scIdSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  371. {
  372. scIds.Add(item);
  373. }
  374. string scsSql = BICommonWay.ManyScSql("c.school", scIds);
  375. string cntSql = $"select value(count(c.id)) from c where {scsSql}";
  376. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIteratorSql<int>(queryText: cntSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  377. {
  378. tchCnt += item;
  379. }
  380. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Student").GetItemQueryIteratorSql<int>(queryText: cntSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  381. {
  382. stuCnt += item;
  383. }
  384. foreach (var scId in scIds)
  385. {
  386. string tchIdSql = $"select value(c.id) from c where array_contains(c.roles,'assist',true) and c.pk='Teacher'";
  387. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<string>(queryText: tchIdSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{scId}") }))
  388. {
  389. tchIds.Add(item);
  390. }
  391. }
  392. List<string> noIds = new();
  393. foreach (var item in tchIds)
  394. {
  395. List<DingDingUserInfo> ddUsers = await table.QueryWhereString<DingDingUserInfo>($"PartitionKey eq '{_option.Location}' and tmdId eq '{item}'");
  396. if (ddUsers.Count > 0)
  397. {
  398. foreach (var dduser in ddUsers)
  399. {
  400. AreaAssist areaAssist = new()
  401. {
  402. userId = dduser.userId,
  403. unionId = dduser.unionId,
  404. name = dduser.name,
  405. mobile = dduser.mobile,
  406. avatar = dduser.avatar,
  407. tmdId = dduser.tmdId,
  408. tmdName = dduser.tmdName,
  409. tmdMobile = dduser.tmdMobile,
  410. picture = dduser.picture,
  411. roles = dduser.roles,
  412. schoolIds = dduser.schoolIds
  413. };
  414. areaAssists.Add(areaAssist);
  415. }
  416. }
  417. else { noIds.Add(item); }
  418. }
  419. if (scIds.Count > 0)
  420. {
  421. string lesSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and {scsSql}";
  422. tLessCnt = await CommonFind.GetSqlValueCount(cosmosClient, new List<string>() { "School", "Teacher" }, lesSql);
  423. string actComSql = BICommonWay.ManyScSql(" and c.school", scIds);
  424. tActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actComSql);
  425. }
  426. return Ok(new { state = RespondCode.Ok, scCnt = scIds.Count, tchCnt, stuCnt, allCnt = tLessCnt + tActCnt, tLessCnt, tActCnt });
  427. }
  428. #region 新的统计接口
  429. /// <summary>
  430. /// 参与的单个学校统计接口
  431. /// </summary>
  432. /// <param name="jsonElement"></param>
  433. /// <returns></returns>
  434. [ProducesDefaultResponseType]
  435. [HttpPost("get-joinschool")]
  436. public async Task<IActionResult> GetJoinSchoolStats(JsonElement jsonElement)
  437. {
  438. if (jsonElement.TryGetProperty("scId", out JsonElement scId)) return BadRequest();
  439. var cosmosClient = _azureCosmos.GetCosmosClient();
  440. School school = new();
  441. ScStats scStats = new();
  442. var respSc = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{scId}", new PartitionKey($"Base"));
  443. if (respSc.StatusCode == System.Net.HttpStatusCode.OK)
  444. {
  445. using var fileJson = await JsonDocument.ParseAsync(respSc.Content);
  446. school = fileJson.ToObject<School>();
  447. }
  448. else
  449. {
  450. return Ok(new { state = RespondCode.NotFound, msg = $"未找到id:{scId};相关的学校,请检查" });
  451. }
  452. StatsInfo statsInfo = null;
  453. List<LastYearLessAndAct> lastYear = new();
  454. var scDataStats = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync($"{DateTimeOffset.UtcNow.Year}-{scId}", new PartitionKey("Statistics"));
  455. if (scDataStats.StatusCode == System.Net.HttpStatusCode.OK)
  456. {
  457. using var fileJson = await JsonDocument.ParseAsync(scDataStats.Content);
  458. statsInfo = fileJson.ToObject<StatsInfo>();
  459. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<LastYearLessAndAct>(queryText: $"select c.activity,c.lesson from c where c.id='{DateTimeOffset.UtcNow.Year - 1}-{scId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Statistics") }))
  460. {
  461. lastYear.Add(item);
  462. }
  463. }
  464. {
  465. scStats.id = $"{DateTimeOffset.UtcNow.Year}-{school.id}";
  466. scStats.schoolId = school.id;
  467. scStats.name = school.name;
  468. scStats.picture = school.picture;
  469. scStats.areaId = school.areaId;
  470. }
  471. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  472. long now = dateTime.ToUnixTimeMilliseconds();
  473. if (statsInfo != null)
  474. {
  475. scStats.id = statsInfo.id;
  476. scStats.schoolId = statsInfo.schoolId;
  477. scStats.name = statsInfo.name;
  478. scStats.picture = statsInfo.picture;
  479. scStats.areaId = statsInfo.areaId;
  480. scStats.tch = statsInfo.tch;
  481. scStats.dayTch = statsInfo.dayTch;
  482. scStats.weekTch = statsInfo.weekTch;
  483. scStats.monthTch = statsInfo.monthTch;
  484. scStats.stu = statsInfo.stu;
  485. scStats.dayStu = statsInfo.dayStu;
  486. scStats.weekStu = statsInfo.weekStu;
  487. scStats.monthStu = statsInfo.monthStu;
  488. scStats.room = statsInfo.room;
  489. scStats.witRoom = statsInfo.witRoom;
  490. scStats.resourceCnt = statsInfo.resourceCnt;
  491. scStats.size = statsInfo.size;
  492. scStats.scCreateTime = statsInfo.scCreateTime;
  493. scStats.upTime = statsInfo.upTime;
  494. scStats.lessStats.all = statsInfo.lesson.all;
  495. scStats.lessStats.open = statsInfo.lesson.open;
  496. scStats.lessStats.less = statsInfo.lesson.less;
  497. scStats.lessStats.lastDay = statsInfo.lesson.lastDay;
  498. scStats.lessStats.day = statsInfo.lesson.day;
  499. scStats.lessStats.lastWeek = statsInfo.lesson.lastWeek;
  500. scStats.lessStats.week = statsInfo.lesson.week;
  501. scStats.lessStats.lastTerm = statsInfo.lesson.lastTerm;
  502. scStats.lessStats.term = statsInfo.lesson.term;
  503. scStats.lessStats.month = statsInfo.lesson.month;
  504. scStats.lessStats.lastMonth = statsInfo.lesson.lastMonth;
  505. scStats.lessStats.lastDayInter = statsInfo.lesson.lastDayInter;
  506. scStats.lessStats.dayInter = statsInfo.lesson.dayInter;
  507. scStats.lessStats.lastMonthInter = statsInfo.lesson.lastMonthInter;
  508. scStats.lessStats.monthInter = statsInfo.lesson.monthInter;
  509. scStats.lessStats.lastYear = ((int)BICommonWay.ManyDoubleMerge(lastYear.Select(s => s.lesson.year).Where(w => w.Count > 0).ToList()).Sum());
  510. scStats.lessStats.lastYearInter = statsInfo.lesson.lastYearInter;
  511. scStats.lessStats.yearInter = statsInfo.lesson.yearInter;
  512. scStats.lessStats.yearInters = TimeHelper.GetYearMonth(statsInfo.lesson.yearInters, dateTime.Year, dateTime.Month);
  513. scStats.lessStats.year = TimeHelper.GetYearMonth(statsInfo.lesson.year, dateTime.Year, dateTime.Month);
  514. scStats.actStats.all = statsInfo.activity.all;
  515. scStats.actStats.exam = statsInfo.activity.exam;
  516. scStats.actStats.survey = statsInfo.activity.survey;
  517. scStats.actStats.vote = statsInfo.activity.vote;
  518. scStats.actStats.homework = statsInfo.activity.homework;
  519. scStats.actStats.lastDay = statsInfo.activity.lastDay;
  520. scStats.actStats.dayCnt = statsInfo.activity.dayCnt;
  521. scStats.actStats.lastWeek = statsInfo.activity.lastWeek;
  522. scStats.actStats.week = statsInfo.activity.week;
  523. scStats.actStats.lastTerm = statsInfo.activity.lastTerm;
  524. scStats.actStats.term = statsInfo.activity.term;
  525. scStats.actStats.lastMonth = statsInfo.activity.lastMonth;
  526. scStats.actStats.month = statsInfo.activity.month;
  527. scStats.actStats.lastYear = ((int)BICommonWay.ManyDoubleMerge(lastYear.Select(s => s.activity.year).Where(w => w.Count > 0).ToList()).Sum());
  528. scStats.actStats.year = TimeHelper.GetYearMonth(statsInfo.activity.year, dateTime.Year, dateTime.Month);
  529. if (statsInfo.study != null)
  530. {
  531. scStats.srStats.learnTime = statsInfo.study.learnTime;
  532. scStats.srStats.online = statsInfo.study.online;
  533. scStats.srStats.offline = statsInfo.study.offline;
  534. scStats.srStats.classRoom = statsInfo.study.classRoom;
  535. scStats.srStats.submit = statsInfo.study.submit;
  536. scStats.srStats.notStarted = statsInfo.study.notStarted;
  537. scStats.srStats.ongoing = statsInfo.study.ongoing;
  538. scStats.srStats.finish = statsInfo.study.finish;
  539. }
  540. }
  541. var weekLess = BICommonWay.weekDoubleMerge(new List<List<double>>() { statsInfo.lesson.year }, dateTime);
  542. var weekAct = BICommonWay.weekDoubleMerge(new List<List<double>>() { statsInfo.activity.year }, dateTime);
  543. return Ok(new { state = RespondCode.Ok, scStats, weekLess, weekAct });
  544. }
  545. /// <summary>
  546. /// 学校统计
  547. /// 新的数据结构
  548. /// </summary>
  549. /// <param name="jsonElement"></param>
  550. /// <returns></returns>
  551. [ProducesDefaultResponseType]
  552. [HttpPost("get-scstats")]
  553. public async Task<IActionResult> GetSchoolStats(JsonElement jsonElement)
  554. {
  555. if (!jsonElement.TryGetProperty("scId", out JsonElement scId)) return BadRequest();
  556. var cosmosClient = _azureCosmos.GetCosmosClient();
  557. School school = new();
  558. ScStats scStats = new();
  559. var respSc = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{scId}", new PartitionKey($"Base"));
  560. if (respSc.StatusCode == System.Net.HttpStatusCode.OK)
  561. {
  562. using var fileJson = await JsonDocument.ParseAsync(respSc.Content);
  563. school = fileJson.ToObject<School>();
  564. }
  565. else
  566. return Ok(new { state = RespondCode.NotFound, msg = $"未找到id:{scId};相关的学校,请检查" });
  567. try
  568. {
  569. StatsInfo statsInfo = null;
  570. List<LastYearLessAndAct> lastYear = new();
  571. var scDataStats = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync($"{DateTimeOffset.UtcNow.Year}-{scId}", new PartitionKey("Statistics"));
  572. if (scDataStats.StatusCode == System.Net.HttpStatusCode.OK)
  573. {
  574. using var fileJson = await JsonDocument.ParseAsync(scDataStats.Content);
  575. statsInfo = fileJson.ToObject<StatsInfo>();
  576. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<LastYearLessAndAct>(queryText: $"select c.activity,c.lesson from c where c.id='{DateTimeOffset.UtcNow.Year - 1}-{scId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Statistics") }))
  577. {
  578. lastYear.Add(item);
  579. }
  580. }
  581. else
  582. {
  583. scStats.id = $"{DateTimeOffset.UtcNow.Year}-{school.id}";
  584. scStats.schoolId = school.id;
  585. scStats.name = school.name;
  586. scStats.picture = school.picture;
  587. scStats.areaId = school.areaId;
  588. }
  589. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  590. long now = dateTime.ToUnixTimeMilliseconds();
  591. if (statsInfo != null)
  592. {
  593. scStats.id = statsInfo.id;
  594. scStats.schoolId = statsInfo.schoolId;
  595. scStats.name = statsInfo.name;
  596. scStats.picture = statsInfo.picture;
  597. scStats.areaId = statsInfo.areaId;
  598. scStats.tch = statsInfo.tch;
  599. scStats.dayTch = statsInfo.dayTch;
  600. scStats.weekTch = statsInfo.weekTch;
  601. scStats.monthTch = statsInfo.monthTch;
  602. scStats.stu = statsInfo.stu;
  603. scStats.dayStu = statsInfo.dayStu;
  604. scStats.weekStu = statsInfo.weekStu;
  605. scStats.monthStu = statsInfo.monthStu;
  606. scStats.room = statsInfo.room;
  607. scStats.witRoom = statsInfo.witRoom;
  608. scStats.resourceCnt = statsInfo.resourceCnt;
  609. scStats.size = statsInfo.size;
  610. scStats.scCreateTime = statsInfo.scCreateTime;
  611. scStats.upTime = statsInfo.upTime;
  612. scStats.lessStats.all = statsInfo.lesson.all;
  613. scStats.lessStats.open = statsInfo.lesson.open;
  614. scStats.lessStats.less = statsInfo.lesson.less;
  615. scStats.lessStats.lastDay = statsInfo.lesson.lastDay;
  616. scStats.lessStats.day = statsInfo.lesson.day;
  617. scStats.lessStats.lastWeek = statsInfo.lesson.lastWeek;
  618. scStats.lessStats.week = statsInfo.lesson.week;
  619. scStats.lessStats.lastTerm = statsInfo.lesson.lastTerm;
  620. scStats.lessStats.term = statsInfo.lesson.term;
  621. scStats.lessStats.month = statsInfo.lesson.month;
  622. scStats.lessStats.lastMonth = statsInfo.lesson.lastMonth;
  623. scStats.lessStats.lastDayInter = statsInfo.lesson.lastDayInter;
  624. scStats.lessStats.dayInter = statsInfo.lesson.dayInter;
  625. scStats.lessStats.lastMonthInter = statsInfo.lesson.lastMonthInter;
  626. scStats.lessStats.monthInter = statsInfo.lesson.monthInter;
  627. scStats.lessStats.lastYear = ((int)BICommonWay.ManyDoubleMerge(lastYear.Select(s => s.lesson.year).Where(w => w.Count > 0).ToList()).Sum());
  628. scStats.lessStats.lastYearInter = statsInfo.lesson.lastYearInter;
  629. scStats.lessStats.yearInter = statsInfo.lesson.yearInter;
  630. scStats.lessStats.yearInters = TimeHelper.GetYearMonth(statsInfo.lesson.yearInters, dateTime.Year, dateTime.Month);
  631. scStats.lessStats.year = TimeHelper.GetYearMonth(statsInfo.lesson.year, dateTime.Year, dateTime.Month);
  632. scStats.actStats.all = statsInfo.activity.all;
  633. scStats.actStats.exam = statsInfo.activity.exam;
  634. scStats.actStats.survey = statsInfo.activity.survey;
  635. scStats.actStats.vote = statsInfo.activity.vote;
  636. scStats.actStats.homework = statsInfo.activity.homework;
  637. scStats.actStats.lastDay = statsInfo.activity.lastDay;
  638. scStats.actStats.dayCnt = statsInfo.activity.dayCnt;
  639. scStats.actStats.lastWeek = statsInfo.activity.lastWeek;
  640. scStats.actStats.week = statsInfo.activity.week;
  641. scStats.actStats.lastTerm = statsInfo.activity.lastTerm;
  642. scStats.actStats.term = statsInfo.activity.term;
  643. scStats.actStats.lastMonth = statsInfo.activity.lastMonth;
  644. scStats.actStats.month = statsInfo.activity.month;
  645. scStats.actStats.lastYear = ((int)BICommonWay.ManyDoubleMerge(lastYear.Select(s => s.activity.year).Where(w => w.Count > 0).ToList()).Sum());
  646. scStats.actStats.year = TimeHelper.GetYearMonth(statsInfo.activity.year, dateTime.Year, dateTime.Month);
  647. if (statsInfo.study != null)
  648. {
  649. scStats.srStats.learnTime = statsInfo.study.learnTime;
  650. scStats.srStats.online = statsInfo.study.online;
  651. scStats.srStats.offline = statsInfo.study.offline;
  652. scStats.srStats.classRoom = statsInfo.study.classRoom;
  653. scStats.srStats.submit = statsInfo.study.submit;
  654. scStats.srStats.notStarted = statsInfo.study.notStarted;
  655. scStats.srStats.ongoing = statsInfo.study.ongoing;
  656. scStats.srStats.finish = statsInfo.study.finish;
  657. }
  658. }
  659. //if(statsInfo.upTime > 0 && !isnew) {
  660. // long timedis = 20 * 60 * 1000;//20分钟
  661. // if (now - statsInfo.upTime < timedis)
  662. // isnew = true;
  663. //}
  664. //if (statsInfo.upTime == 0 && isnew)
  665. // statsInfo.upTime = now;
  666. //if (statsInfo.upTime == 0 && isnew)
  667. // statsInfo.upTime = DateTimeOffset.UtcNow.Add(new TimeSpan(-1, 0, 0, 0)).ToUnixTimeMilliseconds();
  668. //if (!isnew)
  669. //{
  670. // //Function 处理Function 更新或者新增
  671. // //_ = _httpTrigger.RequestHttpTrigger(new { schoolId = $"{school.id}"}, _option.Location, "stats-sc-info");
  672. // //异步方法处理 同步更新
  673. // statsInfo = await SchoolStatsWay.GetSingleSc(cosmosClient, school.id);
  674. // statsInfo.upTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  675. // if (isExist)
  676. // statsInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<StatsInfo>(statsInfo, statsInfo.id, new PartitionKey("Stats"));
  677. // else
  678. // statsInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<StatsInfo>(statsInfo, new PartitionKey("Stats"));
  679. //}
  680. return Ok(new { state = RespondCode.Ok, scStats });
  681. }
  682. catch (Exception ex)
  683. {
  684. await _dingDing.SendBotMsg($"BI,{_option.Location} /school/set-scstats() \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  685. return BadRequest();
  686. }
  687. }
  688. /// <summary>
  689. /// 依据身份统计学校
  690. /// 新的数据结构
  691. /// </summary>
  692. /// <param name="jsonElement"></param>
  693. /// <returns></returns>
  694. [ProducesDefaultResponseType]
  695. [HttpPost("get-rolestats")]
  696. public async Task<IActionResult> GetRoleStats(JsonElement jsonElement)
  697. {
  698. //jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  699. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  700. jsonElement.TryGetProperty("role", out JsonElement role);
  701. //if (string.IsNullOrEmpty($"{areaId}") && string.IsNullOrEmpty($"{tmdId}"))
  702. // return Ok(new { stats = RespondCode.ParamsError, msg = "areaId/tmdId两者参数不能都为空!" });
  703. var cosmosClient = _azureCosmos.GetCosmosClient();
  704. Area area = null;
  705. ScStats areaScStats = new();
  706. List<string> scIds = new();
  707. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  708. List<ScStats> scStatss = new();
  709. List<StatsInfo> statsInfos = new();
  710. StringBuilder scSql = new("select c.id,c.name,c.size,c.scale,c.serial,c.service,c.hard,c.city,c.dist,c.areaId from c");
  711. StringBuilder lastScSql = new("select value(c.id) from c");
  712. //if (!string.IsNullOrEmpty($"{areaId}"))
  713. //{
  714. // scSql.Append($" where c.areaId='{areaId}'");
  715. // lastScSql.Append($" where c.areaId='{areaId}'");
  716. // var respSc = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{areaId}", new PartitionKey($"Base-Area"));
  717. // if (respSc.Status == 200)
  718. // {
  719. // using var fileJson = await JsonDocument.ParseAsync(respSc.Content);
  720. // area = fileJson.ToObject<Area>();
  721. // }
  722. // else
  723. // return Ok(new { state = RespondCode.NotFound, msg = $"未找到id:{areaId};相关的学区,请检查!" });
  724. //}
  725. if (!string.IsNullOrEmpty($"{tmdId}"))
  726. {
  727. switch ($"{role}")
  728. {
  729. case "assist":
  730. scSql.Append($" join a in c.assists where a.id='{tmdId}'");
  731. lastScSql.Append($" join a in c.assists where a.id='{tmdId}'");
  732. break;
  733. case "sales":
  734. scSql.Append($" join a in c.sales where a.id='{tmdId}'");
  735. lastScSql.Append($" join a in c.sales where a.id='{tmdId}'");
  736. break;
  737. default:
  738. return Ok(new { state = RespondCode.ParamsError, msg = "role参数错误" });
  739. }
  740. }
  741. List<BIRelStats> bIRelStats = new();
  742. List<string> tempProduct = new();
  743. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<BIRelStats>(queryText: scSql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
  744. {
  745. if (item.serial == null) item.serial = new List<string>();
  746. if (item.service == null) item.service = new List<string>();
  747. if (item.hard == null) item.hard = new List<string>();
  748. bIRelStats.Add(item);
  749. tempProduct.AddRange(item.serial);
  750. tempProduct.AddRange(item.service);
  751. tempProduct.AddRange(item.hard);
  752. }
  753. if (bIRelStats.Count > 0)
  754. scIds = bIRelStats.Select(s => s.id).ToList();
  755. //scIds = await CommonFind.FindScIds(cosmosClient, scSql.ToString(), "BIRel");
  756. StringBuilder statsSql = new($"select value(c) from c where c.year={dateTime.Year}");
  757. if (scIds.Count > 0)
  758. {
  759. statsSql.Append($" and {BICommonWay.ManyScSql("c.id", scIds, $"{dateTime.Year}-")}");
  760. }
  761. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<StatsInfo>(queryText: statsSql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Statistics") }))
  762. {
  763. statsInfos.Add(item);
  764. }
  765. StringBuilder lastStsSql = new($"select c.lesson,c.activity from c where c.year={dateTime.Year}");
  766. if (scIds.Count > 0)
  767. {
  768. lastStsSql.Append($" and {BICommonWay.ManyScSql("c.id", scIds, $"{DateTimeOffset.UtcNow.Year - 1}-")}");
  769. }
  770. List<LastYearLessAndAct> lastYear = new();
  771. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<LastYearLessAndAct>(queryText: lastStsSql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Statistics") }))
  772. {
  773. lastYear.Add(item);
  774. }
  775. StatsInfo statsInfo = null;
  776. statsInfo = SchoolStatsWay.GetAreaStats(cosmosClient, _option, statsInfos, scIds, area);
  777. if (statsInfo != null)
  778. {
  779. areaScStats.id = statsInfo.id;
  780. areaScStats.schoolId = statsInfo.schoolId;
  781. areaScStats.name = statsInfo.name;
  782. areaScStats.picture = statsInfo.picture;
  783. areaScStats.areaId = statsInfo.areaId;
  784. areaScStats.tch = statsInfo.tch;
  785. areaScStats.dayTch = statsInfo.dayTch;
  786. areaScStats.weekTch = statsInfo.weekTch;
  787. areaScStats.monthTch = statsInfo.monthTch;
  788. areaScStats.stu = statsInfo.stu;
  789. areaScStats.dayStu = statsInfo.dayStu;
  790. areaScStats.weekStu = statsInfo.weekStu;
  791. areaScStats.monthStu = statsInfo.monthStu;
  792. areaScStats.room = statsInfo.room;
  793. areaScStats.witRoom = statsInfo.witRoom;
  794. areaScStats.resourceCnt = statsInfo.witRoom;
  795. areaScStats.size = statsInfo.size;
  796. areaScStats.scCreateTime = statsInfo.scCreateTime;
  797. areaScStats.upTime = statsInfo.upTime;
  798. areaScStats.lessStats.all = statsInfo.lesson.all;
  799. areaScStats.lessStats.open = statsInfo.lesson.open;
  800. areaScStats.lessStats.less = statsInfo.lesson.less;
  801. areaScStats.lessStats.lastDay = statsInfo.lesson.lastDay;
  802. areaScStats.lessStats.day = statsInfo.lesson.day;
  803. areaScStats.lessStats.lastWeek = statsInfo.lesson.lastWeek;
  804. areaScStats.lessStats.week = statsInfo.lesson.week;
  805. areaScStats.lessStats.lastTerm = statsInfo.lesson.lastTerm;
  806. areaScStats.lessStats.term = statsInfo.lesson.term;
  807. areaScStats.lessStats.lastDayInter = statsInfo.lesson.lastDayInter;
  808. areaScStats.lessStats.dayInter = statsInfo.lesson.dayInter;
  809. areaScStats.lessStats.lastMonthInter = statsInfo.lesson.lastMonthInter;
  810. areaScStats.lessStats.monthInter = statsInfo.lesson.monthInter;
  811. areaScStats.lessStats.lastYearInter = statsInfo.lesson.lastYearInter;
  812. areaScStats.lessStats.yearInter = statsInfo.lesson.yearInter;
  813. areaScStats.lessStats.yearInters = TimeHelper.GetYearMonth(statsInfo.lesson.yearInters, dateTime.Year, dateTime.Month);
  814. areaScStats.lessStats.lastYear = ((int)BICommonWay.ManyDoubleMerge(lastYear.Select(s => s.lesson.year).Where(w => w.Count > 0).ToList()).Sum());
  815. areaScStats.lessStats.year = TimeHelper.GetYearMonth(statsInfo.lesson.year, dateTime.Year, dateTime.Month);
  816. areaScStats.actStats.all = statsInfo.activity.all;
  817. areaScStats.actStats.exam = statsInfo.activity.exam;
  818. areaScStats.actStats.survey = statsInfo.activity.survey;
  819. areaScStats.actStats.vote = statsInfo.activity.vote;
  820. areaScStats.actStats.homework = statsInfo.activity.homework;
  821. areaScStats.actStats.lastDay = statsInfo.activity.lastDay;
  822. areaScStats.actStats.dayCnt = statsInfo.activity.dayCnt;
  823. areaScStats.actStats.lastWeek = statsInfo.activity.lastWeek;
  824. areaScStats.actStats.week = statsInfo.activity.week;
  825. areaScStats.actStats.lastTerm = statsInfo.activity.lastTerm;
  826. areaScStats.actStats.term = statsInfo.activity.term;
  827. areaScStats.actStats.lastMonth = statsInfo.activity.lastMonth;
  828. areaScStats.actStats.month = statsInfo.activity.month;
  829. areaScStats.actStats.lastYear = ((int)BICommonWay.ManyDoubleMerge(lastYear.Select(s => s.activity.year).Where(w => w.Count > 0).ToList()).Sum());
  830. areaScStats.actStats.year = TimeHelper.GetYearMonth(statsInfo.activity.year, dateTime.Year, dateTime.Month);
  831. if (statsInfo.study != null)
  832. {
  833. areaScStats.srStats.learnTime = statsInfo.study.learnTime;
  834. areaScStats.srStats.online = statsInfo.study.online;
  835. areaScStats.srStats.offline = statsInfo.study.offline;
  836. areaScStats.srStats.classRoom = statsInfo.study.classRoom;
  837. areaScStats.srStats.submit = statsInfo.study.submit;
  838. areaScStats.srStats.notStarted = statsInfo.study.notStarted;
  839. areaScStats.srStats.ongoing = statsInfo.study.ongoing;
  840. areaScStats.srStats.finish = statsInfo.study.finish;
  841. }
  842. }
  843. var scInfos = statsInfos.Select(s => new { s.id, s.schoolId, s.name, s.picture, size = bIRelStats.Where(w => w.id.Equals(s.schoolId)).Select(si => si.size).FirstOrDefault(), scale = bIRelStats.Where(w => w.id.Equals(s.schoolId)).Select(si => si.scale).FirstOrDefault(), serial = bIRelStats.Where(w => w.id.Equals(s.schoolId)).Select(si => si.serial).FirstOrDefault(), service = bIRelStats.Where(w => w.id.Equals(s.schoolId)).Select(si => si.service).FirstOrDefault(), hard = bIRelStats.Where(w => w.id.Equals(s.schoolId)).Select(si => si.hard).FirstOrDefault(), actLess = (s.lesson.all + s.activity.all), actCnt = s.activity.all, lessCnt = s.lesson.all, lessOpen = s.lesson.open, lessUp = s.lesson.less
  844. ,city = bIRelStats.Where(w => w.id.Equals(s.schoolId)).Select(si => si.city).FirstOrDefault()
  845. ,dist = bIRelStats.Where(w => w.id.Equals(s.schoolId)).Select(si => si.dist).FirstOrDefault()
  846. ,areaId = bIRelStats.Where(w => w.id.Equals(s.schoolId)).Select(si => si.areaId).FirstOrDefault()
  847. }).ToList();
  848. var productGroup = tempProduct.GroupBy(g => g).Select(s => new { code = s.Key, cnt = s.Count() });
  849. return Ok(new { state = RespondCode.Ok, areaScStats, scInfos, productGroup });
  850. }
  851. /// <summary>
  852. /// 依据区级Id统计 新数据结构
  853. /// </summary>
  854. /// <param name="jsonElement"></param>
  855. /// <returns></returns>
  856. [ProducesDefaultResponseType]
  857. [HttpPost("get-areastats")]
  858. public async Task<IActionResult> GetAreaStats(JsonElement jsonElement)
  859. {
  860. if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
  861. var redisClinet = _azureRedis.GetRedisClient(8);
  862. var cosmosClient = _azureCosmos.GetCosmosClient();
  863. var tableClient = _azureStorage.GetCloudTableClient();
  864. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  865. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  866. Area area = null;
  867. AreaStats areaScStats = new();
  868. List<string> scIds = new();
  869. List<BISchoolInfo> schoolInfos = new();
  870. List<ScStats> scStatss = new();
  871. List<StatsInfo> statsInfos = new();
  872. long useSize = 0;
  873. Dictionary<string, double?> typeStics = new(); //所有类型
  874. var (weekS, weekE) = TimeHelper.GetStartOrEnd(dateTime, "week"); //计算本周开始/结束时间
  875. var (mthS, mthE) = TimeHelper.GetStartOrEnd(dateTime, "month"); //本月开始/结束时间
  876. //學區成員修正:若學校(Base)有學區ID而學校中間件無 ->補足
  877. List<string> schInBIRel = new List<string>();
  878. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<string>(queryText: $"SELECT VALUE c.id FROM c WHERE c.areaId='{areaId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
  879. {
  880. schInBIRel.Add(item);
  881. }
  882. await foreach (School school in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<School>(queryText: $"SELECT * FROM c WHERE c.areaId='{areaId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  883. {
  884. string schId = school.id.ToString();
  885. if (!schInBIRel.Contains(schId))
  886. {
  887. await BIStats.SetSchoolBIRelation(cosmosClient, blobClient, tableClient, _dingDing, school);
  888. }
  889. }
  890. //學校中間件資料取得
  891. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<BISchoolInfo>(queryText: $"select c.id,c.name,c.picture,c.areaId,c.areaName,c.size,c.scale,c.assists,c.sales,c.createDate,c.serial,c.service,c.hard from c where c.areaId='{areaId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
  892. {
  893. schoolInfos.Add(item);
  894. }
  895. if (schoolInfos.Count > 0)
  896. scIds = schoolInfos.Select(s => s.id).ToList();
  897. StringBuilder statsSql = new($"select value(c) from c where c.year={dateTime.Year}");
  898. if (scIds.Count > 0)
  899. {
  900. statsSql.Append($" and {BICommonWay.ManyScSql("c.id", scIds, $"{dateTime.Year}-")}");
  901. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<StatsInfo>(queryText: statsSql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Statistics") }))
  902. {
  903. statsInfos.Add(item);
  904. }
  905. }
  906. StringBuilder lastStsSql = new($"select c.lesson,c.activity from c where c.year={dateTime.Year - 1}");
  907. List<LastYearLessAndAct> lastYear = new();
  908. if (scIds.Count > 0)
  909. {
  910. lastStsSql.Append($" and {BICommonWay.ManyScSql("c.id", scIds, $"{dateTime.Year - 1}-")}");
  911. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<LastYearLessAndAct>(queryText: lastStsSql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Statistics") }))
  912. {
  913. lastYear.Add(item);
  914. }
  915. }
  916. //本學區虛擬學校數取得
  917. string schcntSql = $"SELECT VALUE COUNT(c.id) FROM c WHERE c.areaId='{areaId}'";
  918. int sbCnt = await JointlySingleQuery.GetValueInt(cosmosClient, "School", "Base", schcntSql);
  919. int vrCnt = await JointlySingleQuery.GetValueInt(cosmosClient, "School", "VirtualBase", schcntSql);
  920. int schCnt = sbCnt + vrCnt;
  921. StatsInfo statsInfo = null;
  922. statsInfo = SchoolStatsWay.GetAreaStats(cosmosClient, _option, statsInfos, scIds, area);
  923. if (statsInfo != null)
  924. {
  925. //areaScStats = new
  926. //{
  927. // statsInfo.id,
  928. // statsInfo.schoolId,
  929. // statsInfo.name,
  930. // statsInfo.picture,
  931. // statsInfo.areaId,
  932. // weekSc = schoolInfos.Where(w => w.createDate >= weekS && w.createDate <= weekE).Count(),
  933. // monthSc = schoolInfos.Where(w => w.createDate >= mthS && w.createDate <= mthE).Count(),
  934. // statsInfo.tch,
  935. // statsInfo.dayTch,
  936. // statsInfo.weekTch,
  937. // statsInfo.monthTch,
  938. // statsInfo.stu,
  939. // statsInfo.dayStu,
  940. // statsInfo.weekStu,
  941. // statsInfo.monthStu,
  942. // statsInfo.room,
  943. // statsInfo.witRoom,
  944. // statsInfo.size,
  945. // statsInfo.scCreateTime,
  946. // statsInfo.upTime,
  947. // lessStats = new
  948. // {
  949. // statsInfo.lesson.all,
  950. // statsInfo.lesson.open,
  951. // statsInfo.lesson.less,
  952. // statsInfo.lesson.lastDay,
  953. // statsInfo.lesson.day,
  954. // statsInfo.lesson.lastWeek,
  955. // statsInfo.lesson.week,
  956. // statsInfo.lesson.lastTerm,
  957. // statsInfo.lesson.term,
  958. // statsInfo.lesson.lastDayInter,
  959. // statsInfo.lesson.dayInter,
  960. // statsInfo.lesson.lastMonthInter,
  961. // statsInfo.lesson.monthInter,
  962. // statsInfo.lesson.lastYearInter,
  963. // statsInfo.lesson.yearInter,
  964. // yearInters = TimeHelper.GetYearMonth(statsInfo.lesson.yearInters, dateTime.Year, dateTime.Month),
  965. // lastYear = ((int)BICommonWay.ManyDoubleMerge(lastYear.Select(s => s.lesson.year).Where(w => w.Count > 0).ToList()).Sum()),
  966. // year = TimeHelper.GetYearMonth(statsInfo.lesson.year, dateTime.Year, dateTime.Month)
  967. // },
  968. // actStats = new
  969. // {
  970. // statsInfo.activity.all,
  971. // statsInfo.activity.exam,
  972. // statsInfo.activity.survey,
  973. // statsInfo.activity.vote,
  974. // statsInfo.activity.homework,
  975. // statsInfo.activity.lastDay,
  976. // statsInfo.activity.dayCnt,
  977. // statsInfo.activity.lastWeek,
  978. // statsInfo.activity.week,
  979. // statsInfo.activity.lastTerm,
  980. // statsInfo.activity.term,
  981. // lastYear = ((int)BICommonWay.ManyDoubleMerge(lastYear.Select(s => s.activity.year).Where(w => w.Count > 0).ToList()).Sum()),
  982. // year = TimeHelper.GetYearMonth(statsInfo.activity.year, dateTime.Year, dateTime.Month)
  983. // },
  984. // srStats = new
  985. // {
  986. // statsInfo.study.learnTime,
  987. // statsInfo.study.online,
  988. // statsInfo.study.offline,
  989. // statsInfo.study.classRoom,
  990. // statsInfo.study.submit,
  991. // statsInfo.study.notStarted,
  992. // statsInfo.study.ongoing,
  993. // statsInfo.study.finish
  994. // }
  995. //};
  996. areaScStats.id = statsInfo.id;
  997. areaScStats.name = statsInfo.name;
  998. areaScStats.weekSc = schoolInfos.Where(w => w.createDate >= weekS && w.createDate <= weekE).Count();
  999. areaScStats.monthSc = schoolInfos.Where(w => w.createDate >= mthS && w.createDate <= mthE).Count();
  1000. areaScStats.tch = statsInfo.tch;
  1001. areaScStats.dayTch = statsInfo.dayTch;
  1002. areaScStats.weekTch = statsInfo.weekTch;
  1003. areaScStats.monthTch = statsInfo.monthTch;
  1004. areaScStats.stu = statsInfo.stu;
  1005. areaScStats.dayStu = statsInfo.dayStu;
  1006. areaScStats.weekStu = statsInfo.weekStu;
  1007. areaScStats.monthStu = statsInfo.monthStu;
  1008. areaScStats.room = statsInfo.room;
  1009. areaScStats.witRoom = statsInfo.witRoom;
  1010. areaScStats.resourceCnt = statsInfo.resourceCnt;
  1011. areaScStats.size = statsInfo.size;
  1012. //areaScStats.useSize = statsInfo.useSize;
  1013. areaScStats.lessStats.open = statsInfo.lesson.all;
  1014. areaScStats.lessStats.open = statsInfo.lesson.open;
  1015. areaScStats.lessStats.less = statsInfo.lesson.less;
  1016. areaScStats.lessStats.lastDay = statsInfo.lesson.lastDay;
  1017. areaScStats.lessStats.day = statsInfo.lesson.day;
  1018. areaScStats.lessStats.lastWeek = statsInfo.lesson.lastWeek;
  1019. areaScStats.lessStats.week = statsInfo.lesson.week;
  1020. areaScStats.lessStats.lastTerm = statsInfo.lesson.lastTerm;
  1021. areaScStats.lessStats.term = statsInfo.lesson.term;
  1022. areaScStats.lessStats.lastDayInter = statsInfo.lesson.lastDayInter;
  1023. areaScStats.lessStats.dayInter = statsInfo.lesson.dayInter;
  1024. areaScStats.lessStats.lastMonthInter = statsInfo.lesson.lastMonthInter;
  1025. areaScStats.lessStats.monthInter = statsInfo.lesson.monthInter;
  1026. areaScStats.lessStats.lastYearInter = statsInfo.lesson.lastYearInter;
  1027. areaScStats.lessStats.yearInter = statsInfo.lesson.yearInter;
  1028. areaScStats.lessStats.yearInters = TimeHelper.GetYearMonth(statsInfo.lesson.yearInters, dateTime.Year, dateTime.Month);
  1029. areaScStats.lessStats.lastYear = ((int)BICommonWay.ManyDoubleMerge(lastYear.Select(s => s.lesson.year).Where(w => w.Count > 0).ToList()).Sum());
  1030. areaScStats.lessStats.year = TimeHelper.GetYearMonth(statsInfo.lesson.year, dateTime.Year, dateTime.Month);
  1031. areaScStats.actStats.all = statsInfo.activity.all;
  1032. areaScStats.actStats.exam = statsInfo.activity.exam;
  1033. areaScStats.actStats.survey = statsInfo.activity.survey;
  1034. areaScStats.actStats.vote = statsInfo.activity.vote;
  1035. areaScStats.actStats.homework = statsInfo.activity.homework;
  1036. areaScStats.actStats.lastDay = statsInfo.activity.lastDay;
  1037. areaScStats.actStats.dayCnt = statsInfo.activity.dayCnt;
  1038. areaScStats.actStats.lastWeek = statsInfo.activity.lastWeek;
  1039. areaScStats.actStats.week = statsInfo.activity.week;
  1040. areaScStats.actStats.lastTerm = statsInfo.activity.lastTerm;
  1041. areaScStats.actStats.term = statsInfo.activity.term;
  1042. areaScStats.actStats.lastMonth = statsInfo.activity.lastMonth;
  1043. areaScStats.actStats.month = statsInfo.activity.month;
  1044. areaScStats.actStats.lastYear = ((int)BICommonWay.ManyDoubleMerge(lastYear.Select(s => s.activity.year).Where(w => w.Count > 0).ToList()).Sum());
  1045. areaScStats.actStats.year = TimeHelper.GetYearMonth(statsInfo.activity.year, dateTime.Year, dateTime.Month);
  1046. if (statsInfo.study != null)
  1047. {
  1048. areaScStats.srStats.learnTime = statsInfo.study.learnTime;
  1049. areaScStats.srStats.online = statsInfo.study.online;
  1050. areaScStats.srStats.offline = statsInfo.study.offline;
  1051. areaScStats.srStats.classRoom = statsInfo.study.classRoom;
  1052. areaScStats.srStats.submit = statsInfo.study.submit;
  1053. areaScStats.srStats.notStarted = statsInfo.study.notStarted;
  1054. areaScStats.srStats.ongoing = statsInfo.study.ongoing;
  1055. areaScStats.srStats.finish = statsInfo.study.finish;
  1056. }
  1057. }
  1058. List<double> weekLess = BICommonWay.weekDoubleMerge(statsInfos.Select(s => s.lesson.year).Where(w => w.Count > 0).ToList(), dateTime);
  1059. schoolInfos.ForEach(fe =>
  1060. {
  1061. var tempSts = statsInfos.Find(f => f.schoolId.Equals(fe.id));
  1062. if (tempSts != null)
  1063. {
  1064. fe.less = tempSts.lesson.all;
  1065. fe.lastWeekLess = tempSts.lesson.lastWeek;
  1066. fe.monthLess = tempSts.lesson.month;
  1067. }
  1068. });
  1069. List<IdInfo> assits = new();
  1070. schoolInfos.ForEach(fe => assits.AddRange(fe.assists));
  1071. List<IdInfo> saless = new();
  1072. schoolInfos.ForEach(fe => saless.AddRange(fe.sales));
  1073. foreach (var itemId in scIds)
  1074. {
  1075. RedisValue value = redisClinet.HashGet($"Blob:Record", itemId);
  1076. if (value != default && !value.IsNullOrEmpty)
  1077. {
  1078. JsonElement record = value.ToString().ToObject<JsonElement>();
  1079. if (record.TryGetInt64(out long blobsize))
  1080. {
  1081. useSize += blobsize;
  1082. }
  1083. }
  1084. SortedSetEntry[] Scores = redisClinet.SortedSetRangeByScoreWithScores($"Blob:Catalog:{itemId}");
  1085. if (Scores.Length > 0)
  1086. {
  1087. Dictionary<string, double?> schoolStics = new(); //学校空间
  1088. foreach (var score in Scores)
  1089. {
  1090. double val = score.Score;
  1091. string key = score.Element.ToString();
  1092. schoolStics.Add(key, val);
  1093. }
  1094. typeStics = typeStics.Concat(schoolStics).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
  1095. }
  1096. }
  1097. return Ok(new { state = RespondCode.Ok, areaScStats, schCnt, schoolInfos, weekLess, assists = assits.Where((w, i) => assits.FindIndex(s => s.id.Equals(w.id)) == i).ToList(), saless = saless.Where((w, i) => saless.FindIndex(f => f.id.Equals(w.id)) == i).ToList(), useSize, typeStics = typeStics.ToList() });
  1098. }
  1099. /// <summary>
  1100. /// 所有区级的统计
  1101. /// </summary>
  1102. /// <param name="jsonElement"></param>
  1103. /// <returns></returns>
  1104. [ProducesDefaultResponseType]
  1105. [HttpPost("get-allscstats")]
  1106. public async Task<IActionResult> GetAllAreaStats(JsonElement jsonElement)
  1107. {
  1108. var cosmosClient = _azureCosmos.GetCosmosClient();
  1109. AllScStats allScStats = new();
  1110. List<StatsInfo> statsInfos = new();
  1111. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1112. var (lastDayS, lastdayE) = TimeHelper.GetStartOrEnd(dateTime.AddDays(-1)); //昨天开始时间
  1113. var (dayS, dayE) = TimeHelper.GetStartOrEnd(dateTime); //今天开始时间
  1114. var (lastWeekS, lastWeekE) = TimeHelper.GetStartOrEnd(dateTime, "lastweek"); //计算上周开始/结束时间
  1115. var (weekS, weekE) = TimeHelper.GetStartOrEnd(dateTime, "week"); //计算本周开始/结束时间
  1116. var (lastTermS, lastTermE) = TimeHelper.GetStartOrEnd(dateTime, "lastterm"); //计算上学期开始/结束时间
  1117. var (termS, termE) = TimeHelper.GetStartOrEnd(dateTime, "term"); //计算本学期开始/结束时间
  1118. var (lastMthS, LastmthE) = TimeHelper.GetStartOrEnd(dateTime, "lastMonth"); //上月开始/结束时间
  1119. var (mthS, mthE) = TimeHelper.GetStartOrEnd(dateTime, "month"); //本月开始/结束时间
  1120. var (lastYearS, lastYearE) = TimeHelper.GetStartOrEnd(DateTimeOffset.Parse($"{dateTime.Year - 1}-1-1"), "year"); //计算去年开始/结束时间
  1121. var (yearS, yearE) = TimeHelper.GetStartOrEnd(dateTime, "year"); //计算今年开始/结束时间
  1122. string sql = "select value(count(c.id)) from c ";
  1123. List<EasyInfo> easyInfos = new();
  1124. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIteratorSql<EasyInfo>(queryText: $"select c.id,c.code,c.name from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
  1125. {
  1126. easyInfos.Add(item);
  1127. }
  1128. int scCnt = await JointlySingleQuery.GetValueInt(cosmosClient, "School", "Base", sql);
  1129. int vrCnt = await JointlySingleQuery.GetValueInt(cosmosClient, "School", "VirtualBase", sql);
  1130. int scWeekCnt = await JointlySingleQuery.GetValueInt(cosmosClient, "Normal", "Base", $"{sql} where c.createTime >= {weekS} and c.createTime <= {weekE}");
  1131. int scMonthCnt = await JointlySingleQuery.GetValueInt(cosmosClient, "Normal", "Base", $"{sql} where c.createTime >= {mthS} and c.createTime <= {mthE}");
  1132. List<string> scId = new();
  1133. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<StatsInfo>(queryText: $"select value(c) from c where c.year={dateTime.Year}", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Statistics") }))
  1134. {
  1135. statsInfos.Add(item);
  1136. if (item.activity.year.Count > 366)
  1137. {
  1138. scId.Add(item.id);
  1139. }
  1140. }
  1141. List<AreaInfoStats> areaGroup = statsInfos.GroupBy(p => p.areaId).Select(s => new AreaInfoStats() { areaId = s.Key, name = easyInfos.Where(f => f.id.Equals(s.Key)).Select(sn=>sn.name).FirstOrDefault(), lessAct = (s.Select(sl => sl.lesson.all).Sum() + s.Select(sa => sa.activity.all).Sum()), lessCnt = s.Select(sl => sl.lesson.all).Sum(), actCnt = s.Select(sa => sa.activity.all).Sum() }).ToList();
  1142. StatsInfo statsInfo = null;
  1143. statsInfo = SchoolStatsWay.GetAreaStats(cosmosClient, _option, statsInfos);
  1144. if (statsInfo != null)
  1145. {
  1146. allScStats.areaCnt = easyInfos.Count;
  1147. //allScStats.sc = statsInfos.Count;
  1148. allScStats.weekSc = scWeekCnt;
  1149. allScStats.monthSc = scMonthCnt;
  1150. allScStats.tch = statsInfo.tch;
  1151. allScStats.dayTch = statsInfo.dayTch;
  1152. allScStats.weekTch = statsInfo.weekTch;
  1153. allScStats.monthTch = statsInfo.monthTch;
  1154. allScStats.stu = statsInfo.stu;
  1155. allScStats.dayStu = statsInfo.dayStu;
  1156. allScStats.weekStu = statsInfo.weekStu;
  1157. allScStats.monthStu = statsInfo.monthStu;
  1158. allScStats.room = statsInfo.room;
  1159. allScStats.witRoom = statsInfo.witRoom;
  1160. allScStats.resourceCnt = statsInfo.resourceCnt;
  1161. allScStats.size = statsInfo.size;
  1162. allScStats.scCreateTime = statsInfo.scCreateTime;
  1163. allScStats.upTime = statsInfo.upTime;
  1164. allScStats.lessStats.open = statsInfo.lesson.all;
  1165. allScStats.lessStats.open = statsInfo.lesson.open;
  1166. allScStats.lessStats.less = statsInfo.lesson.less;
  1167. allScStats.lessStats.lastDay = statsInfo.lesson.lastDay;
  1168. allScStats.lessStats.day = statsInfo.lesson.day;
  1169. allScStats.lessStats.lastWeek = statsInfo.lesson.lastWeek;
  1170. allScStats.lessStats.week = statsInfo.lesson.week;
  1171. allScStats.lessStats.lastTerm = statsInfo.lesson.lastTerm;
  1172. allScStats.lessStats.term = statsInfo.lesson.term;
  1173. allScStats.lessStats.lastDayInter = statsInfo.lesson.lastDayInter;
  1174. allScStats.lessStats.dayInter = statsInfo.lesson.dayInter;
  1175. allScStats.lessStats.lastMonthInter = statsInfo.lesson.lastMonthInter;
  1176. allScStats.lessStats.monthInter = statsInfo.lesson.monthInter;
  1177. allScStats.lessStats.lastYearInter = statsInfo.lesson.lastYearInter;
  1178. allScStats.lessStats.yearInter = statsInfo.lesson.yearInter;
  1179. allScStats.actStats.all = statsInfo.activity.all;
  1180. allScStats.actStats.exam = statsInfo.activity.exam;
  1181. allScStats.actStats.survey = statsInfo.activity.survey;
  1182. allScStats.actStats.vote = statsInfo.activity.vote;
  1183. allScStats.actStats.homework = statsInfo.activity.homework;
  1184. allScStats.actStats.lastDay = statsInfo.activity.lastDay;
  1185. allScStats.actStats.dayCnt = statsInfo.activity.dayCnt;
  1186. allScStats.actStats.lastWeek = statsInfo.activity.lastWeek;
  1187. allScStats.actStats.week = statsInfo.activity.week;
  1188. allScStats.actStats.lastTerm = statsInfo.activity.lastTerm;
  1189. allScStats.actStats.term = statsInfo.activity.term;
  1190. allScStats.actStats.lastMonth = statsInfo.activity.lastMonth;
  1191. allScStats.actStats.month = statsInfo.activity.month;
  1192. if (statsInfo.study != null)
  1193. {
  1194. allScStats.srStats.learnTime = statsInfo.study.learnTime;
  1195. allScStats.srStats.online = statsInfo.study.online;
  1196. allScStats.srStats.offline = statsInfo.study.offline;
  1197. allScStats.srStats.classRoom = statsInfo.study.classRoom;
  1198. allScStats.srStats.submit = statsInfo.study.submit;
  1199. allScStats.srStats.notStarted = statsInfo.study.notStarted;
  1200. allScStats.srStats.ongoing = statsInfo.study.ongoing;
  1201. allScStats.srStats.finish = statsInfo.study.finish;
  1202. }
  1203. }
  1204. allScStats.sc = scCnt + vrCnt; //學校數
  1205. return Ok(new { state = RespondCode.Ok, allScStats, areaGroup });
  1206. }
  1207. #endregion 新的统计接口
  1208. /// <summary>
  1209. /// 学校课例
  1210. /// </summary>
  1211. /// <param name="jsonElement"></param>
  1212. /// <returns></returns>
  1213. [ProducesDefaultResponseType]
  1214. [HttpPost("get-leseoncnt")]
  1215. public async Task<IActionResult> GetLessonCnt(JsonElement jsonElement)
  1216. {
  1217. if (!jsonElement.TryGetProperty("code", out JsonElement code)) return BadRequest();
  1218. List<LessonRecord> records = new();
  1219. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1220. var (dayS, dayE) = TimeHelper.GetStartOrEnd(dateTime); //今天开始时间
  1221. var (weekS, weekE) = TimeHelper.GetStartOrEnd(dateTime, "week"); //计算本周开始/结束时间
  1222. var (monthS, monthE) = TimeHelper.GetStartOrEnd(dateTime, "month"); //本月开始/结束时间
  1223. var client = _azureCosmos.GetCosmosClient();
  1224. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<LessonRecord>(queryText: "select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{code}") }))
  1225. {
  1226. records.Add(item);
  1227. }
  1228. double itemCount = 0;
  1229. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(queryText: $"SELECT count(1) as items FROM c where c.scope = 'school' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
  1230. {
  1231. using var json = await JsonDocument.ParseAsync(item.Content);
  1232. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1233. {
  1234. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1235. {
  1236. if (obj.TryGetProperty("items", out JsonElement items))
  1237. {
  1238. itemCount = items.GetDouble();
  1239. }
  1240. }
  1241. }
  1242. }
  1243. double paperCount = 0;
  1244. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIteratorSql(queryText: $"SELECT count(1) as papers FROM c where c.scope = 'school' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Paper-{code}") }))
  1245. {
  1246. using var json = await JsonDocument.ParseAsync(item.Content);
  1247. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1248. {
  1249. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1250. {
  1251. if (obj.TryGetProperty("papers", out JsonElement papers))
  1252. {
  1253. paperCount = papers.GetDouble();
  1254. }
  1255. }
  1256. }
  1257. }
  1258. double resourcesCount = itemCount + paperCount; //线上资源
  1259. double attendCount = records.Select(c => c.attendCount).Sum(); //学生参加人数
  1260. double clientInteractionCount = records.Select(c => c.clientInteractionCount).Sum(); //互动总次数
  1261. double workCount = records.Select(c => c.collateCount).Sum();//课堂任务总次数
  1262. double interactionCount = records.Select(c => c.interactionCount).Sum(); //课堂提问中题数
  1263. double duration = records.Select(c => c.duration).Sum(); //课堂总时长
  1264. double dayCnt = records.Where(c => c.startTime >= dayS && c.startTime <= dayE).Count(); //今天课例数
  1265. double weekCnt = records.Where(c => c.startTime >= weekS && c.startTime <= weekE).Count(); //本周课例数
  1266. double monthCnt = records.Where(c => c.startTime >= monthS && c.startTime <= monthE).Count(); //本月课例数
  1267. return Ok(new { state = RespondCode.Ok, cnt = records.Count, dayCnt, weekCnt, monthCnt, resourcesCount, attendCount, clientInteractionCount, workCount, interactionCount, duration });
  1268. }
  1269. /// <summary>
  1270. /// 学校信息中间件查询接口
  1271. /// </summary>
  1272. /// <param name="jsonElement"></param>
  1273. /// <returns></returns>
  1274. [ProducesDefaultResponseType]
  1275. [HttpPost("get-scinfos")]
  1276. public async Task<IActionResult> GetScInfos(JsonElement jsonElement)
  1277. {
  1278. var cosmosClient = _azureCosmos.GetCosmosClient();
  1279. jsonElement.TryGetProperty("role", out JsonElement role);
  1280. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  1281. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  1282. ////IES5實體學校學區名稱
  1283. List<string> AreaIdList = new List<string>();
  1284. StringBuilder sqlBiArea = new($"SELECT DISTINCT VALUE c.areaId FROM c WHERE IS_DEFINED(c.areaId) AND NOT IS_NULL(c.areaId) AND c.areaId != ''");
  1285. await foreach (string item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<string>(queryText: sqlBiArea.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
  1286. {
  1287. AreaIdList.Add(item);
  1288. }
  1289. Dictionary<string, string> areaDic = new Dictionary<string, string>();
  1290. string AreaListStr = JsonSerializer.Serialize(AreaIdList);
  1291. StringBuilder sqlArea = new($"SELECT c.id, c.name FROM c WHERE ARRAY_CONTAINS({AreaListStr}, c.id, true)");
  1292. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryStreamIteratorSql(queryText: sqlArea.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
  1293. {
  1294. var json = await JsonDocument.ParseAsync(item.Content);
  1295. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1296. {
  1297. string arId = obj.GetProperty("id").GetString();
  1298. string arName = obj.GetProperty("name").GetString();
  1299. if(!areaDic.ContainsKey(arId))
  1300. {
  1301. areaDic.Add(arId, arName);
  1302. }
  1303. }
  1304. }
  1305. //IES5實體學校
  1306. StringBuilder sql = new($"select value(c) from c");
  1307. if (!string.IsNullOrEmpty($"{role}") && !string.IsNullOrEmpty($"{tmdId}") && string.IsNullOrEmpty($"{areaId}"))
  1308. {
  1309. switch ($"{role}")
  1310. {
  1311. case "assist":
  1312. sql.Append($" join a in c.assist where a.id='{tmdId}'");
  1313. break;
  1314. case "sales":
  1315. sql.Append($" join a in c.sales where a.id='{tmdId}'");
  1316. break;
  1317. }
  1318. }
  1319. if (!string.IsNullOrEmpty($"{areaId}") && !string.IsNullOrEmpty($"{role}"))
  1320. {
  1321. sql.Append($" where c.areaId ='{areaId}'");
  1322. }
  1323. //取得學校BI統計中間件
  1324. List<BIRelation> scInfos = new();
  1325. List<string> schIds = new();
  1326. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<BIRelation>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BIRel") }))
  1327. {
  1328. if (!string.IsNullOrWhiteSpace(item.areaId) && areaDic.ContainsKey(item.areaId))
  1329. {
  1330. item.areaName = areaDic[item.areaId];
  1331. }
  1332. scInfos.Add(item);
  1333. schIds.Add(item.id);
  1334. }
  1335. //取得學校產品列表
  1336. if(schIds.Count > 0)
  1337. {
  1338. string schIdListStr = JsonSerializer.Serialize(schIds);
  1339. StringBuilder sqlPSum = new($"SELECT * FROM c WHERE ARRAY_CONTAINS({schIdListStr}, c.id, true)");
  1340. await foreach (SchoolProductSum item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<SchoolProductSum>(queryText: sqlPSum.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("ProductSum") }))
  1341. {
  1342. List<string> serialProdList = item.serial.Select(s => s.prodCode).ToList();
  1343. List<string> serviceProdList = item.service.Select(s => s.prodCode).ToList();
  1344. List<string> hardProdList = item.hard.Select(s => s.prodCode).ToList();
  1345. BIRelation scInfo = scInfos.Where(s => s.id.Equals(item.id)).FirstOrDefault();
  1346. if(scInfo != null)
  1347. {
  1348. scInfo.serial = serialProdList;
  1349. scInfo.service = serviceProdList;
  1350. scInfo.hard = hardProdList;
  1351. }
  1352. }
  1353. }
  1354. //虛擬學校
  1355. ////取得虛擬學校學區名稱
  1356. List<string> vrAreaIdList = new List<string>();
  1357. StringBuilder sqlVrArea = new($"SELECT DISTINCT VALUE c.areaId FROM c WHERE IS_DEFINED(c.areaId) AND NOT IS_NULL(c.areaId) AND c.areaId != ''");
  1358. await foreach (string item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<string>(queryText: sqlVrArea.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("VirtualBase") }))
  1359. {
  1360. vrAreaIdList.Add(item);
  1361. }
  1362. //Dictionary<string, string> areaDic = new Dictionary<string, string>();
  1363. string vrAreaListStr = JsonSerializer.Serialize(vrAreaIdList);
  1364. StringBuilder vrSqlArea = new($"SELECT c.id, c.name FROM c WHERE ARRAY_CONTAINS({vrAreaListStr}, c.id, true)");
  1365. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryStreamIteratorSql(queryText: vrSqlArea.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
  1366. {
  1367. var json = await JsonDocument.ParseAsync(item.Content);
  1368. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1369. {
  1370. string arId = obj.GetProperty("id").GetString();
  1371. string arName = obj.GetProperty("name").GetString();
  1372. if (!areaDic.ContainsKey(arId))
  1373. {
  1374. areaDic.Add(arId, arName);
  1375. }
  1376. }
  1377. }
  1378. //取得虛擬學校資料
  1379. StringBuilder sqlV = new($"select value(c) from c");
  1380. if (!string.IsNullOrEmpty($"{areaId}") && !string.IsNullOrEmpty($"{role}"))
  1381. {
  1382. sqlV.Append($" where c.areaId ='{areaId}'");
  1383. }
  1384. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<BIRelation>(queryText: sqlV.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("VirtualBase") }))
  1385. {
  1386. if(!string.IsNullOrWhiteSpace(item.areaId) && areaDic.ContainsKey(item.areaId))
  1387. {
  1388. item.areaName = areaDic[item.areaId];
  1389. }
  1390. scInfos.Add(item);
  1391. }
  1392. return Ok(new { state = RespondCode.Ok, allCnt = scInfos.Count, scInfos });
  1393. }
  1394. /// <summary>
  1395. /// 依据Id查询School容器 数据管理工具——查询工具
  1396. /// </summary>
  1397. /// <param name="jsonElement"></param>
  1398. /// <returns></returns>
  1399. [ProducesDefaultResponseType]
  1400. [HttpPost("get-info")]
  1401. public async Task<IActionResult> GetSchool(JsonElement jsonElement)
  1402. {
  1403. if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1404. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1405. var cosmosClient = _azureCosmos.GetCosmosClient();
  1406. //if ($"{site}".Equals(BIConst.Global))
  1407. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1408. List<object> infos = new List<object>();
  1409. string sqlTxt = $"select value(c) from c where c.id='{id}'";
  1410. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIteratorSql(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { }))
  1411. {
  1412. using var json = await JsonDocument.ParseAsync(item.Content);
  1413. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  1414. {
  1415. infos.Add(obj.ToObject<object>());
  1416. }
  1417. }
  1418. return Ok(new { state = 200, infos });
  1419. }
  1420. public record RecSchoolDate
  1421. {
  1422. public string id { get; set; }
  1423. public string name { get; set; }
  1424. public long dataCount { get; set; }
  1425. }
  1426. }
  1427. }