LessonSticsController.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using TEAMModelOS.Models;
  8. using TEAMModelOS.SDK.DI;
  9. using Microsoft.Extensions.Options;
  10. using Azure.Cosmos;
  11. using System.Text.Json;
  12. using TEAMModelOS.SDK.Models.Cosmos.Common;
  13. using TEAMModelOS.SDK.Models;
  14. using TEAMModelBI.Models;
  15. using TEAMModelOS.SDK.Extension;
  16. using System.Text;
  17. using TEAMModelBI.Tool;
  18. using MathNet.Numerics.LinearAlgebra.Double;
  19. namespace TEAMModelBI.Controllers.Census
  20. {
  21. [Route("lesson")]
  22. [ApiController]
  23. public class LessonSticsController : ControllerBase
  24. {
  25. private readonly AzureCosmosFactory _azureCosmos;
  26. private readonly AzureStorageFactory _azureStorage;
  27. private readonly DingDing _dingDing;
  28. private readonly Option _option;
  29. public LessonSticsController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureFactory, DingDing dingDing, IOptionsSnapshot<Option> option)
  30. {
  31. _azureCosmos = azureCosmos;
  32. _azureStorage = azureFactory;
  33. _dingDing = dingDing;
  34. _option = option?.Value;
  35. }
  36. /// <summary>
  37. /// 查询课例数量
  38. /// </summary>
  39. /// <param name="jsonElement"></param>
  40. /// <returns></returns>
  41. [HttpPost("get-count")]
  42. public async Task<IActionResult> GetCount(JsonElement jsonElement)
  43. {
  44. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  45. if (!jsonElement.TryGetProperty("term", out JsonElement term)) return BadRequest();
  46. var cosmosClient = _azureCosmos.GetCosmosClient();
  47. var (start, end) = DateTimeHeloer.GetTermStartOrEnd(DateTime.Now);
  48. object totals = new object();
  49. if (!string.IsNullOrEmpty($"{tmdId}"))
  50. {
  51. List<SchoolLen> schoolLens = new List<SchoolLen>();
  52. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  53. foreach (var itemId in schoolIds)
  54. {
  55. School school = new();
  56. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(itemId, new PartitionKey("Base"));
  57. if (response.Status == 200)
  58. {
  59. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  60. school = json.ToObject<School>();
  61. }
  62. SchoolLen schoolLen = new SchoolLen() { id = itemId, name = school.name != null ? school.name : itemId };
  63. //string sqlTxt = $"SELECT COUNT(c.id) AS totals FROM c WHERE c.code='LessonRecord-{itemId}'";
  64. StringBuilder sqlTxt = new StringBuilder($"SELECT COUNT(c.id) AS totals FROM c WHERE c.code='LessonRecord-{itemId}'");
  65. if (bool.Parse($"{term}") == true)
  66. {
  67. sqlTxt.Append($" and c.startTime >= {start} and c.startTime <= {end}");
  68. }
  69. schoolLen.totals = await CommonFind.FindTotals(cosmosClient, sqlTxt.ToString(), new List<string>() { "School" });
  70. schoolLens.Add(schoolLen);
  71. }
  72. totals = schoolLens;
  73. }
  74. else
  75. {
  76. StringBuilder sqlTxt = new StringBuilder($"select COUNT(c.id) AS totals from c where c.pk='LessonRecord'");
  77. if (bool.Parse($"{term}") == true)
  78. {
  79. sqlTxt.Append($" and c.startTime >= {start} and c.startTime <= {end}");
  80. }
  81. totals = await CommonFind.FindTotals(cosmosClient, sqlTxt.ToString(), new List<string>() { "School" });
  82. }
  83. return Ok(new { state = 200, totals });
  84. }
  85. /// <summary>
  86. /// 统计所有课例数量
  87. /// </summary>
  88. /// <returns></returns>
  89. [HttpPost("get-total")]
  90. public async Task<IActionResult> GetCount()
  91. {
  92. try
  93. {
  94. var cosmosClient = _azureCosmos.GetCosmosClient();
  95. string lessonSql = $"select COUNT(c.id) AS totals from c where c.pk='LessonRecord'";
  96. long total = await CommonFind.FindTotals(cosmosClient, lessonSql, new List<string>() { "School" });
  97. return Ok(new { state = 200, total });
  98. }
  99. catch (Exception ex)
  100. {
  101. await _dingDing.SendBotMsg($"BI,{_option.Location} /lesson/get-total {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  102. return BadRequest();
  103. }
  104. }
  105. /// <summary>
  106. /// 管家所关联的课例数据
  107. /// </summary>
  108. /// <param name="jsonElement"></param>
  109. /// <returns></returns>
  110. [ProducesDefaultResponseType]
  111. [HttpPost("get-assiist")]
  112. public async Task<IActionResult> GetAssiist(JsonElement jsonElement)
  113. {
  114. try
  115. {
  116. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  117. var cosmosClient = _azureCosmos.GetCosmosClient();
  118. List<SchoolLen> schoolLens = new List<SchoolLen>();
  119. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  120. foreach (var itemId in schoolIds)
  121. {
  122. School school = new();
  123. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(itemId, new PartitionKey("Base"));
  124. if (response.Status == 200)
  125. {
  126. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  127. school = json.ToObject<School>();
  128. }
  129. SchoolLen schoolLen = new SchoolLen() { id = itemId, name = school != null ? school.name : itemId };
  130. string sqlTxt = $"SELECT COUNT(c.id) AS totals FROM c WHERE c.code='LessonRecord-{itemId}'";
  131. schoolLen.totals = await CommonFind.FindTotals(cosmosClient, sqlTxt, new List<string>() { "School" });
  132. schoolLens.Add(schoolLen);
  133. }
  134. return Ok(new { state = 200, schoolLens });
  135. }
  136. catch (Exception ex)
  137. {
  138. await _dingDing.SendBotMsg($"BI, {_option.Location} /lesson/get-assiist {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  139. return BadRequest();
  140. }
  141. }
  142. /// <summary>
  143. /// 统计所有的课例数据
  144. /// </summary>
  145. /// <returns></returns>
  146. [HttpPost("get-diccount")]
  147. public async Task<IActionResult> GetDicCount(JsonElement jsonElement)
  148. {
  149. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  150. var cosmosClient = _azureCosmos.GetCosmosClient();
  151. if (!string.IsNullOrEmpty($"{tmdId}"))
  152. {
  153. jsonElement.TryGetProperty("years", out JsonElement _years);
  154. int years = DateTime.UtcNow.Year;
  155. if (!string.IsNullOrEmpty($"{_years}"))
  156. {
  157. years = _years.GetInt32();
  158. }
  159. List<SchoolLen> schoolLens = new List<SchoolLen>();
  160. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  161. foreach (string schoolId in schoolIds)
  162. {
  163. School school = new();
  164. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(schoolId, new PartitionKey("Base"));
  165. if (response.Status == 200)
  166. {
  167. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  168. school = json.ToObject<School>();
  169. }
  170. SchoolLen schoolLen = new SchoolLen() { id = schoolId, name = school != null ? school.name : schoolId };
  171. List<List<double>> begin = new();
  172. await foreach (var lcount in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<LessonCount>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{schoolId}-{years}") }))
  173. {
  174. begin.Add(lcount.beginCount);
  175. }
  176. schoolLen.totals = (long)DenseMatrix.OfColumns(begin).ColumnSums().Sum();
  177. schoolLens.Add(schoolLen);
  178. }
  179. return Ok(new { state = 200, schoolLens });
  180. }
  181. else
  182. {
  183. List<List<double>> begin = new();
  184. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<LessonCount>(queryText: "select value(c) from c where c.pk='LessonCount'", requestOptions: new QueryRequestOptions() { }))
  185. {
  186. begin.Add(item.beginCount);
  187. }
  188. var count = DenseMatrix.OfColumns(begin).ColumnSums().Sum();
  189. return Ok(new { state = 200, count });
  190. }
  191. }
  192. /// <summary>
  193. /// 顾问关联的学校统计本学期的课例
  194. /// </summary>
  195. /// <param name="jsonElement"></param>
  196. /// <returns></returns>
  197. [HttpPost("get-termcount")]
  198. public async Task<IActionResult> GetTermCount(JsonElement jsonElement)
  199. {
  200. if(jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) BadRequest();
  201. var cosmosClient = _azureCosmos.GetCosmosClient();
  202. List<SchoolLen> schoolLens = new List<SchoolLen>();
  203. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  204. foreach (var scid in schoolIds)
  205. {
  206. School school = new();
  207. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(scid, new PartitionKey("Base"));
  208. if (response.Status == 200)
  209. {
  210. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  211. school = json.ToObject<School>();
  212. }
  213. SchoolLen schoolLen = new SchoolLen() { id = scid, name = !string.IsNullOrEmpty(school.name) ? school.name : scid };
  214. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  215. int year = (dateTime.Month <= 8 && dateTime.Month >= 3) ? dateTime.Year : dateTime.Year - 1;
  216. long stime = DateTimeOffset.Parse($"{year}-9-1").ToUnixTimeMilliseconds();
  217. //long etime = DateTimeOffset.Parse($"{year}-2-{((year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 29 : 28)}").ToUnixTimeMilliseconds();
  218. double totals = 0;
  219. var syear = DateTimeOffset.FromUnixTimeMilliseconds(stime).Year;
  220. var tyear = DateTimeOffset.UtcNow.Year;
  221. var tday = DateTimeOffset.UtcNow.DayOfYear;
  222. //今年多少天
  223. int tdays = (tyear % 4 == 0 && tyear % 100 != 0 || tyear % 400 == 0) ? 366 : 365;
  224. //去年多少天
  225. int pydays = (syear % 4 == 0 && syear % 100 != 0 || syear % 400 == 0) ? 366 : 365;
  226. List<LessonCount> scount = new();
  227. List<LessonCount> tcount = new();
  228. DenseMatrix dense = null;
  229. var queryClass = $"select value(c) from c ";
  230. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<LessonCount>(
  231. queryText: queryClass,
  232. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{scid}-{syear}") }))
  233. {
  234. scount.Add(item);
  235. }
  236. if (tyear > syear)
  237. {
  238. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<LessonCount>(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{scid}-{tyear}") }))
  239. {
  240. tcount.Add(item);
  241. }
  242. if (tcount.Count > 0)
  243. {
  244. List<List<double>> be = new();
  245. foreach (var item in tcount)
  246. {
  247. be.Add(item.beginCount);
  248. }
  249. dense = DenseMatrix.OfColumns(be);
  250. }
  251. }
  252. if (scount.Count > 0)
  253. {
  254. List<List<double>> begin = new List<List<double>>();
  255. foreach (LessonCount lesson in scount)
  256. {
  257. begin.Add(lesson.beginCount);
  258. }
  259. var matrix = DenseMatrix.OfColumns(begin);
  260. //求本学期
  261. var sdays = DateTimeOffset.FromUnixTimeMilliseconds(stime).DayOfYear;
  262. if (tday - sdays < 0)
  263. {
  264. //var tmatrix = DenseMatrix.OfColumns(scount.beginCount);
  265. //跨年后开始到本学期结束
  266. double endMonth = 0;
  267. if (null != dense)
  268. {
  269. endMonth = dense.SubMatrix(0, tday, 0, dense.ColumnCount).ColumnSums().Sum();
  270. }
  271. var startMonth = matrix.SubMatrix(sdays - 1, pydays - sdays, 0, matrix.ColumnCount).ColumnSums().Sum();
  272. totals = (endMonth + startMonth);
  273. }
  274. else
  275. {
  276. var allMonth = matrix.SubMatrix(sdays - 1, tday - sdays + 1, 0, matrix.ColumnCount).ColumnSums().Sum();
  277. totals = allMonth;
  278. }
  279. }
  280. schoolLen.totals = (long)totals;
  281. schoolLens.Add(schoolLen);
  282. }
  283. return Ok(new { state = 200, schoolLens });
  284. }
  285. public record SchoolLen
  286. {
  287. public string id { get; set; }
  288. public string name { get; set;}
  289. public long totals { get; set; }
  290. }
  291. }
  292. }