SchoolController.cs 87 KB

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